text
stringlengths
54
60.6k
<commit_before>#include "log.h" #include <ctime> #include <cstring> #include <algorithm> namespace oak::log { Logger cout{ "msg" }; Logger cwarn{ "warn" }; Logger cerr{ "err" }; Logger::Logger(const char* name) : name_{ name } { } void Logger::addStream(Stream *stream) { streams_.push_back(stream); } void Logger::removeStream(Stream *stream) { streams_.erase(std::remove(std::begin(streams_), std::end(streams_), stream), std::end(streams_)); } void Logger::print(const char* text, Level level, const char* file, int line) { memset(buffer_, 0, 2048); //get time info time_t t = time(NULL); struct tm *tm = localtime(&t); switch (level) { case Level::MINIMAL: sprintf(buffer_, "[%s]: %s\n", name_, text); break; case Level::NORMAL: sprintf(buffer_, "[%i:%i:%i %i/%i/%i][%s]: %s\n", tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_mon+1, tm->tm_mday, 1900+tm->tm_year, name_, text); break; case Level::VERBOSE: sprintf(buffer_, "[%i:%i:%i %i/%i/%i][file]:%s:%i[%s]: %s\n", tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_mon+1, tm->tm_mday, 1900+tm->tm_year, file, line, name_, text); break; } flush(); } void Logger::flush() { for (auto& stream : streams_) { stream->write(buffer_); } } }<commit_msg>fixed log<commit_after>#include "log.h" #include <ctime> #include <cstring> #include <algorithm> namespace oak::log { Logger cout{ "msg" }; Logger cwarn{ "warn" }; Logger cerr{ "err" }; Logger::Logger(const char* name) : name_{ name } { } void Logger::addStream(Stream *stream) { streams_.push_back(stream); } void Logger::removeStream(Stream *stream) { streams_.erase(std::remove(std::begin(streams_), std::end(streams_), stream), std::end(streams_)); } void Logger::print(const char* text, Level level, const char* file, int line) { memset(buffer_, 0, 2048); //get time info time_t t = time(NULL); struct tm *tm = localtime(&t); switch (level) { case Level::MINIMAL: sprintf(buffer_, "[%s]: %s\n", name_, text); break; case Level::NORMAL: sprintf(buffer_, "[%i:%i:%i %i/%i/%i][%s]: %s\n", tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_mon+1, tm->tm_mday, 1900+tm->tm_year, name_, text); break; case Level::VERBOSE: sprintf(buffer_, "[%i:%i:%i %i/%i/%i][file]:%s:%i[%s]: %s\n", tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_mon+1, tm->tm_mday, 1900+tm->tm_year, file, line, name_, text); break; } flush(); } void Logger::flush() { for (auto& stream : streams_) { stream->buffer->write(strlen(buffer_), buffer_); } } }<|endoftext|>
<commit_before>// Copyright (c) 2010 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. // This is a file for random testcases that we run into that at one point or // another have crashed the program. #include "chrome/test/ui/ui_test.h" #include "base/basictypes.h" #include "base/file_path.h" #include "chrome/common/chrome_switches.h" #include "net/base/net_util.h" class GoogleTest : public UITest { protected: GoogleTest() : UITest() { FilePath test_file = test_data_directory_.AppendASCII("google").AppendASCII("google.html"); set_homepage(GURL(net::FilePathToFileURL(test_file)).spec()); } }; // Flakily fails under Valgrind, see http://crbug.com/85863. #if defined(OS_MACOSX) #define MAYBE_Crash FLAKY_Crash #elese #define MAYBE_Crash Crash #endif // defined(OS_MACOSX) TEST_F(GoogleTest, MAYBE_Crash) { std::wstring page_title = L"Google"; // Make sure the navigation succeeded. EXPECT_EQ(page_title, GetActiveTabTitle()); // UITest will check if this crashed. } class ColumnLayout : public UITest { protected: ColumnLayout() : UITest() { FilePath test_file = test_data_directory_.AppendASCII("columns.html"); set_homepage(GURL(net::FilePathToFileURL(test_file)).spec()); } }; TEST_F(ColumnLayout, Crash) { std::wstring page_title = L"Column test"; // Make sure the navigation succeeded. EXPECT_EQ(page_title, GetActiveTabTitle()); // UITest will check if this crashed. } // By passing kTryChromeAgain with a magic value > 10000 we cause Chrome // to exit fairly early. // Quickly exiting Chrome (regardless of this particular flag -- it // doesn't do anything other than cause Chrome to quit on startup on // non-Windows) was a cause of crashes (see bug 34799 for example) so // this is a useful test of the startup/quick-shutdown cycle. class EarlyReturnTest : public UITest { public: EarlyReturnTest() { wait_for_initial_loads_ = false; // Don't wait for any pages to load. launch_arguments_.AppendSwitchASCII(switches::kTryChromeAgain, "10001"); } }; // Disabled: http://crbug.com/45115 // Due to limitations in our test infrastructure, this test currently doesn't // work. TEST_F(EarlyReturnTest, DISABLED_ToastCrasher) { // UITest will check if this crashed. } <commit_msg>Revert 88791 - Valgrind: Mark GoogleTest.Crash as flaky under Mac.<commit_after>// Copyright (c) 2010 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. // This is a file for random testcases that we run into that at one point or // another have crashed the program. #include "chrome/test/ui/ui_test.h" #include "base/basictypes.h" #include "base/file_path.h" #include "chrome/common/chrome_switches.h" #include "net/base/net_util.h" class GoogleTest : public UITest { protected: GoogleTest() : UITest() { FilePath test_file = test_data_directory_.AppendASCII("google").AppendASCII("google.html"); set_homepage(GURL(net::FilePathToFileURL(test_file)).spec()); } }; TEST_F(GoogleTest, Crash) { std::wstring page_title = L"Google"; // Make sure the navigation succeeded. EXPECT_EQ(page_title, GetActiveTabTitle()); // UITest will check if this crashed. } class ColumnLayout : public UITest { protected: ColumnLayout() : UITest() { FilePath test_file = test_data_directory_.AppendASCII("columns.html"); set_homepage(GURL(net::FilePathToFileURL(test_file)).spec()); } }; TEST_F(ColumnLayout, Crash) { std::wstring page_title = L"Column test"; // Make sure the navigation succeeded. EXPECT_EQ(page_title, GetActiveTabTitle()); // UITest will check if this crashed. } // By passing kTryChromeAgain with a magic value > 10000 we cause Chrome // to exit fairly early. // Quickly exiting Chrome (regardless of this particular flag -- it // doesn't do anything other than cause Chrome to quit on startup on // non-Windows) was a cause of crashes (see bug 34799 for example) so // this is a useful test of the startup/quick-shutdown cycle. class EarlyReturnTest : public UITest { public: EarlyReturnTest() { wait_for_initial_loads_ = false; // Don't wait for any pages to load. launch_arguments_.AppendSwitchASCII(switches::kTryChromeAgain, "10001"); } }; // Disabled: http://crbug.com/45115 // Due to limitations in our test infrastructure, this test currently doesn't // work. TEST_F(EarlyReturnTest, DISABLED_ToastCrasher) { // UITest will check if this crashed. } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasielv@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/AST/PrettyPrinter.h" using namespace clang; namespace cling { Transaction::~Transaction() { for (size_t i = 0; i < m_NestedTransactions.size(); ++i) delete m_NestedTransactions[i]; } void Transaction::appendUnique(DeclGroupRef DGR) { for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (DGR.isNull() || (*I).getAsOpaquePtr() == DGR.getAsOpaquePtr()) return; } // register the wrapper if any. if (DGR.isSingleDecl()) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DGR.getSingleDecl())) if (utils::Analyze::IsWrapper(FD)) { assert(!m_WrapperFD && "Two wrappers in one transaction?"); m_WrapperFD = FD; } } m_DeclQueue.push_back(DGR); } void Transaction::dump() const { if (!size()) return; ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext(); PrintingPolicy Policy = C.getPrintingPolicy(); Policy.DumpSourceManager = &C.getSourceManager(); print(llvm::outs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::dumpPretty() const { if (!size()) return; ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext(); PrintingPolicy Policy(C.getLangOpts()); print(llvm::outs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy, unsigned Indent, bool PrintInstantiation) const { int nestedT = 0; for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (I->isNull()) { assert(hasNestedTransactions() && "DGR is null even if no nesting?"); // print the nested decl Out<<"+====================================================+\n"; Out<<"| Nested Transaction" << nestedT << " |\n"; Out<<"+====================================================+\n"; m_NestedTransactions[nestedT++]->print(Out, Policy, Indent, PrintInstantiation); Out<<"+====================================================+\n"; Out<<"| End Transaction" << nestedT << " |\n"; Out<<"+====================================================+\n"; } for (DeclGroupRef::const_iterator J = I->begin(), L = I->end();J != L;++J) if (*J) (*J)->print(Out, Policy, Indent, PrintInstantiation); else Out << "<<NULL DECL>>"; } } } // end namespace cling <commit_msg>If the first decl happens to be null ask the wrapper function for the ASTContext.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasielv@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/AST/PrettyPrinter.h" using namespace clang; namespace cling { Transaction::~Transaction() { for (size_t i = 0; i < m_NestedTransactions.size(); ++i) delete m_NestedTransactions[i]; } void Transaction::appendUnique(DeclGroupRef DGR) { for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (DGR.isNull() || (*I).getAsOpaquePtr() == DGR.getAsOpaquePtr()) return; } // register the wrapper if any. if (DGR.isSingleDecl()) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DGR.getSingleDecl())) if (utils::Analyze::IsWrapper(FD)) { assert(!m_WrapperFD && "Two wrappers in one transaction?"); m_WrapperFD = FD; } } m_DeclQueue.push_back(DGR); } void Transaction::dump() const { if (!size()) return; ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext(); PrintingPolicy Policy = C.getPrintingPolicy(); Policy.DumpSourceManager = &C.getSourceManager(); print(llvm::outs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::dumpPretty() const { if (!size()) return; ASTContext* C; if (m_WrapperFD) C = &(m_WrapperFD->getASTContext()); if (!getFirstDecl().isNull()) C = &(getFirstDecl().getSingleDecl()->getASTContext()); PrintingPolicy Policy(C->getLangOpts()); print(llvm::outs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy, unsigned Indent, bool PrintInstantiation) const { int nestedT = 0; for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (I->isNull()) { assert(hasNestedTransactions() && "DGR is null even if no nesting?"); // print the nested decl Out<< "\n"; Out<<"+====================================================+\n"; Out<<" Nested Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; m_NestedTransactions[nestedT++]->print(Out, Policy, Indent, PrintInstantiation); Out<< "\n"; Out<<"+====================================================+\n"; Out<<" End Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; } for (DeclGroupRef::const_iterator J = I->begin(), L = I->end();J != L;++J) if (*J) (*J)->print(Out, Policy, Indent, PrintInstantiation); else Out << "<<NULL DECL>>"; } } } // end namespace cling <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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/installer/gcapi/gcapi.h" #include <atlbase.h> #include <atlcom.h> #include <windows.h> #include <sddl.h> #include <stdlib.h> #include <strsafe.h> #include <tlhelp32.h> #include "google_update_idl.h" namespace { const wchar_t kChromeRegClientsKey[] = L"Software\\Google\\Update\\Clients\\{8A69D345-D564-463c-AFF1-A69D9E530F96}"; const wchar_t kChromeRegClientStateKey[] = L"Software\\Google\\Update\\ClientState\\{8A69D345-D564-463c-AFF1-A69D9E530F96}"; const wchar_t kChromeRegLaunchCmd[] = L"InstallerSuccessLaunchCmdLine"; const wchar_t kChromeRegLastLaunchCmd[] = L"LastInstallerSuccessLaunchCmdLine"; const wchar_t kChromeRegVersion[] = L"pv"; const wchar_t kNoChromeOfferUntil[] = L"SOFTWARE\\Google\\No Chrome Offer Until"; // Remove any registry key with non-numeric value or with the numeric value // equal or less than today's date represented in YYYYMMDD form. void CleanUpRegistryValues() { HKEY key = NULL; if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, kNoChromeOfferUntil, 0, KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) return; DWORD index = 0; wchar_t value_name[260]; DWORD value_name_len = _countof(value_name); DWORD value_type = REG_DWORD; DWORD value_data = 0; DWORD value_len = sizeof(DWORD); // First, remove any value whose type is not DWORD index = 0; value_len = 0; while (::RegEnumValue(key, index, value_name, &value_name_len, NULL, &value_type, NULL, &value_len) == ERROR_SUCCESS) { if (value_type == REG_DWORD) index++; else ::RegDeleteValue(key, value_name); value_name_len = _countof(value_name); value_type = REG_DWORD; value_len = sizeof(DWORD); } // Get today's date, and format it as YYYYMMDD numeric value SYSTEMTIME now; ::GetLocalTime(&now); DWORD expiration_date = now.wYear * 10000 + now.wMonth * 100 + now.wDay; // Remove any DWORD value smaller than the number represent the // expiration date (YYYYMMDD) index = 0; while (::RegEnumValue(key, index, value_name, &value_name_len, NULL, &value_type, (LPBYTE) &value_data, &value_len) == ERROR_SUCCESS) { if (value_type == REG_DWORD && value_data > expiration_date) index++; // move on to next value else ::RegDeleteValue(key, value_name); // delete this value value_name_len = _countof(value_name); value_type = REG_DWORD; value_data = 0; value_len = sizeof(DWORD); } ::RegCloseKey(key); } // Return the company name specified in the file version info resource. bool GetCompanyName(const wchar_t* filename, wchar_t* buffer, DWORD out_len) { wchar_t file_version_info[8192]; DWORD handle = 0; DWORD buffer_size = 0; buffer_size = ::GetFileVersionInfoSize(filename, &handle); // Cannot stats the file or our buffer size is too small (very unlikely) if (buffer_size == 0 || buffer_size > _countof(file_version_info)) return false; buffer_size = _countof(file_version_info); memset(file_version_info, 0, buffer_size); if (!::GetFileVersionInfo(filename, handle, buffer_size, file_version_info)) return false; DWORD data_len = 0; LPVOID data = NULL; // Retrieve the language and codepage code if exists. buffer_size = 0; if (!::VerQueryValue(file_version_info, TEXT("\\VarFileInfo\\Translation"), reinterpret_cast<LPVOID *>(&data), reinterpret_cast<UINT *>(&data_len))) return false; if (data_len != 4) return false; wchar_t info_name[256]; DWORD lang = 0; // Formulate the string to retrieve the company name of the specific // language codepage. memcpy(&lang, data, 4); ::StringCchPrintf(info_name, _countof(info_name), L"\\StringFileInfo\\%02X%02X%02X%02X\\CompanyName", (lang & 0xff00)>>8, (lang & 0xff), (lang & 0xff000000)>>24, (lang & 0xff0000)>>16); data_len = 0; if (!::VerQueryValue(file_version_info, info_name, reinterpret_cast<LPVOID *>(&data), reinterpret_cast<UINT *>(&data_len))) return false; if (data_len <= 0 || data_len >= out_len) return false; memset(buffer, 0, out_len); ::StringCchCopyN(buffer, out_len, (const wchar_t*)data, data_len); return true; } // Return true if we can re-offer Chrome; false, otherwise. // Each partner can only offer Chrome once every six months. bool CanReOfferChrome() { wchar_t filename[MAX_PATH+1]; wchar_t company[MAX_PATH]; // If we cannot retrieve the version info of the executable or company // name, we allow the Chrome to be offered because there is no past // history to be found. if (::GetModuleFileName(NULL, filename, MAX_PATH) == 0) return true; if (!GetCompanyName(filename, company, sizeof(company))) return true; bool can_re_offer = true; DWORD disposition = 0; HKEY key = NULL; if (::RegCreateKeyEx(HKEY_LOCAL_MACHINE, kNoChromeOfferUntil, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &key, &disposition) == ERROR_SUCCESS) { // Cannot re-offer, if the timer already exists and is not expired yet if (::RegQueryValueEx(key, company, 0, 0, 0, 0) == ERROR_SUCCESS) { // The expired timers were already removed in CleanUpRegistryValues. // So if the key is not found, we can offer the Chrome. can_re_offer = false; } else { // Set expiration date for offer as six months from today, // represented as a YYYYMMDD numeric value SYSTEMTIME timer; ::GetLocalTime(&timer); timer.wMonth = timer.wMonth + 6; if (timer.wMonth > 12) { timer.wMonth = timer.wMonth - 12; timer.wYear = timer.wYear + 1; } DWORD value = timer.wYear * 10000 + timer.wMonth * 100 + timer.wDay; ::RegSetValueEx(key, company, 0, REG_DWORD, (LPBYTE)&value, sizeof(DWORD)); } ::RegCloseKey(key); } return can_re_offer; } // Helper function to read a value from registry. Returns true if value // is read successfully and stored in parameter value. Returns false otherwise. bool ReadValueFromRegistry(HKEY root_key, const wchar_t *sub_key, const wchar_t *value_name, wchar_t *value, size_t *size) { HKEY key; if ((::RegOpenKeyEx(root_key, sub_key, NULL, KEY_READ, &key) == ERROR_SUCCESS) && (::RegQueryValueEx(key, value_name, NULL, NULL, reinterpret_cast<LPBYTE>(value), reinterpret_cast<LPDWORD>(size)) == ERROR_SUCCESS)) { ::RegCloseKey(key); return true; } return false; } bool IsChromeInstalled(HKEY root_key) { wchar_t version[64]; size_t size = _countof(version); if (ReadValueFromRegistry(root_key, kChromeRegClientsKey, kChromeRegVersion, version, &size)) return true; return false; } bool IsWinXPSp1OrLater(bool* is_vista_or_later) { OSVERSIONINFOEX osviex = { sizeof(OSVERSIONINFOEX) }; int r = ::GetVersionEx((LPOSVERSIONINFO)&osviex); // If this failed we're on Win9X or a pre NT4SP6 OS if (!r) return false; if (osviex.dwMajorVersion < 5) return false; if (osviex.dwMajorVersion > 5) { *is_vista_or_later = true; return true; // way beyond Windows XP; } if (osviex.dwMinorVersion >= 1 && osviex.wServicePackMajor >= 1) return true; // Windows XP SP1 or better return false; // Windows 2000, WinXP no Service Pack } // Note this function should not be called on old Windows versions where these // Windows API are not available. We always invoke this function after checking // that current OS is Vista or later. bool VerifyAdminGroup() { SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; PSID Group; BOOL check = ::AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &Group); if (check) { if (!::CheckTokenMembership(NULL, Group, &check)) check = FALSE; } ::FreeSid(Group); return (check == TRUE); } bool VerifyHKLMAccess(const wchar_t* sub_key) { HKEY root = HKEY_LOCAL_MACHINE; wchar_t str[] = L"test"; bool result = false; DWORD disposition = 0; HKEY key = NULL; if (::RegCreateKeyEx(root, sub_key, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &key, &disposition) == ERROR_SUCCESS) { if (::RegSetValueEx(key, str, 0, REG_SZ, (LPBYTE)str, (DWORD)lstrlen(str)) == ERROR_SUCCESS) { result = true; RegDeleteValue(key, str); } // If we create the main key, delete the entire key. if (disposition == REG_CREATED_NEW_KEY) RegDeleteKey(key, NULL); RegCloseKey(key); } return result; } bool IsRunningElevated() { // This method should be called only for Vista or later. bool is_vista_or_later = false; IsWinXPSp1OrLater(&is_vista_or_later); if (!is_vista_or_later || !VerifyAdminGroup()) return false; HANDLE process_token; if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token)) return false; TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault; DWORD size_returned = 0; if (!::GetTokenInformation(process_token, TokenElevationType, &elevation_type, sizeof(elevation_type), &size_returned)) { ::CloseHandle(process_token); return false; } ::CloseHandle(process_token); return (elevation_type == TokenElevationTypeFull); } bool GetUserIdForProcess(size_t pid, wchar_t** user_sid) { HANDLE process_handle = ::OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, pid); if (process_handle == NULL) return false; HANDLE process_token; bool result = false; if (::OpenProcessToken(process_handle, TOKEN_QUERY, &process_token)) { DWORD size = 0; ::GetTokenInformation(process_token, TokenUser, NULL, 0, &size); if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER || ::GetLastError() == ERROR_SUCCESS) { DWORD actual_size = 0; BYTE* token_user = new BYTE[size]; if ((::GetTokenInformation(process_token, TokenUser, token_user, size, &actual_size)) && (actual_size <= size)) { PSID sid = reinterpret_cast<TOKEN_USER*>(token_user)->User.Sid; if (::ConvertSidToStringSid(sid, user_sid)) result = true; } delete[] token_user; } ::CloseHandle(process_token); } ::CloseHandle(process_handle); return result; } } // namespace #pragma comment(linker, "/EXPORT:GoogleChromeCompatibilityCheck=_GoogleChromeCompatibilityCheck@4,PRIVATE") DLLEXPORT BOOL __stdcall GoogleChromeCompatibilityCheck(DWORD *reasons) { DWORD local_reasons = 0; bool is_vista_or_later = false; // System requirements? if (!IsWinXPSp1OrLater(&is_vista_or_later)) local_reasons |= GCCC_ERROR_OSNOTSUPPORTED; if (IsChromeInstalled(HKEY_LOCAL_MACHINE)) local_reasons |= GCCC_ERROR_SYSTEMLEVELALREADYPRESENT; if (IsChromeInstalled(HKEY_CURRENT_USER)) local_reasons |= GCCC_ERROR_USERLEVELALREADYPRESENT; if (!VerifyHKLMAccess(kChromeRegClientsKey)) { local_reasons |= GCCC_ERROR_ACCESSDENIED; } else if (is_vista_or_later && !VerifyAdminGroup()) { // For Vista or later check for elevation since even for admin user we could // be running in non-elevated mode. We require integrity level High. local_reasons |= GCCC_ERROR_INTEGRITYLEVEL; } // First clean up the registry keys left over previously. // Then only check whether we can re-offer, if everything else is OK. CleanUpRegistryValues(); if (local_reasons == 0 && !CanReOfferChrome()) local_reasons |= GCCC_ERROR_ALREADYOFFERED; // Done. Copy/return results. if (reasons != NULL) *reasons = local_reasons; return (*reasons == 0); } #pragma comment(linker, "/EXPORT:LaunchGoogleChrome=_LaunchGoogleChrome@0,PRIVATE") DLLEXPORT BOOL __stdcall LaunchGoogleChrome() { wchar_t launch_cmd[MAX_PATH]; size_t size = _countof(launch_cmd); if (!ReadValueFromRegistry(HKEY_LOCAL_MACHINE, kChromeRegClientStateKey, kChromeRegLastLaunchCmd, launch_cmd, &size)) { size = _countof(launch_cmd); if (!ReadValueFromRegistry(HKEY_LOCAL_MACHINE, kChromeRegClientStateKey, kChromeRegLaunchCmd, launch_cmd, &size)) { return false; } } HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); if (hr != S_OK) { if (hr == S_FALSE) ::CoUninitialize(); return false; } if (::CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IDENTIFY, NULL, EOAC_DYNAMIC_CLOAKING, NULL) != S_OK) { ::CoUninitialize(); return false; } bool impersonation_success = false; if (IsRunningElevated()) { wchar_t* curr_proc_sid; if (!GetUserIdForProcess(GetCurrentProcessId(), &curr_proc_sid)) { ::CoUninitialize(); return false; } DWORD pid = 0; ::GetWindowThreadProcessId(::GetShellWindow(), &pid); if (pid <= 0) { ::LocalFree(curr_proc_sid); ::CoUninitialize(); return false; } wchar_t* exp_proc_sid; if (GetUserIdForProcess(pid, &exp_proc_sid)) { if (_wcsicmp(curr_proc_sid, exp_proc_sid) == 0) { HANDLE process_handle = ::OpenProcess( PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION, TRUE, pid); if (process_handle != NULL) { HANDLE process_token; HANDLE user_token; if (::OpenProcessToken(process_handle, TOKEN_DUPLICATE | TOKEN_QUERY, &process_token) && ::DuplicateTokenEx(process_token, TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE, NULL, SecurityImpersonation, TokenPrimary, &user_token) && (::ImpersonateLoggedOnUser(user_token) != 0)) { impersonation_success = true; } ::CloseHandle(user_token); ::CloseHandle(process_token); ::CloseHandle(process_handle); } } ::LocalFree(exp_proc_sid); } ::LocalFree(curr_proc_sid); if (!impersonation_success) { ::CoUninitialize(); return false; } } bool ret = false; CComPtr<IProcessLauncher> ipl; if (!FAILED(ipl.CoCreateInstance(__uuidof(ProcessLauncherClass), NULL, CLSCTX_LOCAL_SERVER))) { if (!FAILED(ipl->LaunchCmdLine(launch_cmd))) ret = true; ipl.Release(); } if (impersonation_success) ::RevertToSelf(); ::CoUninitialize(); return ret; } <commit_msg>* Remove re-offer check from criteria checker.<commit_after>// Copyright (c) 2006-2008 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/installer/gcapi/gcapi.h" #include <atlbase.h> #include <atlcom.h> #include <windows.h> #include <sddl.h> #include <stdlib.h> #include <strsafe.h> #include <tlhelp32.h> #include "google_update_idl.h" namespace { const wchar_t kChromeRegClientsKey[] = L"Software\\Google\\Update\\Clients\\{8A69D345-D564-463c-AFF1-A69D9E530F96}"; const wchar_t kChromeRegClientStateKey[] = L"Software\\Google\\Update\\ClientState\\{8A69D345-D564-463c-AFF1-A69D9E530F96}"; const wchar_t kChromeRegLaunchCmd[] = L"InstallerSuccessLaunchCmdLine"; const wchar_t kChromeRegLastLaunchCmd[] = L"LastInstallerSuccessLaunchCmdLine"; const wchar_t kChromeRegVersion[] = L"pv"; // Helper function to read a value from registry. Returns true if value // is read successfully and stored in parameter value. Returns false otherwise. bool ReadValueFromRegistry(HKEY root_key, const wchar_t *sub_key, const wchar_t *value_name, wchar_t *value, size_t *size) { HKEY key; if ((::RegOpenKeyEx(root_key, sub_key, NULL, KEY_READ, &key) == ERROR_SUCCESS) && (::RegQueryValueEx(key, value_name, NULL, NULL, reinterpret_cast<LPBYTE>(value), reinterpret_cast<LPDWORD>(size)) == ERROR_SUCCESS)) { ::RegCloseKey(key); return true; } return false; } bool IsChromeInstalled(HKEY root_key) { wchar_t version[64]; size_t size = _countof(version); if (ReadValueFromRegistry(root_key, kChromeRegClientsKey, kChromeRegVersion, version, &size)) return true; return false; } bool IsWinXPSp1OrLater(bool* is_vista_or_later) { OSVERSIONINFOEX osviex = { sizeof(OSVERSIONINFOEX) }; int r = ::GetVersionEx((LPOSVERSIONINFO)&osviex); // If this failed we're on Win9X or a pre NT4SP6 OS if (!r) return false; if (osviex.dwMajorVersion < 5) return false; if (osviex.dwMajorVersion > 5) { *is_vista_or_later = true; return true; // way beyond Windows XP; } if (osviex.dwMinorVersion >= 1 && osviex.wServicePackMajor >= 1) return true; // Windows XP SP1 or better return false; // Windows 2000, WinXP no Service Pack } // Note this function should not be called on old Windows versions where these // Windows API are not available. We always invoke this function after checking // that current OS is Vista or later. bool VerifyAdminGroup() { SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; PSID Group; BOOL check = ::AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &Group); if (check) { if (!::CheckTokenMembership(NULL, Group, &check)) check = FALSE; } ::FreeSid(Group); return (check == TRUE); } bool VerifyHKLMAccess(const wchar_t* sub_key) { HKEY root = HKEY_LOCAL_MACHINE; wchar_t str[] = L"test"; bool result = false; DWORD disposition = 0; HKEY key = NULL; if (::RegCreateKeyEx(root, sub_key, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &key, &disposition) == ERROR_SUCCESS) { if (::RegSetValueEx(key, str, 0, REG_SZ, (LPBYTE)str, (DWORD)lstrlen(str)) == ERROR_SUCCESS) { result = true; RegDeleteValue(key, str); } // If we create the main key, delete the entire key. if (disposition == REG_CREATED_NEW_KEY) RegDeleteKey(key, NULL); RegCloseKey(key); } return result; } bool IsRunningElevated() { // This method should be called only for Vista or later. bool is_vista_or_later = false; IsWinXPSp1OrLater(&is_vista_or_later); if (!is_vista_or_later || !VerifyAdminGroup()) return false; HANDLE process_token; if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token)) return false; TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault; DWORD size_returned = 0; if (!::GetTokenInformation(process_token, TokenElevationType, &elevation_type, sizeof(elevation_type), &size_returned)) { ::CloseHandle(process_token); return false; } ::CloseHandle(process_token); return (elevation_type == TokenElevationTypeFull); } bool GetUserIdForProcess(size_t pid, wchar_t** user_sid) { HANDLE process_handle = ::OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, pid); if (process_handle == NULL) return false; HANDLE process_token; bool result = false; if (::OpenProcessToken(process_handle, TOKEN_QUERY, &process_token)) { DWORD size = 0; ::GetTokenInformation(process_token, TokenUser, NULL, 0, &size); if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER || ::GetLastError() == ERROR_SUCCESS) { DWORD actual_size = 0; BYTE* token_user = new BYTE[size]; if ((::GetTokenInformation(process_token, TokenUser, token_user, size, &actual_size)) && (actual_size <= size)) { PSID sid = reinterpret_cast<TOKEN_USER*>(token_user)->User.Sid; if (::ConvertSidToStringSid(sid, user_sid)) result = true; } delete[] token_user; } ::CloseHandle(process_token); } ::CloseHandle(process_handle); return result; } } // namespace #pragma comment(linker, "/EXPORT:GoogleChromeCompatibilityCheck=_GoogleChromeCompatibilityCheck@4,PRIVATE") DLLEXPORT BOOL __stdcall GoogleChromeCompatibilityCheck(DWORD *reasons) { DWORD local_reasons = 0; bool is_vista_or_later = false; // System requirements? if (!IsWinXPSp1OrLater(&is_vista_or_later)) local_reasons |= GCCC_ERROR_OSNOTSUPPORTED; if (IsChromeInstalled(HKEY_LOCAL_MACHINE)) local_reasons |= GCCC_ERROR_SYSTEMLEVELALREADYPRESENT; if (IsChromeInstalled(HKEY_CURRENT_USER)) local_reasons |= GCCC_ERROR_USERLEVELALREADYPRESENT; if (!VerifyHKLMAccess(kChromeRegClientsKey)) { local_reasons |= GCCC_ERROR_ACCESSDENIED; } else if (is_vista_or_later && !VerifyAdminGroup()) { // For Vista or later check for elevation since even for admin user we could // be running in non-elevated mode. We require integrity level High. local_reasons |= GCCC_ERROR_INTEGRITYLEVEL; } // Done. Copy/return results. if (reasons != NULL) *reasons = local_reasons; return (*reasons == 0); } #pragma comment(linker, "/EXPORT:LaunchGoogleChrome=_LaunchGoogleChrome@0,PRIVATE") DLLEXPORT BOOL __stdcall LaunchGoogleChrome() { wchar_t launch_cmd[MAX_PATH]; size_t size = _countof(launch_cmd); if (!ReadValueFromRegistry(HKEY_LOCAL_MACHINE, kChromeRegClientStateKey, kChromeRegLastLaunchCmd, launch_cmd, &size)) { size = _countof(launch_cmd); if (!ReadValueFromRegistry(HKEY_LOCAL_MACHINE, kChromeRegClientStateKey, kChromeRegLaunchCmd, launch_cmd, &size)) { return false; } } HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); if (hr != S_OK) { if (hr == S_FALSE) ::CoUninitialize(); return false; } if (::CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IDENTIFY, NULL, EOAC_DYNAMIC_CLOAKING, NULL) != S_OK) { ::CoUninitialize(); return false; } bool impersonation_success = false; if (IsRunningElevated()) { wchar_t* curr_proc_sid; if (!GetUserIdForProcess(GetCurrentProcessId(), &curr_proc_sid)) { ::CoUninitialize(); return false; } DWORD pid = 0; ::GetWindowThreadProcessId(::GetShellWindow(), &pid); if (pid <= 0) { ::LocalFree(curr_proc_sid); ::CoUninitialize(); return false; } wchar_t* exp_proc_sid; if (GetUserIdForProcess(pid, &exp_proc_sid)) { if (_wcsicmp(curr_proc_sid, exp_proc_sid) == 0) { HANDLE process_handle = ::OpenProcess( PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION, TRUE, pid); if (process_handle != NULL) { HANDLE process_token; HANDLE user_token; if (::OpenProcessToken(process_handle, TOKEN_DUPLICATE | TOKEN_QUERY, &process_token) && ::DuplicateTokenEx(process_token, TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE, NULL, SecurityImpersonation, TokenPrimary, &user_token) && (::ImpersonateLoggedOnUser(user_token) != 0)) { impersonation_success = true; } ::CloseHandle(user_token); ::CloseHandle(process_token); ::CloseHandle(process_handle); } } ::LocalFree(exp_proc_sid); } ::LocalFree(curr_proc_sid); if (!impersonation_success) { ::CoUninitialize(); return false; } } bool ret = false; CComPtr<IProcessLauncher> ipl; if (!FAILED(ipl.CoCreateInstance(__uuidof(ProcessLauncherClass), NULL, CLSCTX_LOCAL_SERVER))) { if (!FAILED(ipl->LaunchCmdLine(launch_cmd))) ret = true; ipl.Release(); } if (impersonation_success) ::RevertToSelf(); ::CoUninitialize(); return ret; } <|endoftext|>
<commit_before>/* Copyright 2013 SINTEF ICT, Applied Mathematics. */ #include <opm/core/utility/parameters/ParameterGroup.hpp> #include <opm/core/linalg/LinearSolverFactory.hpp> #include <opm/core/utility/ErrorMacros.hpp> #include <opm/autodiff/AutoDiffBlock.hpp> #include <opm/autodiff/AutoDiffHelpers.hpp> #include <opm/core/grid.h> #include <opm/core/grid/GridManager.hpp> #include <algorithm> #include <iterator> #include <iostream> #include <cmath> #include "EquelleRuntimeCPU.hpp" struct UserParameters { // ============= Generated code starts here ================ // k : Scalar = UserSpecifiedScalarWithDefault(0.3) # Heat diffusion constant. double k; // dt : Scalar = UserSpecifiedScalarWithDefault(0.5) # Time step length. double dt; // u0 : Collection Of Scalar On AllCells() = UserSpecifiedCollectionOfScalar( AllCells() ) CollOfScalars u0; // dirichlet_boundary : Collection Of Face On BoundaryFaces() = UserSpecifiedCollectionOfFace( BoundaryFaces() ) CollOfFaces dirichlet_boundary; // dirichlet_val : Collection Of Scalar On dirichlet_boundary = UserSpecifiedCollectionOfScalar( dirichlet_boundary ) CollOfScalars dirichlet_val; // ============= Generated code ends here ================ UserParameters(const Opm::parameter::ParameterGroup& param, const EquelleRuntimeCPU& er) { // ============= Generated code starts here ================ // k : Scalar = UserSpecifiedScalarWithDefault(0.3) # Heat diffusion constant. k = param.getDefault("k", 0.3); // dt : Scalar = UserSpecifiedScalarWithDefault(0.5) # Time step length. dt = param.getDefault("dt", 0.5); // u0 : Collection Of Scalar On AllCells() = UserSpecifiedCollectionOfScalar( AllCells() ) u0 = er.getUserSpecifiedCollectionOfScalar(param, "u0", er.allCells().size()); // dirichlet_boundary : Collection Of Face On BoundaryFaces() = UserSpecifiedCollectionOfFace( BoundaryFaces() ) dirichlet_boundary = er.getUserSpecifiedCollectionOfFaceSubsetOf(param, "dirichlet_boundary", er.boundaryFaces()); // dirichlet_val : Collection Of Scalar On dirichlet_boundary = UserSpecifiedCollectionOfScalar( dirichlet_boundary ) dirichlet_val = er.getUserSpecifiedCollectionOfScalar(param, "dirichlet_val", dirichlet_boundary.size()); // ============= Generated code ends here ================ } }; class ResidualComputer : public ResidualComputerInterface { public: /// Initialization. ResidualComputer(const EquelleRuntimeCPU& er, const UserParameters& up) : er_(er), up_(up) { } // Compute the (possibly nonlinear) residual with derivative information. // This is the most important generated function. CollOfScalarsAD compute(const CollOfScalarsAD& u) const { // ============= Generated code starts here ================ // -------------------------------------------------------------------------------- // vol = Volume( AllCells() ) # Deduced type: Scalar On AllCells() // -------------------------------------------------------------------------------- const CollOfScalars vol = er_.norm( er_.allCells() ); // -------------------------------------------------------------------------------- // interior_faces = InteriorFaces() # Deduced type: Collection Of Face Subset Of AllFaces() // first = FirstCell(interior_faces) # Deduced type: Collection Of Cell On interior_faces // # Equivalent to: Collection Of Cell On InteriorFaces() // second = SecondCell(interior_faces) # Deduced type: Same as for 'first'. // -------------------------------------------------------------------------------- const CollOfFaces interior_faces = er_.interiorFaces(); const CollOfCells first = er_.firstCell( interior_faces ); const CollOfCells second = er_.secondCell( interior_faces ); // -------------------------------------------------------------------------------- // trans : Collection Of Scalar On interior_faces = k * Area(interior_faces) / Length(Centroid(first) - Centroid(second)) // # Deduced (and declared) type: Collection Of Scalar On interior_faces // -------------------------------------------------------------------------------- // trans is a CollOfScalars and not a CollOfScalarsAD since it does not depend on u. const CollOfScalars trans = up_.k * er_.norm(interior_faces) / er_.norm(er_.centroid(first) - er_.centroid(second)); // -------------------------------------------------------------------------------- // fluxes : Collection Of Scalar On interior_faces = - trans * Gradient(u) // # Deduced (and declared) type: Scalar On interior_faces // -------------------------------------------------------------------------------- // fluxes is a CollOfScalarsAD since it depends on u. const CollOfScalarsAD fluxes = trans * (er_.negGradient(u)); // -------------------------------------------------------------------------------- // residual : Collection Of Scalar On AllCells() = u - u0 + (dt / vol) * Divergence(fluxes) // # Deduced (and declared) type: Scalar On AllCells() // -------------------------------------------------------------------------------- // residual is a CollOfScalarsAD since it depends on u and fluxes. const CollOfScalarsAD residual = u - up_.u0 + (up_.dt / vol) * (er_.divergence(fluxes)); // ============= Hopefully generated code ends here ================ return residual; } private: const EquelleRuntimeCPU& er_; const UserParameters& up_; }; int main(int argc, char** argv) { // Get user parameters. Opm::parameter::ParameterGroup param(argc, argv, false); // Create the Equelle runtime. EquelleRuntimeCPU er(param); // ============= Generated code starts here ================ // -------------------------------------------------------------------------------- // k : Scalar = UserSpecifiedScalarWithDefault(0.3) # Heat diffusion constant. // dt : Scalar = UserSpecifiedScalarWithDefault(0.5) # Time step length. // u0 : Collection Of Scalar On AllCells() = UserSpecifiedCollectionOfScalar( AllCells() ) // dirichlet_boundary : Collection Of Face On BoundaryFaces() = UserSpecifiedCollectionOfFace( BoundaryFaces() ) // dirichlet_val : Collection Of Scalar On dirichlet_boundary = UserSpecifiedCollectionOfScalar( dirichlet_boundary ) // -------------------------------------------------------------------------------- const auto k = param.getDefault("k", 0.3); const auto dt = param.getDefault("dt", 0.5); const auto u0 = er.getUserSpecifiedCollectionOfScalar(param, "u0", er.allCells().size()); const auto dirichlet_boundary = er.getUserSpecifiedCollectionOfFaceSubsetOf(param, "dirichlet_boundary", er.boundaryFaces()); const auto dirichlet_val = er.getUserSpecifiedCollectionOfScalar(param, "dirichlet_val", dirichlet_boundary.size()); // -------------------------------------------------------------------------------- // # Compute interior transmissibilities. // vol = |AllCells()| # Deduced type: Collection Of Scalar On AllCells() // interior_faces = InteriorFaces() # Deduced type: Collection Of Face // first = FirstCell(interior_faces) # Deduced type: Collection Of Cell On interior_faces // # Equivalent to: Collection Of Cell On InteriorFaces() // second = SecondCell(interior_faces) # Deduced type: Same as for 'first'. // itrans : Collection Of Scalar On interior_faces = k * |interior_faces| / |Centroid(first) - Centroid(second)| // -------------------------------------------------------------------------------- const auto vol = er.norm(er.allCells()); const auto interior_faces = er.interiorFaces(); const auto first = er.firstCell(interior_faces); const auto second = er.secondCell(interior_faces); const auto itrans = k * er.norm(interior_faces) / er.norm(er.centroid(first) - er.centroid(second)); // -------------------------------------------------------------------------------- // # Compute boundary transmissibilities. // bf = BoundaryFaces() // bf_cells = IsEmpty(FirstCell(bf)) ? SecondCell(bf) : FirstCell(bf) // bf_sign = IsEmpty(FirstCell(bf))) ? (-1 On bf_cells) : (1 On bf_cells) // btrans = k * |bf| / |Centroid(bf) - Centroid(bf_cells)| // -------------------------------------------------------------------------------- const auto bf = er.boundaryFaces(); const auto bf_cells = er.trinaryIf(er.isEmpty(er.firstCell(bf)), er.secondCell(bf), er.firstCell(bf)); const auto bf_sign = er.trinaryIf(er.isEmpty(er.firstCell(bf)), er.operatorOn(double(-1), bf_cells), er.operatorOn(double(1), bf_cells)); const auto btrans = k * er.norm(bf) / er.norm(er.centroid(bf) - er.centroid(bf_cells)); // -------------------------------------------------------------------------------- // # Compute quantities needed for boundary conditions. // dir_sign = bf_sign On dirichlet_boundary // -------------------------------------------------------------------------------- const auto dir_sign = er.operatorOn(bf_sign, bf, dirichlet_boundary); // -------------------------------------------------------------------------------- // # Compute flux for interior faces. // computeInteriorFlux : Function(u : Collection Of Scalar On AllCells()) -> Collection Of Scalar On InteriorFaces() // computeInteriorFlux(u) = { // return -itrans * Gradient(u) // } // -------------------------------------------------------------------------------- auto computeInteriorFlux = [&](const CollOfScalars u) -> CollOfScalars { return -itrans * er.gradient(u); }; auto computeInteriorFluxAD = [&](const CollOfScalarsAD u) -> CollOfScalarsAD { return -itrans * er.gradient(u); }; // -------------------------------------------------------------------------------- // # Compute flux for boundary faces. // computeBoundaryFlux : Function(u : Collection Of Scalar On AllCells()) -> Collection Of Scalar On BoundaryFaces() // computeBoundaryFlux(u) = { // # Compute flux at Dirichlet boundaries. // dir_fluxes = btrans * dir_sign * (u_dirbdycells - dirichlet_val) // # Extending with zero away from Dirichlet boundaries (i.e. assuming no-flow elsewhere). // return dir_fluxes On BoundaryFaces() // } // -------------------------------------------------------------------------------- auto computeBoundaryFlux = [&](const CollOfScalars u) -> CollOfScalars { const auto u_dirbdycells = er.operatorOn(u, er.allCells(), er.operatorOn(bf_cells, bf, dirichlet_boundary)); const CollOfScalars dir_fluxes = dir_sign * (u_dirbdycells - dirichlet_val); return er.operatorOn(dir_fluxes, dirichlet_boundary, er.boundaryFaces()); }; auto computeBoundaryFluxAD = [&](const CollOfScalarsAD u) -> CollOfScalarsAD { const auto u_dirbdycells = er.operatorOn(u, er.allCells(), er.operatorOn(bf_cells, bf, dirichlet_boundary)); const CollOfScalarsAD dir_fluxes = btrans * dir_sign * (u_dirbdycells - dirichlet_val); return er.operatorOn(dir_fluxes, dirichlet_boundary, er.boundaryFaces()); }; // -------------------------------------------------------------------------------- // # Compute the residual for the heat equation. // computeResidual : Function(u : Collection Of Scalar On AllCells()) -> Collection Of Scalar On AllCells() // computeResidual(u) = { // ifluxes = computeInteriorFlux(u) // bfluxes = computeBoundaryFlux(u) // # Extend both ifluxes and bfluxes to AllFaces() and add to get all fluxes. // fluxes = (ifluxes On AllFaces()) + (bfluxes On AllFaces()) // # Deduced type: Collection Of Scalar On AllCells() // residual = u - u0 + (dt / vol) * Divergence(fluxes) // return residual // } // -------------------------------------------------------------------------------- auto computeResidual = [&](const CollOfScalars u) -> CollOfScalars { const auto ifluxes = computeInteriorFlux(u); const auto bfluxes = computeBoundaryFlux(u); const auto fluxes = er.operatorOn(ifluxes, er.interiorFaces(), er.allFaces()) + er.operatorOn(bfluxes, er.boundaryFaces(), er.allFaces()); const auto residual = u - u0 + (dt / vol) * er.divergence(fluxes); return residual; }; auto computeResidualAD = [&](const CollOfScalarsAD u) -> CollOfScalarsAD { const auto ifluxes = computeInteriorFluxAD(u); const auto bfluxes = computeBoundaryFluxAD(u); const auto fluxes = er.operatorOn(ifluxes, er.interiorFaces(), er.allFaces()) + er.operatorOn(bfluxes, er.boundaryFaces(), er.allFaces()); const auto residual = u - u0 + (dt / vol) * er.divergence(fluxes); return residual; }; // -------------------------------------------------------------------------------- // explicitu = u0 + computeResidual(u0) // u = NewtonSolve(computeResidual, u0) // -------------------------------------------------------------------------------- const auto explicitu = u0 + computeResidual(u0); const auto u = er.newtonSolve(computeResidualAD, u0); // -------------------------------------------------------------------------------- // Output(u) // Output(fluxes) // -------------------------------------------------------------------------------- // Not handling output of fluxes currently, since they are not in scope here. er.output("Explicit u is equal to: ", explicitu); er.output("Implicit u is equal to: ", u); // ============= Generated code ends here ================ return 0; } <commit_msg>Removed unused code in example.<commit_after>/* Copyright 2013 SINTEF ICT, Applied Mathematics. */ #include <opm/core/utility/parameters/ParameterGroup.hpp> #include <opm/core/linalg/LinearSolverFactory.hpp> #include <opm/core/utility/ErrorMacros.hpp> #include <opm/autodiff/AutoDiffBlock.hpp> #include <opm/autodiff/AutoDiffHelpers.hpp> #include <opm/core/grid.h> #include <opm/core/grid/GridManager.hpp> #include <algorithm> #include <iterator> #include <iostream> #include <cmath> #include "EquelleRuntimeCPU.hpp" int main(int argc, char** argv) { // Get user parameters. Opm::parameter::ParameterGroup param(argc, argv, false); // Create the Equelle runtime. EquelleRuntimeCPU er(param); // ============= Generated code starts here ================ // -------------------------------------------------------------------------------- // k : Scalar = UserSpecifiedScalarWithDefault(0.3) # Heat diffusion constant. // dt : Scalar = UserSpecifiedScalarWithDefault(0.5) # Time step length. // u0 : Collection Of Scalar On AllCells() = UserSpecifiedCollectionOfScalar( AllCells() ) // dirichlet_boundary : Collection Of Face On BoundaryFaces() = UserSpecifiedCollectionOfFace( BoundaryFaces() ) // dirichlet_val : Collection Of Scalar On dirichlet_boundary = UserSpecifiedCollectionOfScalar( dirichlet_boundary ) // -------------------------------------------------------------------------------- const auto k = param.getDefault("k", 0.3); const auto dt = param.getDefault("dt", 0.5); const auto u0 = er.getUserSpecifiedCollectionOfScalar(param, "u0", er.allCells().size()); const auto dirichlet_boundary = er.getUserSpecifiedCollectionOfFaceSubsetOf(param, "dirichlet_boundary", er.boundaryFaces()); const auto dirichlet_val = er.getUserSpecifiedCollectionOfScalar(param, "dirichlet_val", dirichlet_boundary.size()); // -------------------------------------------------------------------------------- // # Compute interior transmissibilities. // vol = |AllCells()| # Deduced type: Collection Of Scalar On AllCells() // interior_faces = InteriorFaces() # Deduced type: Collection Of Face // first = FirstCell(interior_faces) # Deduced type: Collection Of Cell On interior_faces // # Equivalent to: Collection Of Cell On InteriorFaces() // second = SecondCell(interior_faces) # Deduced type: Same as for 'first'. // itrans : Collection Of Scalar On interior_faces = k * |interior_faces| / |Centroid(first) - Centroid(second)| // -------------------------------------------------------------------------------- const auto vol = er.norm(er.allCells()); const auto interior_faces = er.interiorFaces(); const auto first = er.firstCell(interior_faces); const auto second = er.secondCell(interior_faces); const auto itrans = k * er.norm(interior_faces) / er.norm(er.centroid(first) - er.centroid(second)); // -------------------------------------------------------------------------------- // # Compute boundary transmissibilities. // bf = BoundaryFaces() // bf_cells = IsEmpty(FirstCell(bf)) ? SecondCell(bf) : FirstCell(bf) // bf_sign = IsEmpty(FirstCell(bf))) ? (-1 On bf_cells) : (1 On bf_cells) // btrans = k * |bf| / |Centroid(bf) - Centroid(bf_cells)| // -------------------------------------------------------------------------------- const auto bf = er.boundaryFaces(); const auto bf_cells = er.trinaryIf(er.isEmpty(er.firstCell(bf)), er.secondCell(bf), er.firstCell(bf)); const auto bf_sign = er.trinaryIf(er.isEmpty(er.firstCell(bf)), er.operatorOn(double(-1), bf_cells), er.operatorOn(double(1), bf_cells)); const auto btrans = k * er.norm(bf) / er.norm(er.centroid(bf) - er.centroid(bf_cells)); // -------------------------------------------------------------------------------- // # Compute quantities needed for boundary conditions. // dir_sign = bf_sign On dirichlet_boundary // -------------------------------------------------------------------------------- const auto dir_sign = er.operatorOn(bf_sign, bf, dirichlet_boundary); // -------------------------------------------------------------------------------- // # Compute flux for interior faces. // computeInteriorFlux : Function(u : Collection Of Scalar On AllCells()) -> Collection Of Scalar On InteriorFaces() // computeInteriorFlux(u) = { // return -itrans * Gradient(u) // } // -------------------------------------------------------------------------------- auto computeInteriorFlux = [&](const CollOfScalars u) -> CollOfScalars { return -itrans * er.gradient(u); }; auto computeInteriorFluxAD = [&](const CollOfScalarsAD u) -> CollOfScalarsAD { return -itrans * er.gradient(u); }; // -------------------------------------------------------------------------------- // # Compute flux for boundary faces. // computeBoundaryFlux : Function(u : Collection Of Scalar On AllCells()) -> Collection Of Scalar On BoundaryFaces() // computeBoundaryFlux(u) = { // # Compute flux at Dirichlet boundaries. // dir_fluxes = btrans * dir_sign * (u_dirbdycells - dirichlet_val) // # Extending with zero away from Dirichlet boundaries (i.e. assuming no-flow elsewhere). // return dir_fluxes On BoundaryFaces() // } // -------------------------------------------------------------------------------- auto computeBoundaryFlux = [&](const CollOfScalars u) -> CollOfScalars { const auto u_dirbdycells = er.operatorOn(u, er.allCells(), er.operatorOn(bf_cells, bf, dirichlet_boundary)); const CollOfScalars dir_fluxes = dir_sign * (u_dirbdycells - dirichlet_val); return er.operatorOn(dir_fluxes, dirichlet_boundary, er.boundaryFaces()); }; auto computeBoundaryFluxAD = [&](const CollOfScalarsAD u) -> CollOfScalarsAD { const auto u_dirbdycells = er.operatorOn(u, er.allCells(), er.operatorOn(bf_cells, bf, dirichlet_boundary)); const CollOfScalarsAD dir_fluxes = btrans * dir_sign * (u_dirbdycells - dirichlet_val); return er.operatorOn(dir_fluxes, dirichlet_boundary, er.boundaryFaces()); }; // -------------------------------------------------------------------------------- // # Compute the residual for the heat equation. // computeResidual : Function(u : Collection Of Scalar On AllCells()) -> Collection Of Scalar On AllCells() // computeResidual(u) = { // ifluxes = computeInteriorFlux(u) // bfluxes = computeBoundaryFlux(u) // # Extend both ifluxes and bfluxes to AllFaces() and add to get all fluxes. // fluxes = (ifluxes On AllFaces()) + (bfluxes On AllFaces()) // # Deduced type: Collection Of Scalar On AllCells() // residual = u - u0 + (dt / vol) * Divergence(fluxes) // return residual // } // -------------------------------------------------------------------------------- auto computeResidual = [&](const CollOfScalars u) -> CollOfScalars { const auto ifluxes = computeInteriorFlux(u); const auto bfluxes = computeBoundaryFlux(u); const auto fluxes = er.operatorOn(ifluxes, er.interiorFaces(), er.allFaces()) + er.operatorOn(bfluxes, er.boundaryFaces(), er.allFaces()); const auto residual = u - u0 + (dt / vol) * er.divergence(fluxes); return residual; }; auto computeResidualAD = [&](const CollOfScalarsAD u) -> CollOfScalarsAD { const auto ifluxes = computeInteriorFluxAD(u); const auto bfluxes = computeBoundaryFluxAD(u); const auto fluxes = er.operatorOn(ifluxes, er.interiorFaces(), er.allFaces()) + er.operatorOn(bfluxes, er.boundaryFaces(), er.allFaces()); const auto residual = u - u0 + (dt / vol) * er.divergence(fluxes); return residual; }; // -------------------------------------------------------------------------------- // explicitu = u0 + computeResidual(u0) // u = NewtonSolve(computeResidual, u0) // -------------------------------------------------------------------------------- const auto explicitu = u0 + computeResidual(u0); const auto u = er.newtonSolve(computeResidualAD, u0); // -------------------------------------------------------------------------------- // Output(u) // Output(fluxes) // -------------------------------------------------------------------------------- // Not handling output of fluxes currently, since they are not in scope here. er.output("Explicit u is equal to: ", explicitu); er.output("Implicit u is equal to: ", u); // ============= Generated code ends here ================ return 0; } <|endoftext|>
<commit_before>#include "LIBSPU.H" #include "LIBETC.H" #include <stdio.h> #include "EMULATOR.H" #include "LIBAPI.H" #include <string.h> #define SPU_CENTERNOTE (49152) short _spu_voice_centerNote[24] = { SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE }; SpuCommonAttr dword_424;//Might be wrong struct, need to check int _spu_isCalled = 0; int _spu_FiDMA = 0;///@TODO decl as extern find initial value int _spu_EVdma = 0; int _spu_rev_flag = 0; int _spu_rev_reserve_wa = 0; int _spu_rev_offsetaddr = 0; int _spu_rev_startaddr = 0; int _spu_AllocBlockNum = 0; int _spu_AllocLastNum = 0; int _spu_memList = 0; int _spu_trans_mode = 0; int _spu_transMode = 0; int _spu_keystat = 0; int _spu_RQmask = 0; int _spu_RQvoice = 0; int _spu_env = 0; short* _spu_RXX = (short*)0x1F801C00; int _spu_mem_mode_plus = 3; unsigned long SpuWrite(unsigned char * addr, unsigned long size) { //eprintf("SPU WRITE size=%d\n", size); //memcpy(spu_buf, addr, size); //spu_b_size = size; UNIMPLEMENTED(); return 0; } long SpuSetTransferMode(long mode) { long mode_fix = mode == 0 ? 0 : 1; //trans_mode = mode; //transMode = mode_fix; return mode_fix; } unsigned long SpuSetTransferStartAddr(unsigned long addr) { UNIMPLEMENTED(); return 0; } long SpuIsTransferCompleted(long flag) { UNIMPLEMENTED(); return 0; } void _SpuDataCallback(int a0) { UNIMPLEMENTED(); } void SpuStart()//(F) { long event = 0; if (_spu_isCalled == 0) { _spu_isCalled = 1; EnterCriticalSection(); _SpuDataCallback(_spu_FiDMA); event = OpenEvent(HwSPU, EvSpCOMP, EvMdNOINTR, NULL); _spu_EVdma = event; EnableEvent(event); ExitCriticalSection(); } //loc_348 } void _spu_init(int a0) { UNIMPLEMENTED(); } void _spu_FsetRXX(int a0, int a1, int a2)//(F) { if (a2 == 0) { _spu_RXX[a0] = a1; } else { _spu_RXX[a0] = a1 >> _spu_mem_mode_plus; } } void _SpuInit(int a0) { ResetCallback(); _spu_init(a0); //s0 = a0 if (a0 == 0) { for (int i = 0; i < sizeof(_spu_voice_centerNote) / sizeof(short); i++) { _spu_voice_centerNote[i] = SPU_CENTERNOTE; } } //loc_240 SpuStart(); _spu_rev_flag = 0; _spu_rev_reserve_wa = 0; dword_424.mask = 0; dword_424.mvol.left = 0; dword_424.mvol.right = 0; dword_424.mvolmode.left = 0; dword_424.mvolmode.right = 0; dword_424.mvolx.left = 0; dword_424.mvolx.right = 0; _spu_rev_offsetaddr = _spu_rev_startaddr; _spu_FsetRXX(209, _spu_rev_startaddr, 0); _spu_AllocBlockNum = 0; _spu_AllocLastNum = 0; _spu_memList = 0; _spu_trans_mode = 0; _spu_transMode = 0; _spu_keystat = 0; _spu_RQmask = 0; _spu_RQvoice = 0; _spu_env = 0; } void SpuInit(void) { _SpuInit(0); } long SpuSetReverb(long on_off) { UNIMPLEMENTED(); return 0; } unsigned long SpuSetReverbVoice(long on_off, unsigned long voice_bit) { UNIMPLEMENTED(); return 0; } void SpuSetCommonAttr(SpuCommonAttr * attr) { UNIMPLEMENTED(); } long SpuInitMalloc(long num, char * top) { if (num > 0) { ///memList = top; //AllocLastNum = 0; //AllocBlockNum = num; //*((int*)memList) = mem_mode_plus = 0x4000 | 0x1010; //*((int*)memList + 1) = 0x4000; } return num; } long SpuMalloc(long size) { return 0/*(long)(uintptr_t)malloc(size)*/; } long SpuMallocWithStartAddr(unsigned long addr, long size) { UNIMPLEMENTED(); return 0; } void SpuFree(unsigned long addr) { /*free((void*)(uintptr_t)addr)*/; } void SpuSetCommonMasterVolume(short mvol_left, short mvol_right)// (F) { //MasterVolume.VolumeLeft.Raw = mvol_left; //MasterVolume.VolumeRight.Raw = mvol_right; } long SpuSetReverbModeType(long mode) { UNIMPLEMENTED(); return 0; } void SpuSetReverbModeDepth(short depth_left, short depth_right) { UNIMPLEMENTED(); } <commit_msg>[Emu]: Implement SpuInitMalloc.<commit_after>#include "LIBSPU.H" #include "LIBETC.H" #include <stdio.h> #include "EMULATOR.H" #include "LIBAPI.H" #include <string.h> #define SPU_CENTERNOTE (49152) short _spu_voice_centerNote[24] = { SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE }; SpuCommonAttr dword_424;//Might be wrong struct, need to check int _spu_isCalled = 0; int _spu_FiDMA = 0;///@TODO decl as extern find initial value int _spu_EVdma = 0; int _spu_rev_flag = 0; int _spu_rev_reserve_wa = 0; int _spu_rev_offsetaddr = 0; int _spu_rev_startaddr = 0; int _spu_AllocBlockNum = 0; int _spu_AllocLastNum = 0; int _spu_memList = 0; int _spu_trans_mode = 0; int _spu_transMode = 0; int _spu_keystat = 0; int _spu_RQmask = 0; int _spu_RQvoice = 0; int _spu_env = 0; short* _spu_RXX = (short*)0x1F801C00; int _spu_mem_mode_plus = 3; unsigned long SpuWrite(unsigned char * addr, unsigned long size) { //eprintf("SPU WRITE size=%d\n", size); //memcpy(spu_buf, addr, size); //spu_b_size = size; UNIMPLEMENTED(); return 0; } long SpuSetTransferMode(long mode) { long mode_fix = mode == 0 ? 0 : 1; //trans_mode = mode; //transMode = mode_fix; return mode_fix; } unsigned long SpuSetTransferStartAddr(unsigned long addr) { UNIMPLEMENTED(); return 0; } long SpuIsTransferCompleted(long flag) { UNIMPLEMENTED(); return 0; } void _SpuDataCallback(int a0) { UNIMPLEMENTED(); } void SpuStart()//(F) { long event = 0; if (_spu_isCalled == 0) { _spu_isCalled = 1; EnterCriticalSection(); _SpuDataCallback(_spu_FiDMA); event = OpenEvent(HwSPU, EvSpCOMP, EvMdNOINTR, NULL); _spu_EVdma = event; EnableEvent(event); ExitCriticalSection(); } //loc_348 } void _spu_init(int a0) { UNIMPLEMENTED(); } void _spu_FsetRXX(int a0, int a1, int a2)//(F) { if (a2 == 0) { _spu_RXX[a0] = a1; } else { _spu_RXX[a0] = a1 >> _spu_mem_mode_plus; } } void _SpuInit(int a0) { ResetCallback(); _spu_init(a0); if (a0 == 0) { for (int i = 0; i < sizeof(_spu_voice_centerNote) / sizeof(short); i++) { _spu_voice_centerNote[i] = SPU_CENTERNOTE; } } //loc_240 SpuStart(); _spu_rev_flag = 0; _spu_rev_reserve_wa = 0; dword_424.mask = 0; dword_424.mvol.left = 0; dword_424.mvol.right = 0; dword_424.mvolmode.left = 0; dword_424.mvolmode.right = 0; dword_424.mvolx.left = 0; dword_424.mvolx.right = 0; _spu_rev_offsetaddr = _spu_rev_startaddr; _spu_FsetRXX(209, _spu_rev_startaddr, 0); _spu_AllocBlockNum = 0; _spu_AllocLastNum = 0; _spu_memList = 0; _spu_trans_mode = 0; _spu_transMode = 0; _spu_keystat = 0; _spu_RQmask = 0; _spu_RQvoice = 0; _spu_env = 0; } void SpuInit(void) { _SpuInit(0); } long SpuSetReverb(long on_off) { UNIMPLEMENTED(); return 0; } unsigned long SpuSetReverbVoice(long on_off, unsigned long voice_bit) { UNIMPLEMENTED(); return 0; } void SpuSetCommonAttr(SpuCommonAttr* attr) { UNIMPLEMENTED(); } long SpuInitMalloc(long num, char* top)//(F) { if (num > 0) { //loc_214 ((int*)top)[0] = 0x40001010; _spu_memList = (uintptr_t)top; _spu_AllocLastNum = 0; _spu_AllocBlockNum = num; ((int*)top)[1] = (0x10000000 << _spu_mem_mode_plus) - 0x1010; } return num; } long SpuMalloc(long size) { return 0/*(long)(uintptr_t)malloc(size)*/; } long SpuMallocWithStartAddr(unsigned long addr, long size) { UNIMPLEMENTED(); return 0; } void SpuFree(unsigned long addr) { /*free((void*)(uintptr_t)addr)*/; } void SpuSetCommonMasterVolume(short mvol_left, short mvol_right)// (F) { //MasterVolume.VolumeLeft.Raw = mvol_left; //MasterVolume.VolumeRight.Raw = mvol_right; } long SpuSetReverbModeType(long mode) { UNIMPLEMENTED(); return 0; } void SpuSetReverbModeDepth(short depth_left, short depth_right) { UNIMPLEMENTED(); } <|endoftext|>
<commit_before>/* * EepromManager.cpp * * Created: 23/04/2013 03:15:44 * Author: mat */ #include "brewpi_avr.h" #include <stddef.h> #include "EepromManager.h" #include "TempControl.h" #include "EepromFormat.h" #include "PiLink.h" EepromManager eepromManager; EepromAccess eepromAccess; #define pointerOffset(x) offsetof(EepromFormat, x) EepromManager::EepromManager() { eepromSizeCheck(); } bool EepromManager::hasSettings() { uint8_t version = eepromAccess.readByte(pointerOffset(version)); return (version==EEPROM_FORMAT_VERSION); } void EepromManager::resetEeprom() { tempControl.loadDefaultConstants(); tempControl.loadDefaultSettings(); tempControl.cs.mode = MODE_BEER_CONSTANT; for (uint8_t c=0; c<EepromFormat::MAX_CHAMBERS; c++) { eptr_t pv = pointerOffset(chambers)+(c*sizeof(ChamberBlock)) ; tempControl.storeConstants(pv+offsetof(ChamberBlock, chamberSettings.cc)); pv += offsetof(ChamberBlock, beer)+offsetof(BeerBlock, cs); for (uint8_t b=0; b<ChamberBlock::MAX_BEERS; b++) { tempControl.storeSettings(pv); pv += sizeof(BeerBlock); // advance to next beer } } uint8_t count = saveDefaultDevices(); for (uint16_t offset=pointerOffset(devices)+(sizeof(DeviceConfig)*count); offset<EepromFormat::MAX_EEPROM_SIZE; offset++) eepromAccess.writeByte(offset, 0); eepromAccess.writeByte(0, EEPROM_FORMAT_VERSION); } uint8_t EepromManager::saveDefaultDevices() { #if 1 DeviceConfig config; clear((uint8_t*)&config, sizeof(config)); #if BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_A // single-chamber single beer config from original shield config.chamber = 1; // all devices in chamber 1 config.hw.invert = 1; // all pin devices inverted config.deviceHardware = DEVICE_HARDWARE_PIN; config.deviceFunction = DEVICE_CHAMBER_DOOR; config.hw.pinNr = doorPin; eepromManager.storeDevice(config, 0); config.deviceFunction = DEVICE_CHAMBER_HEAT; config.hw.pinNr = heatingPin; eepromManager.storeDevice(config, 1); config.deviceFunction = DEVICE_CHAMBER_COOL; config.hw.pinNr = heatingPin; eepromManager.storeDevice(config, 2); config.deviceHardware = DEVICE_HARDWARE_ONEWIRE_TEMP; config.hw.pinNr = fridgeSensorPin; config.deviceFunction = DEVICE_CHAMBER_TEMP; eepromManager.storeDevice(config, 3); config.beer = 1; config.hw.pinNr = beerSensorPin; config.deviceFunction = DEVICE_BEER_TEMP; eepromManager.storeDevice(config, 3); return 5; #endif #if BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_C // the only component that's not dynamic is the door return 0; #endif #else return 0; #endif } #define arraySize(x) (sizeof(x)/sizeof(x[0])) bool EepromManager::applySettings() { if (!hasSettings()) return false; // start from a clean state deviceManager.setupUnconfiguredDevices(); DEBUG_MSG(PSTR("Applying settings")); // load the one chamber and one beer for now eptr_t pv = pointerOffset(chambers); tempControl.loadConstants(pv+offsetof(ChamberBlock, chamberSettings.cc)); tempControl.loadSettings(pv+offsetof(ChamberBlock, beer[0].cs)); DEBUG_MSG(PSTR("Applied settings")); DeviceConfig deviceConfig; for (uint8_t index = 0; fetchDevice(deviceConfig, index); index++) { if (deviceConfig.deviceFunction!=0xFF && deviceManager.isDeviceValid(deviceConfig, deviceConfig, index)) deviceManager.installDevice(deviceConfig); else { clear((uint8_t*)&deviceConfig, sizeof(deviceConfig)); eepromManager.storeDevice(deviceConfig, index); } } return true; } void EepromManager::storeTempConstantsAndSettings() { uint8_t chamber = 0; eptr_t pv = pointerOffset(chambers); pv += sizeof(ChamberBlock)*chamber; tempControl.storeConstants(pv+offsetof(ChamberBlock, chamberSettings.cc)); storeTempSettings(); } void EepromManager::storeTempSettings() { uint8_t chamber = 0; eptr_t pv = pointerOffset(chambers); pv += sizeof(ChamberBlock)*chamber; // for now assume just one beer. tempControl.storeSettings(pv+offsetof(ChamberBlock, beer[0].cs)); } bool EepromManager::fetchDevice(DeviceConfig& config, uint8_t deviceIndex) { bool ok = (hasSettings() && deviceIndex<EepromFormat::MAX_DEVICES); if (ok) eepromAccess.readBlock(&config, pointerOffset(devices)+sizeof(DeviceConfig)*deviceIndex, sizeof(DeviceConfig)); return ok; } bool EepromManager::storeDevice(const DeviceConfig& config, uint8_t deviceIndex) { bool ok = (hasSettings() && deviceIndex<EepromFormat::MAX_DEVICES); if (ok) eepromAccess.writeBlock(pointerOffset(devices)+sizeof(DeviceConfig)*deviceIndex, &config, sizeof(DeviceConfig)); return ok; } void fill(int8_t* p, uint8_t size) { while (size-->0) *p++ = -1; } void clear(uint8_t* p, uint8_t size) { while (size-->0) *p++ = 0; } <commit_msg>fix for revA fridge sensor not being initialized<commit_after>/* * EepromManager.cpp * * Created: 23/04/2013 03:15:44 * Author: mat */ #include "brewpi_avr.h" #include <stddef.h> #include "EepromManager.h" #include "TempControl.h" #include "EepromFormat.h" #include "PiLink.h" EepromManager eepromManager; EepromAccess eepromAccess; #define pointerOffset(x) offsetof(EepromFormat, x) EepromManager::EepromManager() { eepromSizeCheck(); } bool EepromManager::hasSettings() { uint8_t version = eepromAccess.readByte(pointerOffset(version)); return (version==EEPROM_FORMAT_VERSION); } void EepromManager::resetEeprom() { tempControl.loadDefaultConstants(); tempControl.loadDefaultSettings(); tempControl.cs.mode = MODE_BEER_CONSTANT; for (uint8_t c=0; c<EepromFormat::MAX_CHAMBERS; c++) { eptr_t pv = pointerOffset(chambers)+(c*sizeof(ChamberBlock)) ; tempControl.storeConstants(pv+offsetof(ChamberBlock, chamberSettings.cc)); pv += offsetof(ChamberBlock, beer)+offsetof(BeerBlock, cs); for (uint8_t b=0; b<ChamberBlock::MAX_BEERS; b++) { tempControl.storeSettings(pv); pv += sizeof(BeerBlock); // advance to next beer } } uint8_t count = saveDefaultDevices(); for (uint16_t offset=pointerOffset(devices)+(sizeof(DeviceConfig)*count); offset<EepromFormat::MAX_EEPROM_SIZE; offset++) eepromAccess.writeByte(offset, 0); eepromAccess.writeByte(0, EEPROM_FORMAT_VERSION); } uint8_t EepromManager::saveDefaultDevices() { #if 1 DeviceConfig config; clear((uint8_t*)&config, sizeof(config)); #if BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_A // single-chamber single beer config from original shield config.chamber = 1; // all devices in chamber 1 config.hw.invert = 1; // all pin devices inverted config.deviceHardware = DEVICE_HARDWARE_PIN; config.deviceFunction = DEVICE_CHAMBER_DOOR; config.hw.pinNr = doorPin; eepromManager.storeDevice(config, 0); config.deviceFunction = DEVICE_CHAMBER_HEAT; config.hw.pinNr = heatingPin; eepromManager.storeDevice(config, 1); config.deviceFunction = DEVICE_CHAMBER_COOL; config.hw.pinNr = heatingPin; eepromManager.storeDevice(config, 2); config.deviceHardware = DEVICE_HARDWARE_ONEWIRE_TEMP; config.hw.pinNr = fridgeSensorPin; config.deviceFunction = DEVICE_CHAMBER_TEMP; eepromManager.storeDevice(config, 3); config.beer = 1; config.hw.pinNr = beerSensorPin; config.deviceFunction = DEVICE_BEER_TEMP; eepromManager.storeDevice(config, 4); return 5; #endif #if BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_C // the only component that's not dynamic is the door return 0; #endif #else return 0; #endif } #define arraySize(x) (sizeof(x)/sizeof(x[0])) bool EepromManager::applySettings() { if (!hasSettings()) return false; // start from a clean state deviceManager.setupUnconfiguredDevices(); DEBUG_MSG(PSTR("Applying settings")); // load the one chamber and one beer for now eptr_t pv = pointerOffset(chambers); tempControl.loadConstants(pv+offsetof(ChamberBlock, chamberSettings.cc)); tempControl.loadSettings(pv+offsetof(ChamberBlock, beer[0].cs)); DEBUG_MSG(PSTR("Applied settings")); DeviceConfig deviceConfig; for (uint8_t index = 0; fetchDevice(deviceConfig, index); index++) { if (deviceConfig.deviceFunction!=0xFF && deviceManager.isDeviceValid(deviceConfig, deviceConfig, index)) deviceManager.installDevice(deviceConfig); else { clear((uint8_t*)&deviceConfig, sizeof(deviceConfig)); eepromManager.storeDevice(deviceConfig, index); } } return true; } void EepromManager::storeTempConstantsAndSettings() { uint8_t chamber = 0; eptr_t pv = pointerOffset(chambers); pv += sizeof(ChamberBlock)*chamber; tempControl.storeConstants(pv+offsetof(ChamberBlock, chamberSettings.cc)); storeTempSettings(); } void EepromManager::storeTempSettings() { uint8_t chamber = 0; eptr_t pv = pointerOffset(chambers); pv += sizeof(ChamberBlock)*chamber; // for now assume just one beer. tempControl.storeSettings(pv+offsetof(ChamberBlock, beer[0].cs)); } bool EepromManager::fetchDevice(DeviceConfig& config, uint8_t deviceIndex) { bool ok = (hasSettings() && deviceIndex<EepromFormat::MAX_DEVICES); if (ok) eepromAccess.readBlock(&config, pointerOffset(devices)+sizeof(DeviceConfig)*deviceIndex, sizeof(DeviceConfig)); return ok; } bool EepromManager::storeDevice(const DeviceConfig& config, uint8_t deviceIndex) { bool ok = (hasSettings() && deviceIndex<EepromFormat::MAX_DEVICES); if (ok) eepromAccess.writeBlock(pointerOffset(devices)+sizeof(DeviceConfig)*deviceIndex, &config, sizeof(DeviceConfig)); return ok; } void fill(int8_t* p, uint8_t size) { while (size-->0) *p++ = -1; } void clear(uint8_t* p, uint8_t size) { while (size-->0) *p++ = 0; } <|endoftext|>
<commit_before>#include "Plane.h" #include <GL/glew.h> #include <MathGeoLib/include/Math/float3.h> #include <MathGeoLib/include/Math/MathFunc.h> #include "Globals.h" ::Plane::Plane(int planeSize) : Primitive(), PlaneSize(planeSize) {} ::Plane::Plane(const float3& position, Quat& rotation, int planeSize) : Primitive(position, rotation), PlaneSize(planeSize) {} ::Plane::Plane(const float3& position, Quat& rotation, const float3& color, int planeSize) : Primitive(position, rotation, color), PlaneSize(planeSize) {} ::Plane::~Plane() {} void ::Plane::Draw() { glDepthMask(GL_FALSE); glPushMatrix(); glTranslatef(Position.x, Position.y, Position.z); float3 axis = Rotation.Axis(); glRotatef(RadToDeg(Rotation.Angle()), axis.x, axis.y, axis.z); glColor4f(0.f, 0.f, 0.f, 0.f); glBegin(GL_QUADS); glVertex3f(-PlaneSize, -0.001, -PlaneSize); glVertex3f(-PlaneSize, -0.001, PlaneSize); glVertex3f(PlaneSize, -0.001, PlaneSize); glVertex3f(PlaneSize, -0.001, -PlaneSize); glEnd(); glBegin(GL_LINES); for (int i = -PlaneSize; i <= PlaneSize; i++) { if (i == -PlaneSize) { glColor3f(.6, .3, .3); } else { glColor3f(.25, .25, .25); }; glVertex3f(i, 0, -PlaneSize); glVertex3f(i, 0, PlaneSize); if (i == -PlaneSize) { glColor3f(.3, .3, .6); } else { glColor3f(.25, .25, .25); }; glVertex3f(-PlaneSize, 0, i); glVertex3f(PlaneSize, 0, i); }; glEnd(); glPopMatrix(); } <commit_msg>Enable depthMask at draw end and Update Color with variable<commit_after>#include "Plane.h" #include <GL/glew.h> #include <MathGeoLib/include/Math/float3.h> #include <MathGeoLib/include/Math/MathFunc.h> #include "Globals.h" ::Plane::Plane(int planeSize) : Primitive(), PlaneSize(planeSize) {} ::Plane::Plane(const float3& position, Quat& rotation, int planeSize) : Primitive(position, rotation), PlaneSize(planeSize) {} ::Plane::Plane(const float3& position, Quat& rotation, const float3& color, int planeSize) : Primitive(position, rotation, color), PlaneSize(planeSize) {} ::Plane::~Plane() {} void ::Plane::Draw() { glDepthMask(GL_FALSE); glPushMatrix(); glTranslatef(Position.x, Position.y, Position.z); float3 axis = Rotation.Axis(); glRotatef(RadToDeg(Rotation.Angle()), axis.x, axis.y, axis.z); glColor4f(Color.x, Color.y, Color.z, 0.f); glBegin(GL_QUADS); glVertex3f(-PlaneSize, -0.001, -PlaneSize); glVertex3f(-PlaneSize, -0.001, PlaneSize); glVertex3f(PlaneSize, -0.001, PlaneSize); glVertex3f(PlaneSize, -0.001, -PlaneSize); glEnd(); glBegin(GL_LINES); for (int i = -PlaneSize; i <= PlaneSize; i++) { if (i == -PlaneSize) { glColor3f(.6, .3, .3); } else { glColor3f(.25, .25, .25); }; glVertex3f(i, 0, -PlaneSize); glVertex3f(i, 0, PlaneSize); if (i == -PlaneSize) { glColor3f(.3, .3, .6); } else { glColor3f(.25, .25, .25); }; glVertex3f(-PlaneSize, 0, i); glVertex3f(PlaneSize, 0, i); }; glEnd(); glPopMatrix(); glDepthMask(GL_TRUE); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkFastNumericConversion.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkFastNumericConversion - Enables fast conversion of floating point to fixed point // .SECTION Description // vtkFastNumericConversion uses a portable (assuming IEEE format) method for converting single and // double precision floating point values to a fixed point representation. This allows fast // integer flooring on platforms, such as Intel X86, in which CPU floating point flooring // algorithms are very slow. It is based on the techniques described in Chris Hecker's article, // "Let's Get to the (Floating) Point", in Game Developer Magazine, Feb/Mar 1996, and the // techniques described in Michael Herf's website, http://www.stereopsis.com/FPU.html. // The Hecker article can be found at http://www.d6.com/users/checker/pdfs/gdmfp.pdf. // Unfortunately, each of these techniques is incomplete, and doesn't floor properly, // in a way that depends on how many bits are reserved for fixed point fractional use, due to // failing to properly account for the default round-towards-even rounding mode of the X86. Thus, // my implementation incorporates some rounding correction that undoes the rounding that the // FPU performs during denormalization of the floating point value. Note that // the rounding affect I'm talking about here is not the effect on the fistp instruction, // but rather the effect that occurs during the denormalization of a value that occurs when // adding it to a much larger value. The bits must be shifted to the right, and when a "1" bit // falls off the edge, the rounding mode determines what happens next, in order // to avoid completely "losing" the 1-bit. Furthermore, my implementation works on Linux, where the // default precision mode is 64-bit extended precision. // This class is contributed to VTK by Chris Volpe of Applied Research Associates, Inc. // (My employer requires me to say that -- CRV) #include "vtkFastNumericConversion.h" #include "vtkObjectFactory.h" #include "vtkTimerLog.h" vtkCxxRevisionMacro(vtkFastNumericConversion, "1.3"); vtkStandardNewMacro(vtkFastNumericConversion); int vtkFastNumericConversion::TestQuickFloor(double val) { return vtkFastNumericConversion::QuickFloor(val); } int vtkFastNumericConversion::TestSafeFloor(double val) { return vtkFastNumericConversion::SafeFloor(val); } int vtkFastNumericConversion::TestRound(double val) { return vtkFastNumericConversion::Round(val); } int vtkFastNumericConversion::TestConvertFixedPointIntPart(double val) { int frac; return this->ConvertFixedPoint(val, frac); } int vtkFastNumericConversion::TestConvertFixedPointFracPart(double val) { int frac; this->ConvertFixedPoint(val, frac); return frac; } void vtkFastNumericConversion::InternalRebuild() { int i; this->fixRound=.5; for (i=this->internalReservedFracBits; i; i--) { this->fixRound *= .5; } this->fracMask = (1<<this->internalReservedFracBits)-1; this->fpDenormalizer = (static_cast<unsigned long>(1) << (52-30-this->internalReservedFracBits)) * this->two30() * this->BorrowBit(); this->epTempDenormalizer = this->fpDenormalizer * (static_cast<unsigned long>(1) << (63-52)); } void vtkFastNumericConversion::PrintSelf(ostream &os, vtkIndent indent) { os << indent << "ReservedFracBits: " << this->internalReservedFracBits << endl; os << indent << "Bare time from last PerformanceTest() call: " << this->bare_time << endl; os << indent << "Cast time from last PerformanceTest() call: " << this->cast_time << endl; os << indent << "ConvertFixedPoint time from last PerformanceTest() call: " << this->convert_time << endl; os << indent << "QuickFloor time from last PerformanceTest() call: " << this->quickfloor_time << endl; os << indent << "SafeFloor time from last PerformanceTest() call: " << this->safefloor_time << endl; os << indent << "Round time from last PerformanceTest() call: " << this->round_time << endl; if (this->bare_time != 0.0) { // Don't do this if we haven't run the tests yet. os << indent << "Speedup ratio from cast to quickfloor is: " << (this->cast_time-this->bare_time)/(this->quickfloor_time-this->bare_time) << endl; os << indent << "Speedup ratio from cast to safefloor is: " << (this->cast_time-this->bare_time)/(this->safefloor_time-this->bare_time) << endl; os << indent << "Speedup ratio from cast to round is: " << (this->cast_time-this->bare_time)/(this->round_time-this->bare_time) << endl; } } void vtkFastNumericConversion::PerformanceTests(void) { const int inner_count = 10000; const int outer_count = 10000; double *dval = new double[inner_count]; int *ival = new int[inner_count]; int *frac = new int[inner_count]; int i,o; vtkTimerLog *timer = vtkTimerLog::New(); for (i=0; i<inner_count; i++) { dval[i] = i; ival[i] = 0; } timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { // Pure bit copy ival[i] = *reinterpret_cast<int *>(&dval[i]); } } timer->StopTimer(); this->bare_time = timer->GetElapsedTime(); // Compute cast time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = static_cast<int>(dval[i]); } } timer->StopTimer(); this->cast_time = timer->GetElapsedTime(); // Compute convert time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = this->ConvertFixedPoint(dval[i], frac[i]); } } timer->StopTimer(); this->convert_time = timer->GetElapsedTime(); // Compute quickfloor time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = vtkFastNumericConversion::QuickFloor(dval[i]); } } timer->StopTimer(); this->quickfloor_time = timer->GetElapsedTime(); // Compute safefloor time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = vtkFastNumericConversion::SafeFloor(dval[i]); } } timer->StopTimer(); this->safefloor_time = timer->GetElapsedTime(); // Compute round time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = vtkFastNumericConversion::Round(dval[i]); } } timer->StopTimer(); this->round_time = timer->GetElapsedTime(); delete [] dval; delete [] ival; delete [] frac; timer->Delete(); } <commit_msg>BUG: Fix divide by zero errors that occur when the test timing is just right...<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkFastNumericConversion.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkFastNumericConversion - Enables fast conversion of floating point to fixed point // .SECTION Description // vtkFastNumericConversion uses a portable (assuming IEEE format) method for converting single and // double precision floating point values to a fixed point representation. This allows fast // integer flooring on platforms, such as Intel X86, in which CPU floating point flooring // algorithms are very slow. It is based on the techniques described in Chris Hecker's article, // "Let's Get to the (Floating) Point", in Game Developer Magazine, Feb/Mar 1996, and the // techniques described in Michael Herf's website, http://www.stereopsis.com/FPU.html. // The Hecker article can be found at http://www.d6.com/users/checker/pdfs/gdmfp.pdf. // Unfortunately, each of these techniques is incomplete, and doesn't floor properly, // in a way that depends on how many bits are reserved for fixed point fractional use, due to // failing to properly account for the default round-towards-even rounding mode of the X86. Thus, // my implementation incorporates some rounding correction that undoes the rounding that the // FPU performs during denormalization of the floating point value. Note that // the rounding affect I'm talking about here is not the effect on the fistp instruction, // but rather the effect that occurs during the denormalization of a value that occurs when // adding it to a much larger value. The bits must be shifted to the right, and when a "1" bit // falls off the edge, the rounding mode determines what happens next, in order // to avoid completely "losing" the 1-bit. Furthermore, my implementation works on Linux, where the // default precision mode is 64-bit extended precision. // This class is contributed to VTK by Chris Volpe of Applied Research Associates, Inc. // (My employer requires me to say that -- CRV) #include "vtkFastNumericConversion.h" #include "vtkObjectFactory.h" #include "vtkTimerLog.h" vtkCxxRevisionMacro(vtkFastNumericConversion, "1.4"); vtkStandardNewMacro(vtkFastNumericConversion); int vtkFastNumericConversion::TestQuickFloor(double val) { return vtkFastNumericConversion::QuickFloor(val); } int vtkFastNumericConversion::TestSafeFloor(double val) { return vtkFastNumericConversion::SafeFloor(val); } int vtkFastNumericConversion::TestRound(double val) { return vtkFastNumericConversion::Round(val); } int vtkFastNumericConversion::TestConvertFixedPointIntPart(double val) { int frac; return this->ConvertFixedPoint(val, frac); } int vtkFastNumericConversion::TestConvertFixedPointFracPart(double val) { int frac; this->ConvertFixedPoint(val, frac); return frac; } void vtkFastNumericConversion::InternalRebuild() { int i; this->fixRound=.5; for (i=this->internalReservedFracBits; i; i--) { this->fixRound *= .5; } this->fracMask = (1<<this->internalReservedFracBits)-1; this->fpDenormalizer = (static_cast<unsigned long>(1) << (52-30-this->internalReservedFracBits)) * this->two30() * this->BorrowBit(); this->epTempDenormalizer = this->fpDenormalizer * (static_cast<unsigned long>(1) << (63-52)); } void vtkFastNumericConversion::PrintSelf(ostream &os, vtkIndent indent) { os << indent << "ReservedFracBits: " << this->internalReservedFracBits << endl; os << indent << "Bare time from last PerformanceTest() call: " << this->bare_time << endl; os << indent << "Cast time from last PerformanceTest() call: " << this->cast_time << endl; os << indent << "ConvertFixedPoint time from last PerformanceTest() call: " << this->convert_time << endl; os << indent << "QuickFloor time from last PerformanceTest() call: " << this->quickfloor_time << endl; os << indent << "SafeFloor time from last PerformanceTest() call: " << this->safefloor_time << endl; os << indent << "Round time from last PerformanceTest() call: " << this->round_time << endl; if (this->bare_time != 0.0) { // Don't do this if we haven't run the tests yet. if (this->quickfloor_time-this->bare_time > 0.0) { os << indent << "Speedup ratio from cast to quickfloor is: " << (this->cast_time-this->bare_time)/(this->quickfloor_time-this->bare_time) << endl; } else { os << indent << "quickfloor_time <= bare_time, cannot calculate speedup ratio" << endl; } if (this->safefloor_time-this->bare_time > 0.0) { os << indent << "Speedup ratio from cast to safefloor is: " << (this->cast_time-this->bare_time)/(this->safefloor_time-this->bare_time) << endl; } else { os << indent << "safefloor_time <= bare_time, cannot calculate speedup ratio" << endl; } if (this->round_time-this->bare_time > 0.0) { os << indent << "Speedup ratio from cast to round is: " << (this->cast_time-this->bare_time)/(this->round_time-this->bare_time) << endl; } else { os << indent << "round_time <= bare_time, cannot calculate speedup ratio" << endl; } } } void vtkFastNumericConversion::PerformanceTests(void) { const int inner_count = 10000; const int outer_count = 10000; double *dval = new double[inner_count]; int *ival = new int[inner_count]; int *frac = new int[inner_count]; int i,o; vtkTimerLog *timer = vtkTimerLog::New(); for (i=0; i<inner_count; i++) { dval[i] = i; ival[i] = 0; } timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { // Pure bit copy ival[i] = *reinterpret_cast<int *>(&dval[i]); } } timer->StopTimer(); this->bare_time = timer->GetElapsedTime(); // Compute cast time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = static_cast<int>(dval[i]); } } timer->StopTimer(); this->cast_time = timer->GetElapsedTime(); // Compute convert time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = this->ConvertFixedPoint(dval[i], frac[i]); } } timer->StopTimer(); this->convert_time = timer->GetElapsedTime(); // Compute quickfloor time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = vtkFastNumericConversion::QuickFloor(dval[i]); } } timer->StopTimer(); this->quickfloor_time = timer->GetElapsedTime(); // Compute safefloor time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = vtkFastNumericConversion::SafeFloor(dval[i]); } } timer->StopTimer(); this->safefloor_time = timer->GetElapsedTime(); // Compute round time timer->StartTimer(); for (o=0; o<outer_count; o++) { for (i=0; i<inner_count; i++) { ival[i] = vtkFastNumericConversion::Round(dval[i]); } } timer->StopTimer(); this->round_time = timer->GetElapsedTime(); delete [] dval; delete [] ival; delete [] frac; timer->Delete(); } <|endoftext|>
<commit_before><commit_msg>Update comment<commit_after><|endoftext|>
<commit_before>//===-------------- ARCAnalysis.cpp - SIL ARC Analysis --------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-arc-analysis" #include "swift/SILAnalysis/ARCAnalysis.h" #include "swift/Basic/Fallthrough.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SILAnalysis/AliasAnalysis.h" #include "swift/SILAnalysis/ValueTracking.h" #include "swift/SILPasses/Utils/Local.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Debug.h" using namespace swift; using namespace swift::arc; //===----------------------------------------------------------------------===// // Decrement Analysis //===----------------------------------------------------------------------===// static bool isKnownToNotDecrementRefCount(FunctionRefInst *FRI) { return llvm::StringSwitch<bool>(FRI->getReferencedFunction()->getName()) .Case("swift_keepAlive", true) .Case("_swift_isUniquelyReferenced", true) .Default(false); } static bool canApplyDecrementRefCount(ApplyInst *AI, SILValue Ptr, AliasAnalysis *AA) { // Ignore any thick functions for now due to us not handling the ref-counted // nature of its context. if (auto FTy = AI->getCallee().getType().getAs<SILFunctionType>()) if (FTy->getExtInfo().hasContext()) return true; // If we have a builtin that is side effect free, we can commute the // ApplyInst and the retain. if (auto *BI = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee())) if (isSideEffectFree(BI)) return false; // swift_keepAlive can not retain values. Remove this when we get rid of that. if (auto *FRI = dyn_cast<FunctionRefInst>(AI->getCallee())) if (isKnownToNotDecrementRefCount(FRI)) return false; // Ok, this apply *MAY* decrement ref counts. Now our strategy is to attempt // to use properties of the pointer, the function's arguments, and the // function itself to prove that the pointer can not have its ref count be // effected by function. // TODO: Put in function property check section here when we get access to // such information. // First make sure that the underlying object of ptr is a local object which // does not escape. This prevents the apply from indirectly via the global // affecting the reference count of the pointer. if (!isNonEscapingLocalObject(getUnderlyingObject(Ptr))) return true; // Now that we know that the function can not affect the pointer indirectly, // make sure that the apply can not affect the pointer directly via the // applies arguments by proving that the pointer can not alias any of the // functions arguments. for (auto Op : AI->getArgumentsWithoutIndirectResult()) { for (int i = 0, e = Ptr->getNumTypes(); i < e; i++) { if (!AA->isNoAlias(Op, SILValue(Ptr.getDef(), i))) return true; } } // Success! The apply inst can not affect the reference count of ptr! return false; } /// Is the may have side effects user by the definition of its value kind unable /// to decrement ref counts. static bool canDecrementRefCountsByValueKind(SILInstruction *User) { assert(User->getMemoryBehavior() == SILInstruction::MemoryBehavior::MayHaveSideEffects && "Invalid argument. Function is only applicable to isntructions with " "side effects."); switch (User->getKind()) { case ValueKind::DeallocStackInst: case ValueKind::StrongRetainInst: case ValueKind::StrongRetainAutoreleasedInst: case ValueKind::StrongRetainUnownedInst: case ValueKind::UnownedRetainInst: case ValueKind::PartialApplyInst: case ValueKind::FixLifetimeInst: case ValueKind::CopyBlockInst: case ValueKind::RetainValueInst: case ValueKind::CondFailInst: return false; case ValueKind::CopyAddrInst: { auto *CA = cast<CopyAddrInst>(User); if (CA->isInitializationOfDest() == IsInitialization_t::IsInitialization) return false; } SWIFT_FALLTHROUGH; default: return true; } } bool swift::arc::canDecrementRefCount(SILInstruction *User, SILValue Ptr, AliasAnalysis *AA) { // If we have an instruction that does not have *pure* side effects, it can // not affect ref counts. // // This distinguishes in between a "write" side effect and ref count side // effects. if (User->getMemoryBehavior() != SILInstruction::MemoryBehavior::MayHaveSideEffects) return false; // Ok, we know that this instruction's generic behavior is // "MayHaveSideEffects". That is a criterion (it has effects not represented // by use-def chains) that is broader than ours (does it effect a particular // pointers ref counts). Thus begin by attempting to prove that the type of // instruction that the user is by definition can not decrement ref counts. if (!canDecrementRefCountsByValueKind(User)) return false; // Ok, this instruction may have ref counts. If it is an apply, attempt to // prove that the callee is unable to affect Ptr. if (auto *AI = dyn_cast<ApplyInst>(User)) return canApplyDecrementRefCount(AI, Ptr, AA); // We can not conservatively prove that this instruction can not decrement the // ref count of Ptr. So assume that it does. return true; } //===----------------------------------------------------------------------===// // Use Analysis //===----------------------------------------------------------------------===// /// Returns true if a builtin apply can not use reference counted values. /// /// The main case that this handles here are builtins that via read none imply /// that they can not read globals and at the same time do not take any /// non-trivial types via the arguments. The reason why we care about taking /// non-trivial types as arguments is that we want to be careful in the face of /// intrinsics that may be equivalent to bitcast and inttoptr operations. static bool canApplyOfBuiltinUseNonTrivialValues(ApplyInst *AI, BuiltinFunctionRefInst *BFRI) { SILModule &Mod = AI->getModule(); auto &II = BFRI->getIntrinsicInfo(); if (II.ID != llvm::Intrinsic::not_intrinsic) { if (II.hasAttribute(llvm::Attribute::ReadNone)) { for (auto &Op : AI->getArgumentOperands()) { if (!Op.get().getType().isTrivial(Mod)) { return false; } } } return true; } auto &BI = BFRI->getBuiltinInfo(); if (BI.isReadNone()) { for (auto &Op : AI->getArgumentOperands()) { if (!Op.get().getType().isTrivial(Mod)) { return false; } } } return true; } /// Returns true if Inst is a function that we know never uses ref count values. static bool canInstUseRefCountValues(SILInstruction *Inst) { switch (Inst->getKind()) { // These instructions do not use other values. case ValueKind::FunctionRefInst: case ValueKind::BuiltinFunctionRefInst: case ValueKind::IntegerLiteralInst: case ValueKind::FloatLiteralInst: case ValueKind::StringLiteralInst: case ValueKind::AllocStackInst: case ValueKind::AllocRefInst: case ValueKind::AllocRefDynamicInst: case ValueKind::AllocBoxInst: case ValueKind::AllocArrayInst: case ValueKind::MetatypeInst: case ValueKind::WitnessMethodInst: return true; // DeallocStackInst do not use reference counted values, only local storage // handles. case ValueKind::DeallocStackInst: return true; // Debug values do not use referenced counted values in a manner we care // about. case ValueKind::DebugValueInst: case ValueKind::DebugValueAddrInst: return true; // Casts do not use pointers in a manner that we care about since we strip // them during our analysis. The reason for this is if the cast is not dead // then there must be some other use after the cast that we will protect if a // release is not in between the cast and the use. case ValueKind::UpcastInst: case ValueKind::AddressToPointerInst: case ValueKind::PointerToAddressInst: case ValueKind::UncheckedRefCastInst: case ValueKind::UncheckedAddrCastInst: case ValueKind::RefToRawPointerInst: case ValueKind::RawPointerToRefInst: case ValueKind::UnconditionalCheckedCastInst: return true; // Typed GEPs do not use pointers. The user of the typed GEP may but we will // catch that via the dataflow. case ValueKind::StructExtractInst: case ValueKind::TupleExtractInst: case ValueKind::StructElementAddrInst: case ValueKind::TupleElementAddrInst: case ValueKind::UncheckedTakeEnumDataAddrInst: case ValueKind::RefElementAddrInst: case ValueKind::UncheckedEnumDataInst: case ValueKind::IndexAddrInst: case ValueKind::IndexRawPointerInst: return true; // Aggregate formation by themselves do not create new uses since it is their // users that would create the appropriate uses. case ValueKind::EnumInst: case ValueKind::StructInst: case ValueKind::TupleInst: return true; // Only uses non reference counted values. case ValueKind::CondFailInst: return true; case ValueKind::ApplyInst: { auto *AI = cast<ApplyInst>(Inst); // Certain builtin function refs we know can never use non-trivial values. if (auto *BFRI = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee())) return canApplyOfBuiltinUseNonTrivialValues(AI, BFRI); return false; } default: return false; } } bool swift::arc::canUseValue(SILInstruction *User, SILValue Ptr, AliasAnalysis *AA) { // If Inst is an instruction that we know can never use values with reference // semantics, return true. if (canInstUseRefCountValues(User)) return false; // If the user is a load or a store and we can prove that it does not access // the object then return true. // Notice that we need to check all of the values of the object. if (isa<StoreInst>(User)) { for (int i = 0, e = Ptr->getNumTypes(); i < e; i++) { if (AA->mayWriteToMemory(User, SILValue(Ptr.getDef(), i))) return true; } return false; } if (isa<LoadInst>(User) ) { for (int i = 0, e = Ptr->getNumTypes(); i < e; i++) { if (AA->mayReadFromMemory(User, SILValue(Ptr.getDef(), i))) return true; } return false; } // TODO: If we add in alias analysis support here for apply inst, we will need // to check that the pointer does not escape. // Otherwise, assume that Inst can use Target. return true; } //===----------------------------------------------------------------------===// // Utility Methods for determining use, decrement of values in a contiguous // instruction range in one BB. //===----------------------------------------------------------------------===// /// Return true if \p Op has arc uses in the instruction range [Start, End). We /// assume that Start and End are both in the same basic block. bool swift::arc:: valueHasARCUsesInInstructionRange(SILValue Op, SILBasicBlock::iterator Start, SILBasicBlock::iterator End, AliasAnalysis *AA) { assert(Start->getParent() == End->getParent() && "Start and End should be in the same basic block"); // If Start == End, then we have an empty range, return false. if (Start == End) return false; // Otherwise, until Start != End. while (Start != End) { // Check if Start can use Op in an ARC relevant way. If so, return true. if (canUseValue(&*Start, Op, AA)) return true; // Otherwise, increment our iterator. ++Start; } // If all such instructions can not use Op, return false. return false; } /// Return true if \p Op has instructions in the instruction range (Start, End] /// which may decrement it. We assume that Start and End are both in the same /// basic block. bool swift::arc:: valueHasARCDecrementsInInstructionRange(SILValue Op, SILBasicBlock::iterator Start, SILBasicBlock::iterator End, AliasAnalysis *AA) { assert(Start->getParent() == End->getParent() && "Start and End should be in the same basic block"); // If Start == End, then we have an empty range, return false. if (Start == End) return false; // Otherwise, until Start != End. while (Start != End) { // Check if Start can decrement Op's ref count. If so, return true. if (canDecrementRefCount(&*Start, Op, AA)) return true; // Otherwise, increment our iterator. ++Start; } // If all such instructions can not decrement Op, return false. return false; } <commit_msg>[arc-analysis] unchecked_ref_bit_cast can never use reference count values in a way we care about. Trivial bit casts do not either as long as we are not converting a ref count value to a trivial value.<commit_after>//===-------------- ARCAnalysis.cpp - SIL ARC Analysis --------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-arc-analysis" #include "swift/SILAnalysis/ARCAnalysis.h" #include "swift/Basic/Fallthrough.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SILAnalysis/AliasAnalysis.h" #include "swift/SILAnalysis/ValueTracking.h" #include "swift/SILPasses/Utils/Local.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Debug.h" using namespace swift; using namespace swift::arc; //===----------------------------------------------------------------------===// // Decrement Analysis //===----------------------------------------------------------------------===// static bool isKnownToNotDecrementRefCount(FunctionRefInst *FRI) { return llvm::StringSwitch<bool>(FRI->getReferencedFunction()->getName()) .Case("swift_keepAlive", true) .Case("_swift_isUniquelyReferenced", true) .Default(false); } static bool canApplyDecrementRefCount(ApplyInst *AI, SILValue Ptr, AliasAnalysis *AA) { // Ignore any thick functions for now due to us not handling the ref-counted // nature of its context. if (auto FTy = AI->getCallee().getType().getAs<SILFunctionType>()) if (FTy->getExtInfo().hasContext()) return true; // If we have a builtin that is side effect free, we can commute the // ApplyInst and the retain. if (auto *BI = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee())) if (isSideEffectFree(BI)) return false; // swift_keepAlive can not retain values. Remove this when we get rid of that. if (auto *FRI = dyn_cast<FunctionRefInst>(AI->getCallee())) if (isKnownToNotDecrementRefCount(FRI)) return false; // Ok, this apply *MAY* decrement ref counts. Now our strategy is to attempt // to use properties of the pointer, the function's arguments, and the // function itself to prove that the pointer can not have its ref count be // effected by function. // TODO: Put in function property check section here when we get access to // such information. // First make sure that the underlying object of ptr is a local object which // does not escape. This prevents the apply from indirectly via the global // affecting the reference count of the pointer. if (!isNonEscapingLocalObject(getUnderlyingObject(Ptr))) return true; // Now that we know that the function can not affect the pointer indirectly, // make sure that the apply can not affect the pointer directly via the // applies arguments by proving that the pointer can not alias any of the // functions arguments. for (auto Op : AI->getArgumentsWithoutIndirectResult()) { for (int i = 0, e = Ptr->getNumTypes(); i < e; i++) { if (!AA->isNoAlias(Op, SILValue(Ptr.getDef(), i))) return true; } } // Success! The apply inst can not affect the reference count of ptr! return false; } /// Is the may have side effects user by the definition of its value kind unable /// to decrement ref counts. static bool canDecrementRefCountsByValueKind(SILInstruction *User) { assert(User->getMemoryBehavior() == SILInstruction::MemoryBehavior::MayHaveSideEffects && "Invalid argument. Function is only applicable to isntructions with " "side effects."); switch (User->getKind()) { case ValueKind::DeallocStackInst: case ValueKind::StrongRetainInst: case ValueKind::StrongRetainAutoreleasedInst: case ValueKind::StrongRetainUnownedInst: case ValueKind::UnownedRetainInst: case ValueKind::PartialApplyInst: case ValueKind::FixLifetimeInst: case ValueKind::CopyBlockInst: case ValueKind::RetainValueInst: case ValueKind::CondFailInst: return false; case ValueKind::CopyAddrInst: { auto *CA = cast<CopyAddrInst>(User); if (CA->isInitializationOfDest() == IsInitialization_t::IsInitialization) return false; } SWIFT_FALLTHROUGH; default: return true; } } bool swift::arc::canDecrementRefCount(SILInstruction *User, SILValue Ptr, AliasAnalysis *AA) { // If we have an instruction that does not have *pure* side effects, it can // not affect ref counts. // // This distinguishes in between a "write" side effect and ref count side // effects. if (User->getMemoryBehavior() != SILInstruction::MemoryBehavior::MayHaveSideEffects) return false; // Ok, we know that this instruction's generic behavior is // "MayHaveSideEffects". That is a criterion (it has effects not represented // by use-def chains) that is broader than ours (does it effect a particular // pointers ref counts). Thus begin by attempting to prove that the type of // instruction that the user is by definition can not decrement ref counts. if (!canDecrementRefCountsByValueKind(User)) return false; // Ok, this instruction may have ref counts. If it is an apply, attempt to // prove that the callee is unable to affect Ptr. if (auto *AI = dyn_cast<ApplyInst>(User)) return canApplyDecrementRefCount(AI, Ptr, AA); // We can not conservatively prove that this instruction can not decrement the // ref count of Ptr. So assume that it does. return true; } //===----------------------------------------------------------------------===// // Use Analysis //===----------------------------------------------------------------------===// /// Returns true if a builtin apply can not use reference counted values. /// /// The main case that this handles here are builtins that via read none imply /// that they can not read globals and at the same time do not take any /// non-trivial types via the arguments. The reason why we care about taking /// non-trivial types as arguments is that we want to be careful in the face of /// intrinsics that may be equivalent to bitcast and inttoptr operations. static bool canApplyOfBuiltinUseNonTrivialValues(ApplyInst *AI, BuiltinFunctionRefInst *BFRI) { SILModule &Mod = AI->getModule(); auto &II = BFRI->getIntrinsicInfo(); if (II.ID != llvm::Intrinsic::not_intrinsic) { if (II.hasAttribute(llvm::Attribute::ReadNone)) { for (auto &Op : AI->getArgumentOperands()) { if (!Op.get().getType().isTrivial(Mod)) { return false; } } } return true; } auto &BI = BFRI->getBuiltinInfo(); if (BI.isReadNone()) { for (auto &Op : AI->getArgumentOperands()) { if (!Op.get().getType().isTrivial(Mod)) { return false; } } } return true; } /// Returns true if Inst is a function that we know never uses ref count values. static bool canInstUseRefCountValues(SILInstruction *Inst) { switch (Inst->getKind()) { // These instructions do not use other values. case ValueKind::FunctionRefInst: case ValueKind::BuiltinFunctionRefInst: case ValueKind::IntegerLiteralInst: case ValueKind::FloatLiteralInst: case ValueKind::StringLiteralInst: case ValueKind::AllocStackInst: case ValueKind::AllocRefInst: case ValueKind::AllocRefDynamicInst: case ValueKind::AllocBoxInst: case ValueKind::AllocArrayInst: case ValueKind::MetatypeInst: case ValueKind::WitnessMethodInst: return true; // DeallocStackInst do not use reference counted values, only local storage // handles. case ValueKind::DeallocStackInst: return true; // Debug values do not use referenced counted values in a manner we care // about. case ValueKind::DebugValueInst: case ValueKind::DebugValueAddrInst: return true; // Casts do not use pointers in a manner that we care about since we strip // them during our analysis. The reason for this is if the cast is not dead // then there must be some other use after the cast that we will protect if a // release is not in between the cast and the use. case ValueKind::UpcastInst: case ValueKind::AddressToPointerInst: case ValueKind::PointerToAddressInst: case ValueKind::UncheckedRefCastInst: case ValueKind::UncheckedAddrCastInst: case ValueKind::RefToRawPointerInst: case ValueKind::RawPointerToRefInst: case ValueKind::UnconditionalCheckedCastInst: case ValueKind::UncheckedRefBitCastInst: return true; // If we have a trivial bit cast between trivial types, it is not something // that can use ref count ops in a way we care about. We do need to be careful // with uses with ref count inputs. In such a case, we assume conservatively // that the bit cast could use it. // // The reason why this is different from the ref bitcast is b/c the use of a // ref bit cast is still a ref typed value implying that our ARC dataflow will // properly handle its users. A conversion of a reference count value to a // trivial value though could be used as a trivial value in ways that ARC // dataflow will not understand implying we need to treat it as a use to be // safe. case ValueKind::UncheckedTrivialBitCastInst: { SILValue Op = cast<UncheckedTrivialBitCastInst>(Inst)->getOperand(); return Op.getType().isTrivial(Inst->getModule()); } // Typed GEPs do not use pointers. The user of the typed GEP may but we will // catch that via the dataflow. case ValueKind::StructExtractInst: case ValueKind::TupleExtractInst: case ValueKind::StructElementAddrInst: case ValueKind::TupleElementAddrInst: case ValueKind::UncheckedTakeEnumDataAddrInst: case ValueKind::RefElementAddrInst: case ValueKind::UncheckedEnumDataInst: case ValueKind::IndexAddrInst: case ValueKind::IndexRawPointerInst: return true; // Aggregate formation by themselves do not create new uses since it is their // users that would create the appropriate uses. case ValueKind::EnumInst: case ValueKind::StructInst: case ValueKind::TupleInst: return true; // Only uses non reference counted values. case ValueKind::CondFailInst: return true; case ValueKind::ApplyInst: { auto *AI = cast<ApplyInst>(Inst); // Certain builtin function refs we know can never use non-trivial values. if (auto *BFRI = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee())) return canApplyOfBuiltinUseNonTrivialValues(AI, BFRI); return false; } default: return false; } } bool swift::arc::canUseValue(SILInstruction *User, SILValue Ptr, AliasAnalysis *AA) { // If Inst is an instruction that we know can never use values with reference // semantics, return true. if (canInstUseRefCountValues(User)) return false; // If the user is a load or a store and we can prove that it does not access // the object then return true. // Notice that we need to check all of the values of the object. if (isa<StoreInst>(User)) { for (int i = 0, e = Ptr->getNumTypes(); i < e; i++) { if (AA->mayWriteToMemory(User, SILValue(Ptr.getDef(), i))) return true; } return false; } if (isa<LoadInst>(User) ) { for (int i = 0, e = Ptr->getNumTypes(); i < e; i++) { if (AA->mayReadFromMemory(User, SILValue(Ptr.getDef(), i))) return true; } return false; } // TODO: If we add in alias analysis support here for apply inst, we will need // to check that the pointer does not escape. // Otherwise, assume that Inst can use Target. return true; } //===----------------------------------------------------------------------===// // Utility Methods for determining use, decrement of values in a contiguous // instruction range in one BB. //===----------------------------------------------------------------------===// /// Return true if \p Op has arc uses in the instruction range [Start, End). We /// assume that Start and End are both in the same basic block. bool swift::arc:: valueHasARCUsesInInstructionRange(SILValue Op, SILBasicBlock::iterator Start, SILBasicBlock::iterator End, AliasAnalysis *AA) { assert(Start->getParent() == End->getParent() && "Start and End should be in the same basic block"); // If Start == End, then we have an empty range, return false. if (Start == End) return false; // Otherwise, until Start != End. while (Start != End) { // Check if Start can use Op in an ARC relevant way. If so, return true. if (canUseValue(&*Start, Op, AA)) return true; // Otherwise, increment our iterator. ++Start; } // If all such instructions can not use Op, return false. return false; } /// Return true if \p Op has instructions in the instruction range (Start, End] /// which may decrement it. We assume that Start and End are both in the same /// basic block. bool swift::arc:: valueHasARCDecrementsInInstructionRange(SILValue Op, SILBasicBlock::iterator Start, SILBasicBlock::iterator End, AliasAnalysis *AA) { assert(Start->getParent() == End->getParent() && "Start and End should be in the same basic block"); // If Start == End, then we have an empty range, return false. if (Start == End) return false; // Otherwise, until Start != End. while (Start != End) { // Check if Start can decrement Op's ref count. If so, return true. if (canDecrementRefCount(&*Start, Op, AA)) return true; // Otherwise, increment our iterator. ++Start; } // If all such instructions can not decrement Op, return false. return false; } <|endoftext|>
<commit_before>//===- SILCodeMotion.cpp - Code Motion Optimizations ----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "codemotion" #include "swift/SILPasses/Passes.h" #include "swift/SIL/Dominance.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILType.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILVisitor.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SILPasses/Transforms.h" #include "swift/SILAnalysis/AliasAnalysis.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/ScopedHashTable.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/RecyclingAllocator.h" STATISTIC(NumSunk, "Number of instructions sunk"); STATISTIC(NumDeadStores, "Number of dead stores removed"); STATISTIC(NumDupLoads, "Number of dup loads removed"); using namespace swift; static const int SinkSearchWindow = 6; static bool isWriteMemBehavior(SILInstruction::MemoryBehavior B) { switch (B) { case SILInstruction::MemoryBehavior::MayWrite: case SILInstruction::MemoryBehavior::MayReadWrite: case SILInstruction::MemoryBehavior::MayHaveSideEffects: return true; case SILInstruction::MemoryBehavior::None: case SILInstruction::MemoryBehavior::MayRead: return false; } } namespace { /// An abstract representation of a SIL Projection that allows one to refer to /// either nominal fields or tuple indices. class Projection { SILType Type; VarDecl *Decl; unsigned Index; public: Projection(SILType T, VarDecl *D) : Type(T), Decl(D), Index(-1) { } Projection(SILType T, unsigned I) : Type(T), Decl(nullptr), Index(I) { } SILType getType() const { return Type; } VarDecl *getDecl() const { return Decl; } unsigned getIndex() const { return Index; } bool operator==(Projection &Other) const { if (Decl) return Decl == Other.getDecl(); else return !Other.getDecl() && Index == Other.getIndex(); } bool operator<(Projection Other) const { // If Proj1 is a decl... if (Decl) { // It should be sorted before Proj2 is Proj2 is not a decl. Otherwise // compare the pointers. if (auto OtherDecl = Other.getDecl()) return uintptr_t(Decl) < uintptr_t(OtherDecl); return true; } // If Proj1 is not a decl, then if Proj2 is a decl, Proj1 is not before // Proj2. If Proj2 is not a decl, compare the indices. return !Other.getDecl() && (Index < Other.Index); } }; } // end anonymous namespace. static bool isAddressProjection(SILValue V) { switch (V->getKind()) { case ValueKind::StructElementAddrInst: case ValueKind::TupleElementAddrInst: return true; default: return false; } } // Given an already emitted load PrevLd, see if we can static SILValue findExtractPathBetweenValues(LoadInst *PrevLI, LoadInst *LI) { SILValue PrevLIOp = PrevLI->getOperand(); SILValue LIOp = LI->getOperand(); // If they are equal, just return PrevLI. if (PrevLIOp == LIOp) return PrevLI; // Otherwise see if LI can be projection extracted from PrevLI. First see if // LI is a projection at all. llvm::SmallVector<Projection, 4> Projections; auto Iter = LIOp; while (isAddressProjection(Iter) && PrevLIOp != Iter) { if (auto *SEA = dyn_cast<StructElementAddrInst>(Iter.getDef())) Projections.push_back(Projection(Iter.getType(), SEA->getField())); else Projections.push_back( Projection(Iter.getType(), cast<TupleElementAddrInst>(*Iter).getFieldNo())); Iter = cast<SILInstruction>(*Iter).getOperand(0); } // We could not find an extract path in between the two values. if (Projections.empty() || PrevLIOp != Iter) return SILValue(); // Use the projection list we created to create the relevant extracts SILValue LastExtract = PrevLI; SILBuilder Builder(LI); while (!Projections.empty()) { auto P = Projections.pop_back_val(); if (auto *D = P.getDecl()) { LastExtract = Builder.createStructExtract(LI->getLoc(), LastExtract, D, P.getType().getObjectType()); cast<StructExtractInst>(*LastExtract).getStructDecl(); } else { LastExtract = Builder.createTupleExtract(LI->getLoc(), LastExtract, P.getIndex(), P.getType().getObjectType()); cast<TupleExtractInst>(*LastExtract).getTupleType(); } } // Return the last extract we created. return LastExtract; } static void invalidateAliasingLoads(SILInstruction *Inst, llvm::SmallPtrSetImpl<LoadInst *> &Loads, AliasAnalysis *AA) { llvm::SmallVector<LoadInst *, 4> InvalidatedLoadList; for (auto *LI : Loads) if (isWriteMemBehavior(AA->getMemoryBehavior(Inst, LI->getOperand()))) InvalidatedLoadList.push_back(LI); for (auto *LI : InvalidatedLoadList) { DEBUG(llvm::dbgs() << " Found an instruction that writes to memory " "such that a load is invalidated:" << *LI); Loads.erase(LI); } } /// \brief Promote stored values to loads, remove dead stores and merge /// duplicated loads. bool promoteMemoryOperationsInBlock(SILBasicBlock *BB, AliasAnalysis *AA) { bool Changed = false; StoreInst *PrevStore = 0; llvm::SmallPtrSet<LoadInst *, 8> Loads; auto II = BB->begin(), E = BB->end(); while (II != E) { SILInstruction *Inst = II++; DEBUG(llvm::dbgs() << "Visiting: " << *Inst); // This is a StoreInst. Let's see if we can remove the previous stores. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { // Invalidate any load that we can not prove does not read from the stores // destination. invalidateAliasingLoads(Inst, Loads, AA); // If we are storing to the previously stored address then delete the old // store. if (PrevStore && PrevStore->getDest() == SI->getDest()) { DEBUG(llvm::dbgs() << " Found a dead previous store... Removing...:" << *PrevStore); Changed = true; recursivelyDeleteTriviallyDeadInstructions(PrevStore, true); PrevStore = SI; NumDeadStores++; continue; } PrevStore = SI; continue; } if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { // If we are loading a value that we just saved then use the saved value. if (PrevStore && PrevStore->getDest() == LI->getOperand()) { DEBUG(llvm::dbgs() << " Forwarding store from: " << *PrevStore); SILValue(LI, 0).replaceAllUsesWith(PrevStore->getSrc()); recursivelyDeleteTriviallyDeadInstructions(LI, true); Changed = true; NumDupLoads++; continue; } // Search the previous loads and replace the current load with one of the // previous loads. for (auto PrevLI : Loads) { SILValue ForwardingExtract = findExtractPathBetweenValues(PrevLI, LI); if (!ForwardingExtract) continue; DEBUG(llvm::dbgs() << " Replacing with previous load: " << *ForwardingExtract); SILValue(LI, 0).replaceAllUsesWith(ForwardingExtract); recursivelyDeleteTriviallyDeadInstructions(LI, true); Changed = true; LI = 0; NumDupLoads++; break; } if (LI) Loads.insert(LI); continue; } // Retains write to memory but they don't affect loads and stores. if (isa<StrongRetainInst>(Inst)) { DEBUG(llvm::dbgs() << " Found strong retain, does not affect loads and" " stores.\n"); continue; } // Dealloc stack does not affect loads and stores. if (isa<DeallocStackInst>(Inst)) { DEBUG(llvm::dbgs() << "Found a dealloc stack. Does not affect loads and " "stores.\n"); continue; } if (auto *AI = dyn_cast<ApplyInst>(Inst)) if (auto *BI = dyn_cast<BuiltinFunctionRefInst>(&*AI->getCallee())) if (isReadNone(BI)) { DEBUG(llvm::dbgs() << " Found readnone builtin, does not affect " "loads and stores.\n"); continue; } // cond_fail does not read/write memory in a manner that we care about. if (isa<CondFailInst>(Inst)) { DEBUG(llvm::dbgs() << " Found a cond fail, does not affect " "loads and stores.\n"); continue; } // All other instructions that read from memory invalidate the store. if (Inst->mayReadFromMemory()) { DEBUG(llvm::dbgs() << " Found an instruction that reads from memory." " Invalidating store.\n"); PrevStore = 0; } // If we have an instruction that may write to memory and we can not prove // that it and its operands can not alias a load we have visited, invalidate // that load. if (Inst->mayWriteToMemory()) // Invalidate any load that we can not prove does not read from one of the // writing instructions operands. invalidateAliasingLoads(Inst, Loads, AA); } return Changed; } /// \brief Returns True if we can sink this instruction to another basic block. static bool canSinkInstruction(SILInstruction *Inst) { return Inst->use_empty() && !isa<TermInst>(Inst); } /// \brief Returns true if this instruction is a skip barrier, which means that /// we can't sink other instructions past it. static bool isSinkBarrier(SILInstruction *Inst) { // We know that some calls do not have side effects. if (const ApplyInst *AI = dyn_cast<ApplyInst>(Inst)) if (BuiltinFunctionRefInst *FR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef())) return !isSideEffectFree(FR); if (isa<TermInst>(Inst)) return false; if (Inst->mayHaveSideEffects()) return true; return false; } /// \brief Search for an instruction that is identical to \p Iden by scanning /// \p BB starting at the end of the block, stopping on sink barriers. SILInstruction *findIdenticalInBlock(SILBasicBlock *BB, SILInstruction *Iden) { int SkipBudget = SinkSearchWindow; SILBasicBlock::iterator InstToSink = BB->getTerminator(); while (SkipBudget) { // If we found a sinkable instruction that is identical to our goal // then return it. if (canSinkInstruction(InstToSink) && Iden->isIdenticalTo(InstToSink)) { DEBUG(llvm::dbgs() << "Found an identical instruction."); return InstToSink; } // If this instruction is a skip-barrier end the scan. if (isSinkBarrier(InstToSink)) return nullptr; // If this is the first instruction in the block then we are done. if (InstToSink == BB->begin()) return nullptr; SkipBudget--; InstToSink = std::prev(InstToSink); DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink); } return nullptr; } static bool sinkCodeFromPredecessors(SILBasicBlock *BB) { bool Changed = false; if (BB->pred_empty()) return Changed; // This block must be the only successor of all the predecessors. for (auto P : BB->getPreds()) if (P->getSingleSuccessor() != BB) return Changed; SILBasicBlock *FirstPred = *BB->pred_begin(); // The first Pred must have at least one non-terminator. if (FirstPred->getTerminator() == FirstPred->begin()) return Changed; DEBUG(llvm::dbgs() << " Sinking values from predecessors.\n"); unsigned SkipBudget = SinkSearchWindow; // Start scanning backwards from the terminator. SILBasicBlock::iterator InstToSink = FirstPred->getTerminator(); while (SkipBudget) { DEBUG(llvm::dbgs() << "Processing: " << *InstToSink); // Save the duplicated instructions in case we need to remove them. SmallVector<SILInstruction *, 4> Dups; if (canSinkInstruction(InstToSink)) { // For all preds: for (auto P : BB->getPreds()) { if (P == FirstPred) continue; // Search the duplicated instruction in the predecessor. if (SILInstruction *DupInst = findIdenticalInBlock(P, InstToSink)) { Dups.push_back(DupInst); } else { DEBUG(llvm::dbgs() << "Instruction mismatch.\n"); Dups.clear(); break; } } // If we found duplicated instructions, sink one of the copies and delete // the rest. if (Dups.size()) { DEBUG(llvm::dbgs() << "Moving: " << *InstToSink); InstToSink->moveBefore(BB->begin()); Changed = true; for (auto I : Dups) { I->replaceAllUsesWith(InstToSink); I->eraseFromParent(); NumSunk++; } // Restart the scan. InstToSink = FirstPred->getTerminator(); DEBUG(llvm::dbgs() << "Restarting scan. Next inst: " << *InstToSink); continue; } } // If this instruction was a barrier then we can't sink anything else. if (isSinkBarrier(InstToSink)) { DEBUG(llvm::dbgs() << "Aborting on barrier: " << *InstToSink); return Changed; } // This is the first instruction, we are done. if (InstToSink == FirstPred->begin()) { DEBUG(llvm::dbgs() << "Reached the first instruction."); return Changed; } SkipBudget--; InstToSink = std::prev(InstToSink); DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink); } return Changed; } class SILCodeMotion : public SILFunctionTransform { /// The entry point to the transformation. void run() { SILFunction &F = *getFunction(); DEBUG(llvm::dbgs() << "***** CodeMotion on function: " << F.getName() << " *****\n"); AliasAnalysis *AA = PM->getAnalysis<AliasAnalysis>(); bool Changed = false; // Remove dead stores and merge duplicate loads. for (auto &BB : F) Changed |= promoteMemoryOperationsInBlock(&BB, AA); // Sink duplicated code from predecessors. for (auto &BB : F) Changed |= sinkCodeFromPredecessors(&BB); if (Changed) invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } StringRef getName() override { return "SIL Code Motion"; } }; SILTransform *swift::createCodeMotion() { return new SILCodeMotion(); } <commit_msg>[sil-code-motion] Change debug assert into a proper assert.<commit_after>//===- SILCodeMotion.cpp - Code Motion Optimizations ----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "codemotion" #include "swift/SILPasses/Passes.h" #include "swift/SIL/Dominance.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILType.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILVisitor.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SILPasses/Transforms.h" #include "swift/SILAnalysis/AliasAnalysis.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/ScopedHashTable.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/RecyclingAllocator.h" STATISTIC(NumSunk, "Number of instructions sunk"); STATISTIC(NumDeadStores, "Number of dead stores removed"); STATISTIC(NumDupLoads, "Number of dup loads removed"); using namespace swift; static const int SinkSearchWindow = 6; static bool isWriteMemBehavior(SILInstruction::MemoryBehavior B) { switch (B) { case SILInstruction::MemoryBehavior::MayWrite: case SILInstruction::MemoryBehavior::MayReadWrite: case SILInstruction::MemoryBehavior::MayHaveSideEffects: return true; case SILInstruction::MemoryBehavior::None: case SILInstruction::MemoryBehavior::MayRead: return false; } } namespace { /// An abstract representation of a SIL Projection that allows one to refer to /// either nominal fields or tuple indices. class Projection { SILType Type; VarDecl *Decl; unsigned Index; public: Projection(SILType T, VarDecl *D) : Type(T), Decl(D), Index(-1) { } Projection(SILType T, unsigned I) : Type(T), Decl(nullptr), Index(I) { } SILType getType() const { return Type; } VarDecl *getDecl() const { return Decl; } unsigned getIndex() const { return Index; } bool operator==(Projection &Other) const { if (Decl) return Decl == Other.getDecl(); else return !Other.getDecl() && Index == Other.getIndex(); } bool operator<(Projection Other) const { // If Proj1 is a decl... if (Decl) { // It should be sorted before Proj2 is Proj2 is not a decl. Otherwise // compare the pointers. if (auto OtherDecl = Other.getDecl()) return uintptr_t(Decl) < uintptr_t(OtherDecl); return true; } // If Proj1 is not a decl, then if Proj2 is a decl, Proj1 is not before // Proj2. If Proj2 is not a decl, compare the indices. return !Other.getDecl() && (Index < Other.Index); } }; } // end anonymous namespace. static bool isAddressProjection(SILValue V) { switch (V->getKind()) { case ValueKind::StructElementAddrInst: case ValueKind::TupleElementAddrInst: return true; default: return false; } } // Given an already emitted load PrevLd, see if we can static SILValue findExtractPathBetweenValues(LoadInst *PrevLI, LoadInst *LI) { SILValue PrevLIOp = PrevLI->getOperand(); SILValue LIOp = LI->getOperand(); // If they are equal, just return PrevLI. if (PrevLIOp == LIOp) return PrevLI; // Otherwise see if LI can be projection extracted from PrevLI. First see if // LI is a projection at all. llvm::SmallVector<Projection, 4> Projections; auto Iter = LIOp; while (isAddressProjection(Iter) && PrevLIOp != Iter) { if (auto *SEA = dyn_cast<StructElementAddrInst>(Iter.getDef())) Projections.push_back(Projection(Iter.getType(), SEA->getField())); else Projections.push_back( Projection(Iter.getType(), cast<TupleElementAddrInst>(*Iter).getFieldNo())); Iter = cast<SILInstruction>(*Iter).getOperand(0); } // We could not find an extract path in between the two values. if (Projections.empty() || PrevLIOp != Iter) return SILValue(); // Use the projection list we created to create the relevant extracts SILValue LastExtract = PrevLI; SILBuilder Builder(LI); while (!Projections.empty()) { auto P = Projections.pop_back_val(); if (auto *D = P.getDecl()) { LastExtract = Builder.createStructExtract(LI->getLoc(), LastExtract, D, P.getType().getObjectType()); assert(cast<StructExtractInst>(*LastExtract).getStructDecl() && "Instruction must have a struct decl!"); } else { LastExtract = Builder.createTupleExtract(LI->getLoc(), LastExtract, P.getIndex(), P.getType().getObjectType()); assert(cast<TupleExtractInst>(*LastExtract).getTupleType() && "Instruction must have a tuple type!"); } } // Return the last extract we created. return LastExtract; } static void invalidateAliasingLoads(SILInstruction *Inst, llvm::SmallPtrSetImpl<LoadInst *> &Loads, AliasAnalysis *AA) { llvm::SmallVector<LoadInst *, 4> InvalidatedLoadList; for (auto *LI : Loads) if (isWriteMemBehavior(AA->getMemoryBehavior(Inst, LI->getOperand()))) InvalidatedLoadList.push_back(LI); for (auto *LI : InvalidatedLoadList) { DEBUG(llvm::dbgs() << " Found an instruction that writes to memory " "such that a load is invalidated:" << *LI); Loads.erase(LI); } } /// \brief Promote stored values to loads, remove dead stores and merge /// duplicated loads. bool promoteMemoryOperationsInBlock(SILBasicBlock *BB, AliasAnalysis *AA) { bool Changed = false; StoreInst *PrevStore = 0; llvm::SmallPtrSet<LoadInst *, 8> Loads; auto II = BB->begin(), E = BB->end(); while (II != E) { SILInstruction *Inst = II++; DEBUG(llvm::dbgs() << "Visiting: " << *Inst); // This is a StoreInst. Let's see if we can remove the previous stores. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { // Invalidate any load that we can not prove does not read from the stores // destination. invalidateAliasingLoads(Inst, Loads, AA); // If we are storing to the previously stored address then delete the old // store. if (PrevStore && PrevStore->getDest() == SI->getDest()) { DEBUG(llvm::dbgs() << " Found a dead previous store... Removing...:" << *PrevStore); Changed = true; recursivelyDeleteTriviallyDeadInstructions(PrevStore, true); PrevStore = SI; NumDeadStores++; continue; } PrevStore = SI; continue; } if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { // If we are loading a value that we just saved then use the saved value. if (PrevStore && PrevStore->getDest() == LI->getOperand()) { DEBUG(llvm::dbgs() << " Forwarding store from: " << *PrevStore); SILValue(LI, 0).replaceAllUsesWith(PrevStore->getSrc()); recursivelyDeleteTriviallyDeadInstructions(LI, true); Changed = true; NumDupLoads++; continue; } // Search the previous loads and replace the current load with one of the // previous loads. for (auto PrevLI : Loads) { SILValue ForwardingExtract = findExtractPathBetweenValues(PrevLI, LI); if (!ForwardingExtract) continue; DEBUG(llvm::dbgs() << " Replacing with previous load: " << *ForwardingExtract); SILValue(LI, 0).replaceAllUsesWith(ForwardingExtract); recursivelyDeleteTriviallyDeadInstructions(LI, true); Changed = true; LI = 0; NumDupLoads++; break; } if (LI) Loads.insert(LI); continue; } // Retains write to memory but they don't affect loads and stores. if (isa<StrongRetainInst>(Inst)) { DEBUG(llvm::dbgs() << " Found strong retain, does not affect loads and" " stores.\n"); continue; } // Dealloc stack does not affect loads and stores. if (isa<DeallocStackInst>(Inst)) { DEBUG(llvm::dbgs() << "Found a dealloc stack. Does not affect loads and " "stores.\n"); continue; } if (auto *AI = dyn_cast<ApplyInst>(Inst)) if (auto *BI = dyn_cast<BuiltinFunctionRefInst>(&*AI->getCallee())) if (isReadNone(BI)) { DEBUG(llvm::dbgs() << " Found readnone builtin, does not affect " "loads and stores.\n"); continue; } // cond_fail does not read/write memory in a manner that we care about. if (isa<CondFailInst>(Inst)) { DEBUG(llvm::dbgs() << " Found a cond fail, does not affect " "loads and stores.\n"); continue; } // All other instructions that read from memory invalidate the store. if (Inst->mayReadFromMemory()) { DEBUG(llvm::dbgs() << " Found an instruction that reads from memory." " Invalidating store.\n"); PrevStore = 0; } // If we have an instruction that may write to memory and we can not prove // that it and its operands can not alias a load we have visited, invalidate // that load. if (Inst->mayWriteToMemory()) // Invalidate any load that we can not prove does not read from one of the // writing instructions operands. invalidateAliasingLoads(Inst, Loads, AA); } return Changed; } /// \brief Returns True if we can sink this instruction to another basic block. static bool canSinkInstruction(SILInstruction *Inst) { return Inst->use_empty() && !isa<TermInst>(Inst); } /// \brief Returns true if this instruction is a skip barrier, which means that /// we can't sink other instructions past it. static bool isSinkBarrier(SILInstruction *Inst) { // We know that some calls do not have side effects. if (const ApplyInst *AI = dyn_cast<ApplyInst>(Inst)) if (BuiltinFunctionRefInst *FR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef())) return !isSideEffectFree(FR); if (isa<TermInst>(Inst)) return false; if (Inst->mayHaveSideEffects()) return true; return false; } /// \brief Search for an instruction that is identical to \p Iden by scanning /// \p BB starting at the end of the block, stopping on sink barriers. SILInstruction *findIdenticalInBlock(SILBasicBlock *BB, SILInstruction *Iden) { int SkipBudget = SinkSearchWindow; SILBasicBlock::iterator InstToSink = BB->getTerminator(); while (SkipBudget) { // If we found a sinkable instruction that is identical to our goal // then return it. if (canSinkInstruction(InstToSink) && Iden->isIdenticalTo(InstToSink)) { DEBUG(llvm::dbgs() << "Found an identical instruction."); return InstToSink; } // If this instruction is a skip-barrier end the scan. if (isSinkBarrier(InstToSink)) return nullptr; // If this is the first instruction in the block then we are done. if (InstToSink == BB->begin()) return nullptr; SkipBudget--; InstToSink = std::prev(InstToSink); DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink); } return nullptr; } static bool sinkCodeFromPredecessors(SILBasicBlock *BB) { bool Changed = false; if (BB->pred_empty()) return Changed; // This block must be the only successor of all the predecessors. for (auto P : BB->getPreds()) if (P->getSingleSuccessor() != BB) return Changed; SILBasicBlock *FirstPred = *BB->pred_begin(); // The first Pred must have at least one non-terminator. if (FirstPred->getTerminator() == FirstPred->begin()) return Changed; DEBUG(llvm::dbgs() << " Sinking values from predecessors.\n"); unsigned SkipBudget = SinkSearchWindow; // Start scanning backwards from the terminator. SILBasicBlock::iterator InstToSink = FirstPred->getTerminator(); while (SkipBudget) { DEBUG(llvm::dbgs() << "Processing: " << *InstToSink); // Save the duplicated instructions in case we need to remove them. SmallVector<SILInstruction *, 4> Dups; if (canSinkInstruction(InstToSink)) { // For all preds: for (auto P : BB->getPreds()) { if (P == FirstPred) continue; // Search the duplicated instruction in the predecessor. if (SILInstruction *DupInst = findIdenticalInBlock(P, InstToSink)) { Dups.push_back(DupInst); } else { DEBUG(llvm::dbgs() << "Instruction mismatch.\n"); Dups.clear(); break; } } // If we found duplicated instructions, sink one of the copies and delete // the rest. if (Dups.size()) { DEBUG(llvm::dbgs() << "Moving: " << *InstToSink); InstToSink->moveBefore(BB->begin()); Changed = true; for (auto I : Dups) { I->replaceAllUsesWith(InstToSink); I->eraseFromParent(); NumSunk++; } // Restart the scan. InstToSink = FirstPred->getTerminator(); DEBUG(llvm::dbgs() << "Restarting scan. Next inst: " << *InstToSink); continue; } } // If this instruction was a barrier then we can't sink anything else. if (isSinkBarrier(InstToSink)) { DEBUG(llvm::dbgs() << "Aborting on barrier: " << *InstToSink); return Changed; } // This is the first instruction, we are done. if (InstToSink == FirstPred->begin()) { DEBUG(llvm::dbgs() << "Reached the first instruction."); return Changed; } SkipBudget--; InstToSink = std::prev(InstToSink); DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink); } return Changed; } class SILCodeMotion : public SILFunctionTransform { /// The entry point to the transformation. void run() { SILFunction &F = *getFunction(); DEBUG(llvm::dbgs() << "***** CodeMotion on function: " << F.getName() << " *****\n"); AliasAnalysis *AA = PM->getAnalysis<AliasAnalysis>(); bool Changed = false; // Remove dead stores and merge duplicate loads. for (auto &BB : F) Changed |= promoteMemoryOperationsInBlock(&BB, AA); // Sink duplicated code from predecessors. for (auto &BB : F) Changed |= sinkCodeFromPredecessors(&BB); if (Changed) invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } StringRef getName() override { return "SIL Code Motion"; } }; SILTransform *swift::createCodeMotion() { return new SILCodeMotion(); } <|endoftext|>
<commit_before>//===- SILCodeMotion.cpp - Code Motion Optimizations ----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "codemotion" #include "swift/SILPasses/Passes.h" #include "swift/SIL/Dominance.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILType.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILVisitor.h" #include "swift/SIL/Projection.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SILPasses/Transforms.h" #include "swift/SILAnalysis/AliasAnalysis.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/ScopedHashTable.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/RecyclingAllocator.h" STATISTIC(NumSunk, "Number of instructions sunk"); using namespace swift; static const int SinkSearchWindow = 6; /// \brief Returns True if we can sink this instruction to another basic block. static bool canSinkInstruction(SILInstruction *Inst) { return Inst->use_empty() && !isa<TermInst>(Inst); } /// \brief Returns true if this instruction is a skip barrier, which means that /// we can't sink other instructions past it. static bool isSinkBarrier(SILInstruction *Inst) { // We know that some calls do not have side effects. if (const ApplyInst *AI = dyn_cast<ApplyInst>(Inst)) if (BuiltinFunctionRefInst *FR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee())) return !isSideEffectFree(FR); if (isa<TermInst>(Inst)) return false; if (Inst->mayHaveSideEffects()) return true; return false; } /// \brief Search for an instruction that is identical to \p Iden by scanning /// \p BB starting at the end of the block, stopping on sink barriers. SILInstruction *findIdenticalInBlock(SILBasicBlock *BB, SILInstruction *Iden) { int SkipBudget = SinkSearchWindow; SILBasicBlock::iterator InstToSink = BB->getTerminator(); while (SkipBudget) { // If we found a sinkable instruction that is identical to our goal // then return it. if (canSinkInstruction(InstToSink) && Iden->isIdenticalTo(InstToSink)) { DEBUG(llvm::dbgs() << "Found an identical instruction."); return InstToSink; } // If this instruction is a skip-barrier end the scan. if (isSinkBarrier(InstToSink)) return nullptr; // If this is the first instruction in the block then we are done. if (InstToSink == BB->begin()) return nullptr; SkipBudget--; InstToSink = std::prev(InstToSink); DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink); } return nullptr; } static bool sinkCodeFromPredecessors(SILBasicBlock *BB) { bool Changed = false; if (BB->pred_empty()) return Changed; // This block must be the only successor of all the predecessors. for (auto P : BB->getPreds()) if (P->getSingleSuccessor() != BB) return Changed; SILBasicBlock *FirstPred = *BB->pred_begin(); // The first Pred must have at least one non-terminator. if (FirstPred->getTerminator() == FirstPred->begin()) return Changed; DEBUG(llvm::dbgs() << " Sinking values from predecessors.\n"); unsigned SkipBudget = SinkSearchWindow; // Start scanning backwards from the terminator. SILBasicBlock::iterator InstToSink = FirstPred->getTerminator(); while (SkipBudget) { DEBUG(llvm::dbgs() << "Processing: " << *InstToSink); // Save the duplicated instructions in case we need to remove them. SmallVector<SILInstruction *, 4> Dups; if (canSinkInstruction(InstToSink)) { // For all preds: for (auto P : BB->getPreds()) { if (P == FirstPred) continue; // Search the duplicated instruction in the predecessor. if (SILInstruction *DupInst = findIdenticalInBlock(P, InstToSink)) { Dups.push_back(DupInst); } else { DEBUG(llvm::dbgs() << "Instruction mismatch.\n"); Dups.clear(); break; } } // If we found duplicated instructions, sink one of the copies and delete // the rest. if (Dups.size()) { DEBUG(llvm::dbgs() << "Moving: " << *InstToSink); InstToSink->moveBefore(BB->begin()); Changed = true; for (auto I : Dups) { I->replaceAllUsesWith(InstToSink); I->eraseFromParent(); NumSunk++; } // Restart the scan. InstToSink = FirstPred->getTerminator(); DEBUG(llvm::dbgs() << "Restarting scan. Next inst: " << *InstToSink); continue; } } // If this instruction was a barrier then we can't sink anything else. if (isSinkBarrier(InstToSink)) { DEBUG(llvm::dbgs() << "Aborting on barrier: " << *InstToSink); return Changed; } // This is the first instruction, we are done. if (InstToSink == FirstPred->begin()) { DEBUG(llvm::dbgs() << "Reached the first instruction."); return Changed; } SkipBudget--; InstToSink = std::prev(InstToSink); DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink); } return Changed; } namespace { class SILCodeMotion : public SILFunctionTransform { /// The entry point to the transformation. void run() { SILFunction &F = *getFunction(); DEBUG(llvm::dbgs() << "***** CodeMotion on function: " << F.getName() << " *****\n"); // Sink duplicated code from predecessors. bool Changed = false; for (auto &BB : F) Changed |= sinkCodeFromPredecessors(&BB); if (Changed) invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } StringRef getName() override { return "SIL Code Motion"; } }; } // end anonymous namespace SILTransform *swift::createCodeMotion() { return new SILCodeMotion(); } <commit_msg>Remove include of unused header.<commit_after>//===- SILCodeMotion.cpp - Code Motion Optimizations ----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "codemotion" #include "swift/SILPasses/Passes.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILType.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILVisitor.h" #include "swift/SIL/Projection.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SILPasses/Transforms.h" #include "swift/SILAnalysis/AliasAnalysis.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/ScopedHashTable.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/RecyclingAllocator.h" STATISTIC(NumSunk, "Number of instructions sunk"); using namespace swift; static const int SinkSearchWindow = 6; /// \brief Returns True if we can sink this instruction to another basic block. static bool canSinkInstruction(SILInstruction *Inst) { return Inst->use_empty() && !isa<TermInst>(Inst); } /// \brief Returns true if this instruction is a skip barrier, which means that /// we can't sink other instructions past it. static bool isSinkBarrier(SILInstruction *Inst) { // We know that some calls do not have side effects. if (const ApplyInst *AI = dyn_cast<ApplyInst>(Inst)) if (BuiltinFunctionRefInst *FR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee())) return !isSideEffectFree(FR); if (isa<TermInst>(Inst)) return false; if (Inst->mayHaveSideEffects()) return true; return false; } /// \brief Search for an instruction that is identical to \p Iden by scanning /// \p BB starting at the end of the block, stopping on sink barriers. SILInstruction *findIdenticalInBlock(SILBasicBlock *BB, SILInstruction *Iden) { int SkipBudget = SinkSearchWindow; SILBasicBlock::iterator InstToSink = BB->getTerminator(); while (SkipBudget) { // If we found a sinkable instruction that is identical to our goal // then return it. if (canSinkInstruction(InstToSink) && Iden->isIdenticalTo(InstToSink)) { DEBUG(llvm::dbgs() << "Found an identical instruction."); return InstToSink; } // If this instruction is a skip-barrier end the scan. if (isSinkBarrier(InstToSink)) return nullptr; // If this is the first instruction in the block then we are done. if (InstToSink == BB->begin()) return nullptr; SkipBudget--; InstToSink = std::prev(InstToSink); DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink); } return nullptr; } static bool sinkCodeFromPredecessors(SILBasicBlock *BB) { bool Changed = false; if (BB->pred_empty()) return Changed; // This block must be the only successor of all the predecessors. for (auto P : BB->getPreds()) if (P->getSingleSuccessor() != BB) return Changed; SILBasicBlock *FirstPred = *BB->pred_begin(); // The first Pred must have at least one non-terminator. if (FirstPred->getTerminator() == FirstPred->begin()) return Changed; DEBUG(llvm::dbgs() << " Sinking values from predecessors.\n"); unsigned SkipBudget = SinkSearchWindow; // Start scanning backwards from the terminator. SILBasicBlock::iterator InstToSink = FirstPred->getTerminator(); while (SkipBudget) { DEBUG(llvm::dbgs() << "Processing: " << *InstToSink); // Save the duplicated instructions in case we need to remove them. SmallVector<SILInstruction *, 4> Dups; if (canSinkInstruction(InstToSink)) { // For all preds: for (auto P : BB->getPreds()) { if (P == FirstPred) continue; // Search the duplicated instruction in the predecessor. if (SILInstruction *DupInst = findIdenticalInBlock(P, InstToSink)) { Dups.push_back(DupInst); } else { DEBUG(llvm::dbgs() << "Instruction mismatch.\n"); Dups.clear(); break; } } // If we found duplicated instructions, sink one of the copies and delete // the rest. if (Dups.size()) { DEBUG(llvm::dbgs() << "Moving: " << *InstToSink); InstToSink->moveBefore(BB->begin()); Changed = true; for (auto I : Dups) { I->replaceAllUsesWith(InstToSink); I->eraseFromParent(); NumSunk++; } // Restart the scan. InstToSink = FirstPred->getTerminator(); DEBUG(llvm::dbgs() << "Restarting scan. Next inst: " << *InstToSink); continue; } } // If this instruction was a barrier then we can't sink anything else. if (isSinkBarrier(InstToSink)) { DEBUG(llvm::dbgs() << "Aborting on barrier: " << *InstToSink); return Changed; } // This is the first instruction, we are done. if (InstToSink == FirstPred->begin()) { DEBUG(llvm::dbgs() << "Reached the first instruction."); return Changed; } SkipBudget--; InstToSink = std::prev(InstToSink); DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink); } return Changed; } namespace { class SILCodeMotion : public SILFunctionTransform { /// The entry point to the transformation. void run() { SILFunction &F = *getFunction(); DEBUG(llvm::dbgs() << "***** CodeMotion on function: " << F.getName() << " *****\n"); // Sink duplicated code from predecessors. bool Changed = false; for (auto &BB : F) Changed |= sinkCodeFromPredecessors(&BB); if (Changed) invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } StringRef getName() override { return "SIL Code Motion"; } }; } // end anonymous namespace SILTransform *swift::createCodeMotion() { return new SILCodeMotion(); } <|endoftext|>
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_MESH_OPERATORS #define MFEM_MESH_OPERATORS #include "../config/config.hpp" #include "../general/array.hpp" #include "mesh.hpp" #include "../fem/estimators.hpp" #include <limits> namespace mfem { /** @brief The MeshOperator class serves as base for mesh manipulation classes. The purpose of the class is to provide a common abstraction for various AMR mesh control schemes. The typical use in an AMR loop is illustrated in examples 6/6p and 15/15p. A more general loop that also supports sequences of mesh operators with multiple updates looks like this: \code for (...) { // computations on the current mesh ... while (mesh_operator->Apply(mesh)) { // update FiniteElementSpaces and interpolate GridFunctions ... if (mesh_operator->Continue()) { break; } } if (mesh_operator->Stop()) { break; } } \endcode */ class MeshOperator { private: int mod; protected: friend class MeshOperatorSequence; /** @brief Implementation of the mesh operation. Invoked by the Apply() public method. @return Combination of ActionInfo constants. */ virtual int ApplyImpl(Mesh &mesh) = 0; /// Constructor to be used by derived classes. MeshOperator() : mod(NONE) { } public: /** @brief Action and information constants and masks. Combinations of constants are returned by the Apply() virtual method and can be accessed directly with GetActionInfo() or indirectly with methods like Stop(), Continue(), etc. The information bits (MASK_INFO) can be set only when the update bit is set (see MASK_UPDATE). */ enum Action { NONE = 0, /**< continue with computations without updating spaces or grid-functions, i.e. the mesh was not modified */ CONTINUE = 1, /**< update spaces and grid-functions and continue computations with the new mesh */ STOP = 2, ///< a stopping criterion was satisfied REPEAT = 3, /**< update spaces and grid-functions and call the operator Apply() method again */ MASK_UPDATE = 1, ///< bit mask for the "update" bit MASK_ACTION = 3 ///< bit mask for all "action" bits }; enum Info { REFINED = 4*1, ///< the mesh was refined DEREFINED = 4*2, ///< the mesh was de-refined REBALANCED = 4*3, ///< the mesh was rebalanced MASK_INFO = ~3 ///< bit mask for all "info" bits }; /** @brief Perform the mesh operation. @return true if FiniteElementSpaces and GridFunctions need to be updated. */ bool Apply(Mesh &mesh) { return ((mod = ApplyImpl(mesh)) & MASK_UPDATE); } /** @brief Check if STOP action is requested, e.g. stopping criterion is satisfied. */ bool Stop() const { return ((mod & MASK_ACTION) == STOP); } /** @brief Check if REPEAT action is requested, i.e. FiniteElementSpaces and GridFunctions need to be updated, and Apply() must be called again. */ bool Repeat() const { return ((mod & MASK_ACTION) == REPEAT); } /** @brief Check if CONTINUE action is requested, i.e. FiniteElementSpaces and GridFunctions need to be updated and computations should continue. */ bool Continue() const { return ((mod & MASK_ACTION) == CONTINUE); } /// Check if the mesh was refined. bool Refined() const { return ((mod & MASK_INFO) == REFINED); } /// Check if the mesh was de-refined. bool Derefined() const { return ((mod & MASK_INFO) == DEREFINED); } /// Check if the mesh was rebalanced. bool Rebalanced() const { return ((mod & MASK_INFO) == REBALANCED); } /** @brief Get the full ActionInfo value generated by the last call to Apply(). */ int GetActionInfo() const { return mod; } /// Reset the MeshOperator. virtual void Reset() = 0; /// The destructor is virtual. virtual ~MeshOperator() { } }; /** Composition of MeshOperators into a sequence. Use the Append() method to create the sequence. */ class MeshOperatorSequence : public MeshOperator { protected: int step; Array<MeshOperator*> sequence; ///< MeshOperators sequence, owned by us. /// Do not allow copy construction, due to assumed ownership. MeshOperatorSequence(const MeshOperatorSequence &) { } /** @brief Apply the MeshOperatorSequence. @return ActionInfo value corresponding to the last applied operator from the sequence. */ virtual int ApplyImpl(Mesh &mesh); public: /// Constructor. Use the Append() method to create the sequence. MeshOperatorSequence() : step(-1) { } /// Delete all operators from the sequence. virtual ~MeshOperatorSequence(); /** @brief Add an operator to the end of the sequence. The MeshOperatorSequence assumes ownership of the operator. */ void Append(MeshOperator *mc) { sequence.Append(mc); } /// Access the underlying sequence. Array<MeshOperator*> &GetSequence() { return sequence; } /// Reset all MeshOperators in the sequence. virtual void Reset(); }; /** @brief Mesh refinement operator using an error threshold. This class uses the given ErrorEstimator to estimate local element errors and then marks for refinement all elements i such that loc_err_i > threshold. The threshold is computed as \code threshold = max(total_err * total_fraction * pow(num_elements,-1.0/p), local_err_goal); \endcode where p (=total_norm_p), total_fraction, and local_err_goal are settable parameters, total_err = (sum_i local_err_i^p)^{1/p}, when p < inf, or total_err = max_i local_err_i, when p = inf. */ class ThresholdRefiner : public MeshOperator { protected: ErrorEstimator &estimator; AnisotropicErrorEstimator *aniso_estimator; double total_norm_p; double total_err_goal; double total_fraction; double local_err_goal; long max_elements; double threshold; long num_marked_elements; Array<Refinement> marked_elements; long current_sequence; int non_conforming; int nc_limit; double GetNorm(const Vector &local_err, Mesh &mesh) const; /** @brief Apply the operator to the mesh. @return STOP if a stopping criterion is satisfied or no elements were marked for refinement; REFINED + CONTINUE otherwise. */ virtual int ApplyImpl(Mesh &mesh); public: /// Construct a ThresholdRefiner using the given ErrorEstimator. ThresholdRefiner(ErrorEstimator &est); // default destructor (virtual) /** @brief Set the exponent, p, of the discrete p-norm used to compute the total error from the local element errors. */ void SetTotalErrorNormP(double norm_p = infinity()) { total_norm_p = norm_p; } /** @brief Set the total error stopping criterion: stop when total_err <= total_err_goal. The default value is zero. */ void SetTotalErrorGoal(double err_goal) { total_err_goal = err_goal; } /** @brief Set the total fraction used in the computation of the threshold. The default value is 1/2. @note If fraction == 0, total_err is essentially ignored in the threshold computation, i.e. threshold = local error goal. */ void SetTotalErrorFraction(double fraction) { total_fraction = fraction; } /** @brief Set the local stopping criterion: stop when local_err_i <= local_err_goal. The default value is zero. @note If local_err_goal == 0, it is essentially ignored in the threshold computation. */ void SetLocalErrorGoal(double err_goal) { local_err_goal = err_goal; } /** @brief Set the maximum number of elements stopping criterion: stop when the input mesh has num_elements >= max_elem. The default value is LONG_MAX. */ void SetMaxElements(long max_elem) { max_elements = max_elem; } /// Use nonconforming refinement, if possible (triangles, quads, hexes). void PreferNonconformingRefinement() { non_conforming = 1; } /** @brief Use conforming refinement, if possible (triangles, tetrahedra) -- this is the default. */ void PreferConformingRefinement() { non_conforming = -1; } /** @brief Set the maximum ratio of refinement levels of adjacent elements (0 = unlimited). */ void SetNCLimit(int nc_limit) { MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit"); this->nc_limit = nc_limit; } /// Get the number of marked elements in the last Apply() call. long GetNumMarkedElements() const { return num_marked_elements; } /// Get the threshold used in the last Apply() call. double GetThreshold() const { return threshold; } /// Reset the associated estimator. virtual void Reset(); }; // TODO: BulkRefiner to refine a portion of the global error /** @brief De-refinement operator using an error threshold. This de-refinement operator marks elements in the hierarchy whose children are leaves and their combined error is below a given threshold. The errors of the children are combined by one of the following operations: - op = 0: minimum of the errors - op = 1: sum of the errors (default) - op = 2: maximum of the errors. */ class ThresholdDerefiner : public MeshOperator { protected: ErrorEstimator &estimator; double threshold; int nc_limit, op; /** @brief Apply the operator to the mesh. @return DEREFINED + CONTINUE if some elements were de-refined; NONE otherwise. */ virtual int ApplyImpl(Mesh &mesh); public: /// Construct a ThresholdDerefiner using the given ErrorEstimator. ThresholdDerefiner(ErrorEstimator &est) : estimator(est) { threshold = 0.0; nc_limit = 0; op = 1; } // default destructor (virtual) /// Set the de-refinement threshold. The default value is zero. void SetThreshold(double thresh) { threshold = thresh; } void SetOp(int op) { this->op = op; } /** @brief Set the maximum ratio of refinement levels of adjacent elements (0 = unlimited). */ void SetNCLimit(int nc_limit) { MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit"); this->nc_limit = nc_limit; } /// Reset the associated estimator. virtual void Reset() { estimator.Reset(); } }; /** @brief Refinement operator to control data oscillation. This class uses the given computes osc_K(f) := || h ⋅ (I - Π) f ||_K at each element K. Here, Π is the L2-projection and ||⋅||_K is the L2-norm, restricted to the element K. All elements satisfying the inequality \code osc_K(f) > threshold ⋅ ||f|| / sqrt(n_el), \endcode are refined. Here, threshold is a postive parameter, ||⋅|| is the L2-norm over the entire domain Ω, and n_el is the number of elements in the mesh. Note that if osc(f) = threshold ⋅ ||f|| / sqrt(n_el) for each K, then \code osc(f) = sqrt( sum_K osc_K^2(f)) = threshold ⋅ ||f||. \endcode This is the reason for the 1/sqrt(n_el) factor. */ class CoefficientRefiner : public MeshOperator { protected: int nc_limit = 1; int nonconforming = -1; int order; long max_elements = std::numeric_limits<long>::max(); double threshold = 1.0e-2; double global_osc = 0.0; Array<int> mesh_refinements; Vector element_oscs; Coefficient *coeff = NULL; GridFunction *gf; const IntegrationRule *ir_default[Geometry::NumGeom]; const IntegrationRule **irs = NULL; /** @brief Apply the operator to the mesh once. @return STOP if a stopping criterion is satisfied or no elements were marked for refinement; REFINED + CONTINUE otherwise. */ virtual int ApplyImpl(Mesh &mesh); public: /// Constructor CoefficientRefiner(int order_) : order(order_) { } /** @brief Apply the operator to the mesh max_it times or until tolerance * achieved. @return STOP if a stopping criterion is satisfied or no elements were marked for refinement; REFINED + CONTINUE otherwise. */ virtual int PreprocessMesh(Mesh &mesh, int max_it); int PreprocessMesh(Mesh &mesh) { int max_it = 10; return PreprocessMesh(mesh, max_it); } /// Set the refinement threshold. The default value is 1.0e-3. void SetThreshold(double threshold_) { threshold = threshold_; } /** @brief Set the maximum number of elements stopping criterion: stop when the input mesh has num_elements >= max_elem. The default value is LONG_MAX. */ void SetMaxElements(long max_elements_) { max_elements = max_elements_; } /// Set the function f void SetCoefficient(Coefficient &coeff_) { global_osc = 0.0; coeff = &coeff_; } /// Reset the oscillation order void SetOrder(double order_) { order = order_; } /** @brief Set the maximum ratio of refinement levels of adjacent elements (0 = unlimited). The default value is 1, which helps ensure appropriate refinements in pathological situations where the default quadrature order is too low. */ void SetNCLimit(int nc_limit_) { MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit"); nc_limit = nc_limit_; } // Set a custom integration rule void SetIntRule(const IntegrationRule *irs_[]) { irs = irs_; } // Return the value of the global relative data oscillation double GetOsc() { return global_osc; } // Return the local relative data oscillation errors Vector GetLocalOscs() { MFEM_ASSERT(element_oscs.Size() > 0, "Local oscillations have not been computed yet") return element_oscs; } /// Reset virtual void Reset(); }; /** @brief ParMesh rebalancing operator. If the mesh is a parallel mesh, perform rebalancing; otherwise, do nothing. */ class Rebalancer : public MeshOperator { protected: /** @brief Rebalance a parallel mesh (only non-conforming parallel meshes are supported). @return CONTINUE + REBALANCE on success, NONE otherwise. */ virtual int ApplyImpl(Mesh &mesh); public: /// Empty. virtual void Reset() { } }; } // namespace mfem #endif // MFEM_MESH_OPERATORS <commit_msg>typo in comment<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_MESH_OPERATORS #define MFEM_MESH_OPERATORS #include "../config/config.hpp" #include "../general/array.hpp" #include "mesh.hpp" #include "../fem/estimators.hpp" #include <limits> namespace mfem { /** @brief The MeshOperator class serves as base for mesh manipulation classes. The purpose of the class is to provide a common abstraction for various AMR mesh control schemes. The typical use in an AMR loop is illustrated in examples 6/6p and 15/15p. A more general loop that also supports sequences of mesh operators with multiple updates looks like this: \code for (...) { // computations on the current mesh ... while (mesh_operator->Apply(mesh)) { // update FiniteElementSpaces and interpolate GridFunctions ... if (mesh_operator->Continue()) { break; } } if (mesh_operator->Stop()) { break; } } \endcode */ class MeshOperator { private: int mod; protected: friend class MeshOperatorSequence; /** @brief Implementation of the mesh operation. Invoked by the Apply() public method. @return Combination of ActionInfo constants. */ virtual int ApplyImpl(Mesh &mesh) = 0; /// Constructor to be used by derived classes. MeshOperator() : mod(NONE) { } public: /** @brief Action and information constants and masks. Combinations of constants are returned by the Apply() virtual method and can be accessed directly with GetActionInfo() or indirectly with methods like Stop(), Continue(), etc. The information bits (MASK_INFO) can be set only when the update bit is set (see MASK_UPDATE). */ enum Action { NONE = 0, /**< continue with computations without updating spaces or grid-functions, i.e. the mesh was not modified */ CONTINUE = 1, /**< update spaces and grid-functions and continue computations with the new mesh */ STOP = 2, ///< a stopping criterion was satisfied REPEAT = 3, /**< update spaces and grid-functions and call the operator Apply() method again */ MASK_UPDATE = 1, ///< bit mask for the "update" bit MASK_ACTION = 3 ///< bit mask for all "action" bits }; enum Info { REFINED = 4*1, ///< the mesh was refined DEREFINED = 4*2, ///< the mesh was de-refined REBALANCED = 4*3, ///< the mesh was rebalanced MASK_INFO = ~3 ///< bit mask for all "info" bits }; /** @brief Perform the mesh operation. @return true if FiniteElementSpaces and GridFunctions need to be updated. */ bool Apply(Mesh &mesh) { return ((mod = ApplyImpl(mesh)) & MASK_UPDATE); } /** @brief Check if STOP action is requested, e.g. stopping criterion is satisfied. */ bool Stop() const { return ((mod & MASK_ACTION) == STOP); } /** @brief Check if REPEAT action is requested, i.e. FiniteElementSpaces and GridFunctions need to be updated, and Apply() must be called again. */ bool Repeat() const { return ((mod & MASK_ACTION) == REPEAT); } /** @brief Check if CONTINUE action is requested, i.e. FiniteElementSpaces and GridFunctions need to be updated and computations should continue. */ bool Continue() const { return ((mod & MASK_ACTION) == CONTINUE); } /// Check if the mesh was refined. bool Refined() const { return ((mod & MASK_INFO) == REFINED); } /// Check if the mesh was de-refined. bool Derefined() const { return ((mod & MASK_INFO) == DEREFINED); } /// Check if the mesh was rebalanced. bool Rebalanced() const { return ((mod & MASK_INFO) == REBALANCED); } /** @brief Get the full ActionInfo value generated by the last call to Apply(). */ int GetActionInfo() const { return mod; } /// Reset the MeshOperator. virtual void Reset() = 0; /// The destructor is virtual. virtual ~MeshOperator() { } }; /** Composition of MeshOperators into a sequence. Use the Append() method to create the sequence. */ class MeshOperatorSequence : public MeshOperator { protected: int step; Array<MeshOperator*> sequence; ///< MeshOperators sequence, owned by us. /// Do not allow copy construction, due to assumed ownership. MeshOperatorSequence(const MeshOperatorSequence &) { } /** @brief Apply the MeshOperatorSequence. @return ActionInfo value corresponding to the last applied operator from the sequence. */ virtual int ApplyImpl(Mesh &mesh); public: /// Constructor. Use the Append() method to create the sequence. MeshOperatorSequence() : step(-1) { } /// Delete all operators from the sequence. virtual ~MeshOperatorSequence(); /** @brief Add an operator to the end of the sequence. The MeshOperatorSequence assumes ownership of the operator. */ void Append(MeshOperator *mc) { sequence.Append(mc); } /// Access the underlying sequence. Array<MeshOperator*> &GetSequence() { return sequence; } /// Reset all MeshOperators in the sequence. virtual void Reset(); }; /** @brief Mesh refinement operator using an error threshold. This class uses the given ErrorEstimator to estimate local element errors and then marks for refinement all elements i such that loc_err_i > threshold. The threshold is computed as \code threshold = max(total_err * total_fraction * pow(num_elements,-1.0/p), local_err_goal); \endcode where p (=total_norm_p), total_fraction, and local_err_goal are settable parameters, total_err = (sum_i local_err_i^p)^{1/p}, when p < inf, or total_err = max_i local_err_i, when p = inf. */ class ThresholdRefiner : public MeshOperator { protected: ErrorEstimator &estimator; AnisotropicErrorEstimator *aniso_estimator; double total_norm_p; double total_err_goal; double total_fraction; double local_err_goal; long max_elements; double threshold; long num_marked_elements; Array<Refinement> marked_elements; long current_sequence; int non_conforming; int nc_limit; double GetNorm(const Vector &local_err, Mesh &mesh) const; /** @brief Apply the operator to the mesh. @return STOP if a stopping criterion is satisfied or no elements were marked for refinement; REFINED + CONTINUE otherwise. */ virtual int ApplyImpl(Mesh &mesh); public: /// Construct a ThresholdRefiner using the given ErrorEstimator. ThresholdRefiner(ErrorEstimator &est); // default destructor (virtual) /** @brief Set the exponent, p, of the discrete p-norm used to compute the total error from the local element errors. */ void SetTotalErrorNormP(double norm_p = infinity()) { total_norm_p = norm_p; } /** @brief Set the total error stopping criterion: stop when total_err <= total_err_goal. The default value is zero. */ void SetTotalErrorGoal(double err_goal) { total_err_goal = err_goal; } /** @brief Set the total fraction used in the computation of the threshold. The default value is 1/2. @note If fraction == 0, total_err is essentially ignored in the threshold computation, i.e. threshold = local error goal. */ void SetTotalErrorFraction(double fraction) { total_fraction = fraction; } /** @brief Set the local stopping criterion: stop when local_err_i <= local_err_goal. The default value is zero. @note If local_err_goal == 0, it is essentially ignored in the threshold computation. */ void SetLocalErrorGoal(double err_goal) { local_err_goal = err_goal; } /** @brief Set the maximum number of elements stopping criterion: stop when the input mesh has num_elements >= max_elem. The default value is LONG_MAX. */ void SetMaxElements(long max_elem) { max_elements = max_elem; } /// Use nonconforming refinement, if possible (triangles, quads, hexes). void PreferNonconformingRefinement() { non_conforming = 1; } /** @brief Use conforming refinement, if possible (triangles, tetrahedra) -- this is the default. */ void PreferConformingRefinement() { non_conforming = -1; } /** @brief Set the maximum ratio of refinement levels of adjacent elements (0 = unlimited). */ void SetNCLimit(int nc_limit) { MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit"); this->nc_limit = nc_limit; } /// Get the number of marked elements in the last Apply() call. long GetNumMarkedElements() const { return num_marked_elements; } /// Get the threshold used in the last Apply() call. double GetThreshold() const { return threshold; } /// Reset the associated estimator. virtual void Reset(); }; // TODO: BulkRefiner to refine a portion of the global error /** @brief De-refinement operator using an error threshold. This de-refinement operator marks elements in the hierarchy whose children are leaves and their combined error is below a given threshold. The errors of the children are combined by one of the following operations: - op = 0: minimum of the errors - op = 1: sum of the errors (default) - op = 2: maximum of the errors. */ class ThresholdDerefiner : public MeshOperator { protected: ErrorEstimator &estimator; double threshold; int nc_limit, op; /** @brief Apply the operator to the mesh. @return DEREFINED + CONTINUE if some elements were de-refined; NONE otherwise. */ virtual int ApplyImpl(Mesh &mesh); public: /// Construct a ThresholdDerefiner using the given ErrorEstimator. ThresholdDerefiner(ErrorEstimator &est) : estimator(est) { threshold = 0.0; nc_limit = 0; op = 1; } // default destructor (virtual) /// Set the de-refinement threshold. The default value is zero. void SetThreshold(double thresh) { threshold = thresh; } void SetOp(int op) { this->op = op; } /** @brief Set the maximum ratio of refinement levels of adjacent elements (0 = unlimited). */ void SetNCLimit(int nc_limit) { MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit"); this->nc_limit = nc_limit; } /// Reset the associated estimator. virtual void Reset() { estimator.Reset(); } }; /** @brief Refinement operator to control data oscillation. This class computes osc_K(f) := || h ⋅ (I - Π) f ||_K at each element K. Here, Π is the L2-projection and ||⋅||_K is the L2-norm, restricted to the element K. All elements satisfying the inequality \code osc_K(f) > threshold ⋅ ||f|| / sqrt(n_el), \endcode are refined. Here, threshold is a postive parameter, ||⋅|| is the L2-norm over the entire domain Ω, and n_el is the number of elements in the mesh. Note that if osc(f) = threshold ⋅ ||f|| / sqrt(n_el) for each K, then \code osc(f) = sqrt( sum_K osc_K^2(f)) = threshold ⋅ ||f||. \endcode This is the reason for the 1/sqrt(n_el) factor. */ class CoefficientRefiner : public MeshOperator { protected: int nc_limit = 1; int nonconforming = -1; int order; long max_elements = std::numeric_limits<long>::max(); double threshold = 1.0e-2; double global_osc = 0.0; Array<int> mesh_refinements; Vector element_oscs; Coefficient *coeff = NULL; GridFunction *gf; const IntegrationRule *ir_default[Geometry::NumGeom]; const IntegrationRule **irs = NULL; /** @brief Apply the operator to the mesh once. @return STOP if a stopping criterion is satisfied or no elements were marked for refinement; REFINED + CONTINUE otherwise. */ virtual int ApplyImpl(Mesh &mesh); public: /// Constructor CoefficientRefiner(int order_) : order(order_) { } /** @brief Apply the operator to the mesh max_it times or until tolerance * achieved. @return STOP if a stopping criterion is satisfied or no elements were marked for refinement; REFINED + CONTINUE otherwise. */ virtual int PreprocessMesh(Mesh &mesh, int max_it); int PreprocessMesh(Mesh &mesh) { int max_it = 10; return PreprocessMesh(mesh, max_it); } /// Set the refinement threshold. The default value is 1.0e-3. void SetThreshold(double threshold_) { threshold = threshold_; } /** @brief Set the maximum number of elements stopping criterion: stop when the input mesh has num_elements >= max_elem. The default value is LONG_MAX. */ void SetMaxElements(long max_elements_) { max_elements = max_elements_; } /// Set the function f void SetCoefficient(Coefficient &coeff_) { global_osc = 0.0; coeff = &coeff_; } /// Reset the oscillation order void SetOrder(double order_) { order = order_; } /** @brief Set the maximum ratio of refinement levels of adjacent elements (0 = unlimited). The default value is 1, which helps ensure appropriate refinements in pathological situations where the default quadrature order is too low. */ void SetNCLimit(int nc_limit_) { MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit"); nc_limit = nc_limit_; } // Set a custom integration rule void SetIntRule(const IntegrationRule *irs_[]) { irs = irs_; } // Return the value of the global relative data oscillation double GetOsc() { return global_osc; } // Return the local relative data oscillation errors Vector GetLocalOscs() { MFEM_ASSERT(element_oscs.Size() > 0, "Local oscillations have not been computed yet") return element_oscs; } /// Reset virtual void Reset(); }; /** @brief ParMesh rebalancing operator. If the mesh is a parallel mesh, perform rebalancing; otherwise, do nothing. */ class Rebalancer : public MeshOperator { protected: /** @brief Rebalance a parallel mesh (only non-conforming parallel meshes are supported). @return CONTINUE + REBALANCE on success, NONE otherwise. */ virtual int ApplyImpl(Mesh &mesh); public: /// Empty. virtual void Reset() { } }; } // namespace mfem #endif // MFEM_MESH_OPERATORS <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $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 Technology Preview License Agreement accompanying ** this package. ** ** 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. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://www.qtsoftware.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include <qservicemanager.h> #include <qserviceinterfacedescriptor.h> #include "servicebrowser.h" Q_DECLARE_METATYPE(QServiceInterfaceDescriptor) ServiceBrowser::ServiceBrowser(QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags) { serviceManager = new QServiceManager(this); registerExampleServices(); initWidgets(); reloadServicesList(); setWindowTitle(tr("Services Browser")); } ServiceBrowser::~ServiceBrowser() { unregisterExampleServices(); } void ServiceBrowser::currentInterfaceImplChanged(QListWidgetItem *current, QListWidgetItem *previous) { Q_UNUSED(previous); if (!current) return; reloadAttributesList(); reloadAttributesRadioButtonText(); QServiceInterfaceDescriptor descriptor = current->data(Qt::UserRole).value<QServiceInterfaceDescriptor>(); if (descriptor.isValid()) { defaultInterfaceButton->setText(tr("Set as default implementation for %1") .arg(descriptor.interfaceName())); defaultInterfaceButton->setEnabled(true); } } void ServiceBrowser::reloadServicesList() { servicesListWidget->clear(); QStringList services = serviceManager->findServices(); for (int i=0; i<services.count(); i++) servicesListWidget->addItem(services[i]); servicesListWidget->addItem(showAllServicesItem); } void ServiceBrowser::reloadInterfaceImplementationsList() { QString serviceName; if (servicesListWidget->currentItem() && servicesListWidget->currentItem() != showAllServicesItem) { serviceName = servicesListWidget->currentItem()->text(); interfacesGroup->setTitle(tr("Interfaces implemented by %1").arg(serviceName)); } else { interfacesGroup->setTitle(tr("All interface implementations")); } QList<QServiceInterfaceDescriptor> descriptors = serviceManager->findInterfaces(serviceName); interfacesListWidget->clear(); for (int i=0; i<descriptors.count(); i++) { QString text = QString("%1 %2.%3") .arg(descriptors[i].interfaceName()) .arg(descriptors[i].majorVersion()) .arg(descriptors[i].minorVersion()); if (serviceName.isEmpty()) text += " (" + descriptors[i].serviceName() + ")"; QServiceInterfaceDescriptor defaultInterfaceImpl = serviceManager->interfaceDefault(descriptors[i].interfaceName()); if (descriptors[i] == defaultInterfaceImpl) text += tr(" (default)"); QListWidgetItem *item = new QListWidgetItem(text); item->setData(Qt::UserRole, qVariantFromValue(descriptors[i])); interfacesListWidget->addItem(item); } defaultInterfaceButton->setEnabled(false); } void ServiceBrowser::reloadAttributesList() { QListWidgetItem *item = interfacesListWidget->currentItem(); if (!item) return; QServiceInterfaceDescriptor selectedImpl = item->data(Qt::UserRole).value<QServiceInterfaceDescriptor>(); QObject *implementationRef; if (selectedImplRadioButton->isChecked()) implementationRef = serviceManager->loadInterface(selectedImpl, 0, 0); else implementationRef = serviceManager->loadInterface(selectedImpl.interfaceName(), 0, 0); attributesListWidget->clear(); if (!implementationRef) { attributesListWidget->addItem(tr("(Error loading service plugin)")); return; } const QMetaObject *metaObject = implementationRef->metaObject(); attributesGroup->setTitle(tr("Invokable attributes for %1 class") .arg(QString(metaObject->className()))); for (int i=0; i<metaObject->methodCount(); i++) { QMetaMethod method = metaObject->method(i); attributesListWidget->addItem("[METHOD] " + QString(method.signature())); } for (int i=0; i<metaObject->propertyCount(); i++) { QMetaProperty property = metaObject->property(i); attributesListWidget->addItem("[PROPERTY] " + QString(property.name())); } } void ServiceBrowser::setDefaultInterfaceImplementation() { QListWidgetItem *item = interfacesListWidget->currentItem(); if (!item) return; QServiceInterfaceDescriptor descriptor = item->data(Qt::UserRole).value<QServiceInterfaceDescriptor>(); if (descriptor.isValid()) { if (serviceManager->setInterfaceDefault(descriptor)) { int currentIndex = interfacesListWidget->row(item); reloadInterfaceImplementationsList(); interfacesListWidget->setCurrentRow(currentIndex); } else { qWarning() << "Unable to set default service for interface:" << descriptor.interfaceName(); } } } void ServiceBrowser::registerExampleServices() { QStringList exampleXmlFiles; exampleXmlFiles << "filemanagerservice.xml" << "bluetoothtransferservice.xml"; foreach (const QString &fileName, exampleXmlFiles) { QString path = QCoreApplication::applicationDirPath() + "/xmldata/" + fileName; serviceManager->addService(path); } } void ServiceBrowser::unregisterExampleServices() { serviceManager->removeService("FileManagerService"); serviceManager->removeService("BluetoothTransferService"); } void ServiceBrowser::reloadAttributesRadioButtonText() { QListWidgetItem *item = interfacesListWidget->currentItem(); if (!item) return; QServiceInterfaceDescriptor selectedImpl = item->data(Qt::UserRole).value<QServiceInterfaceDescriptor>(); QServiceInterfaceDescriptor defaultImpl = serviceManager->interfaceDefault(selectedImpl.interfaceName()); defaultImplRadioButton->setText(tr("Default implementation for %1\n(currently provided by %2)") .arg(defaultImpl.interfaceName()) .arg(defaultImpl.serviceName())); } void ServiceBrowser::initWidgets() { showAllServicesItem = new QListWidgetItem(tr("(All registered services)")); servicesListWidget = new QListWidget; interfacesListWidget = new QListWidget; interfacesListWidget->addItem(tr("(Select a service)")); attributesListWidget = new QListWidget; attributesListWidget->addItem(tr("(Select an interface implementation)")); interfacesListWidget->setMinimumWidth(450); connect(servicesListWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(reloadInterfaceImplementationsList())); connect(interfacesListWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(currentInterfaceImplChanged(QListWidgetItem*,QListWidgetItem*))); defaultInterfaceButton = new QPushButton(tr("Set as default implementation")); defaultInterfaceButton->setEnabled(false); connect(defaultInterfaceButton, SIGNAL(clicked()), this, SLOT(setDefaultInterfaceImplementation())); selectedImplRadioButton = new QRadioButton(tr("Selected interface implementation")); defaultImplRadioButton = new QRadioButton(tr("Default implementation")); selectedImplRadioButton->setChecked(true); QButtonGroup *radioButtons = new QButtonGroup(this); radioButtons->addButton(selectedImplRadioButton); radioButtons->addButton(defaultImplRadioButton); connect(radioButtons, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(reloadAttributesList())); QGroupBox *servicesGroup = new QGroupBox(tr("Show services for:")); QVBoxLayout *servicesLayout = new QVBoxLayout; servicesLayout->addWidget(servicesListWidget); servicesGroup->setLayout(servicesLayout); interfacesGroup = new QGroupBox(tr("Interface implementations")); QVBoxLayout *interfacesLayout = new QVBoxLayout; interfacesLayout->addWidget(interfacesListWidget); interfacesLayout->addWidget(defaultInterfaceButton); interfacesGroup->setLayout(interfacesLayout); attributesGroup = new QGroupBox(tr("Invokable attributes")); QVBoxLayout *attributesLayout = new QVBoxLayout; attributesLayout->addWidget(attributesListWidget); attributesLayout->addWidget(new QLabel(tr("Show attributes for:"))); attributesLayout->addWidget(selectedImplRadioButton); attributesLayout->addWidget(defaultImplRadioButton); attributesGroup->setLayout(attributesLayout); QGridLayout *layout = new QGridLayout; layout->addWidget(servicesGroup, 0, 0); layout->addWidget(attributesGroup, 0, 1, 2, 1); layout->addWidget(interfacesGroup, 1, 0); setLayout(layout); } <commit_msg>Remove spurious file.<commit_after><|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <semaphore.h> #include "PcieTestBenchIndicationWrapper.h" #include "PcieTestBenchRequestProxy.h" #include "GeneratedTypes.h" class PcieTestBenchIndication : public PcieTestBenchIndicationWrapper { sem_t sem; sem_t done_sem; public: uint32_t cnt; void incr_cnt(){ if (++cnt == 7) exit(0); } virtual void finished(uint32_t v){ fprintf(stderr, "finished(%x)\n", v); sem_post(&done_sem); } virtual void started(uint32_t words){ fprintf(stderr, "started(%x)\n", words); } void tlpout(const TLPData16 &tlp) { fprintf(stderr, "Received tlp: %08x%08x%08x%08x\n", tlp.data3, tlp.data2, tlp.data1, tlp.data0); sem_post(&sem); } PcieTestBenchIndication(unsigned int id) : PcieTestBenchIndicationWrapper(id), cnt(0) { sem_init(&sem, 0, 0); sem_init(&done_sem,0,0); } void wait() { sem_wait(&sem); } }; int main(int argc, const char **argv) { PcieTestBenchIndication *indication = new PcieTestBenchIndication(IfcNames_PcieTestBenchIndication); PcieTestBenchRequestProxy *device = new PcieTestBenchRequestProxy(IfcNames_PcieTestBenchRequest); PortalAlloc *srcAlloc; unsigned int *srcBuffer = 0; pthread_t tid; fprintf(stderr, "Main::creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "Main::error creating exec thread\n"); exit(1); } } <commit_msg>flush out the cpp a bit<commit_after> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <semaphore.h> #include <sys/mman.h> #include "StdDmaIndication.h" #include "DmaConfigProxy.h" #include "PcieTestBenchIndicationWrapper.h" #include "PcieTestBenchRequestProxy.h" #include "GeneratedTypes.h" sem_t test_sem; int numWords = 0x12400/4; size_t test_sz = numWords*sizeof(unsigned int); size_t alloc_sz = test_sz; int burstLen = 16; class PcieTestBenchIndication : public PcieTestBenchIndicationWrapper { public: PcieTestBenchRequestProxy *device; virtual void finished(uint32_t v){ fprintf(stderr, "finished(%x)\n", v); sem_post(&test_sem); } virtual void started(uint32_t words){ fprintf(stderr, "started(%x)\n", words); } void tlpout(const TLPData16 &tlp) { fprintf(stderr, "Received tlp: %08x%08x%08x%08x\n", tlp.data3, tlp.data2, tlp.data1, tlp.data0); TLPData16 resp; device->tlpin(resp); } PcieTestBenchIndication(PcieTestBenchRequestProxy *device, unsigned int id) : PcieTestBenchIndicationWrapper(id), device(device){} }; int main(int argc, const char **argv) { PcieTestBenchRequestProxy *device = new PcieTestBenchRequestProxy(IfcNames_PcieTestBenchRequest); PcieTestBenchIndication *deviceIndication = new PcieTestBenchIndication(device, IfcNames_PcieTestBenchIndication); DmaConfigProxy *dma = new DmaConfigProxy(IfcNames_DmaConfig); DmaIndication *dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication); PortalAlloc *srcAlloc; unsigned int *srcBuffer = 0; dma->alloc(alloc_sz, &srcAlloc); srcBuffer = (unsigned int *)mmap(0, alloc_sz, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, srcAlloc->header.fd, 0); for (int i = 0; i < numWords; i++) srcBuffer[i] = i; pthread_t tid; fprintf(stderr, "Main::creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "error creating exec thread\n"); exit(1); } dma->dCacheFlushInval(srcAlloc, srcBuffer); unsigned int ref_srcAlloc = dma->reference(srcAlloc); device->startRead(ref_srcAlloc, numWords, burstLen); sem_wait(&test_sem); } <|endoftext|>
<commit_before>#ifndef BVECT #define BVECT #include <vector> using namespace std; class BVect { private: double _z1; double _z2; vector<double> _x; public: BVect () {} BVect (double z1, double z2, vector<double> x) : _z1(z1), _z2(z2), _x(x) {} BVect (const BVect& b1, const BVect& b2, double lambda) { _z1 = lambda * b1.z1() + (1-lambda) * b2.z1(); _z2 = lambda * b1.z2() + (1-lambda) * b2.z2(); for (unsigned i = 0; i < b1.x().size(); ++i) { _x.push_back(lambda * b1.x().at(i) + (1-lambda) * b2.x().at(i)); } } double z1() const {return _z1;} double z2() const {return _z2;} vector<double> x() const {return _x;} bool operator == (const BVect& bv) const { return (this->z1() == bv.z1() && this->z2() == bv.z2()); } bool operator != (const BVect bv) const { return !(*this == bv); } bool weaklyDominates(const BVect& bv) const { return (this->z1() <= bv.z1() && this->z2() <= bv.z2()); } bool dominates(const BVect& bv) const { return (this->weaklyDominates(bv) && (*this != bv)); } bool strictlyDominates(const BVect& bv) const { return (this->z1() < bv.z1() && this->z2() < bv.z2()); } bool isInA1AreaOf(const BVect& bv) const { return (bv.z1() > this->z1() && bv.z2() < this->z2()); } bool isInA2AreaOf(const BVect& bv) const { return bv.isInA1AreaOf(*this); } }; #endif <commit_msg>BVect: Add << ostream operator<commit_after>#ifndef BVECT #define BVECT #include <vector> #include <iostream> using namespace std; class BVect { private: double _z1; double _z2; vector<double> _x; public: BVect () {} BVect (double z1, double z2, vector<double> x) : _z1(z1), _z2(z2), _x(x) {} BVect (const BVect& b1, const BVect& b2, double lambda) { _z1 = lambda * b1.z1() + (1-lambda) * b2.z1(); _z2 = lambda * b1.z2() + (1-lambda) * b2.z2(); for (unsigned i = 0; i < b1.x().size(); ++i) { _x.push_back(lambda * b1.x().at(i) + (1-lambda) * b2.x().at(i)); } } double z1() const {return _z1;} double z2() const {return _z2;} vector<double> x() const {return _x;} bool operator == (const BVect& bv) const { return (this->z1() == bv.z1() && this->z2() == bv.z2()); } bool operator != (const BVect bv) const { return !(*this == bv); } bool weaklyDominates(const BVect& bv) const { return (this->z1() <= bv.z1() && this->z2() <= bv.z2()); } bool dominates(const BVect& bv) const { return (this->weaklyDominates(bv) && (*this != bv)); } bool strictlyDominates(const BVect& bv) const { return (this->z1() < bv.z1() && this->z2() < bv.z2()); } bool isInA1AreaOf(const BVect& bv) const { return (bv.z1() > this->z1() && bv.z2() < this->z2()); } bool isInA2AreaOf(const BVect& bv) const { return bv.isInA1AreaOf(*this); } friend ostream& operator << (ostream& s, const BVect& bv) { s << "(" << bv.z1() << ", " << bv.z2() << ")"; return s; } }; #endif <|endoftext|>
<commit_before>/// /// @file Wheel.hpp /// @brief Data structures related to wheel factorization. /// Wheel factorization is used to skip multiples of small /// primes in the sieve of Eratosthenes. /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef WHEEL_HPP #define WHEEL_HPP #include <pmath.hpp> #include <stdint.h> #include <algorithm> #include <cassert> #include <vector> namespace primecount { /// The InitWheel data structure is used to calculate the first /// multiple >= start of each sieving prime. /// struct InitWheel { int8_t next_multiple_factor; int8_t wheel_index; }; struct NextWheel { int8_t next_multiple_factor; int8_t next_wheel_index; }; struct WheelItem { WheelItem(int64_t multiple, int8_t i) : next_multiple(multiple), wheel_index(i) { } int64_t next_multiple; int8_t wheel_index; }; class Wheel { public: template <typename Primes> Wheel(Primes& primes, int64_t low, int64_t size, int64_t c) { assert(size <= primes.size()); int64_t b = 1; wheelItems_.reserve(size); // primecount uses 1-indexing, 0-index is a dummy wheelItems_.push_back(WheelItem(0, 0)); // for the first c primes only multiples of 2 are skipped for (; b < std::min(c + 1, size); b++) { int64_t prime = primes[b]; int64_t multiple = ceil_div(low, prime) * prime; multiple += prime * (~multiple & 1); #if __cplusplus >= 201103L wheelItems_.emplace_back(multiple, 0); #else wheelItems_.push_back(WheelItem(multiple, 0)); #endif } for (; b < size; b++) { int64_t prime = primes[b]; int64_t quotient = ceil_div(low, prime); // calculate the first multiple of prime >= low int64_t multiple = prime * quotient; if (multiple % 2 == 0) { multiple += prime; quotient += 1; } // calculate the next multiple of prime that is not // divisible by any of the wheel's factors (2, 3, 5, 7) uint64_t next_multiple_factor = initWheel210[quotient % 210].next_multiple_factor; multiple += prime * next_multiple_factor; int8_t wheel_index = initWheel210[quotient % 210].wheel_index; #if __cplusplus >= 201103L wheelItems_.emplace_back(multiple, wheel_index); #else wheelItems_.push_back(WheelItem(multiple, wheel_index)); #endif } } WheelItem& operator[](int64_t i) { return wheelItems_[i]; } static int64_t next_multiple_factor(int64_t* wheel_index) { assert(i < 8); int64_t next_multiple_factor = nextWheel210[*wheel_index].next_multiple_factor; *wheel_index = nextWheel210[*wheel_index].next_wheel_index; return next_multiple_factor; } private: static const InitWheel initWheel210[210]; static const NextWheel nextWheel210[48]; std::vector<WheelItem> wheelItems_; }; } // namespace primecount #endif <commit_msg>Remove assert<commit_after>/// /// @file Wheel.hpp /// @brief Data structures related to wheel factorization. /// Wheel factorization is used to skip multiples of small /// primes in the sieve of Eratosthenes. /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef WHEEL_HPP #define WHEEL_HPP #include <pmath.hpp> #include <stdint.h> #include <algorithm> #include <cassert> #include <vector> namespace primecount { /// The InitWheel data structure is used to calculate the first /// multiple >= start of each sieving prime. /// struct InitWheel { int8_t next_multiple_factor; int8_t wheel_index; }; struct NextWheel { int8_t next_multiple_factor; int8_t next_wheel_index; }; struct WheelItem { WheelItem(int64_t multiple, int8_t i) : next_multiple(multiple), wheel_index(i) { } int64_t next_multiple; int8_t wheel_index; }; class Wheel { public: template <typename Primes> Wheel(Primes& primes, int64_t low, int64_t size, int64_t c) { assert(size <= primes.size()); int64_t b = 1; wheelItems_.reserve(size); // primecount uses 1-indexing, 0-index is a dummy wheelItems_.push_back(WheelItem(0, 0)); // for the first c primes only multiples of 2 are skipped for (; b < std::min(c + 1, size); b++) { int64_t prime = primes[b]; int64_t multiple = ceil_div(low, prime) * prime; multiple += prime * (~multiple & 1); #if __cplusplus >= 201103L wheelItems_.emplace_back(multiple, 0); #else wheelItems_.push_back(WheelItem(multiple, 0)); #endif } for (; b < size; b++) { int64_t prime = primes[b]; int64_t quotient = ceil_div(low, prime); // calculate the first multiple of prime >= low int64_t multiple = prime * quotient; if (multiple % 2 == 0) { multiple += prime; quotient += 1; } // calculate the next multiple of prime that is not // divisible by any of the wheel's factors (2, 3, 5, 7) uint64_t next_multiple_factor = initWheel210[quotient % 210].next_multiple_factor; multiple += prime * next_multiple_factor; int8_t wheel_index = initWheel210[quotient % 210].wheel_index; #if __cplusplus >= 201103L wheelItems_.emplace_back(multiple, wheel_index); #else wheelItems_.push_back(WheelItem(multiple, wheel_index)); #endif } } WheelItem& operator[](int64_t i) { return wheelItems_[i]; } static int64_t next_multiple_factor(int64_t* wheel_index) { int64_t next_multiple_factor = nextWheel210[*wheel_index].next_multiple_factor; *wheel_index = nextWheel210[*wheel_index].next_wheel_index; return next_multiple_factor; } private: static const InitWheel initWheel210[210]; static const NextWheel nextWheel210[48]; std::vector<WheelItem> wheelItems_; }; } // namespace primecount #endif <|endoftext|>
<commit_before>/** * Copyright 2012-2013 Sergio Arroutbi Braojos <sarroutbi@gmail.com> * * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted, provided that * the above copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE * OR PERFORMANCE OF THIS SOFTWARE. **/ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <list> #include <iostream> #include "HtmlParser.h" using namespace std; inline void trim(const char* cstr, char* trimmed, uint32_t trim_length) { std::string str(cstr); str.erase(0, str.find_first_not_of(' ')); str.erase(str.find_last_not_of(' ')+1); strncpy(trimmed, str.c_str(), trim_length); } HtmlParser::HtmlParser () { memset(_file, 0, FILENAME_MAX); } HtmlParser::HtmlParser (const char* file) { setFile(file); } HtmlParser::~HtmlParser () { _bikeList.clear(); } uint8_t HtmlParser::dissertUrl (const char* url, char* link, const uint16_t urlMax, char* urlText, const uint16_t urlTextMax) { /** * URL input here has next format * "http://url.com/the_url" target="_blank">URL TEXT */ char* now = const_cast<char*>(url); char* aux; now = strstr(now, "\""); if(!now) { goto error_no_link; } now += 1; // avoid '"' character if(sscanf(now, "%[^\"]>", link) <1) { goto error_no_link; } now += strlen(link); if((aux = strstr(now, "target=\"_blank\">"))) { now = aux; now += strlen("target=\"_blank\">"); } if(sscanf(now, "%[^<]</td>", urlText) <= 0) { goto error_no_link; } return 0; error_no_link: fprintf(stderr, "Error parsing link. Could parse up to:=>%s<=\n", now); return 1; } void HtmlParser::setFile(const char* file) { if(file) strncpy(_file, file, FILENAME_MAX); } uint8_t HtmlParser::dummyBikeFill (Bike* bike) { if(bike) bike->set("Specialized", "2013", "http://test.com/test-url", "TheStore", "Specialized 2013", (rand()*999), BIKE_TYPE_MTB); } uint8_t HtmlParser::parseABike (const char* htmlPiece, uint32_t htmlPieceSize, Bike* bike) { uint8_t err = 0; /* Each html piece of each bike is of the type: * <td> Trademark </td> * <td> Model </td> * <td> Type </td> * <td> Price </td> * <td> Store </td> * <td><a href="http://url.com/the_url">URL TEXT</a></td> */ char trademark[MAX_TRADEMARK] = ""; char model [MAX_MODEL] = ""; char store [MAX_STORE] = ""; char c_type [MAX_TYPE] = ""; char c_price [MAX_PRICE] = ""; char url [MAX_URL] = ""; char url_text [MAX_URL_TEXT] = ""; char url_all [MAX_HTML_PIECE_LINE] = ""; float price = 0; bike_type_t type = BIKE_TYPE_UNDEFINED; if(bike) { char* now = const_cast<char*>(htmlPiece); while(now = strstr(now, "<td>")) { now += strlen("<td>"); if(!strlen(trademark)) { sscanf(now, "%[^<]</td>", trademark); now += strlen(trademark); } else if(!strlen(model)) { sscanf(now, "%[^<]</td>", model); now += strlen(model); } else if(!strlen(c_type)) { sscanf(now, "%[^<]</td>", c_type); now += strlen(c_type); } else if(!strlen(c_price)) { sscanf(now, "%[^<]</td>", c_price); now += strlen(c_price); price = strtod(c_price, NULL); } else if(!strlen(store)) { sscanf(now, "%[^<]</td>", store); now += strlen(store); } else if(!strlen(url_all)) { now += 1; // avoid '<' of <a href>....</a></td> sscanf(now, "%[^<]</a>", url_all); dissertUrl(url_all, url, MAX_URL, url_text, MAX_URL_TEXT); } else { break; } now += strlen("</td>"); } bike->set(trademark, model, store, url, url_text, price, type); } else { err = 1; } return err; } uint16_t HtmlParser::getHtmlPiece (FILE* f, char* htmlPiece, const uint16_t maxHtml) { uint16_t read = 0; bool pieceStart = false; bool finish = false; if(f && htmlPiece) { char line[MAX_HTML_PIECE_LINE]; char trimmedLine[MAX_HTML_PIECE_LINE]; uint16_t piecePending = MAX_HTML_PIECE_LINE; while((fgets(line, MAX_HTML_PIECE, f)) && (!finish) && (read <= maxHtml)) { if (strstr(line, "<tr>")) { pieceStart = true; } else if(pieceStart && strstr(line, "</tr>")) { pieceStart = false; finish = true; } else if(pieceStart) { piecePending -= strlen(line); read += strlen(line); strncat(htmlPiece, line, piecePending); } } } return read; } void HtmlParser:: logList () { BikeList::iterator i; for(i = _bikeList.begin(); i != _bikeList.end(); ++i) (*i).log(); } uint8_t HtmlParser::parse () { uint8_t err = 0; uint16_t pieceLength = 0; FILE* f = fopen(_file, "r"); char htmlPiece[MAX_HTML_PIECE]; memset(htmlPiece, 0, MAX_HTML_PIECE); if(!f) { err = 1; } else { while((pieceLength = getHtmlPiece(f, htmlPiece, MAX_HTML_PIECE))>0) { //fprintf(stderr, "Read html piece of [%d] bytes, =>%s<=\n", // pieceLength, htmlPiece); Bike bike; parseABike(htmlPiece, pieceLength, &bike); memset(htmlPiece, 0, MAX_HTML_PIECE); _bikeList.push_back(bike); } fclose(f); } return err; } uint8_t HtmlParser::parse (const char* file) { uint8_t err = 1; if(file) { setFile(file); err = parse(); } return err; } const BikeList & HtmlParser::getList () { parse(_file); return _bikeList; } <commit_msg>Fixing issue that was making half of the results to be dumped<commit_after>/** * Copyright 2012-2013 Sergio Arroutbi Braojos <sarroutbi@gmail.com> * * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted, provided that * the above copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE * OR PERFORMANCE OF THIS SOFTWARE. **/ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <list> #include <iostream> #include "HtmlParser.h" using namespace std; inline void trim(const char* cstr, char* trimmed, uint32_t trim_length) { std::string str(cstr); str.erase(0, str.find_first_not_of(' ')); str.erase(str.find_last_not_of(' ')+1); strncpy(trimmed, str.c_str(), trim_length); } HtmlParser::HtmlParser () { memset(_file, 0, FILENAME_MAX); } HtmlParser::HtmlParser (const char* file) { setFile(file); } HtmlParser::~HtmlParser () { _bikeList.clear(); } uint8_t HtmlParser::dissertUrl (const char* url, char* link, const uint16_t urlMax, char* urlText, const uint16_t urlTextMax) { /** * URL input here has next format * "http://url.com/the_url" target="_blank">URL TEXT */ char* now = const_cast<char*>(url); char* aux; now = strstr(now, "\""); if(!now) { goto error_no_link; } now += 1; // avoid '"' character if(sscanf(now, "%[^\"]>", link) <1) { goto error_no_link; } now += strlen(link); if((aux = strstr(now, "target=\"_blank\">"))) { now = aux; now += strlen("target=\"_blank\">"); } if(sscanf(now, "%[^<]</td>", urlText) <= 0) { goto error_no_link; } return 0; error_no_link: fprintf(stderr, "Error parsing link. Could parse up to:=>%s<=\n", now); return 1; } void HtmlParser::setFile(const char* file) { if(file) strncpy(_file, file, FILENAME_MAX); } uint8_t HtmlParser::dummyBikeFill (Bike* bike) { if(bike) bike->set("Specialized", "2013", "http://test.com/test-url", "TheStore", "Specialized 2013", (rand()*999), BIKE_TYPE_MTB); } uint8_t HtmlParser::parseABike (const char* htmlPiece, uint32_t htmlPieceSize, Bike* bike) { uint8_t err = 0; /* Each html piece of each bike is of the type: * <td> Trademark </td> * <td> Model </td> * <td> Type </td> * <td> Price </td> * <td> Store </td> * <td><a href="http://url.com/the_url">URL TEXT</a></td> */ char trademark[MAX_TRADEMARK] = ""; char model [MAX_MODEL] = ""; char store [MAX_STORE] = ""; char c_type [MAX_TYPE] = ""; char c_price [MAX_PRICE] = ""; char url [MAX_URL] = ""; char url_text [MAX_URL_TEXT] = ""; char url_all [MAX_HTML_PIECE_LINE] = ""; float price = 0; bike_type_t type = BIKE_TYPE_UNDEFINED; if(bike) { char* now = const_cast<char*>(htmlPiece); while(now = strstr(now, "<td>")) { now += strlen("<td>"); if(!strlen(trademark)) { sscanf(now, "%[^<]</td>", trademark); now += strlen(trademark); } else if(!strlen(model)) { sscanf(now, "%[^<]</td>", model); now += strlen(model); } else if(!strlen(c_type)) { sscanf(now, "%[^<]</td>", c_type); now += strlen(c_type); } else if(!strlen(c_price)) { sscanf(now, "%[^<]</td>", c_price); now += strlen(c_price); price = strtod(c_price, NULL); } else if(!strlen(store)) { sscanf(now, "%[^<]</td>", store); now += strlen(store); } else if(!strlen(url_all)) { now += 1; // avoid '<' of <a href>....</a></td> sscanf(now, "%[^<]</a>", url_all); dissertUrl(url_all, url, MAX_URL, url_text, MAX_URL_TEXT); } else { break; } now += strlen("</td>"); } bike->set(trademark, model, store, url, url_text, price, type); } else { err = 1; } return err; } uint16_t HtmlParser::getHtmlPiece (FILE* f, char* htmlPiece, const uint16_t maxHtml) { uint16_t read = 0; bool pieceStart = false; bool finish = false; if(f && htmlPiece) { char line[MAX_HTML_PIECE_LINE]; char trimmedLine[MAX_HTML_PIECE_LINE]; uint16_t piecePending = MAX_HTML_PIECE_LINE; while((!finish) && (read <= maxHtml) && (fgets(line, MAX_HTML_PIECE, f))) { // fprintf(stderr, "Line:=>%s<=", line); if (strstr(line, "<tr>")) { pieceStart = true; } else if(pieceStart && strstr(line, "</tr>")) { pieceStart = false; finish = true; } else if(pieceStart && (!finish)) { strncat(htmlPiece, line, piecePending); read += strlen(line); } } } return read; } void HtmlParser:: logList () { BikeList::iterator i; for(i = _bikeList.begin(); i != _bikeList.end(); ++i) (*i).log(); cout << "Total number of bikes:=>" << _bikeList.size() << "<=" << endl; } uint8_t HtmlParser::parse () { uint8_t err = 0; uint16_t pieceLength = 0; FILE* f = fopen(_file, "r"); char htmlPiece[MAX_HTML_PIECE]; memset(htmlPiece, 0, MAX_HTML_PIECE); if(!f) { err = 1; } else { while((pieceLength = getHtmlPiece(f, htmlPiece, MAX_HTML_PIECE))>0) { // fprintf(stderr, "Read html piece of [%d] bytes, =>%s<=\n", // pieceLength, htmlPiece); Bike bike; parseABike(htmlPiece, pieceLength, &bike); memset(htmlPiece, 0, MAX_HTML_PIECE); _bikeList.push_back(bike); } fclose(f); } return err; } uint8_t HtmlParser::parse (const char* file) { uint8_t err = 1; if(file) { setFile(file); err = parse(); } return err; } const BikeList & HtmlParser::getList () { parse(_file); return _bikeList; } <|endoftext|>
<commit_before><commit_msg>remove unnecessary debug message<commit_after><|endoftext|>
<commit_before><commit_msg>Make search provider enforce that keyword search term visits have a decreasing relevance. Without this we could end up with visits having the same relevance, which results in randomness as to which is first, when we really wanted one to be before the other.<commit_after><|endoftext|>
<commit_before><commit_msg>Disable flaky TabDraggingTest.Tab1Tab3Escape.<commit_after><|endoftext|>
<commit_before><commit_msg>Fixed a corner case issue with printing XPS documents to the Microsoft XPS Document Writer which would not generate a job id.<commit_after><|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include <cling/UserInterface/UserInterface.h> #include <cling/MetaProcessor/MetaProcessor.h> #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include <iostream> #include <sys/stat.h> namespace llvm { class Module; } //--------------------------------------------------------------------------- // Construct an interface for an interpreter //--------------------------------------------------------------------------- cling::UserInterface::UserInterface(Interpreter& interp, const char* prompt /*= "[cling] $"*/): m_MetaProcessor(new MetaProcessor(interp)) { } //--------------------------------------------------------------------------- // Destruct the interface //--------------------------------------------------------------------------- cling::UserInterface::~UserInterface() { delete m_MetaProcessor; } //--------------------------------------------------------------------------- // Interact with the user using a prompt //--------------------------------------------------------------------------- void cling::UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { std::cerr << std::endl; std::cerr << "****************** CLING ******************" << std::endl; std::cerr << "* Type C++ code and press enter to run it *" << std::endl; std::cerr << "* Type .q to exit *" << std::endl; std::cerr << "*******************************************" << std::endl; } static const char* histfile = ".cling_history"; std::string Prompt("[cling]$ "); using namespace textinput; StreamReader* R = StreamReader::Create(); TerminalDisplay* D = TerminalDisplay::Create(); TextInput TI(*R, *D, histfile); TI.SetPrompt(Prompt.c_str()); std::string line; MetaProcessorOpts& MPOpts = m_MetaProcessor->getMetaProcessorOpts(); while (!MPOpts.Quitting) { TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { MPOpts.Quitting = true; continue; } int indent = m_MetaProcessor->process(line.c_str()); Prompt = "[cling]"; if (MPOpts.RawInput) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } } <commit_msg>Don't use iostream.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include <cling/UserInterface/UserInterface.h> #include <cling/MetaProcessor/MetaProcessor.h> #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include "llvm/Support/raw_ostream.h" //--------------------------------------------------------------------------- // Construct an interface for an interpreter //--------------------------------------------------------------------------- cling::UserInterface::UserInterface(Interpreter& interp, const char* prompt /*= "[cling] $"*/): m_MetaProcessor(new MetaProcessor(interp)) { } //--------------------------------------------------------------------------- // Destruct the interface //--------------------------------------------------------------------------- cling::UserInterface::~UserInterface() { delete m_MetaProcessor; } //--------------------------------------------------------------------------- // Interact with the user using a prompt //--------------------------------------------------------------------------- void cling::UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { llvm::outs() << "\n"; llvm::outs() << "****************** CLING ******************" << "\n"; llvm::outs() << "* Type C++ code and press enter to run it *" << "\n"; llvm::outs() << "* Type .q to exit *" << "\n"; llvm::outs() << "*******************************************" << "\n"; } static const char* histfile = ".cling_history"; std::string Prompt("[cling]$ "); using namespace textinput; StreamReader* R = StreamReader::Create(); TerminalDisplay* D = TerminalDisplay::Create(); TextInput TI(*R, *D, histfile); TI.SetPrompt(Prompt.c_str()); std::string line; MetaProcessorOpts& MPOpts = m_MetaProcessor->getMetaProcessorOpts(); while (!MPOpts.Quitting) { TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { MPOpts.Quitting = true; continue; } int indent = m_MetaProcessor->process(line.c_str()); Prompt = "[cling]"; if (MPOpts.RawInput) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } } <|endoftext|>
<commit_before>#include "BilliardBuddy.h" int BilliardBuddy::frameIterator = 0; cv::vector<Vec2i> BilliardBuddy::cueCoords = cv::vector<Vec2i>(0, 0); int main(int argc, char* argv[]) { BilliardBuddy::help(); // Read config settings. const string inputSettingsFile = argc > 1 ? argv[1] : "config.xml"; FileStorage fs(inputSettingsFile, FileStorage::READ); if (!fs.isOpened()) { std::cout << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << std::endl; return -1; } Settings settings; fs["Settings"] >> settings; fs.release(); // Check validity of inputs before training begins. if (!settings.goodInput) { std::cout << "Invalid input detected. Application stopping. " << std::endl; return -1; } // MAIN LOGIC BilliardBuddy::process(settings); return 0; } void BilliardBuddy::process(Settings& settings) { bool preprocess = true; // Initialize CameraInterface CameraInterface cameraInterface = CameraInterface(settings); // Initialize PreProcessor Mat cameraMatrix, distCoeffs; cameraMatrix = settings.getCameraMatrix(); distCoeffs = settings.getDistCoeffs(); PreProcessor preProcessor = PreProcessor(cameraMatrix, distCoeffs); // Initialize Feature Detector(s) PoolTableDetector poolTableDetector = PoolTableDetector(); CueDetector cueDetector = CueDetector(); //Initialize Physics Model Calculator PhysicsModel physicsModel = PhysicsModel(); // Initialize Visual Augmentors TextAugmentor textAugmentor = TextAugmentor(); CueAugmentor cueAugmentor = CueAugmentor(); // Initialize HMD interface. HMDInterface hmdInterface = HMDInterface(); // Processing Loop bool result; do { result = processFrame(preprocess, cameraInterface, preProcessor, poolTableDetector, cueDetector, physicsModel, textAugmentor, cueAugmentor, hmdInterface); result = pollKeyboard(preprocess); } while (result == true); } bool BilliardBuddy::pollKeyboard(bool& preprocess) { // Check for keyboard inputs. char key = (char)waitKey(1); const char ESC_KEY = 27; if (key == 'u') preprocess = !preprocess; if (key == ESC_KEY) return false; return true; } bool BilliardBuddy::processFrame(bool& preprocess, CameraInterface& cameraInterface, PreProcessor& preProcessor, PoolTableDetector& poolTableDetector, CueDetector& cueDetector, PhysicsModel& physicsModel, TextAugmentor& textAugmentor, CueAugmentor& cueAugmentor, HMDInterface& hmdInterface) { // Fetch feed from camera interface. Mat leftFrame, rightFrame; cameraInterface.getFrames(leftFrame, rightFrame); // Pre-process feed. if (preprocess) { preProcessor.preProcess(leftFrame); preProcessor.preProcess(rightFrame); } // Detect features. cv::vector<pocket> pocketPoints = poolTableDetector.detectTable(rightFrame, frameIterator); //Detect Cue if (frameIterator == 1 || frameIterator == 0) { cueCoords = cueDetector.detect(rightFrame, frameIterator); } //Detect White Ball //TODO cv::vector<Vec2i> whiteBall(1); whiteBall[0] = { 200, 100 }; //Detect other balls //TODO?? Brian? cv::vector<Vec2i> balls(2); balls[0] = { 200, 140 }; balls[1] = { 200, 170 }; //balls[2] = { 150, 150 }; // Calculate Physics Model //cv::vector<Path> pathVector = physicsModel.calculate(rightFrame, pocketPoints, cueCoords, whiteBall, balls); // Visually augment. textAugmentor.augment(rightFrame); cueAugmentor.augment(rightFrame, cueCoords); hmdInterface.drawToHMD(leftFrame, rightFrame); if (frameIterator == 5) { frameIterator = 1; } else { frameIterator++; } // check for errors and return false at some point return true; } int BilliardBuddy::getFrameIterator() { return frameIterator; } void BilliardBuddy::help() { std::cout << "Welcome to the BilliardBuddy trainer!" << std::endl << "Usage: BilliardBuddy.exe <configpath.xml>" << std::endl << "Near the sample file you'll find the configuration file, which has detailed help of " "how to edit it. It may be any OpenCV supported file format XML/YAML." << std::endl; } void read(const FileNode& node, Settings& x, const Settings& default_value = Settings()) { // This is called when the ">>" operator is used between a FileNode and a Settings. if (node.empty()) x = default_value; else x.read(node); }<commit_msg>Fixed frameIteration not iterating through full range - range max from 5 to 6<commit_after>#include "BilliardBuddy.h" int BilliardBuddy::frameIterator = 0; cv::vector<Vec2i> BilliardBuddy::cueCoords = cv::vector<Vec2i>(0, 0); int main(int argc, char* argv[]) { BilliardBuddy::help(); // Read config settings. const string inputSettingsFile = argc > 1 ? argv[1] : "config.xml"; FileStorage fs(inputSettingsFile, FileStorage::READ); if (!fs.isOpened()) { std::cout << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << std::endl; return -1; } Settings settings; fs["Settings"] >> settings; fs.release(); // Check validity of inputs before training begins. if (!settings.goodInput) { std::cout << "Invalid input detected. Application stopping. " << std::endl; return -1; } // MAIN LOGIC BilliardBuddy::process(settings); return 0; } void BilliardBuddy::process(Settings& settings) { bool preprocess = true; // Initialize CameraInterface CameraInterface cameraInterface = CameraInterface(settings); // Initialize PreProcessor Mat cameraMatrix, distCoeffs; cameraMatrix = settings.getCameraMatrix(); distCoeffs = settings.getDistCoeffs(); PreProcessor preProcessor = PreProcessor(cameraMatrix, distCoeffs); // Initialize Feature Detector(s) PoolTableDetector poolTableDetector = PoolTableDetector(); CueDetector cueDetector = CueDetector(); //Initialize Physics Model Calculator PhysicsModel physicsModel = PhysicsModel(); // Initialize Visual Augmentors TextAugmentor textAugmentor = TextAugmentor(); CueAugmentor cueAugmentor = CueAugmentor(); // Initialize HMD interface. HMDInterface hmdInterface = HMDInterface(); // Processing Loop bool result; do { result = processFrame(preprocess, cameraInterface, preProcessor, poolTableDetector, cueDetector, physicsModel, textAugmentor, cueAugmentor, hmdInterface); result = pollKeyboard(preprocess); } while (result == true); } bool BilliardBuddy::pollKeyboard(bool& preprocess) { // Check for keyboard inputs. char key = (char)waitKey(1); const char ESC_KEY = 27; if (key == 'u') preprocess = !preprocess; if (key == ESC_KEY) return false; return true; } bool BilliardBuddy::processFrame(bool& preprocess, CameraInterface& cameraInterface, PreProcessor& preProcessor, PoolTableDetector& poolTableDetector, CueDetector& cueDetector, PhysicsModel& physicsModel, TextAugmentor& textAugmentor, CueAugmentor& cueAugmentor, HMDInterface& hmdInterface) { // Fetch feed from camera interface. Mat leftFrame, rightFrame; cameraInterface.getFrames(leftFrame, rightFrame); // Pre-process feed. if (preprocess) { preProcessor.preProcess(leftFrame); preProcessor.preProcess(rightFrame); } // Detect features. cv::vector<pocket> pocketPoints = poolTableDetector.detectTable(rightFrame, frameIterator); //Detect Cue if (frameIterator == 1 || frameIterator == 0) { cueCoords = cueDetector.detect(rightFrame, frameIterator); } //Detect White Ball //TODO cv::vector<Vec2i> whiteBall(1); whiteBall[0] = { 200, 100 }; //Detect other balls //TODO?? Brian? cv::vector<Vec2i> balls(2); balls[0] = { 200, 140 }; balls[1] = { 200, 170 }; //balls[2] = { 150, 150 }; // Calculate Physics Model //cv::vector<Path> pathVector = physicsModel.calculate(rightFrame, pocketPoints, cueCoords, whiteBall, balls); // Visually augment. textAugmentor.augment(rightFrame); cueAugmentor.augment(rightFrame, cueCoords); hmdInterface.drawToHMD(leftFrame, rightFrame); if (frameIterator == 7) { frameIterator = 1; } else { frameIterator++; } // check for errors and return false at some point return true; } int BilliardBuddy::getFrameIterator() { return frameIterator; } void BilliardBuddy::help() { std::cout << "Welcome to the BilliardBuddy trainer!" << std::endl << "Usage: BilliardBuddy.exe <configpath.xml>" << std::endl << "Near the sample file you'll find the configuration file, which has detailed help of " "how to edit it. It may be any OpenCV supported file format XML/YAML." << std::endl; } void read(const FileNode& node, Settings& x, const Settings& default_value = Settings()) { // This is called when the ">>" operator is used between a FileNode and a Settings. if (node.empty()) x = default_value; else x.read(node); }<|endoftext|>
<commit_before>#include <iostream> #include <cstring> // Needed for memset #include <sys/socket.h> // Needed for the socket functions #include <netdb.h> // Needed for the socket functions #include <unistd.h> #include <assert.h> #include <memory> // unique_ptr #include "sim.h" #include "jsoncpp/json/json.h" #define PORT "25041" /** * \brief Read from environment variable as string */ static char* get_env_str(const char *envname, const char *defaultvalue) { char *env; env = getenv (envname); if (env==NULL) { return (char*) defaultvalue; } return env; } int smlt_tree_parse_wrapper(const char* json_string, unsigned ncores, uint16_t** model, uint32_t** leafs, uint32_t* t_root, uint32_t* len_model) { Json::Value root; // Json::CharReaderBuilder rbuilder; // rbuilder["collectComments"] = false; std::string errs; // bool ok = Json::parseFromStream(rbuilder, rec, &root, &errs); Json::CharReaderBuilder rbuilder; Json::CharReader* reader = rbuilder.newCharReader(); reader->parse(json_string, json_string+strlen(json_string)-1, &root, &errs); // Extract last node Json::Value ln = root.get("root", ""); int lnval = ln.asInt(); *t_root = (uint32_t)lnval; // Extract leaf node Json::Value leafs_j = root.get("leaf_nodes", ""); *leafs = (uint32_t*) malloc(sizeof(uint32_t)*leafs_j.size()); assert(*leafs != NULL); for (unsigned i=0; i<leafs_j.size(); i++) { (*leafs)[i] = leafs_j.get(i, Json::Value()).asInt(); } Json::Value elem = root.get("model", ""); *model = (uint16_t*) malloc(sizeof(uint16_t)*elem.size()*elem.size()); assert(*model != NULL); int x = 0; int y = 0; *len_model = elem.size(); for (Json::ValueIterator i=elem.begin(); i != elem.end(); i++) { y = 0; Json::Value inner = (*i); for (Json::ValueIterator k=inner.begin(); k != inner.end(); k++) { Json::Value val = (*k); (*model)[x*elem.size()+y] = (uint32_t) val.asInt(); y++; } x++; } return 0; } static int smlt_tree_config_request(const char *hostname, const char* msg, unsigned ncores, uint16_t** model, uint32_t** leafs, uint32_t* t_root, uint32_t* len_model) { int status; struct addrinfo host_info; // The struct that getaddrinfo() fills up with data. struct addrinfo *host_info_list; // Pointer to the to the linked list of host_info's. // The MAN page of getaddrinfo() states "All the other fields in the structure pointed // to by hints must contain either 0 or a null pointer, as appropriate." When a struct // is created in c++, it will be given a block of memory. This memory is not nessesary // empty. Therefor we use the memset function to make sure all fields are NULL. memset(&host_info, 0, sizeof host_info); host_info.ai_family = AF_UNSPEC; // IP version not specified. Can be both. host_info.ai_socktype = SOCK_STREAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP. // Now fill up the linked list of host_info structs with google's address information. status = getaddrinfo(hostname, PORT, &host_info, &host_info_list); // getaddrinfo returns 0 on succes, or some other value when an error occured. // (translated into human readable text by the gai_gai_strerror function). if (status != 0) { std::cout << "getaddrinfo error" << gai_strerror(status) ; return 1; } int socketfd ; // The socket descripter socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol); if (socketfd == -1) { std::cout << "socket error " ; return 1; } status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen); if (status == -1) { std::cout << "connect error" ; return 1; } int len = strlen(msg); int bytes_sent; bytes_sent = send(socketfd, msg, len, 0); assert (bytes_sent==len); ssize_t bytes_recieved; char incomming_data_buffer[1000]; std::string rec; do { bytes_recieved = recv(socketfd, incomming_data_buffer,1000, 0); // If no data arrives, the program will just wait here until some data arrives. if (bytes_recieved > 0) { incomming_data_buffer[bytes_recieved] = '\0' ; rec.append(incomming_data_buffer); } else { if (bytes_recieved == 0) { printf("host shut down \n"); } else if (bytes_recieved == -1) { printf("receive error \n"); return 1; } } } while(bytes_recieved>0); freeaddrinfo(host_info_list); shutdown(socketfd, SHUT_RDWR); assert(model != NULL); char* inp = (char*) rec.c_str(); return smlt_tree_parse_wrapper(inp, ncores, model, leafs, t_root, len_model); } #define NAMELEN 1000U int smlt_tree_generate_wrapper(unsigned ncores, uint32_t* cores, const char* tree_name, uint16_t** model, uint32_t** leafs, uint32_t* t_root, uint32_t* len_model) { // Ask the Simulator to build a model const char *host = get_env_str("SMLT_HOSTNAME", ""); const char *machine = get_env_str("SMLT_MACHINE", "unknown"); // Determine hostname of this machine char thishost[NAMELEN]; gethostname(thishost, NAMELEN); if (strlen(host)>0) { printf("Hostname is %s \n", host); } else { printf("No hostname give, not contacting generator \n"); return 1; } Json::StreamWriterBuilder wbuilder; wbuilder["indentatin"] = "\t"; // Override hostname if given as environment variable if (strcmp(machine, "unknown") != 0) { printf("Overriding hosname %s --> %s\n", thishost, machine); strncpy(thishost, machine, NAMELEN); } Json::Value root; // 'root' will contain the root value after parsing. root["machine"] = thishost; if (tree_name == NULL) { root["topology"] = "adaptivetree"; } else { root["topology"] = tree_name; } Json::Value coreids; if (cores != NULL) { for (unsigned i=0; i<ncores; i++) coreids.append(cores[i]); } else { for (unsigned i=0; i<ncores; i++) coreids.append(i); } root["cores"] = coreids; std::string doc = Json::writeString(wbuilder, root); return smlt_tree_config_request(host, doc.c_str(), ncores, model, leafs, t_root, len_model); } <commit_msg>Added env variable SMLT_TOPO to set topology to be generated<commit_after>#include <iostream> #include <cstring> // Needed for memset #include <sys/socket.h> // Needed for the socket functions #include <netdb.h> // Needed for the socket functions #include <unistd.h> #include <assert.h> #include <memory> // unique_ptr #include "sim.h" #include "jsoncpp/json/json.h" #define PORT "25041" /** * \brief Read from environment variable as string */ static char* get_env_str(const char *envname, const char *defaultvalue) { char *env; env = getenv (envname); if (env==NULL) { return (char*) defaultvalue; } return env; } int smlt_tree_parse_wrapper(const char* json_string, unsigned ncores, uint16_t** model, uint32_t** leafs, uint32_t* t_root, uint32_t* len_model) { Json::Value root; // Json::CharReaderBuilder rbuilder; // rbuilder["collectComments"] = false; std::string errs; // bool ok = Json::parseFromStream(rbuilder, rec, &root, &errs); Json::CharReaderBuilder rbuilder; Json::CharReader* reader = rbuilder.newCharReader(); reader->parse(json_string, json_string+strlen(json_string)-1, &root, &errs); // Extract last node Json::Value ln = root.get("root", ""); int lnval = ln.asInt(); *t_root = (uint32_t)lnval; // Extract leaf node Json::Value leafs_j = root.get("leaf_nodes", ""); *leafs = (uint32_t*) malloc(sizeof(uint32_t)*leafs_j.size()); assert(*leafs != NULL); for (unsigned i=0; i<leafs_j.size(); i++) { (*leafs)[i] = leafs_j.get(i, Json::Value()).asInt(); } Json::Value elem = root.get("model", ""); *model = (uint16_t*) malloc(sizeof(uint16_t)*elem.size()*elem.size()); assert(*model != NULL); int x = 0; int y = 0; *len_model = elem.size(); for (Json::ValueIterator i=elem.begin(); i != elem.end(); i++) { y = 0; Json::Value inner = (*i); for (Json::ValueIterator k=inner.begin(); k != inner.end(); k++) { Json::Value val = (*k); (*model)[x*elem.size()+y] = (uint32_t) val.asInt(); y++; } x++; } return 0; } static int smlt_tree_config_request(const char *hostname, const char* msg, unsigned ncores, uint16_t** model, uint32_t** leafs, uint32_t* t_root, uint32_t* len_model) { int status; struct addrinfo host_info; // The struct that getaddrinfo() fills up with data. struct addrinfo *host_info_list; // Pointer to the to the linked list of host_info's. // The MAN page of getaddrinfo() states "All the other fields in the structure pointed // to by hints must contain either 0 or a null pointer, as appropriate." When a struct // is created in c++, it will be given a block of memory. This memory is not nessesary // empty. Therefor we use the memset function to make sure all fields are NULL. memset(&host_info, 0, sizeof host_info); host_info.ai_family = AF_UNSPEC; // IP version not specified. Can be both. host_info.ai_socktype = SOCK_STREAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP. // Now fill up the linked list of host_info structs with google's address information. status = getaddrinfo(hostname, PORT, &host_info, &host_info_list); // getaddrinfo returns 0 on succes, or some other value when an error occured. // (translated into human readable text by the gai_gai_strerror function). if (status != 0) { std::cout << "getaddrinfo error" << gai_strerror(status) ; return 1; } int socketfd ; // The socket descripter socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol); if (socketfd == -1) { std::cout << "socket error " ; return 1; } status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen); if (status == -1) { std::cout << "connect error" ; return 1; } int len = strlen(msg); int bytes_sent; bytes_sent = send(socketfd, msg, len, 0); assert (bytes_sent==len); ssize_t bytes_recieved; char incomming_data_buffer[1000]; std::string rec; do { bytes_recieved = recv(socketfd, incomming_data_buffer,1000, 0); // If no data arrives, the program will just wait here until some data arrives. if (bytes_recieved > 0) { incomming_data_buffer[bytes_recieved] = '\0' ; rec.append(incomming_data_buffer); } else { if (bytes_recieved == 0) { printf("host shut down \n"); } else if (bytes_recieved == -1) { printf("receive error \n"); return 1; } } } while(bytes_recieved>0); freeaddrinfo(host_info_list); shutdown(socketfd, SHUT_RDWR); assert(model != NULL); char* inp = (char*) rec.c_str(); return smlt_tree_parse_wrapper(inp, ncores, model, leafs, t_root, len_model); } #define NAMELEN 1000U int smlt_tree_generate_wrapper(unsigned ncores, uint32_t* cores, const char* tree_name, uint16_t** model, uint32_t** leafs, uint32_t* t_root, uint32_t* len_model) { // Ask the Simulator to build a model const char *host = get_env_str("SMLT_HOSTNAME", ""); const char *machine = get_env_str("SMLT_MACHINE", "unknown"); // Determine hostname of this machine char thishost[NAMELEN]; gethostname(thishost, NAMELEN); if (strlen(host)>0) { printf("Hostname is %s \n", host); } else { printf("No hostname give, not contacting generator \n"); return 1; } Json::StreamWriterBuilder wbuilder; wbuilder["indentatin"] = "\t"; // Override hostname if given as environment variable if (strcmp(machine, "unknown") != 0) { printf("Overriding hosname %s --> %s\n", thishost, machine); strncpy(thishost, machine, NAMELEN); } Json::Value root; // 'root' will contain the root value after parsing. root["machine"] = thishost; const char *topo_name; if (tree_name == NULL) { printf("Getting topo from env string\n"); topo_name = get_env_str("SMLT_TOPO", "adaptivetree"); } else { topo_name = tree_name; } root["topology"] = topo_name; printf("Requesting topology: %s\n", topo_name); Json::Value coreids; if (cores != NULL) { for (unsigned i=0; i<ncores; i++) coreids.append(cores[i]); } else { for (unsigned i=0; i<ncores; i++) coreids.append(i); } root["cores"] = coreids; std::string doc = Json::writeString(wbuilder, root); return smlt_tree_config_request(host, doc.c_str(), ncores, model, leafs, t_root, len_model); } <|endoftext|>
<commit_before>#include <cstdlib> #include "buffer.hh" namespace mimosa { namespace stream { Buffer::Buffer(uint64_t size) : size_(size), data_(reinterpret_cast<char *>(::malloc(size + 4))) { data_[size_ - 3] = 0; data_[size_ - 2] = 0; data_[size_ - 1] = 0; data_[size_] = 0; } Buffer::~Buffer() { free(data_); size_ = 0; data_ = nullptr; } void Buffer::resize(uint64_t size) { data_ = reinterpret_cast<char *>(::realloc(data_, size + 4)); size_ = size; data_[size_ - 3] = 0; data_[size_ - 2] = 0; data_[size_ - 1] = 0; data_[size_] = 0; } } } <commit_msg>Buffer has now 4 trailling null bytes which make more sense in case of utf-16 or utf-32 buffer.<commit_after>#include <cstdlib> #include "buffer.hh" namespace mimosa { namespace stream { Buffer::Buffer(uint64_t size) : size_(size), data_(reinterpret_cast<char *>(::malloc(size + 4))) { data_[size_ + 3] = 0; data_[size_ + 2] = 0; data_[size_ + 1] = 0; data_[size_] = 0; } Buffer::~Buffer() { free(data_); size_ = 0; data_ = nullptr; } void Buffer::resize(uint64_t size) { data_ = reinterpret_cast<char *>(::realloc(data_, size + 4)); size_ = size; data_[size_ + 3] = 0; data_[size_ + 2] = 0; data_[size_ + 1] = 0; data_[size_] = 0; } } } <|endoftext|>
<commit_before><commit_msg>Edit a comment.<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkContextMouseEvent.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkContextMouseEvent.h" #include "vtkRenderWindowInteractor.h" int vtkContextMouseEvent::GetModifiers() const { int modifier = vtkContextMouseEvent::NO_MODIFIER; if (this->Interactor) { if (this->Interactor->GetAltKey() > 0) { modifier |= vtkContextMouseEvent::ALT_MODIFIER; } if (this->Interactor->GetShiftKey() > 0) { modifier |= vtkContextMouseEvent::SHIFT_MODIFIER; } if (this->Interactor->GetControlKey() > 0) { modifier |= vtkContextMouseEvent::CONTROL_MODIFIER; } } return modifier; } <commit_msg>COMP: Fix AIX include order issues.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkContextMouseEvent.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkRenderWindowInteractor.h" // AIX include order issues. #include "vtkContextMouseEvent.h" int vtkContextMouseEvent::GetModifiers() const { int modifier = vtkContextMouseEvent::NO_MODIFIER; if (this->Interactor) { if (this->Interactor->GetAltKey() > 0) { modifier |= vtkContextMouseEvent::ALT_MODIFIER; } if (this->Interactor->GetShiftKey() > 0) { modifier |= vtkContextMouseEvent::SHIFT_MODIFIER; } if (this->Interactor->GetControlKey() > 0) { modifier |= vtkContextMouseEvent::CONTROL_MODIFIER; } } return modifier; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkScatterPlotMatrix.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkScatterPlotMatrix.h" #include "vtkTable.h" #include "vtkFloatArray.h" #include "vtkIntArray.h" #include "vtkChartXY.h" #include "vtkPlot.h" #include "vtkAxis.h" #include "vtkStdString.h" #include "vtkStringArray.h" #include "vtkNew.h" #include "vtkMathUtilities.h" #include "vtkObjectFactory.h" class vtkScatterPlotMatrix::PIMPL { public: PIMPL() : VisibleColumnsModified(true), BigChart(NULL) { } ~PIMPL() { } vtkNew<vtkTable> Histogram; bool VisibleColumnsModified; vtkChart* BigChart; }; namespace { int NumberOfBins = 10; // This is just here for now - quick and dirty historgram calculations... bool PopulateHistograms(vtkTable *input, vtkTable *output, vtkStringArray *s) { // The output table will have the twice the number of columns, they will be // the x and y for input column. This is the bin centers, and the population. for (vtkIdType i = output->GetNumberOfColumns() - 1; i >= 0; --i) { output->RemoveColumn(i); } for (vtkIdType i = 0; i < s->GetNumberOfTuples(); ++i) { double minmax[2] = { 0.0, 0.0 }; vtkStdString name(s->GetValue(i)); vtkDataArray *in = vtkDataArray::SafeDownCast(input->GetColumnByName(name.c_str())); if (in) { // The bin values are the centers, extending +/- half an inc either side in->GetRange(minmax); if (minmax[0] == minmax[1]) { minmax[1] = minmax[0] + 1.0; } double inc = (minmax[1] - minmax[0]) / NumberOfBins; double halfInc = inc / 2.0; vtkNew<vtkFloatArray> extents; extents->SetName(vtkStdString(name + "_extents").c_str()); extents->SetNumberOfTuples(NumberOfBins); float *centers = static_cast<float *>(extents->GetVoidPointer(0)); for (int j = 0; j < NumberOfBins; ++j) { extents->SetValue(j, minmax[0] + j * inc); } vtkNew<vtkIntArray> populations; populations->SetName(vtkStdString(name + "_pops").c_str()); populations->SetNumberOfTuples(NumberOfBins); int *pops = static_cast<int *>(populations->GetVoidPointer(0)); for (int k = 0; k < NumberOfBins; ++k) { pops[k] = 0; } for (vtkIdType j = 0; j < in->GetNumberOfTuples(); ++j) { double v(0.0); in->GetTuple(j, &v); for (int k = 0; k < NumberOfBins; ++k) { if (vtkMathUtilities::FuzzyCompare(v, double(centers[k]), halfInc)) { ++pops[k]; break; } } } output->AddColumn(extents.GetPointer()); output->AddColumn(populations.GetPointer()); } } return true; } } vtkStandardNewMacro(vtkScatterPlotMatrix) vtkScatterPlotMatrix::vtkScatterPlotMatrix() { this->Private = new PIMPL; } vtkScatterPlotMatrix::~vtkScatterPlotMatrix() { delete this->Private; } void vtkScatterPlotMatrix::Update() { if (this->Private->VisibleColumnsModified) { // We need to handle layout changes due to modified visibility. // Build up our histograms data before updating the layout. PopulateHistograms(this->Input.GetPointer(), this->Private->Histogram.GetPointer(), this->VisibleColumns.GetPointer()); this->UpdateLayout(); this->Private->VisibleColumnsModified = false; } } bool vtkScatterPlotMatrix::Paint(vtkContext2D *painter) { this->Update(); return Superclass::Paint(painter); } bool vtkScatterPlotMatrix::SetActivePlot(const vtkVector2i &pos) { if (pos.X() + pos.Y() + 1 < this->Size.X() && pos.X() < this->Size.X() && pos.Y() < this->Size.Y()) { // The supplied index is valid (in the lower quadrant). this->ActivePlot = pos; if (this->Private->BigChart) { vtkPlot *plot = this->Private->BigChart->GetPlot(0); if (!plot) { plot = this->Private->BigChart->AddPlot(vtkChart::POINTS); vtkChartXY *xy = vtkChartXY::SafeDownCast(this->Private->BigChart); if (xy) { xy->SetPlotCorner(plot, 2); } } plot->SetInput(this->Input.GetPointer(), this->VisibleColumns->GetValue(pos.X()), this->VisibleColumns->GetValue(this->Size.X() - pos.Y() - 1)); } return true; } else { return false; } } vtkVector2i vtkScatterPlotMatrix::GetActivePlot() { return this->ActivePlot; } void vtkScatterPlotMatrix::SetInput(vtkTable *table) { if(table && table->GetNumberOfRows() == 0) { // do nothing if the table is emtpy return; } if (this->Input != table) { // Set the input, then update the size of the scatter plot matrix, set // their inputs and all the other stuff needed. this->Input = table; this->Modified(); if (table == NULL) { this->SetSize(vtkVector2i(0, 0)); this->SetColumnVisibilityAll(true); return; } int n = static_cast<int>(this->Input->GetNumberOfColumns()); this->SetColumnVisibilityAll(true); this->SetSize(vtkVector2i(n, n)); } } void vtkScatterPlotMatrix::SetColumnVisibility(const vtkStdString &name, bool visible) { if (visible) { for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { // Already there, nothing more needs to be done return; } } // Add the column to the end of the list this->VisibleColumns->InsertNextValue(name); this->Private->VisibleColumnsModified = true; this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(), this->VisibleColumns->GetNumberOfTuples())); this->Modified(); } else { // Remove the value if present for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { // Move all the later elements down by one, and reduce the size while (i < this->VisibleColumns->GetNumberOfTuples()-1) { this->VisibleColumns->SetValue(i, this->VisibleColumns->GetValue(i+1)); ++i; } this->VisibleColumns->SetNumberOfTuples( this->VisibleColumns->GetNumberOfTuples()-1); this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(), this->VisibleColumns->GetNumberOfTuples())); this->Private->VisibleColumnsModified = true; this->Modified(); return; } } } } bool vtkScatterPlotMatrix::GetColumnVisibility(const vtkStdString &name) { for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { return true; } } return false; } void vtkScatterPlotMatrix::SetColumnVisibilityAll(bool visible) { if (visible && this->Input) { vtkIdType n = this->Input->GetNumberOfColumns(); this->VisibleColumns->SetNumberOfTuples(n); for (vtkIdType i = 0; i < n; ++i) { this->VisibleColumns->SetValue(i, this->Input->GetColumnName(i)); } } else { this->SetSize(vtkVector2i(0, 0)); this->VisibleColumns->SetNumberOfTuples(0); } this->Private->VisibleColumnsModified = true; } vtkStringArray* vtkScatterPlotMatrix::GetVisibleColumns() { return this->VisibleColumns.GetPointer(); } void vtkScatterPlotMatrix::UpdateLayout() { // We want scatter plots on the lower-left triangle, then histograms along // the diagonal and a big plot in the top-right. The basic layout is, // // 0 H +++ // 1 S H +++ // 2 S S H // 3 S S S H // 0 1 2 3 // // Where the indices are those of the columns. The indices of the charts // originate in the bottom-left. int n = this->Size.X(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { vtkVector2i pos(i, j); if (i + j + 1 < n) { // Lower-left triangle - scatter plots. vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::POINTS); plot->SetInput(this->Input.GetPointer(), i, n - j - 1); } else if (i == n - j - 1) { // We are on the diagonal - need a histogram plot. vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::BAR); vtkStdString name(this->VisibleColumns->GetValue(i)); plot->SetInput(this->Private->Histogram.GetPointer(), name + "_extents", name + "_pops"); vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::TOP); axis->SetTitle(name.c_str()); if (i != n - 1) { axis->SetBehavior(vtkAxis::FIXED); } // Set the plot corner to the top-right vtkChartXY *xy = vtkChartXY::SafeDownCast(this->GetChart(pos)); if (xy) { xy->SetPlotCorner(plot, 2); } } else if (i == static_cast<int>(n / 2.0) + n % 2 && i == j) { // This big plot in the top-right this->Private->BigChart = this->GetChart(pos); this->SetChartSpan(pos, vtkVector2i(n - i, n - j)); this->SetActivePlot(vtkVector2i(0, n - 2)); } // Only show bottom axis label for bottom plots if (j > 0) { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM); axis->SetTitle(""); axis->SetLabelsVisible(false); axis->SetBehavior(vtkAxis::FIXED); } else { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM); axis->SetTitle(this->VisibleColumns->GetValue(i)); this->AttachAxisRangeListener(axis); } // Only show the left axis labels for left-most plots if (i > 0) { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT); axis->SetTitle(""); axis->SetLabelsVisible(false); axis->SetBehavior(vtkAxis::FIXED); } else { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT); axis->SetTitle(this->VisibleColumns->GetValue(n - j - 1)); this->AttachAxisRangeListener(axis); } } } } void vtkScatterPlotMatrix::AttachAxisRangeListener(vtkAxis* axis) { axis->AddObserver(vtkChart::UpdateRange, this, &vtkScatterPlotMatrix::AxisRangeForwarderCallback); } void vtkScatterPlotMatrix::AxisRangeForwarderCallback(vtkObject*, unsigned long, void*) { // Only set on the end axes, and propagated to all other matching axes. double r[2]; int n = this->GetSize().X() - 1; for (int i = 0; i < n; ++i) { this->GetChart(vtkVector2i(i, 0))->GetAxis(vtkAxis::BOTTOM)->GetRange(r); for (int j = 1; j < n - i; ++j) { this->GetChart(vtkVector2i(i, j))->GetAxis(vtkAxis::BOTTOM)->SetRange(r); } this->GetChart(vtkVector2i(i, n-i))->GetAxis(vtkAxis::TOP)->SetRange(r); this->GetChart(vtkVector2i(0, i))->GetAxis(vtkAxis::LEFT)->GetRange(r); for (int j = 1; j < n - i; ++j) { this->GetChart(vtkVector2i(j, i))->GetAxis(vtkAxis::LEFT)->SetRange(r); } } } void vtkScatterPlotMatrix::PrintSelf(ostream &os, vtkIndent indent) { Superclass::PrintSelf(os, indent); } <commit_msg>BUG: Delete all charts, then resize.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkScatterPlotMatrix.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkScatterPlotMatrix.h" #include "vtkTable.h" #include "vtkFloatArray.h" #include "vtkIntArray.h" #include "vtkChartXY.h" #include "vtkPlot.h" #include "vtkAxis.h" #include "vtkStdString.h" #include "vtkStringArray.h" #include "vtkNew.h" #include "vtkMathUtilities.h" #include "vtkObjectFactory.h" class vtkScatterPlotMatrix::PIMPL { public: PIMPL() : VisibleColumnsModified(true), BigChart(NULL) { } ~PIMPL() { } vtkNew<vtkTable> Histogram; bool VisibleColumnsModified; vtkChart* BigChart; }; namespace { int NumberOfBins = 10; // This is just here for now - quick and dirty historgram calculations... bool PopulateHistograms(vtkTable *input, vtkTable *output, vtkStringArray *s) { // The output table will have the twice the number of columns, they will be // the x and y for input column. This is the bin centers, and the population. for (vtkIdType i = output->GetNumberOfColumns() - 1; i >= 0; --i) { output->RemoveColumn(i); } for (vtkIdType i = 0; i < s->GetNumberOfTuples(); ++i) { double minmax[2] = { 0.0, 0.0 }; vtkStdString name(s->GetValue(i)); vtkDataArray *in = vtkDataArray::SafeDownCast(input->GetColumnByName(name.c_str())); if (in) { // The bin values are the centers, extending +/- half an inc either side in->GetRange(minmax); if (minmax[0] == minmax[1]) { minmax[1] = minmax[0] + 1.0; } double inc = (minmax[1] - minmax[0]) / NumberOfBins; double halfInc = inc / 2.0; vtkNew<vtkFloatArray> extents; extents->SetName(vtkStdString(name + "_extents").c_str()); extents->SetNumberOfTuples(NumberOfBins); float *centers = static_cast<float *>(extents->GetVoidPointer(0)); for (int j = 0; j < NumberOfBins; ++j) { extents->SetValue(j, minmax[0] + j * inc); } vtkNew<vtkIntArray> populations; populations->SetName(vtkStdString(name + "_pops").c_str()); populations->SetNumberOfTuples(NumberOfBins); int *pops = static_cast<int *>(populations->GetVoidPointer(0)); for (int k = 0; k < NumberOfBins; ++k) { pops[k] = 0; } for (vtkIdType j = 0; j < in->GetNumberOfTuples(); ++j) { double v(0.0); in->GetTuple(j, &v); for (int k = 0; k < NumberOfBins; ++k) { if (vtkMathUtilities::FuzzyCompare(v, double(centers[k]), halfInc)) { ++pops[k]; break; } } } output->AddColumn(extents.GetPointer()); output->AddColumn(populations.GetPointer()); } } return true; } } vtkStandardNewMacro(vtkScatterPlotMatrix) vtkScatterPlotMatrix::vtkScatterPlotMatrix() { this->Private = new PIMPL; } vtkScatterPlotMatrix::~vtkScatterPlotMatrix() { delete this->Private; } void vtkScatterPlotMatrix::Update() { if (this->Private->VisibleColumnsModified) { // We need to handle layout changes due to modified visibility. // Build up our histograms data before updating the layout. PopulateHistograms(this->Input.GetPointer(), this->Private->Histogram.GetPointer(), this->VisibleColumns.GetPointer()); this->UpdateLayout(); this->Private->VisibleColumnsModified = false; } } bool vtkScatterPlotMatrix::Paint(vtkContext2D *painter) { this->Update(); return Superclass::Paint(painter); } bool vtkScatterPlotMatrix::SetActivePlot(const vtkVector2i &pos) { if (pos.X() + pos.Y() + 1 < this->Size.X() && pos.X() < this->Size.X() && pos.Y() < this->Size.Y()) { // The supplied index is valid (in the lower quadrant). this->ActivePlot = pos; if (this->Private->BigChart) { vtkPlot *plot = this->Private->BigChart->GetPlot(0); if (!plot) { plot = this->Private->BigChart->AddPlot(vtkChart::POINTS); vtkChartXY *xy = vtkChartXY::SafeDownCast(this->Private->BigChart); if (xy) { xy->SetPlotCorner(plot, 2); } } plot->SetInput(this->Input.GetPointer(), this->VisibleColumns->GetValue(pos.X()), this->VisibleColumns->GetValue(this->Size.X() - pos.Y() - 1)); } return true; } else { return false; } } vtkVector2i vtkScatterPlotMatrix::GetActivePlot() { return this->ActivePlot; } void vtkScatterPlotMatrix::SetInput(vtkTable *table) { if(table && table->GetNumberOfRows() == 0) { // do nothing if the table is emtpy return; } if (this->Input != table) { // Set the input, then update the size of the scatter plot matrix, set // their inputs and all the other stuff needed. this->Input = table; this->SetSize(vtkVector2i(0, 0)); this->Modified(); if (table == NULL) { this->SetColumnVisibilityAll(true); return; } int n = static_cast<int>(this->Input->GetNumberOfColumns()); this->SetColumnVisibilityAll(true); this->SetSize(vtkVector2i(n, n)); } } void vtkScatterPlotMatrix::SetColumnVisibility(const vtkStdString &name, bool visible) { if (visible) { for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { // Already there, nothing more needs to be done return; } } // Add the column to the end of the list this->VisibleColumns->InsertNextValue(name); this->Private->VisibleColumnsModified = true; this->SetSize(vtkVector2i(0, 0)); this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(), this->VisibleColumns->GetNumberOfTuples())); this->Modified(); } else { // Remove the value if present for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { // Move all the later elements down by one, and reduce the size while (i < this->VisibleColumns->GetNumberOfTuples()-1) { this->VisibleColumns->SetValue(i, this->VisibleColumns->GetValue(i+1)); ++i; } this->VisibleColumns->SetNumberOfTuples( this->VisibleColumns->GetNumberOfTuples()-1); this->SetSize(vtkVector2i(0, 0)); this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(), this->VisibleColumns->GetNumberOfTuples())); this->Private->VisibleColumnsModified = true; this->Modified(); return; } } } } bool vtkScatterPlotMatrix::GetColumnVisibility(const vtkStdString &name) { for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { return true; } } return false; } void vtkScatterPlotMatrix::SetColumnVisibilityAll(bool visible) { if (visible && this->Input) { vtkIdType n = this->Input->GetNumberOfColumns(); this->VisibleColumns->SetNumberOfTuples(n); for (vtkIdType i = 0; i < n; ++i) { this->VisibleColumns->SetValue(i, this->Input->GetColumnName(i)); } } else { this->SetSize(vtkVector2i(0, 0)); this->VisibleColumns->SetNumberOfTuples(0); } this->Private->VisibleColumnsModified = true; } vtkStringArray* vtkScatterPlotMatrix::GetVisibleColumns() { return this->VisibleColumns.GetPointer(); } void vtkScatterPlotMatrix::UpdateLayout() { // We want scatter plots on the lower-left triangle, then histograms along // the diagonal and a big plot in the top-right. The basic layout is, // // 0 H +++ // 1 S H +++ // 2 S S H // 3 S S S H // 0 1 2 3 // // Where the indices are those of the columns. The indices of the charts // originate in the bottom-left. int n = this->Size.X(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { vtkVector2i pos(i, j); if (i + j + 1 < n) { // Lower-left triangle - scatter plots. vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::POINTS); plot->SetInput(this->Input.GetPointer(), i, n - j - 1); } else if (i == n - j - 1) { // We are on the diagonal - need a histogram plot. vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::BAR); vtkStdString name(this->VisibleColumns->GetValue(i)); plot->SetInput(this->Private->Histogram.GetPointer(), name + "_extents", name + "_pops"); vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::TOP); axis->SetTitle(name.c_str()); if (i != n - 1) { axis->SetBehavior(vtkAxis::FIXED); } // Set the plot corner to the top-right vtkChartXY *xy = vtkChartXY::SafeDownCast(this->GetChart(pos)); if (xy) { xy->SetPlotCorner(plot, 2); } } else if (i == static_cast<int>(n / 2.0) + n % 2 && i == j) { // This big plot in the top-right this->Private->BigChart = this->GetChart(pos); this->SetChartSpan(pos, vtkVector2i(n - i, n - j)); this->SetActivePlot(vtkVector2i(0, n - 2)); } // Only show bottom axis label for bottom plots if (j > 0) { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM); axis->SetTitle(""); axis->SetLabelsVisible(false); axis->SetBehavior(vtkAxis::FIXED); } else { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM); axis->SetTitle(this->VisibleColumns->GetValue(i)); this->AttachAxisRangeListener(axis); } // Only show the left axis labels for left-most plots if (i > 0) { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT); axis->SetTitle(""); axis->SetLabelsVisible(false); axis->SetBehavior(vtkAxis::FIXED); } else { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT); axis->SetTitle(this->VisibleColumns->GetValue(n - j - 1)); this->AttachAxisRangeListener(axis); } } } } void vtkScatterPlotMatrix::AttachAxisRangeListener(vtkAxis* axis) { axis->AddObserver(vtkChart::UpdateRange, this, &vtkScatterPlotMatrix::AxisRangeForwarderCallback); } void vtkScatterPlotMatrix::AxisRangeForwarderCallback(vtkObject*, unsigned long, void*) { // Only set on the end axes, and propagated to all other matching axes. double r[2]; int n = this->GetSize().X() - 1; for (int i = 0; i < n; ++i) { this->GetChart(vtkVector2i(i, 0))->GetAxis(vtkAxis::BOTTOM)->GetRange(r); for (int j = 1; j < n - i; ++j) { this->GetChart(vtkVector2i(i, j))->GetAxis(vtkAxis::BOTTOM)->SetRange(r); } this->GetChart(vtkVector2i(i, n-i))->GetAxis(vtkAxis::TOP)->SetRange(r); this->GetChart(vtkVector2i(0, i))->GetAxis(vtkAxis::LEFT)->GetRange(r); for (int j = 1; j < n - i; ++j) { this->GetChart(vtkVector2i(j, i))->GetAxis(vtkAxis::LEFT)->SetRange(r); } } } void vtkScatterPlotMatrix::PrintSelf(ostream &os, vtkIndent indent) { Superclass::PrintSelf(os, indent); } <|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include "core/cthread.h" namespace clever { CCondition::CCondition() { pthread_cond_init(&condition, NULL); } CCondition::~CCondition() { pthread_cond_destroy(&condition); } bool CCondition::signal() { return pthread_cond_signal(&condition) == 0; } bool CCondition::broadcast() { return pthread_cond_broadcast(&condition) == 0; } bool CCondition::wait(CMutex& m) { return pthread_cond_wait(&condition, &m.m_mut) == 0; } CMutex::CMutex() { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 pthread_mutex_init(&m_mut, NULL); # else m_mut = CreateMutex(NULL, FALSE, NULL); # endif #endif } CMutex::~CMutex() { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 pthread_mutex_destroy(&m_mut); # else CloseHandle(m_mut); # endif #endif } bool CMutex::lock() { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 return pthread_mutex_lock(&m_mut) == 0; # else WaitForSingleObject(m_mut, INFINITE); # endif #endif } bool CMutex::trylock() { return pthread_mutex_trylock(&m_mut) == 0; } bool CMutex::unlock() { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 return pthread_mutex_unlock(&m_mut) == 0; # else ReleaseMutex(m_mut); # endif #endif } void CThread::create(ThreadFunc thread_func, void* args) { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&t_handler, &attr, thread_func, args); pthread_attr_destroy(&attr); # else t_handler = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread_func, args, 0, NULL); # endif #endif m_is_running = true; } int CThread::wait() { #ifdef CLEVER_THREADS int status; #ifndef CLEVER_WIN32 status = pthread_join(t_handler, NULL); #else status = WaitForSingleObject(t_handler, INFINITE); status = (status != WAIT_FAILED ? 0x0 : status); CloseHandle(t_handler); #endif m_is_running = false; return status; #else return 0; #endif } } // clever <commit_msg>- Cosmetics<commit_after>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include "core/cthread.h" namespace clever { CCondition::CCondition() { pthread_cond_init(&condition, NULL); } CCondition::~CCondition() { pthread_cond_destroy(&condition); } bool CCondition::signal() { return pthread_cond_signal(&condition) == 0; } bool CCondition::broadcast() { return pthread_cond_broadcast(&condition) == 0; } bool CCondition::wait(CMutex& m) { return pthread_cond_wait(&condition, &m.m_mut) == 0; } CMutex::CMutex() { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 pthread_mutex_init(&m_mut, NULL); # else m_mut = CreateMutex(NULL, FALSE, NULL); # endif #endif } CMutex::~CMutex() { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 pthread_mutex_destroy(&m_mut); # else CloseHandle(m_mut); # endif #endif } bool CMutex::lock() { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 return pthread_mutex_lock(&m_mut) == 0; # else WaitForSingleObject(m_mut, INFINITE); # endif #endif } bool CMutex::trylock() { return pthread_mutex_trylock(&m_mut) == 0; } bool CMutex::unlock() { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 return pthread_mutex_unlock(&m_mut) == 0; # else ReleaseMutex(m_mut); # endif #endif } void CThread::create(ThreadFunc thread_func, void* args) { #ifdef CLEVER_THREADS # ifndef CLEVER_WIN32 pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&t_handler, &attr, thread_func, args); pthread_attr_destroy(&attr); # else t_handler = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread_func, args, 0, NULL); # endif #endif m_is_running = true; } int CThread::wait() { #ifdef CLEVER_THREADS int status; #ifndef CLEVER_WIN32 status = pthread_join(t_handler, NULL); #else status = WaitForSingleObject(t_handler, INFINITE); status = (status != WAIT_FAILED ? 0x0 : status); CloseHandle(t_handler); #endif m_is_running = false; return status; #else return 0; #endif } } // clever <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - The Lightweight Desktop Environment * https://lxqt.org * * Copyright: 2010-2011 Razor team * Authors: * Petr Vanek <petr@scribus.info> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "lxqtaboutdialog.h" #include "ui_lxqtaboutdialog.h" #include "lxqtaboutdialog_p.h" #include "technicalinfo.h" #include "translatorsinfo/translatorsinfo.h" #include <QDebug> #include <QDate> #include <QClipboard> AboutDialogPrivate::AboutDialogPrivate() { setupUi(this); QString css=QStringLiteral("<style TYPE='text/css'> " "body { font-family: sans-serif;} " ".name { font-size: 16pt; } " "a { white-space: nowrap ;} " "h2 { font-size: 10pt;} " "li { line-height: 120%;} " ".techInfoKey { white-space: nowrap ; margin: 0 20px 0 16px; } " "</style>") ; iconLabel->setFixedSize(48, 48); iconLabel->setScaledContents(true); iconLabel->setPixmap(QPixmap(QStringLiteral(LXQT_SHARE_DIR) + QStringLiteral("/graphics/lxqt_logo.png"))); nameLabel->setText(css + titleText()); aboutBrowser->setHtml(css + aboutText()); aboutBrowser->viewport()->setAutoFillBackground(false); autorsBrowser->setHtml(css + authorsText()); autorsBrowser->viewport()->setAutoFillBackground(false); thanksBrowser->setHtml(css + thanksText()); thanksBrowser->viewport()->setAutoFillBackground(false); translationsBrowser->setHtml(css + translationsText()); translationsBrowser->viewport()->setAutoFillBackground(false); TechnicalInfo info; techBrowser->setHtml(info.html()); techBrowser->viewport()->setAutoFillBackground(false); connect(techCopyToClipboardButton, SIGNAL(clicked()), this, SLOT(copyToCliboardTechInfo())); this->setAttribute(Qt::WA_DeleteOnClose); show(); } QString AboutDialogPrivate::titleText() const { return QStringLiteral("<div class=name>%1</div><div class=ver>%2</div>").arg(QStringLiteral("LXQt"), tr("Version: %1").arg(QStringLiteral(LXQT_VERSION))); } QString AboutDialogPrivate::aboutText() const { return QStringLiteral( "<p>%1</p>" "<p>%2</p>" "<p>%3</p>" "<p>%4</p>" "<p>%5</p>") .arg( tr("Advanced, easy-to-use, and fast desktop environment based on Qt technologies.", "About dialog, 'About' tab text"), tr("LXQt would not have been possible without the <a %1>Razor-qt</a> project and its many contributors.", "About dialog, 'About' tab text").arg(QStringLiteral("href=\"https://blog.lxqt.org/2014/11/in-memory-of-razor-qt/\"")), tr("Copyright: © %1-%2 %3", "About dialog, 'About' tab text") .arg(QStringLiteral("2010"), QDate::currentDate().toString(QStringLiteral("yyyy")), QStringLiteral("LXQt team")), tr("Homepage: %1", "About dialog, 'About' tab text") .arg(QStringLiteral("<a href=\"https://lxqt.github.io\">https://lxqt.github.io</a>")), tr("License: %1", "About dialog, 'About' tab text") .arg(QStringLiteral("<a href=\"https://www.gnu.org/licenses/lgpl-2.1.html\">GNU Lesser General Public License version 2.1 or later</a>" " and partly under the " "<a href=\"https://www.gnu.org/licenses/gpl-2.0.html\">GNU General Public License version 2</a>")) ); } QString AboutDialogPrivate::authorsText() const { return QStringLiteral("<p>%1</p><p>%2</p>").arg( tr("LXQt is developed by the <a %1>LXQt Team and contributors</a>.", "About dialog, 'Authors' tab text") .arg(QStringLiteral(" href=\"https://github.com/lxqt/lxqt\"")), tr("If you are interested in working with our development team, <a %1>join us</a>.", "About dialog, 'Authors' tab text") .arg(QStringLiteral("href=\"https://lxqt.github.io\"")) ); } QString AboutDialogPrivate::thanksText() const { return QStringLiteral( "%1" "<ul>" "<li>Alexey Nosov (for the A-MeGo theme)</li>" "<li>Alexander Zakher (the Razor-qt name)</li>" "<li>Andy Fitzsimon (logo/icon)</li>" "<li>Eugene Pivnev (QtDesktop)</li>" "<li>Manuel Meier (for ideas)</li>" "<li>KDE &lt;<a href=\"https://kde.org/\">https://kde.org/</a>&gt;</li>" ).arg(tr("Special thanks to:", "About dialog, 'Thanks' tab text")); } QString AboutDialogPrivate::translationsText() const { TranslatorsInfo translatorsInfo; return QStringLiteral("%1<p><ul>%2</ul>").arg( tr("LXQt is translated into many languages thanks to the work of the translation teams all over the world.", "About dialog, 'Translations' tab text"), translatorsInfo.asHtml() ); } AboutDialog::AboutDialog() { d_ptr = new AboutDialogPrivate(); } void AboutDialogPrivate::copyToCliboardTechInfo() { TechnicalInfo info; QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(info.text()); } <commit_msg>Fixed Razor-qt link<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - The Lightweight Desktop Environment * https://lxqt.org * * Copyright: 2010-2011 Razor team * Authors: * Petr Vanek <petr@scribus.info> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "lxqtaboutdialog.h" #include "ui_lxqtaboutdialog.h" #include "lxqtaboutdialog_p.h" #include "technicalinfo.h" #include "translatorsinfo/translatorsinfo.h" #include <QDebug> #include <QDate> #include <QClipboard> AboutDialogPrivate::AboutDialogPrivate() { setupUi(this); QString css=QStringLiteral("<style TYPE='text/css'> " "body { font-family: sans-serif;} " ".name { font-size: 16pt; } " "a { white-space: nowrap ;} " "h2 { font-size: 10pt;} " "li { line-height: 120%;} " ".techInfoKey { white-space: nowrap ; margin: 0 20px 0 16px; } " "</style>") ; iconLabel->setFixedSize(48, 48); iconLabel->setScaledContents(true); iconLabel->setPixmap(QPixmap(QStringLiteral(LXQT_SHARE_DIR) + QStringLiteral("/graphics/lxqt_logo.png"))); nameLabel->setText(css + titleText()); aboutBrowser->setHtml(css + aboutText()); aboutBrowser->viewport()->setAutoFillBackground(false); autorsBrowser->setHtml(css + authorsText()); autorsBrowser->viewport()->setAutoFillBackground(false); thanksBrowser->setHtml(css + thanksText()); thanksBrowser->viewport()->setAutoFillBackground(false); translationsBrowser->setHtml(css + translationsText()); translationsBrowser->viewport()->setAutoFillBackground(false); TechnicalInfo info; techBrowser->setHtml(info.html()); techBrowser->viewport()->setAutoFillBackground(false); connect(techCopyToClipboardButton, SIGNAL(clicked()), this, SLOT(copyToCliboardTechInfo())); this->setAttribute(Qt::WA_DeleteOnClose); show(); } QString AboutDialogPrivate::titleText() const { return QStringLiteral("<div class=name>%1</div><div class=ver>%2</div>").arg(QStringLiteral("LXQt"), tr("Version: %1").arg(QStringLiteral(LXQT_VERSION))); } QString AboutDialogPrivate::aboutText() const { return QStringLiteral( "<p>%1</p>" "<p>%2</p>" "<p>%3</p>" "<p>%4</p>" "<p>%5</p>") .arg( tr("Advanced, easy-to-use, and fast desktop environment based on Qt technologies.", "About dialog, 'About' tab text"), tr("LXQt would not have been possible without the <a %1>Razor-qt</a> project and its many contributors.", "About dialog, 'About' tab text").arg(QStringLiteral("href=\"https://blog.lxde.org/2014/11/21/in-memory-of-razor-qt/\"")), tr("Copyright: © %1-%2 %3", "About dialog, 'About' tab text") .arg(QStringLiteral("2010"), QDate::currentDate().toString(QStringLiteral("yyyy")), QStringLiteral("LXQt team")), tr("Homepage: %1", "About dialog, 'About' tab text") .arg(QStringLiteral("<a href=\"https://lxqt.github.io\">https://lxqt.github.io</a>")), tr("License: %1", "About dialog, 'About' tab text") .arg(QStringLiteral("<a href=\"https://www.gnu.org/licenses/lgpl-2.1.html\">GNU Lesser General Public License version 2.1 or later</a>" " and partly under the " "<a href=\"https://www.gnu.org/licenses/gpl-2.0.html\">GNU General Public License version 2</a>")) ); } QString AboutDialogPrivate::authorsText() const { return QStringLiteral("<p>%1</p><p>%2</p>").arg( tr("LXQt is developed by the <a %1>LXQt Team and contributors</a>.", "About dialog, 'Authors' tab text") .arg(QStringLiteral(" href=\"https://github.com/lxqt/lxqt\"")), tr("If you are interested in working with our development team, <a %1>join us</a>.", "About dialog, 'Authors' tab text") .arg(QStringLiteral("href=\"https://lxqt.github.io\"")) ); } QString AboutDialogPrivate::thanksText() const { return QStringLiteral( "%1" "<ul>" "<li>Alexey Nosov (for the A-MeGo theme)</li>" "<li>Alexander Zakher (the Razor-qt name)</li>" "<li>Andy Fitzsimon (logo/icon)</li>" "<li>Eugene Pivnev (QtDesktop)</li>" "<li>Manuel Meier (for ideas)</li>" "<li>KDE &lt;<a href=\"https://kde.org/\">https://kde.org/</a>&gt;</li>" ).arg(tr("Special thanks to:", "About dialog, 'Thanks' tab text")); } QString AboutDialogPrivate::translationsText() const { TranslatorsInfo translatorsInfo; return QStringLiteral("%1<p><ul>%2</ul>").arg( tr("LXQt is translated into many languages thanks to the work of the translation teams all over the world.", "About dialog, 'Translations' tab text"), translatorsInfo.asHtml() ); } AboutDialog::AboutDialog() { d_ptr = new AboutDialogPrivate(); } void AboutDialogPrivate::copyToCliboardTechInfo() { TechnicalInfo info; QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(info.text()); } <|endoftext|>
<commit_before>#include "GLFramebuffer.h" #include "GL.h" #include "GLRenderbuffer.h" #include "GLRenderTexture2D.h" #include "GLRenderTexture2DRectangle.h" #include <iostream> #include "GLUtility.h" using namespace std; // ---------------------------------------------------------------------------- // Need to use this factory to create FBOs GLFramebuffer* GLFramebuffer::New(int width, int height) { // Check for framebuffer support if (!GLEW_EXT_framebuffer_object) { // Oops, not supported cerr << "GLFramebuffer: Framebuffer objects not supported!" << endl; return 0; } // Create and return new FBO return new GLFramebuffer(width, height); } // ---------------------------------------------------------------------------- GLFramebuffer::GLFramebuffer(int width, int height) : id(0), width(width), height(height), bound(false) { // Create the framebuffer //cout << "GLFramebuffer: Constructor" << endl; glGenFramebuffersEXT(1, &id); #ifndef NDEBUG GLUtility::CheckOpenGLError("GLFramebuffer: glGenFramebuffersEXT()"); #endif } // ---------------------------------------------------------------------------- GLFramebuffer::~GLFramebuffer() { //cout << "GLFramebuffer: Destructor" << endl; // Delete all attachments for (map<int, GLRendertarget*>::iterator i = attachments.begin(); i != attachments.end(); ) { int attachment = i->first; i++; GLRendertarget *rt = DetachRendertarget(attachment); // Delete the rendertarget if it's no longer attached anywhere if (rt->GetTimesAttached() == 0) delete rt; } // Delete the framebuffer glDeleteFramebuffersEXT(1, &id); #ifndef NDEBUG GLUtility::CheckOpenGLError("GLFramebuffer: glDeleteFramebuffersEXT()"); #endif } // ---------------------------------------------------------------------------- GLRendertarget *GLFramebuffer::AttachRendertarget(int attachment, GLRendertarget *rt) { if (!rt) { return DetachRendertarget(attachment); } else { return AttachRendertarget(attachment, *rt); } } // ---------------------------------------------------------------------------- GLRendertarget *GLFramebuffer::AttachRendertarget(int attachment, GLRendertarget &rt) { if (!bound) Bind(); // Remove the old render target (if any) GLRendertarget *oldRt = DetachRendertarget(attachment); // Attach the new target rt.AttachToBoundFBO(attachment); attachments[attachment] = &rt; // Return the old attachment (or null) return oldRt; } // ---------------------------------------------------------------------------- GLRendertarget* GLFramebuffer::DetachRendertarget(int attachment) { if (!bound) Bind(); // Release the old render target (if any) to the caller and remove it from the map GLRendertarget *rt = 0; map<int, GLRendertarget*>::iterator it = attachments.find(attachment); if (it != attachments.end()) { rt = it->second; rt->DetachFromBoundFBO(attachment); } attachments.erase(attachment); return rt; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateDepthBuffer(int format) { // Abuse the color buffer utility functions return CreateColorBuffer(GL_DEPTH_ATTACHMENT_EXT, format); } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateDepthTexture(int format) { // Abuse the color buffer utility functions return CreateColorTexture(GL_DEPTH_ATTACHMENT_EXT, format, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE); } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateDepthTextureRectangle(int format) { // Abuse the color buffer utility functions return CreateColorTextureRectangle(GL_DEPTH_ATTACHMENT_EXT, format, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE); } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreatePackedDepthStencilBuffer() { if (!GLEW_EXT_packed_depth_stencil) return false; GLRendertarget *dsb = GLRenderbuffer::New(width, height, GL_DEPTH24_STENCIL8_EXT); // Attach as depth buffer GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } // Attach as stencil old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreatePackedDepthStencilTexture() { if (!GLEW_EXT_packed_depth_stencil) return false; if (!GLEW_ARB_depth_texture && !GLEW_SGIX_depth_texture) return false; GLRendertarget *dsb = GLRenderTexture2D::New(width, height, GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT); // Attach as depth buffer GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } // Attach as stencil old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreatePackedDepthStencilTextureRectangle() { if (!GLEW_ARB_texture_rectangle) return false; if (!GLEW_EXT_packed_depth_stencil) return false; if (!GLEW_ARB_depth_texture && !GLEW_SGIX_depth_texture) return false; GLRendertarget *dsb = GLRenderTexture2DRectangle::New(width, height, GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT); // Attach as depth buffer GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } // Attach as stencil old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateColorBuffer(int attachment, int format) { GLRendertarget *buffer = GLRenderbuffer::New( width, height, format); // Attach to target GLRendertarget *old = AttachRendertarget(attachment, *buffer); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateColorTexture(int attachment, int internalformat, int format, int type) { GLRendertarget *buffer = GLRenderTexture2D::New( width, height, internalformat, format, type); // Attach to target GLRendertarget *old = AttachRendertarget(attachment, *buffer); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateColorTextureRectangle(int attachment, int internalformat, int format, int type) { if (!GLEW_ARB_texture_rectangle) return false; GLRendertarget *buffer = GLRenderTexture2DRectangle::New( width, height, internalformat, format, type); // Attach to target GLRendertarget *old = AttachRendertarget(attachment, *buffer); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- void GLFramebuffer::Bind() { if (bound) { cerr << "GLFramebuffer: Bind() called, but framebuffer was already bound" << endl; return; } // Store old viewport glPushAttrib(GL_VIEWPORT_BIT); // Bind FBO glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id); // Set viewport glViewport(0, 0, width, height); bound = true; #ifndef NDEBUG GLUtility::CheckOpenGLError("GLFramebuffer: Bind()"); #endif } // ---------------------------------------------------------------------------- void GLFramebuffer::Unbind() { glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); if (bound) { // Restore viewport glPopAttrib(); } else { cerr << "GLFramebuffer: Unbind() called, but framebuffer was not bound" << endl; } bound = false; #ifndef NDEBUG GLUtility::CheckOpenGLError("GLFramebuffer: Unbind()"); #endif } // ---------------------------------------------------------------------------- int GLFramebuffer::GetStatus() { if (!bound) Bind(); return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); } // ---------------------------------------------------------------------------- bool GLFramebuffer::IsOk() { int status = GetStatus(); switch (status) { case GL_FRAMEBUFFER_COMPLETE_EXT: return true; break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: return false; break; default: //assert(false); // Error in framebuffer code! return false; break; } } // ---------------------------------------------------------------------------- GLTexture* GLFramebuffer::GetTexture2D(int attachment) { // Try to cast, return null if that attachment isn't a rendertarget GLRenderTexture2D *rt = dynamic_cast<GLRenderTexture2D*>(attachments[attachment]); if (!rt) return 0; // Return texture return rt->GetTexture(); } // ---------------------------------------------------------------------------- const GLTexture* GLFramebuffer::GetTexture2D(int attachment) const { // Try to cast, return null if that attachment isn't a rendertarget map<int, GLRendertarget*>::const_iterator atit = attachments.find(attachment); if (atit == attachments.end()) return 0; const GLRenderTexture2D *rt = dynamic_cast<const GLRenderTexture2D*>(atit->second); if (!rt) return 0; // Return texture return rt->GetTexture(); } // ---------------------------------------------------------------------------- bool GLFramebuffer::Resize(int width, int height) { // Resize all attachments for (map<int, GLRendertarget*>::iterator i = attachments.begin(); i != attachments.end(); ) { int attachment = i->first; i++; // We need to detach, because the internal rendertarget might change GLRendertarget *rt = DetachRendertarget(attachment); if (!rt->Resize(width, height)) { cerr << "GLFrameBuffer: Resize failed for attachment " << attachment << endl; delete rt; return false; } // Re-attach the rendertarget AttachRendertarget(attachment, *rt); } // Update framebuffer size this->width = width; this->height = height; // Unbind the framebuffer if bound if (bound) Unbind(); return true; } <commit_msg>Fixed bug where ghost attachments could be created by requesting an invalid attachment's texture.<commit_after>#include "GLFramebuffer.h" #include "GL.h" #include "GLRenderbuffer.h" #include "GLRenderTexture2D.h" #include "GLRenderTexture2DRectangle.h" #include <iostream> #include "GLUtility.h" using namespace std; // ---------------------------------------------------------------------------- // Need to use this factory to create FBOs GLFramebuffer* GLFramebuffer::New(int width, int height) { // Check for framebuffer support if (!GLEW_EXT_framebuffer_object) { // Oops, not supported cerr << "GLFramebuffer: Framebuffer objects not supported!" << endl; return 0; } // Create and return new FBO return new GLFramebuffer(width, height); } // ---------------------------------------------------------------------------- GLFramebuffer::GLFramebuffer(int width, int height) : id(0), width(width), height(height), bound(false) { // Create the framebuffer //cout << "GLFramebuffer: Constructor" << endl; glGenFramebuffersEXT(1, &id); #ifndef NDEBUG GLUtility::CheckOpenGLError("GLFramebuffer: glGenFramebuffersEXT()"); #endif } // ---------------------------------------------------------------------------- GLFramebuffer::~GLFramebuffer() { //cout << "GLFramebuffer: Destructor" << endl; // Delete all attachments for (map<int, GLRendertarget*>::iterator i = attachments.begin(); i != attachments.end(); ) { int attachment = i->first; i++; GLRendertarget *rt = DetachRendertarget(attachment); // Delete the rendertarget if it's no longer attached anywhere if (rt->GetTimesAttached() == 0) delete rt; } // Delete the framebuffer glDeleteFramebuffersEXT(1, &id); #ifndef NDEBUG GLUtility::CheckOpenGLError("GLFramebuffer: glDeleteFramebuffersEXT()"); #endif } // ---------------------------------------------------------------------------- GLRendertarget *GLFramebuffer::AttachRendertarget(int attachment, GLRendertarget *rt) { if (!rt) { return DetachRendertarget(attachment); } else { return AttachRendertarget(attachment, *rt); } } // ---------------------------------------------------------------------------- GLRendertarget *GLFramebuffer::AttachRendertarget(int attachment, GLRendertarget &rt) { if (!bound) Bind(); // Remove the old render target (if any) GLRendertarget *oldRt = DetachRendertarget(attachment); // Attach the new target rt.AttachToBoundFBO(attachment); attachments[attachment] = &rt; // Return the old attachment (or null) return oldRt; } // ---------------------------------------------------------------------------- GLRendertarget* GLFramebuffer::DetachRendertarget(int attachment) { if (!bound) Bind(); // Release the old render target (if any) to the caller and remove it from the map GLRendertarget *rt = 0; map<int, GLRendertarget*>::iterator it = attachments.find(attachment); if (it != attachments.end()) { rt = it->second; rt->DetachFromBoundFBO(attachment); } attachments.erase(attachment); return rt; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateDepthBuffer(int format) { // Abuse the color buffer utility functions return CreateColorBuffer(GL_DEPTH_ATTACHMENT_EXT, format); } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateDepthTexture(int format) { // Abuse the color buffer utility functions return CreateColorTexture(GL_DEPTH_ATTACHMENT_EXT, format, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE); } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateDepthTextureRectangle(int format) { // Abuse the color buffer utility functions return CreateColorTextureRectangle(GL_DEPTH_ATTACHMENT_EXT, format, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE); } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreatePackedDepthStencilBuffer() { if (!GLEW_EXT_packed_depth_stencil) return false; GLRendertarget *dsb = GLRenderbuffer::New(width, height, GL_DEPTH24_STENCIL8_EXT); // Attach as depth buffer GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } // Attach as stencil old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreatePackedDepthStencilTexture() { if (!GLEW_EXT_packed_depth_stencil) return false; if (!GLEW_ARB_depth_texture && !GLEW_SGIX_depth_texture) return false; GLRendertarget *dsb = GLRenderTexture2D::New(width, height, GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT); // Attach as depth buffer GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } // Attach as stencil old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreatePackedDepthStencilTextureRectangle() { if (!GLEW_ARB_texture_rectangle) return false; if (!GLEW_EXT_packed_depth_stencil) return false; if (!GLEW_ARB_depth_texture && !GLEW_SGIX_depth_texture) return false; GLRendertarget *dsb = GLRenderTexture2DRectangle::New(width, height, GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT); // Attach as depth buffer GLRendertarget *old = AttachRendertarget(GL_DEPTH_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } // Attach as stencil old = AttachRendertarget(GL_STENCIL_ATTACHMENT_EXT, *dsb); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateColorBuffer(int attachment, int format) { GLRendertarget *buffer = GLRenderbuffer::New( width, height, format); // Attach to target GLRendertarget *old = AttachRendertarget(attachment, *buffer); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateColorTexture(int attachment, int internalformat, int format, int type) { GLRendertarget *buffer = GLRenderTexture2D::New( width, height, internalformat, format, type); // Attach to target GLRendertarget *old = AttachRendertarget(attachment, *buffer); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- bool GLFramebuffer::CreateColorTextureRectangle(int attachment, int internalformat, int format, int type) { if (!GLEW_ARB_texture_rectangle) return false; GLRendertarget *buffer = GLRenderTexture2DRectangle::New( width, height, internalformat, format, type); // Attach to target GLRendertarget *old = AttachRendertarget(attachment, *buffer); if (old) { if (old->GetTimesAttached() == 0) delete old; } return true; } // ---------------------------------------------------------------------------- void GLFramebuffer::Bind() { if (bound) { cerr << "GLFramebuffer: Bind() called, but framebuffer was already bound" << endl; return; } // Store old viewport glPushAttrib(GL_VIEWPORT_BIT); // Bind FBO glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id); // Set viewport glViewport(0, 0, width, height); bound = true; #ifndef NDEBUG GLUtility::CheckOpenGLError("GLFramebuffer: Bind()"); #endif } // ---------------------------------------------------------------------------- void GLFramebuffer::Unbind() { glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); if (bound) { // Restore viewport glPopAttrib(); } else { cerr << "GLFramebuffer: Unbind() called, but framebuffer was not bound" << endl; } bound = false; #ifndef NDEBUG GLUtility::CheckOpenGLError("GLFramebuffer: Unbind()"); #endif } // ---------------------------------------------------------------------------- int GLFramebuffer::GetStatus() { if (!bound) Bind(); return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); } // ---------------------------------------------------------------------------- bool GLFramebuffer::IsOk() { int status = GetStatus(); switch (status) { case GL_FRAMEBUFFER_COMPLETE_EXT: return true; break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: return false; break; default: //assert(false); // Error in framebuffer code! return false; break; } } // ---------------------------------------------------------------------------- GLTexture* GLFramebuffer::GetTexture2D(int attachment) { // Look up the texture, return 0 if nothing's attached map<int, GLRendertarget*>::iterator atit = attachments.find(attachment); if (atit == attachments.end()) return 0; GLRenderTexture2D *rt = dynamic_cast<GLRenderTexture2D*>(atit->second); if (!rt) return 0; // Return texture return rt->GetTexture(); } // ---------------------------------------------------------------------------- const GLTexture* GLFramebuffer::GetTexture2D(int attachment) const { // Look up the texture, return 0 if nothing's attached map<int, GLRendertarget*>::const_iterator atit = attachments.find(attachment); if (atit == attachments.end()) return 0; const GLRenderTexture2D *rt = dynamic_cast<const GLRenderTexture2D*>(atit->second); if (!rt) return 0; // Return texture return rt->GetTexture(); } // ---------------------------------------------------------------------------- bool GLFramebuffer::Resize(int width, int height) { // Resize all attachments for (map<int, GLRendertarget*>::iterator i = attachments.begin(); i != attachments.end(); ) { int attachment = i->first; i++; // We need to detach, because the internal rendertarget might change GLRendertarget *rt = DetachRendertarget(attachment); if (!rt->Resize(width, height)) { cerr << "GLFrameBuffer: Resize failed for attachment " << attachment << endl; delete rt; return false; } // Re-attach the rendertarget AttachRendertarget(attachment, *rt); } // Update framebuffer size this->width = width; this->height = height; // Unbind the framebuffer if bound if (bound) Unbind(); return true; } <|endoftext|>
<commit_before> #include <NdbApi.hpp> #include <NdbOut.hpp> #include <NdbTick.h> struct S_Scan { const char * m_table; const char * m_index; NdbIndexScanOperation * m_scan; NdbResultSet * m_result; Uint32 metaid; Uint32 match_count; Uint32 row_count; }; static S_Scan g_scans[] = { { "affiliatestometa", "ind_affiliatestometa", 0, 0, 0, 0, 0 }, { "media", "metaid", 0, 0, 0, 0, 0 }, { "meta", "PRIMARY", 0, 0, 0, 0, 0 }, { "artiststometamap", "PRIMARY", 0, 0, 0, 0, 0 }, { "subgenrestometamap", "metaid", 0, 0, 0, 0, 0 } }; #define require(x) if(!(x)) { ndbout << "LINE: " << __LINE__ << endl;abort(); } #define require2(o, x) if(!(x)) { ndbout << o->getNdbError() << endl; abort(); } Uint32 g_affiliateid = 2; Uint32 g_formatids[] = { 8, 31, 76 }; Uint64 start; Uint32 g_artistid = 0; Uint32 g_subgenreid = 0; NdbConnection* g_trans = 0; static void lookup(); int main(void){ Ndb g_ndb("test"); g_ndb.init(1024); require(g_ndb.waitUntilReady() == 0); g_trans = g_ndb.startTransaction(); require(g_trans); size_t i, j; const size_t cnt = sizeof(g_scans)/sizeof(g_scans[0]); start = NdbTick_CurrentMillisecond(); for(i = 0; i<cnt; i++){ ndbout_c("starting scan on: %s %s", g_scans[i].m_table, g_scans[i].m_index); g_scans[i].m_scan = g_trans->getNdbIndexScanOperation(g_scans[i].m_index, g_scans[i].m_table); NdbIndexScanOperation* scan = g_scans[i].m_scan; require(scan); g_scans[i].m_result = scan->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0, true); require(g_scans[i].m_result); } require(!g_scans[0].m_scan->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, &g_affiliateid, sizeof(g_affiliateid))); #if 0 require(!g_scans[1].m_scan->setBound((Uint32)0, NdbIndexScanOperation::BoundLE, &g_formatids[0], sizeof(g_formatids[0]))); #endif NdbScanFilter sf(g_scans[1].m_scan); sf.begin(NdbScanFilter::OR); sf.eq(2, g_formatids[0]); sf.eq(2, g_formatids[1]); sf.eq(2, g_formatids[2]); sf.end(); // affiliatestometa require(g_scans[0].m_scan->getValue("uniquekey")); require(g_scans[0].m_scan->getValue("xml")); // media require(g_scans[1].m_scan->getValue("path")); require(g_scans[1].m_scan->getValue("mediaid")); require(g_scans[1].m_scan->getValue("formatid")); // meta require(g_scans[2].m_scan->getValue("name")); require(g_scans[2].m_scan->getValue("xml")); // artiststometamap require(g_scans[3].m_scan->getValue("artistid", (char*)&g_artistid)); // subgenrestometamap require(g_scans[4].m_scan->getValue("subgenreid", (char*)&g_subgenreid)); for(i = 0; i<cnt; i++){ g_scans[i].m_scan->getValue("metaid", (char*)&g_scans[i].metaid); } g_trans->execute(NoCommit, AbortOnError, 1); Uint32 max_val = 0; Uint32 match_val = 0; S_Scan * F [5], * Q [5], * nextF [5]; Uint32 F_sz = 0, Q_sz = 0; for(i = 0; i<cnt; i++){ F_sz++; F[i] = &g_scans[i]; } Uint32 match_count = 0; while(F_sz > 0){ Uint32 prev_F_sz = F_sz; F_sz = 0; bool found = false; //for(i = 0; i<cnt; i++) //ndbout_c("%s - %d", g_scans[i].m_table, g_scans[i].metaid); for(i = 0; i<prev_F_sz; i++){ int res = F[i]->m_result->nextResult(); if(res == -1) abort(); if(res == 1){ continue; } Uint32 metaid = F[i]->metaid; F[i]->row_count++; if(metaid == match_val){ //ndbout_c("flera"); nextF[F_sz++] = F[i]; require(F_sz >= 0 && F_sz <= cnt); F[i]->match_count++; Uint32 comb = 1; for(j = 0; j<cnt; j++){ comb *= (&g_scans[j] == F[i] ? 1 : g_scans[j].match_count); } match_count += comb; found = true; continue; } if(metaid < max_val){ nextF[F_sz++] = F[i]; require(F_sz >= 0 && F_sz <= cnt); continue; } if(metaid > max_val){ for(j = 0; j<Q_sz; j++) nextF[F_sz++] = Q[j]; require(F_sz >= 0 && F_sz <= cnt); Q_sz = 0; max_val = metaid; } Q[Q_sz++] = F[i]; require(Q_sz >= 0 && Q_sz <= cnt); } if(F_sz == 0 && Q_sz > 0){ match_val = max_val; for(j = 0; j<Q_sz; j++){ nextF[F_sz++] = Q[j]; Q[j]->match_count = 1; } require(F_sz >= 0 && F_sz <= cnt); require(Q_sz >= 0 && Q_sz <= cnt); Q_sz = 0; match_count++; lookup(); } else if(!found && F_sz + Q_sz < cnt){ F_sz = 0; } require(F_sz >= 0 && F_sz <= cnt); for(i = 0; i<F_sz; i++) F[i] = nextF[i]; } start = NdbTick_CurrentMillisecond() - start; ndbout_c("Elapsed: %lldms", start); ndbout_c("rows: %d", match_count); for(i = 0; i<cnt; i++){ ndbout_c("%s : %d", g_scans[i].m_table, g_scans[i].row_count); } } static void lookup(){ { NdbOperation* op = g_trans->getNdbOperation("artists"); require2(g_trans, op); require2(op, op->readTuple() == 0); require2(op, op->equal("artistid", g_artistid) == 0); require2(op, op->getValue("name")); } { NdbOperation* op = g_trans->getNdbOperation("subgenres"); require2(g_trans, op); require2(op, op->readTuple() == 0); require2(op, op->equal("subgenreid", g_subgenreid) == 0); require2(op, op->getValue("name")); } static int loop = 0; if(loop++ >= 16){ loop = 0; require(g_trans->execute(NoCommit) == 0); } //require(g_trans->restart() == 0); } <commit_msg>run in loop<commit_after> #include <NdbApi.hpp> #include <NdbOut.hpp> #include <NdbTick.h> struct S_Scan { const char * m_table; const char * m_index; NdbIndexScanOperation * m_scan; NdbResultSet * m_result; Uint32 metaid; Uint32 match_count; Uint32 row_count; }; static S_Scan g_scans[] = { { "affiliatestometa", "ind_affiliatestometa", 0, 0, 0, 0, 0 }, { "media", "metaid", 0, 0, 0, 0, 0 }, { "meta", "PRIMARY", 0, 0, 0, 0, 0 }, { "artiststometamap", "PRIMARY", 0, 0, 0, 0, 0 }, { "subgenrestometamap", "metaid", 0, 0, 0, 0, 0 } }; #define require(x) if(!(x)) { ndbout << "LINE: " << __LINE__ << endl;abort(); } #define require2(o, x) if(!(x)) { ndbout << o->getNdbError() << endl; abort(); } Uint32 g_affiliateid = 2; Uint32 g_formatids[] = { 8, 31, 76 }; Uint64 start; Uint32 g_artistid = 0; Uint32 g_subgenreid = 0; NdbConnection* g_trans = 0; static void lookup(); int main(void){ Ndb g_ndb("test"); g_ndb.init(1024); require(g_ndb.waitUntilReady() == 0); while(true){ g_trans = g_ndb.startTransaction(); require(g_trans); size_t i, j; const size_t cnt = sizeof(g_scans)/sizeof(g_scans[0]); start = NdbTick_CurrentMillisecond(); for(i = 0; i<cnt; i++){ ndbout_c("starting scan on: %s %s", g_scans[i].m_table, g_scans[i].m_index); g_scans[i].m_scan = g_trans->getNdbIndexScanOperation(g_scans[i].m_index, g_scans[i].m_table); NdbIndexScanOperation* scan = g_scans[i].m_scan; require(scan); g_scans[i].m_result = scan->readTuples(NdbScanOperation::LM_CommittedRead, 0, 0, true); require(g_scans[i].m_result); } require(!g_scans[0].m_scan->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, &g_affiliateid, sizeof(g_affiliateid))); #if 0 require(!g_scans[1].m_scan->setBound((Uint32)0, NdbIndexScanOperation::BoundLE, &g_formatids[0], sizeof(g_formatids[0]))); #endif NdbScanFilter sf(g_scans[1].m_scan); sf.begin(NdbScanFilter::OR); sf.eq(2, g_formatids[0]); sf.eq(2, g_formatids[1]); sf.eq(2, g_formatids[2]); sf.end(); // affiliatestometa require(g_scans[0].m_scan->getValue("uniquekey")); require(g_scans[0].m_scan->getValue("xml")); // media require(g_scans[1].m_scan->getValue("path")); require(g_scans[1].m_scan->getValue("mediaid")); require(g_scans[1].m_scan->getValue("formatid")); // meta require(g_scans[2].m_scan->getValue("name")); require(g_scans[2].m_scan->getValue("xml")); // artiststometamap require(g_scans[3].m_scan->getValue("artistid", (char*)&g_artistid)); // subgenrestometamap require(g_scans[4].m_scan->getValue("subgenreid", (char*)&g_subgenreid)); for(i = 0; i<cnt; i++){ g_scans[i].m_scan->getValue("metaid", (char*)&g_scans[i].metaid); } g_trans->execute(NoCommit, AbortOnError, 1); Uint32 max_val = 0; Uint32 match_val = 0; S_Scan * F [5], * Q [5], * nextF [5]; Uint32 F_sz = 0, Q_sz = 0; for(i = 0; i<cnt; i++){ F_sz++; F[i] = &g_scans[i]; } Uint32 match_count = 0; while(F_sz > 0){ Uint32 prev_F_sz = F_sz; F_sz = 0; bool found = false; //for(i = 0; i<cnt; i++) //ndbout_c("%s - %d", g_scans[i].m_table, g_scans[i].metaid); for(i = 0; i<prev_F_sz; i++){ int res = F[i]->m_result->nextResult(); if(res == -1) abort(); if(res == 1){ continue; } Uint32 metaid = F[i]->metaid; F[i]->row_count++; if(metaid == match_val){ //ndbout_c("flera"); nextF[F_sz++] = F[i]; require(F_sz >= 0 && F_sz <= cnt); F[i]->match_count++; Uint32 comb = 1; for(j = 0; j<cnt; j++){ comb *= (&g_scans[j] == F[i] ? 1 : g_scans[j].match_count); } match_count += comb; found = true; continue; } if(metaid < max_val){ nextF[F_sz++] = F[i]; require(F_sz >= 0 && F_sz <= cnt); continue; } if(metaid > max_val){ for(j = 0; j<Q_sz; j++) nextF[F_sz++] = Q[j]; require(F_sz >= 0 && F_sz <= cnt); Q_sz = 0; max_val = metaid; } Q[Q_sz++] = F[i]; require(Q_sz >= 0 && Q_sz <= cnt); } if(F_sz == 0 && Q_sz > 0){ match_val = max_val; for(j = 0; j<Q_sz; j++){ nextF[F_sz++] = Q[j]; Q[j]->match_count = 1; } require(F_sz >= 0 && F_sz <= cnt); require(Q_sz >= 0 && Q_sz <= cnt); Q_sz = 0; match_count++; lookup(); } else if(!found && F_sz + Q_sz < cnt){ F_sz = 0; } require(F_sz >= 0 && F_sz <= cnt); for(i = 0; i<F_sz; i++) F[i] = nextF[i]; } start = NdbTick_CurrentMillisecond() - start; ndbout_c("Elapsed: %lldms", start); ndbout_c("rows: %d", match_count); for(i = 0; i<cnt; i++){ ndbout_c("%s : %d", g_scans[i].m_table, g_scans[i].row_count); } g_trans->close(); } } static void lookup(){ { NdbOperation* op = g_trans->getNdbOperation("artists"); require2(g_trans, op); require2(op, op->readTuple() == 0); require2(op, op->equal("artistid", g_artistid) == 0); require2(op, op->getValue("name")); } { NdbOperation* op = g_trans->getNdbOperation("subgenres"); require2(g_trans, op); require2(op, op->readTuple() == 0); require2(op, op->equal("subgenreid", g_subgenreid) == 0); require2(op, op->getValue("name")); } static int loop = 0; if(loop++ >= 16){ loop = 0; require(g_trans->execute(NoCommit) == 0); } //require(g_trans->restart() == 0); } <|endoftext|>
<commit_before>/* $Id$ */ /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Eclipse Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin ad_input.cpp$$ $spell Cpp cstddef $$ $section AD Output Operator: Example and Test$$ $index <<, AD example$$ $index input, AD example$$ $index example, AD input$$ $index test, AD input$$ $code $verbatim%example/ad_input.cpp%0%// BEGIN C++%// END C++%1%$$ $$ $end */ // BEGIN C++ # include <cppad/cppad.hpp> # include <sstream> // std::istringstream # include <string> // std::string bool ad_input(void) { bool ok = true; std::string str ("123 456"); std::istringstream is(str); CppAD::AD<double> x(1.), y(2.); is >> x >> y; ok &= (x == 123.); ok &= (y == 456.); return ok; } // END C++ <commit_msg>ad_input.cpp: Show, by example, result of input is a parameter.<commit_after>/* $Id$ */ /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Eclipse Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin ad_input.cpp$$ $spell Cpp cstddef $$ $section AD Output Operator: Example and Test$$ $index <<, AD example$$ $index input, AD example$$ $index example, AD input$$ $index test, AD input$$ $code $verbatim%example/ad_input.cpp%0%// BEGIN C++%// END C++%1%$$ $$ $end */ // BEGIN C++ # include <cppad/cppad.hpp> # include <sstream> // std::istringstream # include <string> // std::string bool ad_input(void) { bool ok = true; // create the input string stream is. std::string str ("123 456"); std::istringstream is(str); // start and AD<double> recording CPPAD_TESTVECTOR( CppAD::AD<double> ) x(1), y(1); x[0] = 1.0; CppAD::Independent(x); CppAD::AD<double> z = x[0]; ok &= Variable(z); // read first number into z and second into y[0] is >> z >> y[0]; ok &= Parameter(z); ok &= (z == 123.); ok &= Parameter(y[0]); ok &= (y[0] == 456.); // // terminate recording starting by call to Independent CppAD::ADFun<double> f(x, y); return ok; } // END C++ <|endoftext|>
<commit_before>#pragma once // Project specific #include <AudioHandler.hpp> #include <Doremi/Core/Include/InputHandler.hpp> #include <Doremi/Core/Include/InputHandlerClient.hpp> #include <DoremiEngine/Physics/Include/PhysicsModule.hpp> #include <DoremiEngine/Physics/Include/RigidBodyManager.hpp> //#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp> #include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp> #include <EntityComponent/EntityHandler.hpp> #include <DoremiEngine/Audio/Include/AudioModule.hpp> #include <iostream> #include <PlayerHandler.hpp> #include <FrequencyBufferHandler.hpp> // Events #include <EventHandler/EventHandler.hpp> #include <EventHandler/Events/ChangeMenuState.hpp> // Logging #include <DoremiEngine/Logging/Include/LoggingModule.hpp> #include <DoremiEngine/Logging/Include/SubmoduleManager.hpp> #include <DoremiEngine/Logging/Include/Logger/Logger.hpp> // Timing #include <DoremiEngine/Timing/Include/Measurement/TimeMeasurementManager.hpp> namespace Doremi { namespace Core { AudioHandler::AudioHandler(const DoremiEngine::Core::SharedContext& p_sharedContext) : m_sharedContext(p_sharedContext), m_logger(nullptr) { m_logger = &m_sharedContext.GetLoggingModule().GetSubModuleManager().GetLogger(); m_currentFrequency = 0; /* 99999 is a default "error" value. It is used to create a new channel in module. We send the channelID to the module and if it is 99999 it is treated as uninitialized This has been fixed. 999999 is now -1 and starts a new channel that is returned to the variable.*/ m_continuousFrequencyAnalyserChannelID = -1; m_continuousFrequencyAnalyserSoundID = 0; m_repeatableFrequencyAnalyserChannelID = -1; m_repeatableFrequencyAnalyserSoundID = 0; m_outputRepeatableSoundChannelID = -1; m_outputRepeatableSoundID = 0; m_accumulatedDeltaTime = 0; m_repeatableAnalysisComplete = false; m_frequencyVectorPrecision = 0.01f; m_timeGunReloadButtonWasPressed = 0.0f; // Load the background sounds m_backgroundSounds[BackgroundSound::InGameMainTheme] = m_sharedContext.GetAudioModule().LoadSound("Sounds/BackgroundGame.wav", 0.5, 5000); EventHandler::GetInstance()->Subscribe(EventType::ChangeMenuState, this); } AudioHandler::~AudioHandler() { // Do not delete m_logger, internally handled by loggingmodule } void AudioHandler::StartAudioHandler(const DoremiEngine::Core::SharedContext& p_sharedContext) { if(m_singleton == nullptr) { m_singleton = new AudioHandler(p_sharedContext); } } void AudioHandler::StopAudioHandler() { delete m_singleton; m_singleton = nullptr; } void AudioHandler::Initialize() {} AudioHandler* AudioHandler::m_singleton = nullptr; AudioHandler* AudioHandler::GetInstance() { return m_singleton; } void AudioHandler::SetGunButtonDownTime(double p_time) { m_timeGunReloadButtonWasPressed = p_time; } void AudioHandler::SetupContinuousRecording() { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); m_continuousFrequencyAnalyserSoundID = t_audioModule.SetupRecording(true); } void AudioHandler::SetupRepeatableRecording() { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); m_repeatableFrequencyAnalyserSoundID = t_audioModule.SetupRecording(false); } void AudioHandler::StartContinuousRecording() { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); t_audioModule.StopRecording(); t_audioModule.StartRecording(m_continuousFrequencyAnalyserSoundID, true); m_SoundState = HOLDCONTINUOUSANALYSIS; } void AudioHandler::StartRepeatableRecording() { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); t_audioModule.StopRecording(); m_currentFrequency = 0; t_audioModule.StartRecording(m_repeatableFrequencyAnalyserSoundID, false); /**TODOLH Behvs stop start recording?*/ // t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, // 0.0f); /**TODOLH Detta setvolume p recordkanalernas playback knns inte optimalt. Revisit maybe*/ m_SoundState = HOLDREPEATABLEANALYSIS; m_repeatableAnalysisComplete = false; } float AudioHandler::GetRepeatableSoundFrequency() { TIME_FUNCTION_START // Make sure that the analysis is complete otherwise m_frequencies wont be filled and we can get index out of range if(m_repeatableAnalysisComplete) { // Get the audiomodule DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); // check how far into the sound that the repeatable sound is in milliseconds double t_timeElapsed = t_audioModule.GetSoundTimePointer(m_outputRepeatableSoundChannelID); // Get the full lenght of the sound in milliseconds double t_soundLength = t_audioModule.GetSoundLength(m_outputRepeatableSoundID); // Calculate how far into the sound that the pointer is. Percentual double t_percentualPosition = t_timeElapsed / t_soundLength; // Get the full range of the vector double t_size = static_cast<double>(m_frequencies.size() - 1); // Calculate where in the array we should access the frequency int arrayPosition = static_cast<int>(t_size * t_percentualPosition); // Get the frequency float retValue = m_frequencies[arrayPosition]; TIME_FUNCTION_STOP return retValue; } else { TIME_FUNCTION_STOP return 0; } } void AudioHandler::PlayRepeatableRecordedSound() { // This is a dangerous function since soundID starts at 0. If there is no sound on 0 we will crash if(m_SoundState != HOLDREPEATABLEANALYSIS && m_SoundState != ANALYSEREPEATABLE) { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); t_audioModule.PlayASound(m_outputRepeatableSoundID, false, m_outputRepeatableSoundChannelID); } } void AudioHandler::Update(double p_deltaTime) { TIME_FUNCTION_START unsigned int recordPointer; DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); switch(m_SoundState) { case Doremi::Core::AudioHandler::ANALYSECONTINUOUS: m_currentFrequency = t_audioModule.AnalyseSoundSpectrum(m_continuousFrequencyAnalyserChannelID); break; case Doremi::Core::AudioHandler::HOLDCONTINUOUSANALYSIS: recordPointer = t_audioModule.GetRecordPointer(); // kollar s att vi har spelat in en bit innan vi startar analysen. Om man startar analysen Dirr buggar det ut. if(recordPointer > 9600) { m_SoundState = ANALYSECONTINUOUS; // Default vrde som inte kan anvndas. I komponenterna stts det i defaultkontruktorn. if(m_continuousFrequencyAnalyserChannelID != -1) { /** TODOLH Behvs nog uppdatera ljudposition till listener position. */ t_audioModule.PlaySoundOnSpecificChannel(m_continuousFrequencyAnalyserSoundID, true, m_continuousFrequencyAnalyserChannelID); t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 0.0f); } else { t_audioModule.PlayASound(m_continuousFrequencyAnalyserSoundID, true, m_continuousFrequencyAnalyserChannelID); t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 0.0f); } t_audioModule.SetPriority(m_continuousFrequencyAnalyserChannelID, 0); /** TODOLH osker p om detta behvs. Tydligen kan det bli s att fmod snor kanaler. Men d tar den kanaler som har lg prio*/ } break; case Doremi::Core::AudioHandler::ANALYSEREPEATABLE: recordPointer = t_audioModule.GetRecordPointer(); // Kolla om ljudet r "klart" isfall verg till andra inspelingssttet. if(!t_audioModule.IsRecording()) { m_SoundState = HOLDCONTINUOUSANALYSIS; m_repeatableAnalysisComplete = true; t_audioModule.StopRecording(); t_audioModule.StartRecording(m_continuousFrequencyAnalyserSoundID, true); t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 1.0f); m_outputRepeatableSoundID = t_audioModule.CopySound(m_repeatableFrequencyAnalyserSoundID, m_outputRepeatableSoundID, m_timeGunReloadButtonWasPressed); t_audioModule.PlayASound(m_outputRepeatableSoundID, false, m_outputRepeatableSoundChannelID); t_audioModule.SetVolumeOnChannel(m_outputRepeatableSoundChannelID, 0); } else { // Fixa in i array fr att anvndas med beamen senare! m_accumulatedDeltaTime += p_deltaTime; if(m_accumulatedDeltaTime > m_frequencyVectorPrecision) { m_accumulatedDeltaTime = 0; /// Ta tidsintervallet multiplicera med m_frequencyVectorPrecision ta det arrayvrdet!! m_frequencies.push_back(t_audioModule.AnalyseSoundSpectrum(m_repeatableFrequencyAnalyserChannelID)); } else { // do nothing } } break; case Doremi::Core::AudioHandler::HOLDREPEATABLEANALYSIS: recordPointer = t_audioModule.GetRecordPointer(); // kollar s att vi har spelat in en bit innan vi startar analysen. Om man startar analysen Dirr buggar det ut. TODOLH Definea // 9600 kanske? if(recordPointer > 9600) { m_SoundState = ANALYSEREPEATABLE; m_frequencies.clear(); t_audioModule.PlayASound(m_repeatableFrequencyAnalyserSoundID, false, m_repeatableFrequencyAnalyserChannelID); t_audioModule.SetVolumeOnChannel(m_repeatableFrequencyAnalyserChannelID, 0.0f); t_audioModule.SetPriority(m_repeatableFrequencyAnalyserChannelID, 1); } break; default: break; } InputHandlerClient* inputHandler = (InputHandlerClient*)PlayerHandler::GetInstance()->GetDefaultInputHandler(); if(inputHandler != nullptr) { if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency0)) { m_currentFrequency = 0; } else if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency500)) { m_currentFrequency = 500; } else if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency1000)) { m_currentFrequency = 1000; } } // Send frequence to buffer FrequencyBufferHandler* freqBufferHandler = PlayerHandler::GetInstance()->GetDefaultFrequencyBufferHandler(); if(freqBufferHandler != nullptr) { freqBufferHandler->BufferFrequency(m_currentFrequency); using namespace Doremi::Utilities::Logging; m_logger->DebugLog(LogTag::AUDIO, LogLevel::MASS_DATA_PRINT, "F, %f", m_currentFrequency); } TIME_FUNCTION_STOP } void AudioHandler::OnEvent(Event* p_event) { if(p_event->eventType == EventType::ChangeMenuState) { ChangeMenuState* t_stateEvent = static_cast<ChangeMenuState*>(p_event); if(t_stateEvent->state == DoremiStates::RUNGAME) { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); t_audioModule.PlayASound(m_backgroundSounds[BackgroundSound::InGameMainTheme], true, m_backgroundChannelId); } } } } } <commit_msg>Error check on map<commit_after>#pragma once // Project specific #include <AudioHandler.hpp> #include <Doremi/Core/Include/InputHandler.hpp> #include <Doremi/Core/Include/InputHandlerClient.hpp> #include <DoremiEngine/Physics/Include/PhysicsModule.hpp> #include <DoremiEngine/Physics/Include/RigidBodyManager.hpp> //#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp> #include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp> #include <EntityComponent/EntityHandler.hpp> #include <DoremiEngine/Audio/Include/AudioModule.hpp> #include <iostream> #include <PlayerHandler.hpp> #include <FrequencyBufferHandler.hpp> // Events #include <EventHandler/EventHandler.hpp> #include <EventHandler/Events/ChangeMenuState.hpp> // Logging #include <DoremiEngine/Logging/Include/LoggingModule.hpp> #include <DoremiEngine/Logging/Include/SubmoduleManager.hpp> #include <DoremiEngine/Logging/Include/Logger/Logger.hpp> // Timing #include <DoremiEngine/Timing/Include/Measurement/TimeMeasurementManager.hpp> namespace Doremi { namespace Core { AudioHandler::AudioHandler(const DoremiEngine::Core::SharedContext& p_sharedContext) : m_sharedContext(p_sharedContext), m_logger(nullptr) { m_logger = &m_sharedContext.GetLoggingModule().GetSubModuleManager().GetLogger(); m_currentFrequency = 0; /* 99999 is a default "error" value. It is used to create a new channel in module. We send the channelID to the module and if it is 99999 it is treated as uninitialized This has been fixed. 999999 is now -1 and starts a new channel that is returned to the variable.*/ m_continuousFrequencyAnalyserChannelID = -1; m_continuousFrequencyAnalyserSoundID = 0; m_repeatableFrequencyAnalyserChannelID = -1; m_repeatableFrequencyAnalyserSoundID = 0; m_outputRepeatableSoundChannelID = -1; m_outputRepeatableSoundID = 0; m_accumulatedDeltaTime = 0; m_repeatableAnalysisComplete = false; m_frequencyVectorPrecision = 0.01f; m_timeGunReloadButtonWasPressed = 0.0f; // Load the background sounds m_backgroundSounds[BackgroundSound::InGameMainTheme] = m_sharedContext.GetAudioModule().LoadSound("Sounds/BackgroundGame.wav", 0.5, 5000); EventHandler::GetInstance()->Subscribe(EventType::ChangeMenuState, this); } AudioHandler::~AudioHandler() { // Do not delete m_logger, internally handled by loggingmodule } void AudioHandler::StartAudioHandler(const DoremiEngine::Core::SharedContext& p_sharedContext) { if(m_singleton == nullptr) { m_singleton = new AudioHandler(p_sharedContext); } } void AudioHandler::StopAudioHandler() { delete m_singleton; m_singleton = nullptr; } void AudioHandler::Initialize() {} AudioHandler* AudioHandler::m_singleton = nullptr; AudioHandler* AudioHandler::GetInstance() { return m_singleton; } void AudioHandler::SetGunButtonDownTime(double p_time) { m_timeGunReloadButtonWasPressed = p_time; } void AudioHandler::SetupContinuousRecording() { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); m_continuousFrequencyAnalyserSoundID = t_audioModule.SetupRecording(true); } void AudioHandler::SetupRepeatableRecording() { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); m_repeatableFrequencyAnalyserSoundID = t_audioModule.SetupRecording(false); } void AudioHandler::StartContinuousRecording() { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); t_audioModule.StopRecording(); t_audioModule.StartRecording(m_continuousFrequencyAnalyserSoundID, true); m_SoundState = HOLDCONTINUOUSANALYSIS; } void AudioHandler::StartRepeatableRecording() { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); t_audioModule.StopRecording(); m_currentFrequency = 0; t_audioModule.StartRecording(m_repeatableFrequencyAnalyserSoundID, false); /**TODOLH Behvs stop start recording?*/ // t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, // 0.0f); /**TODOLH Detta setvolume p recordkanalernas playback knns inte optimalt. Revisit maybe*/ m_SoundState = HOLDREPEATABLEANALYSIS; m_repeatableAnalysisComplete = false; } float AudioHandler::GetRepeatableSoundFrequency() { TIME_FUNCTION_START // Make sure that the analysis is complete otherwise m_frequencies wont be filled and we can get index out of range if(m_repeatableAnalysisComplete) { // Get the audiomodule DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); // check how far into the sound that the repeatable sound is in milliseconds double t_timeElapsed = t_audioModule.GetSoundTimePointer(m_outputRepeatableSoundChannelID); // Get the full lenght of the sound in milliseconds double t_soundLength = t_audioModule.GetSoundLength(m_outputRepeatableSoundID); // Calculate how far into the sound that the pointer is. Percentual double t_percentualPosition = t_timeElapsed / t_soundLength; // Get the full range of the vector double t_size = static_cast<double>(m_frequencies.size() - 1); // Calculate where in the array we should access the frequency int arrayPosition = static_cast<int>(t_size * t_percentualPosition); // Get the frequency float retValue = m_frequencies[arrayPosition]; TIME_FUNCTION_STOP return retValue; } else { TIME_FUNCTION_STOP return 0; } } void AudioHandler::PlayRepeatableRecordedSound() { // This is a dangerous function since soundID starts at 0. If there is no sound on 0 we will crash if(m_SoundState != HOLDREPEATABLEANALYSIS && m_SoundState != ANALYSEREPEATABLE) { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); t_audioModule.PlayASound(m_outputRepeatableSoundID, false, m_outputRepeatableSoundChannelID); } } void AudioHandler::Update(double p_deltaTime) { TIME_FUNCTION_START unsigned int recordPointer; DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); switch(m_SoundState) { case Doremi::Core::AudioHandler::ANALYSECONTINUOUS: m_currentFrequency = t_audioModule.AnalyseSoundSpectrum(m_continuousFrequencyAnalyserChannelID); break; case Doremi::Core::AudioHandler::HOLDCONTINUOUSANALYSIS: recordPointer = t_audioModule.GetRecordPointer(); // kollar s att vi har spelat in en bit innan vi startar analysen. Om man startar analysen Dirr buggar det ut. if(recordPointer > 9600) { m_SoundState = ANALYSECONTINUOUS; // Default vrde som inte kan anvndas. I komponenterna stts det i defaultkontruktorn. if(m_continuousFrequencyAnalyserChannelID != -1) { /** TODOLH Behvs nog uppdatera ljudposition till listener position. */ t_audioModule.PlaySoundOnSpecificChannel(m_continuousFrequencyAnalyserSoundID, true, m_continuousFrequencyAnalyserChannelID); t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 0.0f); } else { t_audioModule.PlayASound(m_continuousFrequencyAnalyserSoundID, true, m_continuousFrequencyAnalyserChannelID); t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 0.0f); } t_audioModule.SetPriority(m_continuousFrequencyAnalyserChannelID, 0); /** TODOLH osker p om detta behvs. Tydligen kan det bli s att fmod snor kanaler. Men d tar den kanaler som har lg prio*/ } break; case Doremi::Core::AudioHandler::ANALYSEREPEATABLE: recordPointer = t_audioModule.GetRecordPointer(); // Kolla om ljudet r "klart" isfall verg till andra inspelingssttet. if(!t_audioModule.IsRecording()) { m_SoundState = HOLDCONTINUOUSANALYSIS; m_repeatableAnalysisComplete = true; t_audioModule.StopRecording(); t_audioModule.StartRecording(m_continuousFrequencyAnalyserSoundID, true); t_audioModule.SetVolumeOnChannel(m_continuousFrequencyAnalyserChannelID, 1.0f); m_outputRepeatableSoundID = t_audioModule.CopySound(m_repeatableFrequencyAnalyserSoundID, m_outputRepeatableSoundID, m_timeGunReloadButtonWasPressed); t_audioModule.PlayASound(m_outputRepeatableSoundID, false, m_outputRepeatableSoundChannelID); t_audioModule.SetVolumeOnChannel(m_outputRepeatableSoundChannelID, 0); } else { // Fixa in i array fr att anvndas med beamen senare! m_accumulatedDeltaTime += p_deltaTime; if(m_accumulatedDeltaTime > m_frequencyVectorPrecision) { m_accumulatedDeltaTime = 0; /// Ta tidsintervallet multiplicera med m_frequencyVectorPrecision ta det arrayvrdet!! m_frequencies.push_back(t_audioModule.AnalyseSoundSpectrum(m_repeatableFrequencyAnalyserChannelID)); } else { // do nothing } } break; case Doremi::Core::AudioHandler::HOLDREPEATABLEANALYSIS: recordPointer = t_audioModule.GetRecordPointer(); // kollar s att vi har spelat in en bit innan vi startar analysen. Om man startar analysen Dirr buggar det ut. TODOLH Definea // 9600 kanske? if(recordPointer > 9600) { m_SoundState = ANALYSEREPEATABLE; m_frequencies.clear(); t_audioModule.PlayASound(m_repeatableFrequencyAnalyserSoundID, false, m_repeatableFrequencyAnalyserChannelID); t_audioModule.SetVolumeOnChannel(m_repeatableFrequencyAnalyserChannelID, 0.0f); t_audioModule.SetPriority(m_repeatableFrequencyAnalyserChannelID, 1); } break; default: break; } InputHandlerClient* inputHandler = (InputHandlerClient*)PlayerHandler::GetInstance()->GetDefaultInputHandler(); if(inputHandler != nullptr) { if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency0)) { m_currentFrequency = 0; } else if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency500)) { m_currentFrequency = 500; } else if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::SetFrequency1000)) { m_currentFrequency = 1000; } } // Send frequence to buffer FrequencyBufferHandler* freqBufferHandler = PlayerHandler::GetInstance()->GetDefaultFrequencyBufferHandler(); if(freqBufferHandler != nullptr) { freqBufferHandler->BufferFrequency(m_currentFrequency); using namespace Doremi::Utilities::Logging; m_logger->DebugLog(LogTag::AUDIO, LogLevel::MASS_DATA_PRINT, "F, %f", m_currentFrequency); } TIME_FUNCTION_STOP } void AudioHandler::OnEvent(Event* p_event) { if(p_event->eventType == EventType::ChangeMenuState) { ChangeMenuState* t_stateEvent = static_cast<ChangeMenuState*>(p_event); if(t_stateEvent->state == DoremiStates::RUNGAME) { if(m_backgroundSounds.count(BackgroundSound::InGameMainTheme) != 0) { DoremiEngine::Audio::AudioModule& t_audioModule = m_sharedContext.GetAudioModule(); t_audioModule.PlayASound(m_backgroundSounds[BackgroundSound::InGameMainTheme], true, m_backgroundChannelId); } } } } } } <|endoftext|>
<commit_before>// Project specific #include <Editor.hpp> // Third party // Standard libraries #ifdef _WIN32 #include <windows.h> #include <DbgHelp.h> #include <stdlib.h> #include <string.h> #include <tchar.h> #else #error Platform not supported #endif #include <exception> #include <iostream> #include <exception> // std::set_unexpected // The method called when shutting down void attemptGracefulShutdown(); // Methods set as unexpected and terminate functions void g_unexpected(); void g_terminate(); // Prints the current stack void printStack(); // Start the important singletons void startup(); // Shutdown the important singletons void shutdown(); // Controlhandler BOOL CtrlHandler(DWORD fdwCtrlType); void localMain() { try { DoremiEditor::EditorMain editor; editor.Start(); } catch(const std::exception& e) { // TODORT log std::cout << "Unhandled exception: " << e.what() << std::endl; attemptGracefulShutdown(); exit(1); } catch(...) { // TODORT log std::cout << "Unhandled unknown exception" << std::endl; attemptGracefulShutdown(); exit(1); } } #ifdef _WIN32 int main(int argc, const char* argv[]) #else #error Platform not supported #endif { std::set_terminate(g_terminate); std::set_unexpected(g_unexpected); SetErrorMode(SEM_FAILCRITICALERRORS); SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE); // Run startup code startup(); // TODORT // This row is required later as it disables the standard output terminal, we do now want that. // However, as people are currently using cout for debugging we'll need this for the moment. // FreeConsole(); __try { localMain(); } __except(EXCEPTION_EXECUTE_HANDLER) { attemptGracefulShutdown(); exit(1); } // Run shutdown code shutdown(); return 0; } void g_unexpected() { attemptGracefulShutdown(); } void g_terminate() { attemptGracefulShutdown(); } void startup() { // TODORT // TODOLOG // using namespace Utility::Timer; // using namespace Utility::DebugLog; // ConsoleManager::Startup(); // MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Start(); } void shutdown() { // TODORT // TODOLOG // using namespace Utility::Timer; // using namespace Utility::DebugLog; // MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Stop(); // MeasureTimer::GetInstance().DumpData("client_timings"); // ConsoleManager::Shutdown(); } void attemptGracefulShutdown() { // printStack(); shutdown(); #ifdef _DEBUG std::cin.get(); #endif } #ifdef _WIN32 // void printStack() //{ // unsigned int i; // void* stack[100]; // unsigned short frames; // SYMBOL_INFO* symbol; // HANDLE process; // // process = GetCurrentProcess(); // // SymInitialize(process, NULL, TRUE); // // frames = CaptureStackBackTrace(0, 100, stack, NULL); // symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1); // symbol->MaxNameLen = 255; // symbol->SizeOfStruct = sizeof(SYMBOL_INFO); // // TODORT // // TODOLOG // // using namespace Utility::DebugLog; // // VirtualConsole& console = ConsoleManager::GetInstance().CreateNewConsole("stackPrint", false); // for (i = 0; i < frames; i++) // { // SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol); // // TODORT // // TODOLOG // // console.LogText(LogTag::NOTAG, LogLevel::MASS_DATA_PRINT, "%i: %s - 0x%0X\n", frames - i - 1, symbol->Name, symbol->Address); // } // // free(symbol); //} BOOL CtrlHandler(DWORD fdwCtrlType) { switch(fdwCtrlType) { // Handle the CTRL-C signal. case CTRL_C_EVENT: attemptGracefulShutdown(); return (TRUE); // CTRL-CLOSE: confirm that the user wants to exit. case CTRL_CLOSE_EVENT: attemptGracefulShutdown(); return (TRUE); default: return FALSE; } } #endif<commit_msg>Removed link to dbghelper for Editor<commit_after>// Project specific #include <Editor.hpp> // Third party // Standard libraries #ifdef _WIN32 #include <windows.h> #include <stdlib.h> #include <string.h> #include <tchar.h> #else #error Platform not supported #endif #include <exception> #include <iostream> #include <exception> // std::set_unexpected // The method called when shutting down void attemptGracefulShutdown(); // Methods set as unexpected and terminate functions void g_unexpected(); void g_terminate(); // Start the important singletons void startup(); // Shutdown the important singletons void shutdown(); // Controlhandler BOOL CtrlHandler(DWORD fdwCtrlType); void localMain() { try { DoremiEditor::EditorMain editor; editor.Start(); } catch(const std::exception& e) { // TODORT log std::cout << "Unhandled exception: " << e.what() << std::endl; attemptGracefulShutdown(); exit(1); } catch(...) { // TODORT log std::cout << "Unhandled unknown exception" << std::endl; attemptGracefulShutdown(); exit(1); } } #ifdef _WIN32 int main(int argc, const char* argv[]) #else #error Platform not supported #endif { std::set_terminate(g_terminate); std::set_unexpected(g_unexpected); SetErrorMode(SEM_FAILCRITICALERRORS); SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE); // Run startup code startup(); // TODORT // This row is required later as it disables the standard output terminal, we do now want that. // However, as people are currently using cout for debugging we'll need this for the moment. // FreeConsole(); __try { localMain(); } __except(EXCEPTION_EXECUTE_HANDLER) { attemptGracefulShutdown(); exit(1); } // Run shutdown code shutdown(); return 0; } void g_unexpected() { attemptGracefulShutdown(); } void g_terminate() { attemptGracefulShutdown(); } void startup() { // TODORT // TODOLOG // using namespace Utility::Timer; // using namespace Utility::DebugLog; // ConsoleManager::Startup(); // MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Start(); } void shutdown() { // TODORT // TODOLOG // using namespace Utility::Timer; // using namespace Utility::DebugLog; // MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Stop(); // MeasureTimer::GetInstance().DumpData("client_timings"); // ConsoleManager::Shutdown(); } void attemptGracefulShutdown() { shutdown(); #ifdef _DEBUG std::cin.get(); #endif } #ifdef _WIN32 BOOL CtrlHandler(DWORD fdwCtrlType) { switch(fdwCtrlType) { // Handle the CTRL-C signal. case CTRL_C_EVENT: attemptGracefulShutdown(); return (TRUE); // CTRL-CLOSE: confirm that the user wants to exit. case CTRL_CLOSE_EVENT: attemptGracefulShutdown(); return (TRUE); default: return FALSE; } } #endif<|endoftext|>
<commit_before><commit_msg>fix empty w:tblW<commit_after><|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once // File <-> streams adapters // // Seastar files are block-based due to the reliance on DMA - you must read // on sector boundaries. The adapters in this file provide a byte stream // interface to files, while retaining the zero-copy characteristics of // seastar files. #include "file.hh" #include "iostream.hh" #include "shared_ptr.hh" /// Data structure describing options for opening a file input stream struct file_input_stream_options { size_t buffer_size = 8192; ///< I/O buffer size unsigned read_ahead = 0; ///< Number of extra read-ahead operations ::io_priority_class io_priority_class = default_priority_class(); }; // Create an input_stream for a given file, with the specified options. // Multiple fibers of execution (continuations) may safely open // multiple input streams concurrently for the same file. input_stream<char> make_file_input_stream( file file, uint64_t offset, file_input_stream_options = {}); // Create an input_stream for reading starting at a given position of the // given file. Multiple fibers of execution (continuations) may safely open // multiple input streams concurrently for the same file. input_stream<char> make_file_input_stream( file file, file_input_stream_options = {}); inline input_stream<char> make_file_input_stream( file file, uint64_t offset, uint64_t buffer_size) { file_input_stream_options options; options.buffer_size = buffer_size; return make_file_input_stream(std::move(file), offset, std::move(options)); } struct file_output_stream_options { unsigned buffer_size = 8192; unsigned preallocation_size = 1024*1024; // 1MB unsigned write_behind = 1; ///< Number of buffers to write in parallel ::io_priority_class io_priority_class = default_priority_class(); }; // Create an output_stream for writing starting at the position zero of a // newly created file. // NOTE: flush() should be the last thing to be called on a file output stream. output_stream<char> make_file_output_stream( file file, uint64_t buffer_size = 8192); /// Create an output_stream for writing starting at the position zero of a /// newly created file. /// NOTE: flush() should be the last thing to be called on a file output stream. output_stream<char> make_file_output_stream( file file, file_output_stream_options options); <commit_msg>fstream: remove unused interface<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once // File <-> streams adapters // // Seastar files are block-based due to the reliance on DMA - you must read // on sector boundaries. The adapters in this file provide a byte stream // interface to files, while retaining the zero-copy characteristics of // seastar files. #include "file.hh" #include "iostream.hh" #include "shared_ptr.hh" /// Data structure describing options for opening a file input stream struct file_input_stream_options { size_t buffer_size = 8192; ///< I/O buffer size unsigned read_ahead = 0; ///< Number of extra read-ahead operations ::io_priority_class io_priority_class = default_priority_class(); }; // Create an input_stream for a given file, with the specified options. // Multiple fibers of execution (continuations) may safely open // multiple input streams concurrently for the same file. input_stream<char> make_file_input_stream( file file, uint64_t offset, file_input_stream_options = {}); // Create an input_stream for reading starting at a given position of the // given file. Multiple fibers of execution (continuations) may safely open // multiple input streams concurrently for the same file. input_stream<char> make_file_input_stream( file file, file_input_stream_options = {}); struct file_output_stream_options { unsigned buffer_size = 8192; unsigned preallocation_size = 1024*1024; // 1MB unsigned write_behind = 1; ///< Number of buffers to write in parallel ::io_priority_class io_priority_class = default_priority_class(); }; // Create an output_stream for writing starting at the position zero of a // newly created file. // NOTE: flush() should be the last thing to be called on a file output stream. output_stream<char> make_file_output_stream( file file, uint64_t buffer_size = 8192); /// Create an output_stream for writing starting at the position zero of a /// newly created file. /// NOTE: flush() should be the last thing to be called on a file output stream. output_stream<char> make_file_output_stream( file file, file_output_stream_options options); <|endoftext|>
<commit_before>/** * \file */ #pragma once #include <rleahylib/rleahylib.hpp> #include <fma.hpp> #include <algorithm> #include <cmath> #include <cstring> #include <functional> #include <limits> #include <unordered_map> #include <utility> #include <type_traits> #pragma GCC optimize ("fast-math") namespace MCPP { /** * Generates simplex noise. */ class Simplex { private: Byte permutation [512]; template <typename T> inline Byte get_random (T & gen, Byte bound) noexcept(noexcept(gen())) { typedef typename T::result_type stype; typedef typename std::make_unsigned<stype>::type type; union { type r; stype r_in; }; // If the bound is the maximum integer // for the unsigned result type, it cannot // be affected by modulo bias, so we simply // return the next integer generated if (bound==std::numeric_limits<type>::max()) { r_in=gen(); return r; } type d=static_cast<type>(bound)+1; // This is the maximum number the random // number generator may yield, divided // by the divisor. type q=std::numeric_limits<type>::max()/d; // Loop until we retrieve a random // number unaffected by modulo bias // over the given range do r_in=gen(); while( // This eliminates modulo bias by // asking: // // If I restrict the inputs to // modulus to the range [(r/d)*d,((r/d)+1)*d) // could I obtain all values within // the bound given the maximum output // of the random number generator? // // If the answer is no a new number is // obtained. // // Example: // // The function is called with a generator // which generates [-128,127] (i.e. the range // of a signed byte), and a bound of 5 (i.e. // the output range is [0,5]. // // The union of r and r_in will map this range // to an output range of [0,255] (i.e. the range // of an unsigned byte). // // If the random number generates a number on // the range [252,255], modulo bias would occur. // // Consider the outputs that would be yielded // by blindly applying modulus to this range: // // 252 = 0 // 253 = 1 // 254 = 2 // 255 = 3 // // The numbers 4 and 5 from the desired output // range are not present, increasing the likelihood // of obtaining outputs in the range [0,3]. // // In this case: // // d=6 // q=255/6=42 // // Consider the case r=252: // // (r/d)+1=43 // // This means that in order for 252 not to // produce modulo bias (if not discarded) // the random number generator would have to // be capable of generating numbers up to // at least (43*d)-1=257 (which it is not). // // But we see that ((r/d)+1)>q, which // causes this result to be discarded. ((r/d)+1)>q ); // Current result will not produce // modulo bias, apply modulus and return return static_cast<Byte>(r%d); } template <typename T> inline void init (T & gen) noexcept(noexcept(gen())) { // Populate and shuffle the first half // of the table using Fisher-Yates-Knuth // shuffle for (Word i=0;i<(sizeof(permutation)/2);++i) { permutation[i]=static_cast<Byte>(i); std::swap( permutation[i], permutation[ get_random( gen, static_cast<Byte>(i) ) ] ); } // Copy the first half of the table // into the last half memcpy( &permutation[sizeof(permutation)/2], permutation, sizeof(permutation)/2 ); } public: /** * Creates a new simplex noise generator * with a randomly-chosen seed. */ Simplex (); /** * Creates a new simplex noise generator * seeded with a certain seed. * * \param [in] seed * The seed which shall be used to * seed the noise generator. */ explicit Simplex (UInt64 seed) noexcept; /** * Creates a new simplex noise generator * seeded by a provided random number * generator. * * \param [in] gen * A random number generator which * shall be used to seed the noise * generator. */ template <typename T, typename=typename std::enable_if<!std::numeric_limits<T>::is_integer>::type> explicit Simplex (T & gen) noexcept(noexcept(std::declval<Simplex>().init(gen))) { init(gen); } /** * Retrieves raw 2D noise. * * \param [in] x * The x value. * \param [i] y * The y value. * * \return * The raw noise output. */ Double operator () (Double x, Double y) const noexcept; /** * Retrieves raw 3D noise. * * \param [in] x * The x value. * \param [in] y * The y value. * param [in] z * The z value. * * \return * The raw noise output. */ Double operator () (Double x, Double y, Double z) const noexcept; /** * Retrieves raw 4D noise. * * \param [in] w * The w value. * \param [in] x * The x value. * \param [in] y * The y value. * \param [in] z * The z value. * * \return * The raw noise output. */ Double operator () (Double w, Double x, Double y, Double z) const noexcept; }; /** * Selects a value from a range based on * a multiplier between 0 and 1. * * \param [in] lo * The low end of the range to choose * from. * \param [in] hi * The high end of the range to choose * from. * \param [in] val * A value between zero and one (inclusive). * Input values close to one will yield * results close to \em hi, input values * close to zero will yield results close * to \em lo. * * \return * A result chosen between \em lo and \em hi * according to \em val. The exact algorithm * used shall be equivalent to ((hi-lo)*val)+lo. */ inline Double Select (Double lo, Double hi, Double val) noexcept { return fma( hi-lo, val, lo ); } /** * Normalizes a value, yielding a value between 0 * and 1 which specifies how far between a maximum * and minimum it is. * * \param [in] lo * The number a \em val of 0 shall yield. * \param [in] hi * The number a \em val of 1 shall yield. * \param [in] val * A number between 0 and 1. * * \return * A result chosen between \em lo and \em hi * such that this result multiplied by the * range gives the distance from \em lo. * For values of \em hi, 1 is returned, for * values of \em lo, 0 is returned, and all * values beteween 0 and 1 are placed proportionally * there between. */ inline Double Normalize (Double lo, Double hi, Double val) noexcept { if (lo==hi) { if (val==lo) return 0.5; if (val>lo) return 1; return 0; } bool complement; if (lo>hi) { complement=true; std::swap(lo,hi); } else { complement=false; } Double difference=val-lo; Double range=hi-lo; if (difference<0) return complement ? 1 : 0; if (difference>range) return complement ? 0 : 1; Double result=difference/range; return complement ? (1-result) : result; } /** * Given an input on a range, adjusts the value * such that it is on a different range. * * \param [in] lo * The low end of the desired range. * \param [in] hi * The high end of the desired range. * \param [in] in_lo * The low end of the range of the * input. * \param [in] in_hi * The high end of the range of the * input. * \param [in] in * The input. * * \return * The value that \em in would have were * it on the range given by \em lo, \em hi, * as opposed to the range \em in_lo, \em in_hi. */ inline Double Scale (Double lo, Double hi, Double in_lo, Double in_hi, Double in) noexcept { return Select( lo, hi, Normalize( in_lo, in_hi, in ) ); } /** * Given a simplex noise generator and * arguments to forward through to it, * adjusts the output of the noise * generator to place it on some * arbitrary range. * * \tparam Args * The types of the arguments which * shall be forwarded through to the * simplex noise generator. * * \param [in] lo * The low end of the desired range. * \param [in] hi * The high end of the desired range. * \param [in] gen * A reference to a simplex noise * generator. * \param [in] args * The arguments which shall be forwarded * through to \em gen. * * \return * A noise value adjusted to the range * \em lo, \em hi. */ template <typename... Args> Double Scale (Double lo, Double hi, const Simplex & gen, Args &&... args) noexcept { return fma( gen(std::forward<Args>(args)...), (hi-lo)/2, (hi+lo)/2 ); } /** * \cond */ inline Double octave_helper (Double arg, Double frequency) noexcept { return arg*frequency; } /** * \endcond */ /** * Applies an octave filter to the output * of a certain generator. * * \tparam T * The type of generator whose output * shall be filtered. * \tparam Args * The types of the arguments to forward * through to the generator. * * \param [in] octaves * The number of octaves which shall be * applied. * \param [in] persistence * The persistence of the noise from each * octave. * \param [in] frequency * The starting sampling frequency. * \param [in] func * The generator. * \param [in] args * The arguments to forward through to * \em generator. * * \return * A filtered value from \em func. */ template <typename T, typename... Args> Double Octave (Word octaves, Double persistence, Double frequency, T && func, const Args &... args) noexcept( noexcept(func(args...)) ) { Double total=0; Double amplitude=1; Double max_amp=0; for (Word i=0;i<octaves;++i) { total=fma( func( octave_helper( args, frequency )... ), amplitude, total ); frequency*=2; max_amp+=amplitude; amplitude*=persistence; } return total/max_amp; } /** * Applies a bias filter to a value. Given a value * on the range [0,1], a bias filter pushes values * towards 1 for bias values greater than 0.5, * towards 0 for bias values less than 0.5, and * does nothing for bias values of exactly 0.5. * * \param [in] bias * The bias value. * \param [in] input * Input on the range [0,1]. * * \return * A biased noise value. */ inline Double Bias (Double bias, Double input) noexcept { return pow( input, log(bias)/log(0.5) ); } /** * Applies a gain filter to a value. Given a value * on the range [0,1], a gain filter pushes values * towards 0 and 1 for gain values greater than 0.5, * towards 0.5 for gain values less than 0.5, and * does nothing for gain values of exactly 0.5. * * \param [in] gain * The gain value. * \param [in] input * Input on the range [0,1]. * * \return * A filtered noise value. */ inline Double Gain (Double gain, Double input) noexcept { Double complement=1-gain; input*=2; return ( (input<0.5) ? (Bias( complement, input )/2) : (1-(Bias( complement, 2-input )/2)) ); } /** * Creates a ridged multifractal. * * \param [in] input * A particular noise value. * * \return * The corresponding value mapped to * a ridged multifractal. */ inline Double Ridged (Double input) noexcept { return 1-fabs(input); } } #pragma GCC reset_options <commit_msg>Bias and Gain Improvements<commit_after>/** * \file */ #pragma once #include <rleahylib/rleahylib.hpp> #include <fma.hpp> #include <algorithm> #include <cmath> #include <cstring> #include <functional> #include <limits> #include <unordered_map> #include <utility> #include <type_traits> #pragma GCC optimize ("fast-math") namespace MCPP { /** * Generates simplex noise. */ class Simplex { private: Byte permutation [512]; template <typename T> inline Byte get_random (T & gen, Byte bound) noexcept(noexcept(gen())) { typedef typename T::result_type stype; typedef typename std::make_unsigned<stype>::type type; union { type r; stype r_in; }; // If the bound is the maximum integer // for the unsigned result type, it cannot // be affected by modulo bias, so we simply // return the next integer generated if (bound==std::numeric_limits<type>::max()) { r_in=gen(); return r; } type d=static_cast<type>(bound)+1; // This is the maximum number the random // number generator may yield, divided // by the divisor. type q=std::numeric_limits<type>::max()/d; // Loop until we retrieve a random // number unaffected by modulo bias // over the given range do r_in=gen(); while( // This eliminates modulo bias by // asking: // // If I restrict the inputs to // modulus to the range [(r/d)*d,((r/d)+1)*d) // could I obtain all values within // the bound given the maximum output // of the random number generator? // // If the answer is no a new number is // obtained. // // Example: // // The function is called with a generator // which generates [-128,127] (i.e. the range // of a signed byte), and a bound of 5 (i.e. // the output range is [0,5]. // // The union of r and r_in will map this range // to an output range of [0,255] (i.e. the range // of an unsigned byte). // // If the random number generates a number on // the range [252,255], modulo bias would occur. // // Consider the outputs that would be yielded // by blindly applying modulus to this range: // // 252 = 0 // 253 = 1 // 254 = 2 // 255 = 3 // // The numbers 4 and 5 from the desired output // range are not present, increasing the likelihood // of obtaining outputs in the range [0,3]. // // In this case: // // d=6 // q=255/6=42 // // Consider the case r=252: // // (r/d)+1=43 // // This means that in order for 252 not to // produce modulo bias (if not discarded) // the random number generator would have to // be capable of generating numbers up to // at least (43*d)-1=257 (which it is not). // // But we see that ((r/d)+1)>q, which // causes this result to be discarded. ((r/d)+1)>q ); // Current result will not produce // modulo bias, apply modulus and return return static_cast<Byte>(r%d); } template <typename T> inline void init (T & gen) noexcept(noexcept(gen())) { // Populate and shuffle the first half // of the table using Fisher-Yates-Knuth // shuffle for (Word i=0;i<(sizeof(permutation)/2);++i) { permutation[i]=static_cast<Byte>(i); std::swap( permutation[i], permutation[ get_random( gen, static_cast<Byte>(i) ) ] ); } // Copy the first half of the table // into the last half memcpy( &permutation[sizeof(permutation)/2], permutation, sizeof(permutation)/2 ); } public: /** * Creates a new simplex noise generator * with a randomly-chosen seed. */ Simplex (); /** * Creates a new simplex noise generator * seeded with a certain seed. * * \param [in] seed * The seed which shall be used to * seed the noise generator. */ explicit Simplex (UInt64 seed) noexcept; /** * Creates a new simplex noise generator * seeded by a provided random number * generator. * * \param [in] gen * A random number generator which * shall be used to seed the noise * generator. */ template <typename T, typename=typename std::enable_if<!std::numeric_limits<T>::is_integer>::type> explicit Simplex (T & gen) noexcept(noexcept(std::declval<Simplex>().init(gen))) { init(gen); } /** * Retrieves raw 2D noise. * * \param [in] x * The x value. * \param [i] y * The y value. * * \return * The raw noise output. */ Double operator () (Double x, Double y) const noexcept; /** * Retrieves raw 3D noise. * * \param [in] x * The x value. * \param [in] y * The y value. * param [in] z * The z value. * * \return * The raw noise output. */ Double operator () (Double x, Double y, Double z) const noexcept; /** * Retrieves raw 4D noise. * * \param [in] w * The w value. * \param [in] x * The x value. * \param [in] y * The y value. * \param [in] z * The z value. * * \return * The raw noise output. */ Double operator () (Double w, Double x, Double y, Double z) const noexcept; }; /** * Selects a value from a range based on * a multiplier between 0 and 1. * * \param [in] lo * The low end of the range to choose * from. * \param [in] hi * The high end of the range to choose * from. * \param [in] val * A value between zero and one (inclusive). * Input values close to one will yield * results close to \em hi, input values * close to zero will yield results close * to \em lo. * * \return * A result chosen between \em lo and \em hi * according to \em val. The exact algorithm * used shall be equivalent to ((hi-lo)*val)+lo. */ inline Double Select (Double lo, Double hi, Double val) noexcept { return fma( hi-lo, val, lo ); } /** * Normalizes a value, yielding a value between 0 * and 1 which specifies how far between a maximum * and minimum it is. * * \param [in] lo * The number a \em val of 0 shall yield. * \param [in] hi * The number a \em val of 1 shall yield. * \param [in] val * A number between 0 and 1. * * \return * A result chosen between \em lo and \em hi * such that this result multiplied by the * range gives the distance from \em lo. * For values of \em hi, 1 is returned, for * values of \em lo, 0 is returned, and all * values beteween 0 and 1 are placed proportionally * there between. */ inline Double Normalize (Double lo, Double hi, Double val) noexcept { if (lo==hi) { if (val==lo) return 0.5; if (val>lo) return 1; return 0; } bool complement; if (lo>hi) { complement=true; std::swap(lo,hi); } else { complement=false; } Double difference=val-lo; Double range=hi-lo; if (difference<0) return complement ? 1 : 0; if (difference>range) return complement ? 0 : 1; Double result=difference/range; return complement ? (1-result) : result; } /** * Given an input on a range, adjusts the value * such that it is on a different range. * * \param [in] lo * The low end of the desired range. * \param [in] hi * The high end of the desired range. * \param [in] in_lo * The low end of the range of the * input. * \param [in] in_hi * The high end of the range of the * input. * \param [in] in * The input. * * \return * The value that \em in would have were * it on the range given by \em lo, \em hi, * as opposed to the range \em in_lo, \em in_hi. */ inline Double Scale (Double lo, Double hi, Double in_lo, Double in_hi, Double in) noexcept { return Select( lo, hi, Normalize( in_lo, in_hi, in ) ); } /** * Given a simplex noise generator and * arguments to forward through to it, * adjusts the output of the noise * generator to place it on some * arbitrary range. * * \tparam Args * The types of the arguments which * shall be forwarded through to the * simplex noise generator. * * \param [in] lo * The low end of the desired range. * \param [in] hi * The high end of the desired range. * \param [in] gen * A reference to a simplex noise * generator. * \param [in] args * The arguments which shall be forwarded * through to \em gen. * * \return * A noise value adjusted to the range * \em lo, \em hi. */ template <typename... Args> Double Scale (Double lo, Double hi, const Simplex & gen, Args &&... args) noexcept { return fma( gen(std::forward<Args>(args)...), (hi-lo)/2, (hi+lo)/2 ); } /** * \cond */ inline Double octave_helper (Double arg, Double frequency) noexcept { return arg*frequency; } /** * \endcond */ /** * Applies an octave filter to the output * of a certain generator. * * \tparam T * The type of generator whose output * shall be filtered. * \tparam Args * The types of the arguments to forward * through to the generator. * * \param [in] octaves * The number of octaves which shall be * applied. * \param [in] persistence * The persistence of the noise from each * octave. * \param [in] frequency * The starting sampling frequency. * \param [in] func * The generator. * \param [in] args * The arguments to forward through to * \em generator. * * \return * A filtered value from \em func. */ template <typename T, typename... Args> Double Octave (Word octaves, Double persistence, Double frequency, T && func, const Args &... args) noexcept( noexcept(func(args...)) ) { Double total=0; Double amplitude=1; Double max_amp=0; for (Word i=0;i<octaves;++i) { total=fma( func( octave_helper( args, frequency )... ), amplitude, total ); frequency*=2; max_amp+=amplitude; amplitude*=persistence; } return total/max_amp; } /** * Applies a bias filter to a value. Given a value * on the range [0,1], a bias filter pushes values * towards 1 for bias values greater than 0.5, * towards 0 for bias values less than 0.5, and * does nothing for bias values of exactly 0.5. * * \param [in] bias * The bias value. * \param [in] input * Input on the range [0,1]. * * \return * A biased noise value. */ inline Double Bias (Double bias, Double input) noexcept { // Do not do expensive pow + log x2 for // bias values which would not change // the input anyway. if (bias==0.5) return input; return pow( input, log(bias)/log(0.5) ); } /** * Applies a gain filter to a value. Given a value * on the range [0,1], a gain filter pushes values * towards 0 and 1 for gain values greater than 0.5, * towards 0.5 for gain values less than 0.5, and * does nothing for gain values of exactly 0.5. * * \param [in] gain * The gain value. * \param [in] input * Input on the range [0,1]. * * \return * A filtered noise value. */ inline Double Gain (Double gain, Double input) noexcept { // Do not do expensive bias etc. for gain // values which would not change the input // anyway if (gain==0.5) return input; Double complement=1-gain; input*=2; return ( (input<0.5) ? (Bias( complement, input )/2) : (1-(Bias( complement, 2-input )/2)) ); } /** * Creates a ridged multifractal. * * \param [in] input * A particular noise value. * * \return * The corresponding value mapped to * a ridged multifractal. */ inline Double Ridged (Double input) noexcept { return 1-fabs(input); } } #pragma GCC reset_options <|endoftext|>
<commit_before>#include "stdafx.h" #include "Model.h" //void ConvertOBJ(std::string &f_path, std::string &f_out) //{ // try // { // std::vector<glm::vec3> temp_vertex; // std::vector<glm::vec2> temp_uv; // std::vector<glm::vec3> temp_normal; // // std::vector<std::string> l_materialNames; // std::vector<std::string> l_materialTextureNames; // std::vector<unsigned char> l_materialTypes; // int l_currentMaterial = -1; // bool l_defaultMaterial = true; // // std::ifstream l_objectFile; // l_objectFile.open(f_path + ".obj", std::ios::in); // if(l_objectFile.fail()) throw std::exception("Unable to load input file"); // // std::string l_buffer; // // std::ifstream l_materialFile; // l_materialFile.open(f_path + ".mtl", std::ios::in); // if(!l_materialFile.fail()) // { // l_defaultMaterial = false; // //Materials parsing // while(std::getline(l_materialFile, l_buffer)) // { // if(l_buffer.empty()) continue; // if(l_buffer.at(0U) == 'N' || l_buffer.at(0U) == 'K' || l_buffer.at(0U) == 'd' || l_buffer.at(0U) == 'i') continue; // if(l_buffer.find("newmtl ") != std::string::npos) // { // std::string l_materialName = l_buffer.substr(7U); // l_materialNames.push_back(l_materialName); // continue; // } // if(l_buffer.find("type ") != std::string::npos) // this is custom line, you have to insert it in file with value based on material bits // { // std::string l_typeString = l_buffer.substr(5U); // l_materialTypes.push_back(static_cast<unsigned char>(std::stoi(l_typeString))); // continue; // } // if(l_buffer.find("map_Kd ") != std::string::npos || l_buffer.find("map_kd ") != std::string::npos) // { // std::string l_textureName = l_buffer.substr(7U); // l_textureName.insert(0U, "textures/"); // l_materialTextureNames.push_back(l_textureName); // continue; // } // } // l_materialFile.close(); // } // else std::cout << "No .mtl file, assumed that all materials are default" << std::endl; // // if(l_materialNames.size() == 0U) // { // l_materialNames.push_back("DefaultMaterial"); // l_currentMaterial = 0; // } // // if(l_materialTextureNames.size() < l_materialNames.size()) // { // for(size_t i = 0U, j = l_materialNames.size() - l_materialTextureNames.size(); i < j; i++) // { // l_materialTextureNames.push_back(""); // } // } // // if(l_materialTypes.size() < l_materialNames.size()) // { // for(size_t i = 0U, j = l_materialNames.size() - l_materialTypes.size(); i < j; i++) // { // l_materialTypes.push_back(3U); // } // } // // std::ofstream l_outputFile(f_out, std::ios::out | std::ios::binary); // if(l_outputFile.fail()) throw std::exception("Unable to create output file"); // // l_outputFile.write("ROC", 3U); // unsigned char l_setter = 0x1U; // l_outputFile.write(reinterpret_cast<char*>(&l_setter), sizeof(unsigned char)); // // bool l_dataParsed = false; // bool l_materialsSizeParsed = false; // std::vector<Face> l_faceVector; // std::vector<unsigned char> l_compressedData; // // while(std::getline(l_objectFile, l_buffer)) // { // if(l_buffer.empty()) continue; // if(l_buffer.at(0U) == '#' || l_buffer.at(0U) == 's' || l_buffer.at(0U) == 'm' || l_buffer.at(0U) == 'o') continue; // if(l_buffer.find("v ") != std::string::npos) // { // std::stringstream l_vertexStream(l_buffer.substr(2U)); // glm::vec3 l_vert; // l_vertexStream >> l_vert.x >> l_vert.y >> l_vert.z; // temp_vertex.push_back(l_vert); // continue; // } // if(l_buffer.find("vn ") != std::string::npos) // { // std::stringstream l_normalStream(l_buffer.substr(3U)); // glm::vec3 l_norm; // l_normalStream >> l_norm.x >> l_norm.y >> l_norm.z; // temp_normal.push_back(l_norm); // continue; // } // if(l_buffer.find("vt ") != std::string::npos) // { // std::stringstream l_uvStream(l_buffer.substr(3U)); // glm::vec2 l_uv; // l_uvStream >> l_uv.x >> l_uv.y; // l_uv.y = 1.f - l_uv.y; // temp_uv.push_back(l_uv); // continue; // } // if(!l_dataParsed) // { // l_dataParsed = true; // // unsigned int l_origSize = temp_vertex.size()*sizeof(glm::vec3); // unsigned int l_maxSize = GetMaxCompressedLen(l_origSize); // l_compressedData.resize(static_cast<size_t>(l_maxSize)); // unsigned int l_compressedSize = CompressData(temp_vertex.data(), l_origSize, l_compressedData.data(), l_maxSize); // if(l_compressedSize == 0U) throw std::exception("Unable to compress vertices"); // l_outputFile.write(reinterpret_cast<char*>(&l_compressedSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(&l_origSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(l_compressedData.data()), l_compressedSize); // std::cout << temp_vertex.size() << " vertices" << std::endl; // // l_origSize = temp_uv.size()*sizeof(glm::vec2); // l_maxSize = GetMaxCompressedLen(l_origSize); // l_compressedData.resize(static_cast<size_t>(l_maxSize)); // l_compressedSize = CompressData(temp_uv.data(), l_origSize, l_compressedData.data(), l_maxSize); // if(l_compressedSize == 0U) throw std::exception("Unable to compress UVs"); // l_outputFile.write(reinterpret_cast<char*>(&l_compressedSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(&l_origSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(l_compressedData.data()), l_compressedSize); // std::cout << temp_vertex.size() << " UVs" << std::endl; // // l_origSize = temp_normal.size()*sizeof(glm::vec3); // l_maxSize = GetMaxCompressedLen(l_origSize); // l_compressedData.resize(static_cast<size_t>(l_maxSize)); // l_compressedSize = CompressData(temp_normal.data(), l_origSize, l_compressedData.data(), l_maxSize); // if(l_compressedSize == -1) throw std::exception("Unable to compress normals"); // l_outputFile.write(reinterpret_cast<char*>(&l_compressedSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(&l_origSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(l_compressedData.data()), l_compressedSize); // std::cout << temp_vertex.size() << " normals" << std::endl; // } // if(l_buffer.find("usemtl ") != std::string::npos) // { // if(!l_materialsSizeParsed) // { // int l_materialsSizeI = static_cast<int>(l_materialNames.size()); // l_outputFile.write(reinterpret_cast<char*>(&l_materialsSizeI), sizeof(int)); // l_materialsSizeParsed = true; // std::cout << l_materialsSizeI << " material(s)" << std::endl; // } // if(l_defaultMaterial) continue; // if(l_currentMaterial != -1) // { // std::cout << "Building material " << l_currentMaterial << " ..." << std::endl; // // l_setter = static_cast<unsigned char>(l_materialTypes[static_cast<size_t>(l_currentMaterial)]); // l_outputFile.write(reinterpret_cast<char*>(&l_setter), sizeof(unsigned char)); // glm::vec4 l_params(1.f); // l_outputFile.write(reinterpret_cast<char*>(&l_params), sizeof(glm::vec4)); // l_setter = static_cast<unsigned char>(l_materialTextureNames[static_cast<size_t>(l_currentMaterial)].size()); // l_outputFile.write(reinterpret_cast<char*>(&l_setter), sizeof(unsigned char)); // if(l_setter) l_outputFile.write(l_materialTextureNames[static_cast<size_t>(l_currentMaterial)].data(), l_setter); // // unsigned int l_origSize = l_faceVector.size()*sizeof(Face); // unsigned int l_maxSize = GetMaxCompressedLen(l_origSize); // l_compressedData.resize(static_cast<size_t>(l_maxSize)); // unsigned int l_compressedSize = CompressData(l_faceVector.data(), l_origSize, l_compressedData.data(), l_maxSize); // if(l_compressedSize == 0U) throw std::exception("Unable to compress faces"); // l_outputFile.write(reinterpret_cast<char*>(&l_compressedSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(&l_origSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(l_compressedData.data()), l_compressedSize); // std::cout << l_faceVector.size() << " faces" << std::endl; // l_faceVector.clear(); // } // std::string l_textureName = l_buffer.substr(7U); // l_currentMaterial = static_cast<int>(std::distance(l_materialNames.begin(), std::find(l_materialNames.begin(), l_materialNames.end(), l_textureName))); // if(l_currentMaterial >= int(l_materialNames.size()) || l_currentMaterial < 0) throw std::exception("Unable to parse materials"); // continue; // } // if(l_buffer.find("f ") != std::string::npos) // { // if(!l_materialsSizeParsed) // { // int l_materialsSizeI = static_cast<int>(l_materialNames.size()); // l_outputFile.write(reinterpret_cast<char*>(&l_materialsSizeI), sizeof(int)); // l_materialsSizeParsed = true; // std::cout << l_materialsSizeI << " material(s)" << std::endl; // } // std::string l_faceString = l_buffer.substr(2U); // std::replace(l_faceString.begin(), l_faceString.end(), '/', ' '); // std::stringstream l_faceStream(l_faceString); // Face l_face; // l_faceStream >> // l_face.m_materialIndices[0] >> l_face.m_materialIndices[3] >> l_face.m_materialIndices[6] >> // l_face.m_materialIndices[1] >> l_face.m_materialIndices[4] >> l_face.m_materialIndices[7] >> // l_face.m_materialIndices[2] >> l_face.m_materialIndices[5] >> l_face.m_materialIndices[8]; // if(l_faceStream.fail()) throw std::exception("Invalid face line"); // // for(int i = 0; i < 9; i++) l_face.m_materialIndices[i]--; // l_faceVector.push_back(l_face); // continue; // } // } // if(l_currentMaterial != -1) // { // std::cout << "Building material " << l_currentMaterial << " ..." << std::endl; // // l_setter = static_cast<unsigned char>(l_materialTypes[static_cast<size_t>(l_currentMaterial)]); // l_outputFile.write(reinterpret_cast<char*>(&l_setter), sizeof(unsigned char)); // glm::vec4 l_params(1.f); // l_outputFile.write(reinterpret_cast<char*>(&l_params), sizeof(glm::vec4)); // l_setter = static_cast<unsigned char>(l_materialTextureNames[static_cast<size_t>(l_currentMaterial)].size()); // l_outputFile.write(reinterpret_cast<char*>(&l_setter), sizeof(unsigned char)); // if(l_setter) l_outputFile.write(l_materialTextureNames[static_cast<size_t>(l_currentMaterial)].data(), l_setter); // // unsigned int l_origSize = l_faceVector.size()*sizeof(Face); // unsigned int l_maxSize = GetMaxCompressedLen(l_origSize); // l_compressedData.resize(static_cast<size_t>(l_maxSize)); // unsigned int l_compressedSize = CompressData(l_faceVector.data(), l_origSize, l_compressedData.data(), l_maxSize); // if(l_compressedSize == 0U) throw std::exception("Unable to compress faces"); // l_outputFile.write(reinterpret_cast<char*>(&l_compressedSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(&l_origSize), sizeof(unsigned int)); // l_outputFile.write(reinterpret_cast<char*>(l_compressedData.data()), l_compressedSize); // std::cout << l_faceVector.size() << " faces" << std::endl; // l_faceVector.clear(); // } // l_objectFile.close(); // l_outputFile.flush(); // l_outputFile.close(); // // l_compressedData.clear(); // // std::cout << "Converted to " << f_out << std::endl; // } // catch(const std::exception &e) // { // std::cout << "Failed: " << e.what() << std::endl; // // std::cout << "Cleaning ..." << std::endl; // std::remove(f_out.c_str()); // } //} int main(int argc, char *argv[]) { if(argc > 1) { std::string l_inputFile(argv[1]); Model *l_model = new Model(); bool l_loadResult = false; if(l_inputFile.find(".obj") != std::string::npos) l_loadResult = l_model->LoadOBJ(l_inputFile); else if(l_inputFile.find(".json") != std::string::npos) l_loadResult = l_model->LoadJSON(l_inputFile); else std::cout << "Error: Unknown model file for conversion. Only OBJ and THREE.js are supported" << std::endl; if(l_loadResult) { std::string l_outputFile(l_inputFile + ".rmf"); l_model->Generate(l_outputFile); } delete l_model; } else std::cout << "Usage: [input_file]" << std::endl; std::cout << "Press any key to exit" << std::endl; std::getchar(); return EXIT_SUCCESS; } <commit_msg>Forgotten commented old code<commit_after>#include "stdafx.h" #include "Model.h" int main(int argc, char *argv[]) { if(argc > 1) { std::string l_inputFile(argv[1]); Model *l_model = new Model(); bool l_loadResult = false; if(l_inputFile.find(".obj") != std::string::npos) l_loadResult = l_model->LoadOBJ(l_inputFile); else if(l_inputFile.find(".json") != std::string::npos) l_loadResult = l_model->LoadJSON(l_inputFile); else std::cout << "Error: Unknown model file for conversion. Only OBJ and THREE.js are supported" << std::endl; if(l_loadResult) { std::string l_outputFile(l_inputFile + ".rmf"); l_model->Generate(l_outputFile); } delete l_model; } else std::cout << "Usage: [input_file]" << std::endl; std::cout << "Press any key to exit" << std::endl; std::getchar(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "file.h" #include <sys/stat.h> #include "format.h" #include "log.h" #ifdef _WIN32 #include <windows.h> #endif #include <unistd.h> #include <iomanip> #include <dirent.h> #include <stdlib.h> #ifdef APPLE #include <mach-o/dyld.h> #endif #include <mutex> #ifndef PATH_MAX #define PATH_MAX 4096 #endif namespace utils { using namespace std; File File::NO_FILE; File File::appDir ("/usr/share/" APP_NAME_STR); File File::userDir; File File::cacheDir; File File::configDir; File File::exeDir; File File::homeDir; static mutex fm; File::File() : size(-1), writeFP(nullptr), readFP(nullptr) {} File::File(const string &name, const Mode mode) : fileName(rstrip(name, '/')), size(-1), writeFP(nullptr), readFP(nullptr) { if(mode != NONE) open(mode); } File::File(const string &parent, const string &name, const Mode mode) : size(-1), writeFP(nullptr), readFP(nullptr) { if(parent == "") fileName = rstrip(name, '/'); else fileName = rstrip(parent, '/') + "/" + rstrip(name, '/'); if(mode != NONE) open(mode); } vector<File> File::listFiles() const { DIR *dir; struct dirent *ent; vector<File> rc; if( (dir = opendir(fileName.c_str())) != nullptr) { while ((ent = readdir (dir)) != nullptr) { char *p = ent->d_name; if(p[0] == '.' && (p[1] == 0 || (p[1] == '.' && p[2] == 0))) continue; rc.emplace_back(fileName + "/" + ent->d_name); } } closedir(dir); return rc; } vector<uint8_t> File::readAll() { vector<uint8_t> data; seek(0); data.resize(getSize()); int rc = read(&data[0], data.size()); if(rc != data.size()) throw io_exception{}; return data; } void File::open(const Mode mode) { if(mode == READ) { if(!readFP) { readFP = fopen(fileName.c_str(), "rb"); if(!readFP) throw file_not_found_exception(fileName); } } else if(mode == WRITE) { if(!writeFP) { //makedirs(fileName); writeFP = fopen(fileName.c_str(), "wb"); if(!writeFP) throw io_exception { "Could not open file for writing" }; } } else throw io_exception { "Can't open file with no mode" }; } bool File::isChildOf(const File &f) const { string myPath = resolvePath(getName()); string parentPath = resolvePath(f.getName()); return (myPath.find(parentPath) == 0); } void File::seek(int64_t where) { open(READ); if(!readFP) throw file_not_found_exception(fileName); fseek(readFP, where, SEEK_SET); } int64_t File::tell() { open(READ); if(!readFP) throw file_not_found_exception(fileName); return ftell(readFP); } vector<string> File::getLines() { vector<string> lines; auto data = readAll(); string source { reinterpret_cast<char*>(&data[0]), (unsigned int)data.size() }; stringstream ss(source); string to; while(getline(ss, to)) { auto l = to.length()-1; while(to[l] == 10 || to[l] == 13) to = to.substr(0, l--); lines.push_back(to); } return lines; } void File::write(const uint8_t *data, const int size) { open(WRITE); fwrite(data, 1, size, writeFP); } void File::write(const string &data) { open(WRITE); fwrite(data.c_str(), 1, data.length(), writeFP); } void File::copyFrom(File &otherFile) { open(WRITE); const auto data = otherFile.readAll(); fwrite(&data[0], 1, data.size(), writeFP); } void File::copyFrom(const string &other) { File f { other }; copyFrom(f); f.close(); } void File::close() { if(writeFP) fclose(writeFP); else if(readFP) fclose(readFP); writeFP = readFP = nullptr; } bool File::exists() const { struct stat ss; return (stat(fileName.c_str(), &ss) == 0); } bool File::exists(const string &fileName) { struct stat ss; return (stat(fileName.c_str(), &ss) == 0); } string File::makePath(vector<File> files) { string path = ""; string sep = ""; for(const File& f : files) { path = path + sep + f.getName(); sep = PATH_SEPARATOR_STR; } return path; } File File::findFile(const string &path, const string &name) { LOGD("Find '%s'", name); if(name == "") return NO_FILE; auto parts = split(path, PATH_SEPARATOR_STR); for(string p : parts) { if(p.length() > 0) { if(p[p.length()-1] != '/') p += "/"; LOGD("...in path %s", p); File f { p + name }; if(f.exists()) return f; } } return NO_FILE; } const File& File::getHomeDir() { if(!homeDir) { #ifdef _WIN32 char path[MAX_PATH]; string h = getenv("HOMEPATH"); if(h[0] == '\\') { h = string("C:") + h; replace_char(h, '\\', '/'); } homeDir = File(h); #else homeDir = File(getenv("HOME")); #endif } return homeDir; } static std::string getHome() { return File::getHomeDir().getName(); } #ifdef APP_NAME const File& File::getCacheDir() { lock_guard<mutex> lock(fm); if(!cacheDir) { string home = getHome(); #ifdef _WIN32 replace_char(home, '\\', '/'); #endif auto d = format("%s/.cache/" APP_NAME_STR, home); LOGD("CACHE: %s", d); if(!exists(d)) utils::makedirs(d); cacheDir = File(d); } return cacheDir; } const File& File::getConfigDir() { lock_guard<mutex> lock(fm); if(!configDir) { std::string home = getHome(); #ifdef _WIN32 replace_char(home, '\\', '/'); #endif auto d = format("%s/.config/" APP_NAME_STR, home); LOGD("CACHE: %s", d); if(!exists(d)) utils::makedirs(d); configDir = File(d); } return configDir; } const std::string File::getUserDir() { std::string home = getHome(); #ifdef _WIN32 replace_char(home, '\\', '/'); #endif auto d = format("%s/" APP_NAME_STR, home); if(!exists(d)) utils::makedirs(d); return d + "/"; } #endif uint64_t File::getModified() const { struct stat ss; if(stat(fileName.c_str(), &ss) != 0) throw io_exception {"Could not stat file"}; return (uint64_t)ss.st_mtime; } uint64_t File::getModified(const std::string &fileName) { struct stat ss; if(stat(fileName.c_str(), &ss) != 0) throw io_exception {"Could not stat file"}; return (uint64_t)ss.st_mtime; } int64_t File::getSize() const { if(size < 0) { struct stat ss; if(stat(fileName.c_str(), &ss) != 0) throw io_exception {"Could not stat file"}; size = (uint64_t)ss.st_size; } return size; } bool File::isDir() const { struct stat ss; if(stat(fileName.c_str(), &ss) != 0) throw io_exception {"Could not stat file"}; return S_ISDIR(ss.st_mode); } void File::remove() { close(); if(std::remove(fileName.c_str()) != 0) throw io_exception {"Could not delete file"}; } void File::rename(const std::string &newName) { if(std::rename(fileName.c_str(), newName.c_str()) != 0) throw io_exception {"Could not rename file"}; fileName = newName; } void File::remove(const std::string &fileName) { if(std::remove(fileName.c_str()) != 0) throw io_exception {"Could not delete file"}; } std::string File::read() { open(READ); auto data = readAll(); return std::string(reinterpret_cast<const char *>(&data[0]), (unsigned long)data.size()); } void File::copy(const std::string &from, const std::string &to) { File f0 { from }; File f1 { to }; f1.copyFrom(f0); } std::string File::resolvePath(const std::string &fileName) { char temp[PATH_MAX]; #ifdef _WIN32 //if(GetFullPathNameA(fileName.c_str(), PATH_MAX, temp, NULL) > 0) if(_fullpath(temp, fileName.c_str(), PATH_MAX)) { replace_char(temp, '\\', '/'); return std::string(temp); } #else if(::realpath(fileName.c_str(), temp)) return std::string(temp); #endif return fileName; } File& File::resolve() { char temp[PATH_MAX]; #ifdef _WIN32 if(_fullpath(temp, fileName.c_str(), PATH_MAX)) { replace_char(temp, '\\', '/'); fileName = temp; } #else if(::realpath(fileName.c_str(), temp)) { fileName = temp; } #endif else fileName = ""; return *this; } File File::cwd() { char temp[PATH_MAX]; if(::getcwd(temp, sizeof(temp))) { #ifdef _WIN32 replace_char(temp, '\\', '/'); #endif return File(temp); } throw io_exception {"Could not get current directory"}; } File::~File() { if(readFP) fclose(readFP); if(writeFP) fclose(writeFP); } const File& File::getExeDir() { lock_guard<mutex> lock(fm); if(!exeDir) { static char buf[1024]; #if defined _WIN32 GetModuleFileName(nullptr, buf, sizeof(buf)-1); replace_char(buf, '\\', '/'); char *ptr = &buf[strlen(buf)-1]; while(ptr > buf && *ptr != '/') *ptr-- = 0; *ptr = 0; exeDir = File(buf); #elif defined APPLE uint32_t size = sizeof(buf); if(_NSGetExecutablePath(buf, &size) == 0) { exeDir = File(path_directory(buf)); } #elif defined UNIX int rc = readlink("/proc/self/exe", buf, sizeof(buf)-1); if(rc >= 0) { buf[rc] = 0; exeDir = File(path_directory(buf)); } #endif } LOGD("EXEDIR:%s", exeDir.getName()); exeDir.resolve(); return exeDir; } void File::setAppDir(const std::string &a) { lock_guard<mutex> lock(fm); LOGD("Setting appdir to %s", a); appDir = a; } const File& File::getAppDir() { lock_guard<mutex> lock(fm); if(!appDir) { if(APP_NAME_STR != "") appDir = File("/usr/share/" APP_NAME_STR); else throw io_exception("No appDir specified"); } return appDir; } void File::writeln(const std::string &line) { write(line + "\n"); } File File::changeSuffix(const std::string &ext) { int dot = fileName.find_last_of('.'); if(dot != string::npos) return File(fileName.substr(0, dot) + ext); return File(fileName + ext); } std::string File::suffix() const { int dot = fileName.find_last_of('.'); if(dot != string::npos) return fileName.substr(dot); return ""; } } // namespace #ifdef UNIT_TEST #include "catch.hpp" TEST_CASE("utils::File", "File operations") { using namespace utils; using namespace std; // Delete to be safe std::remove("temp.text"); // File File file { "temp.text" }; REQUIRE(file.getName() == "temp.text"); file.write("First line\nSecond line"); file.close(); REQUIRE(file.exists()); REQUIRE(file.getSize() > 5); REQUIRE(file.getSize() < 50); file = File { "temp.text" }; auto data = file.readAll(); REQUIRE(data.size() > 0); vector<string> lines = file.getLines(); REQUIRE(lines.size() == 2); file.remove(); REQUIRE(!file.exists()); } #endif <commit_msg>Mem trash fix in File::getLines<commit_after>#include "file.h" #include <sys/stat.h> #include "format.h" #include "log.h" #ifdef _WIN32 #include <windows.h> #endif #include <unistd.h> #include <iomanip> #include <dirent.h> #include <stdlib.h> #ifdef APPLE #include <mach-o/dyld.h> #endif #include <mutex> #ifndef PATH_MAX #define PATH_MAX 4096 #endif namespace utils { using namespace std; File File::NO_FILE; File File::appDir ("/usr/share/" APP_NAME_STR); File File::userDir; File File::cacheDir; File File::configDir; File File::exeDir; File File::homeDir; static mutex fm; File::File() : size(-1), writeFP(nullptr), readFP(nullptr) {} File::File(const string &name, const Mode mode) : fileName(rstrip(name, '/')), size(-1), writeFP(nullptr), readFP(nullptr) { if(mode != NONE) open(mode); } File::File(const string &parent, const string &name, const Mode mode) : size(-1), writeFP(nullptr), readFP(nullptr) { if(parent == "") fileName = rstrip(name, '/'); else fileName = rstrip(parent, '/') + "/" + rstrip(name, '/'); if(mode != NONE) open(mode); } vector<File> File::listFiles() const { DIR *dir; struct dirent *ent; vector<File> rc; if( (dir = opendir(fileName.c_str())) != nullptr) { while ((ent = readdir (dir)) != nullptr) { char *p = ent->d_name; if(p[0] == '.' && (p[1] == 0 || (p[1] == '.' && p[2] == 0))) continue; rc.emplace_back(fileName + "/" + ent->d_name); } } closedir(dir); return rc; } vector<uint8_t> File::readAll() { vector<uint8_t> data; seek(0); data.resize(getSize()); int rc = read(&data[0], data.size()); if(rc != data.size()) throw io_exception{}; return data; } void File::open(const Mode mode) { if(mode == READ) { if(!readFP) { readFP = fopen(fileName.c_str(), "rb"); if(!readFP) throw file_not_found_exception(fileName); } } else if(mode == WRITE) { if(!writeFP) { //makedirs(fileName); writeFP = fopen(fileName.c_str(), "wb"); if(!writeFP) throw io_exception { "Could not open file for writing" }; } } else throw io_exception { "Can't open file with no mode" }; } bool File::isChildOf(const File &f) const { string myPath = resolvePath(getName()); string parentPath = resolvePath(f.getName()); return (myPath.find(parentPath) == 0); } void File::seek(int64_t where) { open(READ); if(!readFP) throw file_not_found_exception(fileName); fseek(readFP, where, SEEK_SET); } int64_t File::tell() { open(READ); if(!readFP) throw file_not_found_exception(fileName); return ftell(readFP); } vector<string> File::getLines() { vector<string> lines; auto data = readAll(); string source { reinterpret_cast<char*>(&data[0]), (unsigned int)data.size() }; stringstream ss(source); string to; while(getline(ss, to)) { auto l = to.length(); while(l > 0 && (to[l-1] == 10 || to[l-1] == 13)) l--; lines.push_back(to.substr(0,l)); } return lines; } void File::write(const uint8_t *data, const int size) { open(WRITE); fwrite(data, 1, size, writeFP); } void File::write(const string &data) { open(WRITE); fwrite(data.c_str(), 1, data.length(), writeFP); } void File::copyFrom(File &otherFile) { open(WRITE); const auto data = otherFile.readAll(); fwrite(&data[0], 1, data.size(), writeFP); } void File::copyFrom(const string &other) { File f { other }; copyFrom(f); f.close(); } void File::close() { if(writeFP) fclose(writeFP); else if(readFP) fclose(readFP); writeFP = readFP = nullptr; } bool File::exists() const { struct stat ss; return (stat(fileName.c_str(), &ss) == 0); } bool File::exists(const string &fileName) { struct stat ss; return (stat(fileName.c_str(), &ss) == 0); } string File::makePath(vector<File> files) { string path = ""; string sep = ""; for(const File& f : files) { path = path + sep + f.getName(); sep = PATH_SEPARATOR_STR; } return path; } File File::findFile(const string &path, const string &name) { LOGD("Find '%s'", name); if(name == "") return NO_FILE; auto parts = split(path, PATH_SEPARATOR_STR); for(string p : parts) { if(p.length() > 0) { if(p[p.length()-1] != '/') p += "/"; LOGD("...in path %s", p); File f { p + name }; if(f.exists()) return f; } } return NO_FILE; } const File& File::getHomeDir() { if(!homeDir) { #ifdef _WIN32 char path[MAX_PATH]; string h = getenv("HOMEPATH"); if(h[0] == '\\') { h = string("C:") + h; replace_char(h, '\\', '/'); } homeDir = File(h); #else homeDir = File(getenv("HOME")); #endif } return homeDir; } static std::string getHome() { return File::getHomeDir().getName(); } #ifdef APP_NAME const File& File::getCacheDir() { lock_guard<mutex> lock(fm); if(!cacheDir) { string home = getHome(); #ifdef _WIN32 replace_char(home, '\\', '/'); #endif auto d = format("%s/.cache/" APP_NAME_STR, home); LOGD("CACHE: %s", d); if(!exists(d)) utils::makedirs(d); cacheDir = File(d); } return cacheDir; } const File& File::getConfigDir() { lock_guard<mutex> lock(fm); if(!configDir) { std::string home = getHome(); #ifdef _WIN32 replace_char(home, '\\', '/'); #endif auto d = format("%s/.config/" APP_NAME_STR, home); LOGD("CACHE: %s", d); if(!exists(d)) utils::makedirs(d); configDir = File(d); } return configDir; } const std::string File::getUserDir() { std::string home = getHome(); #ifdef _WIN32 replace_char(home, '\\', '/'); #endif auto d = format("%s/" APP_NAME_STR, home); if(!exists(d)) utils::makedirs(d); return d + "/"; } #endif uint64_t File::getModified() const { struct stat ss; if(stat(fileName.c_str(), &ss) != 0) throw io_exception {"Could not stat file"}; return (uint64_t)ss.st_mtime; } uint64_t File::getModified(const std::string &fileName) { struct stat ss; if(stat(fileName.c_str(), &ss) != 0) throw io_exception {"Could not stat file"}; return (uint64_t)ss.st_mtime; } int64_t File::getSize() const { if(size < 0) { struct stat ss; if(stat(fileName.c_str(), &ss) != 0) throw io_exception {"Could not stat file"}; size = (uint64_t)ss.st_size; } return size; } bool File::isDir() const { struct stat ss; if(stat(fileName.c_str(), &ss) != 0) throw io_exception {"Could not stat file"}; return S_ISDIR(ss.st_mode); } void File::remove() { close(); if(std::remove(fileName.c_str()) != 0) throw io_exception {"Could not delete file"}; } void File::rename(const std::string &newName) { if(std::rename(fileName.c_str(), newName.c_str()) != 0) throw io_exception {"Could not rename file"}; fileName = newName; } void File::remove(const std::string &fileName) { if(std::remove(fileName.c_str()) != 0) throw io_exception {"Could not delete file"}; } std::string File::read() { open(READ); auto data = readAll(); return std::string(reinterpret_cast<const char *>(&data[0]), (unsigned long)data.size()); } void File::copy(const std::string &from, const std::string &to) { File f0 { from }; File f1 { to }; f1.copyFrom(f0); } std::string File::resolvePath(const std::string &fileName) { char temp[PATH_MAX]; #ifdef _WIN32 //if(GetFullPathNameA(fileName.c_str(), PATH_MAX, temp, NULL) > 0) if(_fullpath(temp, fileName.c_str(), PATH_MAX)) { replace_char(temp, '\\', '/'); return std::string(temp); } #else if(::realpath(fileName.c_str(), temp)) return std::string(temp); #endif return fileName; } File& File::resolve() { char temp[PATH_MAX]; #ifdef _WIN32 if(_fullpath(temp, fileName.c_str(), PATH_MAX)) { replace_char(temp, '\\', '/'); fileName = temp; } #else if(::realpath(fileName.c_str(), temp)) { fileName = temp; } #endif else fileName = ""; return *this; } File File::cwd() { char temp[PATH_MAX]; if(::getcwd(temp, sizeof(temp))) { #ifdef _WIN32 replace_char(temp, '\\', '/'); #endif return File(temp); } throw io_exception {"Could not get current directory"}; } File::~File() { if(readFP) fclose(readFP); if(writeFP) fclose(writeFP); } const File& File::getExeDir() { lock_guard<mutex> lock(fm); if(!exeDir) { static char buf[1024]; #if defined _WIN32 GetModuleFileName(nullptr, buf, sizeof(buf)-1); replace_char(buf, '\\', '/'); char *ptr = &buf[strlen(buf)-1]; while(ptr > buf && *ptr != '/') *ptr-- = 0; *ptr = 0; exeDir = File(buf); #elif defined APPLE uint32_t size = sizeof(buf); if(_NSGetExecutablePath(buf, &size) == 0) { exeDir = File(path_directory(buf)); } #elif defined UNIX int rc = readlink("/proc/self/exe", buf, sizeof(buf)-1); if(rc >= 0) { buf[rc] = 0; exeDir = File(path_directory(buf)); } #endif } LOGD("EXEDIR:%s", exeDir.getName()); exeDir.resolve(); return exeDir; } void File::setAppDir(const std::string &a) { lock_guard<mutex> lock(fm); LOGD("Setting appdir to %s", a); appDir = a; } const File& File::getAppDir() { lock_guard<mutex> lock(fm); if(!appDir) { if(APP_NAME_STR != "") appDir = File("/usr/share/" APP_NAME_STR); else throw io_exception("No appDir specified"); } return appDir; } void File::writeln(const std::string &line) { write(line + "\n"); } File File::changeSuffix(const std::string &ext) { int dot = fileName.find_last_of('.'); if(dot != string::npos) return File(fileName.substr(0, dot) + ext); return File(fileName + ext); } std::string File::suffix() const { int dot = fileName.find_last_of('.'); if(dot != string::npos) return fileName.substr(dot); return ""; } } // namespace #ifdef UNIT_TEST #include "catch.hpp" TEST_CASE("utils::File", "File operations") { using namespace utils; using namespace std; // Delete to be safe std::remove("temp.text"); // File File file { "temp.text" }; REQUIRE(file.getName() == "temp.text"); file.write("First line\nSecond line"); file.close(); REQUIRE(file.exists()); REQUIRE(file.getSize() > 5); REQUIRE(file.getSize() < 50); file = File { "temp.text" }; auto data = file.readAll(); REQUIRE(data.size() > 0); vector<string> lines = file.getLines(); REQUIRE(lines.size() == 2); file.remove(); REQUIRE(!file.exists()); } #endif <|endoftext|>
<commit_before>#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> template <typename T1, typename T2> void construct(T1 * ptr, T2 const & value) { new(ptr) T1 (value); } template <typename T> void destroy(T * ptr) noexcept { ptr->~T(); } template <typename FwdIter> void destroy(FwdIter first, FwdIter last) noexcept { for (; first != last; ++first) { destroy(&*first); } } template <typename T> class allocator { protected: allocator(size_t size = 0); ~allocator(); auto swap(allocator & other) -> void; allocator(allocator const &) = delete; auto operator =(allocator const &) -> allocator & = delete; T * ptr_; size_t size_; size_t count_; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), count_(0){}; template<typename T> allocator<T>::~allocator() { operator delete(ptr_); } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(count_, other.count_); std::swap(size_, other.size_); } template <typename T> class stack : private allocator<T> { public: stack(size_t size = 0); //noexcept stack(stack const &); //strong ~stack(); //noexcept size_t count() const; //noexcept auto push(T const &) -> void; //strong void pop(); //basic const T& top(); //strong auto operator=(stack const & right)->stack &; //strong auto empty() const -> bool; //noexcept }; template<typename T> auto newcopy(const T * item, size_t size, size_t count) -> T* //strong { T * buff = new T[size]; try { std::copy(item, item + count, buff); } catch (...) { delete[] buff; throw; } return buff; } template <typename T> size_t stack<T>::count() const { return allocator<T>::count_; } template <typename T> stack<T>::stack(size_t size):allocator<T>(size){} template<typename T> stack<T>::stack(stack const & other) : allocator<T>(other.size_) { for (size_t i = 0; i < other.count_; i++) construct(allocator<T>::ptr_ + i, other.ptr_[i]); allocator<T>::count_ = other.count_; }; template <typename T> stack<T>::~stack() { delete[] array_; } template<typename T> void stack<T>::push(T const &item) { if (allocator<T>::count_ == allocator<T>::array_size_) { size_t array_size = allocator<T>::size_ * 2 + (allocator<T>::size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::ptr_[temp.count()]); this->swap(temp); } construct(allocator<T>::ptr_ + allocator<T>::count_, item); ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator<T>::count_ == 0) { throw ("Stack is empty!"); } else { allocator<T>::count_--; } } template<typename T> const T& stack<T>::top() { if (allocator<T>::count_ == 0) { throw ("Stack is empty!"); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { stack<T> temp (right.size_); while (temp.count_ < right.count_) { construct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]); ++temp.count_; } this -> swap(temp); } return *this; } template<typename T> auto stack<T>::empty() const -> bool { if (allocator<T>::count_ == 0) { return true; } else { return false; } } #endif <commit_msg>Update stack.cpp<commit_after>#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> template <typename T1, typename T2> void construct(T1 * ptr, T2 const & value) { new(ptr) T1 (value); } template <typename T> void destroy(T * ptr) noexcept { ptr->~T(); } template <typename FwdIter> void destroy(FwdIter first, FwdIter last) noexcept { for (; first != last; ++first) { destroy(&*first); } } template <typename T> class allocator { protected: allocator(size_t size = 0); ~allocator(); auto swap(allocator & other) -> void; allocator(allocator const &) = delete; auto operator =(allocator const &) -> allocator & = delete; T * ptr_; size_t size_; size_t count_; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), count_(0){}; template<typename T> allocator<T>::~allocator() { operator delete(ptr_); } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(count_, other.count_); std::swap(size_, other.size_); } template <typename T> class stack : private allocator<T> { public: stack(size_t size = 0); //noexcept stack(stack const &); //strong ~stack(); //noexcept size_t count() const; //noexcept auto push(T const &) -> void; //strong void pop(); //basic const T& top(); //strong auto operator=(stack const & right)->stack &; //strong auto empty() const -> bool; //noexcept }; template<typename T> auto newcopy(const T * item, size_t size, size_t count) -> T* //strong { T * buff = new T[size]; try { std::copy(item, item + count, buff); } catch (...) { delete[] buff; throw; } return buff; } template <typename T> size_t stack<T>::count() const { return allocator<T>::count_; } template <typename T> stack<T>::stack(size_t size):allocator<T>(size){} template<typename T> stack<T>::stack(stack const & other) : allocator<T>(other.size_) { for (size_t i = 0; i < other.count_; i++) construct(allocator<T>::ptr_ + i, other.ptr_[i]); allocator<T>::count_ = other.count_; }; template <typename T> stack<T>::~stack() { delete[] array_; } template<typename T> void stack<T>::push(T const &item) { if (allocator<T>::count_ == allocator<T>::size_) { size_t array_size = allocator<T>::size_ * 2 + (allocator<T>::size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::ptr_[temp.count()]); this->swap(temp); } construct(allocator<T>::ptr_ + allocator<T>::count_, item); ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator<T>::count_ == 0) { throw ("Stack is empty!"); } else { allocator<T>::count_--; } } template<typename T> const T& stack<T>::top() { if (allocator<T>::count_ == 0) { throw ("Stack is empty!"); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { stack<T> temp (right.size_); while (temp.count_ < right.count_) { construct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]); ++temp.count_; } this -> swap(temp); } return *this; } template<typename T> auto stack<T>::empty() const -> bool { if (allocator<T>::count_ == 0) { return true; } else { return false; } } #endif <|endoftext|>
<commit_before> #include "../Flare.h" #include "FlareTravel.h" #include "FlareWorld.h" #include "FlareGame.h" #include "FlareGameTools.h" #include "../Player/FlarePlayerController.h" #include "../UI/Components/FlareNotification.h" #include "../Economy/FlareCargoBay.h" static const double TRAVEL_DURATION_PER_PHASE_KM = 0.4; static const double TRAVEL_DURATION_PER_ALTITUDE_KM = 6; #define LOCTEXT_NAMESPACE "FlareTravelInfos" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareTravel::UFlareTravel(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } void UFlareTravel::Load(const FFlareTravelSave& Data) { Game = Cast<UFlareWorld>(GetOuter())->GetGame(); TravelData = Data; TravelShips.Empty(); Fleet = Game->GetGameWorld()->FindFleet(TravelData.FleetIdentifier); DestinationSector = Game->GetGameWorld()->FindSector(TravelData.DestinationSectorIdentifier); OriginSector = Game->GetGameWorld()->FindSector(TravelData.OriginSectorIdentifier); for (int ShipIndex = 0; ShipIndex < Fleet->GetShips().Num(); ShipIndex++) { TravelShips.Add(Fleet->GetShips()[ShipIndex]); } Fleet->SetCurrentTravel(this); GenerateTravelDuration(); FFlareSectorOrbitParameters OrbitParameters; OrbitParameters = *OriginSector->GetOrbitParameters(); SectorDescription.Name = LOCTEXT("TravelSectorName", "Travelling ..."); SectorDescription.Description = LOCTEXT("TravelSectorDescription", "Travel local sector"); SectorDescription.Identifier=Fleet->GetIdentifier(); SectorDescription.Phase = 0; SectorDescription.IsPeaceful = true; SectorDescription.IsIcy = false; SectorDescription.IsGeostationary = false; SectorDescription.IsSolarPoor = false; SectorDescription.LevelName = NAME_None; SectorDescription.DebrisFieldInfo.DebrisCatalog = NULL; SectorDescription.LevelTrack = EFlareMusicTrack::Pacific; SectorDescription.DebrisFieldInfo.DebrisFieldDensity = 0; SectorDescription.DebrisFieldInfo.MaxDebrisSize = 0; SectorDescription.DebrisFieldInfo.MinDebrisSize = 0; TravelSector = NewObject<UFlareSimulatedSector>(this, UFlareSimulatedSector::StaticClass()); TravelSector->Load(&SectorDescription, Data.SectorData, OrbitParameters); Fleet->SetCurrentSector(TravelSector); TravelSector->AddFleet(Fleet); } FFlareTravelSave* UFlareTravel::Save() { return &TravelData; } /*---------------------------------------------------- Gameplay ----------------------------------------------------*/ void UFlareTravel::Simulate() { if (GetRemainingTravelDuration() <= 0) { EndTravel(); } } void UFlareTravel::EndTravel() { Fleet->SetCurrentSector(DestinationSector); DestinationSector->AddFleet(Fleet); // Place correctly new ships to avoid collision // TODO People migration // Price migration for(int32 ResourceIndex = 0; ResourceIndex < Game->GetResourceCatalog()->Resources.Num(); ResourceIndex++) { FFlareResourceDescription* Resource = &Game->GetResourceCatalog()->Resources[ResourceIndex]->Data; float ContaminationFactor = 0.00f; for (int ShipIndex = 0; ShipIndex < Fleet->GetShips().Num(); ShipIndex++) { UFlareSimulatedSpacecraft* Ship = Fleet->GetShips()[ShipIndex]; if (Ship->GetCargoBay()->GetResourceQuantity(Resource, Ship->GetCompany()) > 0) { ContaminationFactor += Ship->GetCargoBay()->GetResourceQuantity(Resource, Ship->GetCompany()) / 1000.f; //TODO scale bay world stock/flow } } ContaminationFactor = FMath::Min(ContaminationFactor, 1.f); float OriginPrice = OriginSector->GetPreciseResourcePrice(Resource); float DestinationPrice = DestinationSector->GetPreciseResourcePrice(Resource); float Mean = (OriginPrice + DestinationPrice) / 2.f; float NewOriginPrice = (OriginPrice * (1 - ContaminationFactor)) + (ContaminationFactor * Mean); float NewDestinationPrice = (DestinationPrice * (1 - ContaminationFactor)) + (ContaminationFactor * Mean); //FLOGV("Travel start from %s. %s price ajusted from %f to %f (Mean: %f)", *OriginSector->GetSectorName().ToString(), *Resource->Name.ToString(), OriginPrice/100., NewOriginPrice/100., Mean/100.); //FLOGV("Travel end from %s. %s price ajusted from %f to %f (Mean: %f)", *DestinationSector->GetSectorName().ToString(), *Resource->Name.ToString(), DestinationPrice/100., NewDestinationPrice/100., Mean/100.); OriginSector->SetPreciseResourcePrice(Resource, NewOriginPrice); DestinationSector->SetPreciseResourcePrice(Resource, NewDestinationPrice); } Game->GetGameWorld()->DeleteTravel(this); // Notify travel ended if (Fleet->GetFleetCompany() == Game->GetPC()->GetCompany() && Fleet->GetCurrentTradeRoute() == NULL) { FFlareMenuParameterData Data; Data.Sector = DestinationSector; Game->GetPC()->Notify(LOCTEXT("TravelEnded", "Travel ended"), FText::Format(LOCTEXT("TravelEndedFormat", "{0} arrived at {1}"), Fleet->GetFleetName(), DestinationSector->GetSectorName()), FName("travel-end"), EFlareNotification::NT_Economy, false, EFlareMenu::MENU_Sector, Data); } } int64 UFlareTravel::GetElapsedTime() { return Game->GetGameWorld()->GetDate() - TravelData.DepartureDate; } int64 UFlareTravel::GetRemainingTravelDuration() { return TravelDuration - GetElapsedTime(); } void UFlareTravel::ChangeDestination(UFlareSimulatedSector* NewDestinationSector) { if (!CanChangeDestination()) { return; } DestinationSector = NewDestinationSector; TravelData.DestinationSectorIdentifier = DestinationSector->GetIdentifier(); // Reset travel duration // TODO intelligent travel remaining duration change TravelData.DepartureDate = Game->GetGameWorld()->GetDate(); GenerateTravelDuration(); } bool UFlareTravel::CanChangeDestination() { // Travel not possible once started return GetElapsedTime() <= 0; } void UFlareTravel::GenerateTravelDuration() { TravelDuration = ComputeTravelDuration(Game->GetGameWorld(), OriginSector, DestinationSector); } int64 UFlareTravel::ComputeTravelDuration(UFlareWorld* World, UFlareSimulatedSector* OriginSector, UFlareSimulatedSector* DestinationSector) { int64 TravelDuration = 0; if (OriginSector == DestinationSector) { return 0; } double OriginAltitude; double DestinationAltitude; double OriginPhase; double DestinationPhase; FName OriginCelestialBodyIdentifier; FName DestinationCelestialBodyIdentifier; OriginAltitude = OriginSector->GetOrbitParameters()->Altitude; OriginCelestialBodyIdentifier = OriginSector->GetOrbitParameters()->CelestialBodyIdentifier; OriginPhase = OriginSector->GetOrbitParameters()->Phase; DestinationAltitude = DestinationSector->GetOrbitParameters()->Altitude; DestinationCelestialBodyIdentifier = DestinationSector->GetOrbitParameters()->CelestialBodyIdentifier; DestinationPhase = DestinationSector->GetOrbitParameters()->Phase; if (OriginCelestialBodyIdentifier == DestinationCelestialBodyIdentifier && OriginAltitude == DestinationAltitude) { // Phase change travel FFlareCelestialBody* CelestialBody = World->GetPlanerarium()->FindCelestialBody(OriginCelestialBodyIdentifier); TravelDuration = ComputePhaseTravelDuration(World, CelestialBody, OriginAltitude, OriginPhase, DestinationPhase) / UFlareGameTools::SECONDS_IN_DAY; } else { // Altitude change travel FFlareCelestialBody* OriginCelestialBody = World->GetPlanerarium()->FindCelestialBody(OriginCelestialBodyIdentifier); FFlareCelestialBody* DestinationCelestialBody = World->GetPlanerarium()->FindCelestialBody(DestinationCelestialBodyIdentifier); TravelDuration = ComputeAltitudeTravelDuration(World, OriginCelestialBody, OriginAltitude, DestinationCelestialBody, DestinationAltitude) / UFlareGameTools::SECONDS_IN_DAY; } return FMath::Max((int64) 1, TravelDuration); } double UFlareTravel::ComputeSphereOfInfluenceAltitude(UFlareWorld* World, FFlareCelestialBody* CelestialBody) { FFlareCelestialBody* ParentCelestialBody = World->GetPlanerarium()->FindParent(CelestialBody); return CelestialBody->OrbitDistance * pow(CelestialBody->Mass / ParentCelestialBody->Mass, 0.4) - CelestialBody->Radius; } int64 UFlareTravel::ComputePhaseTravelDuration(UFlareWorld* World, FFlareCelestialBody* CelestialBody, double Altitude, double OriginPhase, double DestinationPhase) { double TravelPhase = FMath::Abs(FMath::UnwindDegrees(DestinationPhase - OriginPhase)); double OrbitRadius = CelestialBody->Radius + Altitude; double OrbitPerimeter = 2 * PI * OrbitRadius; double TravelDistance = OrbitPerimeter * TravelPhase / 360; return TRAVEL_DURATION_PER_PHASE_KM * TravelDistance; } int64 UFlareTravel::ComputeAltitudeTravelDuration(UFlareWorld* World, FFlareCelestialBody* OriginCelestialBody, double OriginAltitude, FFlareCelestialBody* DestinationCelestialBody, double DestinationAltitude) { double TravelAltitude; if (OriginCelestialBody == DestinationCelestialBody) { TravelAltitude = ComputeAltitudeTravelDistance(World, OriginAltitude, DestinationAltitude); } else if (World->GetPlanerarium()->IsSatellite(DestinationCelestialBody, OriginCelestialBody)) { // Planet to moon TravelAltitude = ComputeAltitudeTravelToMoonDistance(World, OriginCelestialBody, OriginAltitude, DestinationCelestialBody) + ComputeAltitudeTravelToSoiDistance(World, DestinationCelestialBody, DestinationAltitude); } else if (World->GetPlanerarium()->IsSatellite(OriginCelestialBody, DestinationCelestialBody)) { // Moon to planet TravelAltitude = ComputeAltitudeTravelToSoiDistance(World, OriginCelestialBody, OriginAltitude) + ComputeAltitudeTravelToMoonDistance(World, DestinationCelestialBody, DestinationAltitude, OriginCelestialBody); } else { TravelAltitude = ComputeAltitudeTravelToSoiDistance(World, OriginCelestialBody, OriginAltitude) + ComputeAltitudeTravelMoonToMoonDistance(World, OriginCelestialBody, DestinationCelestialBody) + ComputeAltitudeTravelToSoiDistance(World, DestinationCelestialBody, DestinationAltitude); } return TRAVEL_DURATION_PER_ALTITUDE_KM * TravelAltitude; } double UFlareTravel::ComputeAltitudeTravelDistance(UFlareWorld* World, double OriginAltitude, double DestinationAltitude) { // Altitude change in same celestial body return FMath::Abs(DestinationAltitude - OriginAltitude); } double UFlareTravel::ComputeAltitudeTravelToSoiDistance(UFlareWorld* World, FFlareCelestialBody* CelestialBody, double Altitude) { double MoonSoiAltitude = ComputeSphereOfInfluenceAltitude(World, CelestialBody); // Travel from moon SOI to moon target altitude return FMath::Abs(Altitude - MoonSoiAltitude); } double UFlareTravel::ComputeAltitudeTravelToMoonDistance(UFlareWorld* World, FFlareCelestialBody* ParentCelestialBody, double Altitude, FFlareCelestialBody* MoonCelestialBody) { double MoonAltitude = MoonCelestialBody->OrbitDistance - ParentCelestialBody->Radius; // Travel to moon altitude return FMath::Abs(MoonAltitude - Altitude); } double UFlareTravel::ComputeAltitudeTravelMoonToMoonDistance(UFlareWorld* World, FFlareCelestialBody* OriginCelestialBody, FFlareCelestialBody* DestinationCelestialBody) { // Moon1 orbit to moon2 orbit return FMath::Abs(DestinationCelestialBody->OrbitDistance - OriginCelestialBody->OrbitDistance); } void UFlareTravel::InitTravelSector(FFlareSectorSave& NewSectorData) { // Init new travel sector NewSectorData.GivenName = FText(); NewSectorData.Identifier = TEXT("Travel"); NewSectorData.LocalTime = 0; NewSectorData.IsTravelSector = true; // Init population NewSectorData.PeopleData.Population = 0; NewSectorData.PeopleData.BirthPoint = 0; NewSectorData.PeopleData.DeathPoint = 0; NewSectorData.PeopleData.FoodStock = 0; NewSectorData.PeopleData.FuelStock = 0; NewSectorData.PeopleData.ToolStock = 0; NewSectorData.PeopleData.TechStock = 0; NewSectorData.PeopleData.FoodConsumption = 0; NewSectorData.PeopleData.FuelConsumption = 0; NewSectorData.PeopleData.ToolConsumption = 0; NewSectorData.PeopleData.TechConsumption = 0; NewSectorData.PeopleData.HappinessPoint = 0; NewSectorData.PeopleData.HungerPoint = 0; NewSectorData.PeopleData.Money = 0; NewSectorData.PeopleData.Dept = 0; } #undef LOCTEXT_NAMESPACE <commit_msg>#415 Fix not consistent travel duration<commit_after> #include "../Flare.h" #include "FlareTravel.h" #include "FlareWorld.h" #include "FlareGame.h" #include "FlareGameTools.h" #include "../Player/FlarePlayerController.h" #include "../UI/Components/FlareNotification.h" #include "../Economy/FlareCargoBay.h" static const double TRAVEL_DURATION_PER_PHASE_KM = 0.4; static const double TRAVEL_DURATION_PER_ALTITUDE_KM = 6.0; #define LOCTEXT_NAMESPACE "FlareTravelInfos" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareTravel::UFlareTravel(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } void UFlareTravel::Load(const FFlareTravelSave& Data) { Game = Cast<UFlareWorld>(GetOuter())->GetGame(); TravelData = Data; TravelShips.Empty(); Fleet = Game->GetGameWorld()->FindFleet(TravelData.FleetIdentifier); DestinationSector = Game->GetGameWorld()->FindSector(TravelData.DestinationSectorIdentifier); OriginSector = Game->GetGameWorld()->FindSector(TravelData.OriginSectorIdentifier); for (int ShipIndex = 0; ShipIndex < Fleet->GetShips().Num(); ShipIndex++) { TravelShips.Add(Fleet->GetShips()[ShipIndex]); } Fleet->SetCurrentTravel(this); GenerateTravelDuration(); FFlareSectorOrbitParameters OrbitParameters; OrbitParameters = *OriginSector->GetOrbitParameters(); SectorDescription.Name = LOCTEXT("TravelSectorName", "Travelling ..."); SectorDescription.Description = LOCTEXT("TravelSectorDescription", "Travel local sector"); SectorDescription.Identifier=Fleet->GetIdentifier(); SectorDescription.Phase = 0; SectorDescription.IsPeaceful = true; SectorDescription.IsIcy = false; SectorDescription.IsGeostationary = false; SectorDescription.IsSolarPoor = false; SectorDescription.LevelName = NAME_None; SectorDescription.DebrisFieldInfo.DebrisCatalog = NULL; SectorDescription.LevelTrack = EFlareMusicTrack::Pacific; SectorDescription.DebrisFieldInfo.DebrisFieldDensity = 0; SectorDescription.DebrisFieldInfo.MaxDebrisSize = 0; SectorDescription.DebrisFieldInfo.MinDebrisSize = 0; TravelSector = NewObject<UFlareSimulatedSector>(this, UFlareSimulatedSector::StaticClass()); TravelSector->Load(&SectorDescription, Data.SectorData, OrbitParameters); Fleet->SetCurrentSector(TravelSector); TravelSector->AddFleet(Fleet); } FFlareTravelSave* UFlareTravel::Save() { return &TravelData; } /*---------------------------------------------------- Gameplay ----------------------------------------------------*/ void UFlareTravel::Simulate() { if (GetRemainingTravelDuration() <= 0) { EndTravel(); } } void UFlareTravel::EndTravel() { Fleet->SetCurrentSector(DestinationSector); DestinationSector->AddFleet(Fleet); // Place correctly new ships to avoid collision // TODO People migration // Price migration for(int32 ResourceIndex = 0; ResourceIndex < Game->GetResourceCatalog()->Resources.Num(); ResourceIndex++) { FFlareResourceDescription* Resource = &Game->GetResourceCatalog()->Resources[ResourceIndex]->Data; float ContaminationFactor = 0.00f; for (int ShipIndex = 0; ShipIndex < Fleet->GetShips().Num(); ShipIndex++) { UFlareSimulatedSpacecraft* Ship = Fleet->GetShips()[ShipIndex]; if (Ship->GetCargoBay()->GetResourceQuantity(Resource, Ship->GetCompany()) > 0) { ContaminationFactor += Ship->GetCargoBay()->GetResourceQuantity(Resource, Ship->GetCompany()) / 1000.f; //TODO scale bay world stock/flow } } ContaminationFactor = FMath::Min(ContaminationFactor, 1.f); float OriginPrice = OriginSector->GetPreciseResourcePrice(Resource); float DestinationPrice = DestinationSector->GetPreciseResourcePrice(Resource); float Mean = (OriginPrice + DestinationPrice) / 2.f; float NewOriginPrice = (OriginPrice * (1 - ContaminationFactor)) + (ContaminationFactor * Mean); float NewDestinationPrice = (DestinationPrice * (1 - ContaminationFactor)) + (ContaminationFactor * Mean); //FLOGV("Travel start from %s. %s price ajusted from %f to %f (Mean: %f)", *OriginSector->GetSectorName().ToString(), *Resource->Name.ToString(), OriginPrice/100., NewOriginPrice/100., Mean/100.); //FLOGV("Travel end from %s. %s price ajusted from %f to %f (Mean: %f)", *DestinationSector->GetSectorName().ToString(), *Resource->Name.ToString(), DestinationPrice/100., NewDestinationPrice/100., Mean/100.); OriginSector->SetPreciseResourcePrice(Resource, NewOriginPrice); DestinationSector->SetPreciseResourcePrice(Resource, NewDestinationPrice); } Game->GetGameWorld()->DeleteTravel(this); // Notify travel ended if (Fleet->GetFleetCompany() == Game->GetPC()->GetCompany() && Fleet->GetCurrentTradeRoute() == NULL) { FFlareMenuParameterData Data; Data.Sector = DestinationSector; Game->GetPC()->Notify(LOCTEXT("TravelEnded", "Travel ended"), FText::Format(LOCTEXT("TravelEndedFormat", "{0} arrived at {1}"), Fleet->GetFleetName(), DestinationSector->GetSectorName()), FName("travel-end"), EFlareNotification::NT_Economy, false, EFlareMenu::MENU_Sector, Data); } } int64 UFlareTravel::GetElapsedTime() { return Game->GetGameWorld()->GetDate() - TravelData.DepartureDate; } int64 UFlareTravel::GetRemainingTravelDuration() { return TravelDuration - GetElapsedTime(); } void UFlareTravel::ChangeDestination(UFlareSimulatedSector* NewDestinationSector) { if (!CanChangeDestination()) { return; } DestinationSector = NewDestinationSector; TravelData.DestinationSectorIdentifier = DestinationSector->GetIdentifier(); // Reset travel duration // TODO intelligent travel remaining duration change TravelData.DepartureDate = Game->GetGameWorld()->GetDate(); GenerateTravelDuration(); } bool UFlareTravel::CanChangeDestination() { // Travel not possible once started return GetElapsedTime() <= 0; } void UFlareTravel::GenerateTravelDuration() { TravelDuration = ComputeTravelDuration(Game->GetGameWorld(), OriginSector, DestinationSector); } int64 UFlareTravel::ComputeTravelDuration(UFlareWorld* World, UFlareSimulatedSector* OriginSector, UFlareSimulatedSector* DestinationSector) { int64 TravelDuration = 0; if (OriginSector == DestinationSector) { return 0; } double OriginAltitude; double DestinationAltitude; double OriginPhase; double DestinationPhase; FName OriginCelestialBodyIdentifier; FName DestinationCelestialBodyIdentifier; OriginAltitude = OriginSector->GetOrbitParameters()->Altitude; OriginCelestialBodyIdentifier = OriginSector->GetOrbitParameters()->CelestialBodyIdentifier; OriginPhase = OriginSector->GetOrbitParameters()->Phase; DestinationAltitude = DestinationSector->GetOrbitParameters()->Altitude; DestinationCelestialBodyIdentifier = DestinationSector->GetOrbitParameters()->CelestialBodyIdentifier; DestinationPhase = DestinationSector->GetOrbitParameters()->Phase; if (OriginCelestialBodyIdentifier == DestinationCelestialBodyIdentifier && OriginAltitude == DestinationAltitude) { // Phase change travel FFlareCelestialBody* CelestialBody = World->GetPlanerarium()->FindCelestialBody(OriginCelestialBodyIdentifier); TravelDuration = ComputePhaseTravelDuration(World, CelestialBody, OriginAltitude, OriginPhase, DestinationPhase) / UFlareGameTools::SECONDS_IN_DAY; } else { // Altitude change travel FFlareCelestialBody* OriginCelestialBody = World->GetPlanerarium()->FindCelestialBody(OriginCelestialBodyIdentifier); FFlareCelestialBody* DestinationCelestialBody = World->GetPlanerarium()->FindCelestialBody(DestinationCelestialBodyIdentifier); TravelDuration = (UFlareGameTools::SECONDS_IN_DAY/2 + ComputeAltitudeTravelDuration(World, OriginCelestialBody, OriginAltitude, DestinationCelestialBody, DestinationAltitude)) / UFlareGameTools::SECONDS_IN_DAY; } return FMath::Max((int64) 1, TravelDuration); } double UFlareTravel::ComputeSphereOfInfluenceAltitude(UFlareWorld* World, FFlareCelestialBody* CelestialBody) { FFlareCelestialBody* ParentCelestialBody = World->GetPlanerarium()->FindParent(CelestialBody); return CelestialBody->OrbitDistance * pow(CelestialBody->Mass / ParentCelestialBody->Mass, 0.4) - CelestialBody->Radius; } int64 UFlareTravel::ComputePhaseTravelDuration(UFlareWorld* World, FFlareCelestialBody* CelestialBody, double Altitude, double OriginPhase, double DestinationPhase) { double TravelPhase = FMath::Abs(FMath::UnwindDegrees(DestinationPhase - OriginPhase)); double OrbitRadius = CelestialBody->Radius + Altitude; double OrbitPerimeter = 2 * PI * OrbitRadius; double TravelDistance = OrbitPerimeter * TravelPhase / 360; return TRAVEL_DURATION_PER_PHASE_KM * TravelDistance; } int64 UFlareTravel::ComputeAltitudeTravelDuration(UFlareWorld* World, FFlareCelestialBody* OriginCelestialBody, double OriginAltitude, FFlareCelestialBody* DestinationCelestialBody, double DestinationAltitude) { double TravelAltitude; if (OriginCelestialBody == DestinationCelestialBody) { TravelAltitude = ComputeAltitudeTravelDistance(World, OriginAltitude, DestinationAltitude); } else if (World->GetPlanerarium()->IsSatellite(DestinationCelestialBody, OriginCelestialBody)) { // Planet to moon TravelAltitude = ComputeAltitudeTravelToMoonDistance(World, OriginCelestialBody, OriginAltitude, DestinationCelestialBody) + ComputeAltitudeTravelToSoiDistance(World, DestinationCelestialBody, DestinationAltitude); } else if (World->GetPlanerarium()->IsSatellite(OriginCelestialBody, DestinationCelestialBody)) { // Moon to planet TravelAltitude = ComputeAltitudeTravelToSoiDistance(World, OriginCelestialBody, OriginAltitude) + ComputeAltitudeTravelToMoonDistance(World, DestinationCelestialBody, DestinationAltitude, OriginCelestialBody); } else { TravelAltitude = ComputeAltitudeTravelToSoiDistance(World, OriginCelestialBody, OriginAltitude) + ComputeAltitudeTravelMoonToMoonDistance(World, OriginCelestialBody, DestinationCelestialBody) + ComputeAltitudeTravelToSoiDistance(World, DestinationCelestialBody, DestinationAltitude); } return TRAVEL_DURATION_PER_ALTITUDE_KM * TravelAltitude; } double UFlareTravel::ComputeAltitudeTravelDistance(UFlareWorld* World, double OriginAltitude, double DestinationAltitude) { // Altitude change in same celestial body return FMath::Abs(DestinationAltitude - OriginAltitude); } double UFlareTravel::ComputeAltitudeTravelToSoiDistance(UFlareWorld* World, FFlareCelestialBody* CelestialBody, double Altitude) { double MoonSoiAltitude = ComputeSphereOfInfluenceAltitude(World, CelestialBody); // Travel from moon SOI to moon target altitude return FMath::Abs(Altitude - MoonSoiAltitude); } double UFlareTravel::ComputeAltitudeTravelToMoonDistance(UFlareWorld* World, FFlareCelestialBody* ParentCelestialBody, double Altitude, FFlareCelestialBody* MoonCelestialBody) { double MoonAltitude = MoonCelestialBody->OrbitDistance - ParentCelestialBody->Radius; // Travel to moon altitude return FMath::Abs(MoonAltitude - Altitude); } double UFlareTravel::ComputeAltitudeTravelMoonToMoonDistance(UFlareWorld* World, FFlareCelestialBody* OriginCelestialBody, FFlareCelestialBody* DestinationCelestialBody) { // Moon1 orbit to moon2 orbit return FMath::Abs(DestinationCelestialBody->OrbitDistance - OriginCelestialBody->OrbitDistance); } void UFlareTravel::InitTravelSector(FFlareSectorSave& NewSectorData) { // Init new travel sector NewSectorData.GivenName = FText(); NewSectorData.Identifier = TEXT("Travel"); NewSectorData.LocalTime = 0; NewSectorData.IsTravelSector = true; // Init population NewSectorData.PeopleData.Population = 0; NewSectorData.PeopleData.BirthPoint = 0; NewSectorData.PeopleData.DeathPoint = 0; NewSectorData.PeopleData.FoodStock = 0; NewSectorData.PeopleData.FuelStock = 0; NewSectorData.PeopleData.ToolStock = 0; NewSectorData.PeopleData.TechStock = 0; NewSectorData.PeopleData.FoodConsumption = 0; NewSectorData.PeopleData.FuelConsumption = 0; NewSectorData.PeopleData.ToolConsumption = 0; NewSectorData.PeopleData.TechConsumption = 0; NewSectorData.PeopleData.HappinessPoint = 0; NewSectorData.PeopleData.HungerPoint = 0; NewSectorData.PeopleData.Money = 0; NewSectorData.PeopleData.Dept = 0; } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>/* * Copyright 2014 Cloudius Systems */ #ifndef SSTRING_HH_ #define SSTRING_HH_ #include <stdint.h> #include <algorithm> #include <string> #include <cstring> #include <stdexcept> #include <initializer_list> #include <iostream> #include <functional> #include <cstdio> #include <experimental/string_view> #include "core/temporary_buffer.hh" template <typename char_type, typename size_type, size_type max_size> class basic_sstring { union contents { struct external_type { char* str; size_type size; int8_t pad; } external; struct internal_type { char str[max_size]; int8_t size; } internal; static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small"); static_assert(max_size <= 127, "max_size too large"); } u; bool is_internal() const noexcept { return u.internal.size >= 0; } bool is_external() const noexcept { return !is_internal(); } const char* str() const { return is_internal() ? u.internal.str : u.external.str; } char* str() { return is_internal() ? u.internal.str : u.external.str; } public: struct initialized_later {}; basic_sstring() noexcept { u.internal.size = 0; u.internal.str[0] = '\0'; } basic_sstring(const basic_sstring& x) { if (x.is_internal()) { u.internal = x.u.internal; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char*>(std::malloc(x.u.external.size + 1)); if (!u.external.str) { throw std::bad_alloc(); } std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str); u.external.size = x.u.external.size; } } basic_sstring(basic_sstring&& x) noexcept { u = x.u; x.u.internal.size = 0; x.u.internal.str[0] = '\0'; } basic_sstring(initialized_later, size_t size) { if (size_type(size) != size) { throw std::overflow_error("sstring overflow"); } if (size + 1 <= sizeof(u.internal.str)) { u.internal.str[size] = '\0'; u.internal.size = size; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char*>(std::malloc(size + 1)); if (!u.external.str) { throw std::bad_alloc(); } u.external.size = size; u.external.str[size] = '\0'; } } basic_sstring(const char_type* x, size_t size) { if (size_type(size) != size) { throw std::overflow_error("sstring overflow"); } if (size + 1 <= sizeof(u.internal.str)) { std::copy(x, x + size, u.internal.str); u.internal.str[size] = '\0'; u.internal.size = size; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char*>(std::malloc(size + 1)); if (!u.external.str) { throw std::bad_alloc(); } u.external.size = size; std::copy(x, x + size, u.external.str); u.external.str[size] = '\0'; } } basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {} basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {} basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {} basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {} basic_sstring(const std::basic_string<char_type>& s) : basic_sstring(s.data(), s.size()) {} ~basic_sstring() noexcept { if (is_external()) { std::free(u.external.str); } } basic_sstring& operator=(const basic_sstring& x) { basic_sstring tmp(x); swap(tmp); return *this; } basic_sstring& operator=(basic_sstring&& x) noexcept { if (this != &x) { swap(x); x.reset(); } return *this; } operator std::string() const { return { str(), size() }; } size_t size() const noexcept { return is_internal() ? u.internal.size : u.external.size; } bool empty() const noexcept { return u.internal.size == 0; } void reset() noexcept { if (is_external()) { std::free(u.external.str); } u.internal.size = 0; u.internal.str[0] = '\0'; } temporary_buffer<char_type> release() && { if (is_external()) { auto ptr = u.external.str; auto size = u.external.size; u.external.str = nullptr; u.external.size = 0; return temporary_buffer<char_type>(ptr, size, make_free_deleter(ptr)); } else { auto buf = temporary_buffer<char_type>(u.internal.size); std::copy(u.internal.str, u.internal.str + u.internal.size, buf.get_write()); u.internal.size = 0; u.internal.str[0] = '\0'; return buf; } } void swap(basic_sstring& x) noexcept { contents tmp; tmp = x.u; x.u = u; u = tmp; } const char* c_str() const { return str(); } const char_type* begin() const { return str(); } const char_type* end() const { return str() + size(); } char_type* begin() { return str(); } char_type* end() { return str() + size(); } bool operator==(const basic_sstring& x) const { return size() == x.size() && std::equal(begin(), end(), x.begin()); } bool operator!=(const basic_sstring& x) const { return !operator==(x); } basic_sstring operator+(const basic_sstring& x) const { basic_sstring ret(initialized_later(), size() + x.size()); std::copy(begin(), end(), ret.begin()); std::copy(x.begin(), x.end(), ret.begin() + size()); return ret; } basic_sstring& operator+=(const basic_sstring& x) { return *this = *this + x; } operator std::experimental::string_view() const { return std::experimental::string_view(str(), size()); } }; template <size_t N> static inline size_t str_len(const char(&s)[N]) { return N - 1; } template <size_t N> static inline const char* str_begin(const char(&s)[N]) { return s; } template <size_t N> static inline const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); } template <typename char_type, typename size_type, size_type max_size> static inline const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); } template <typename char_type, typename size_type, size_type max_size> static inline const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); } template <typename char_type, typename size_type, size_type max_size> static inline size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); } template <typename First, typename Second, typename... Tail> static inline const size_t str_len(const First& first, const Second& second, const Tail&... tail) { return str_len(first) + str_len(second, tail...); } template <typename char_type, typename size_type, size_type max_size> inline void swap(basic_sstring<char_type, size_type, max_size>& x, basic_sstring<char_type, size_type, max_size>& y) noexcept { return x.swap(y); } template <typename char_type, typename size_type, size_type max_size, typename char_traits> inline std::basic_ostream<char_type, char_traits>& operator<<(std::basic_ostream<char_type, char_traits>& os, const basic_sstring<char_type, size_type, max_size>& s) { return os.write(s.begin(), s.size()); } namespace std { template <typename char_type, typename size_type, size_type max_size> struct hash<basic_sstring<char_type, size_type, max_size>> { size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const { return std::hash<std::experimental::string_view>()(s); } }; } using sstring = basic_sstring<char, uint32_t, 15>; static inline char* copy_str_to(char* dst) { return dst; } template <typename Head, typename... Tail> static inline char* copy_str_to(char* dst, const Head& head, const Tail&... tail) { return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...); } template <typename String = sstring, typename... Args> static String make_sstring(Args&&... args) { String ret(sstring::initialized_later(), str_len(args...)); copy_str_to(ret.begin(), args...); return ret; } template <typename T, typename String = sstring, typename for_enable_if = void*> String to_sstring(T value, for_enable_if); template <typename T> inline sstring to_sstring_sprintf(T value, const char* fmt) { char tmp[sizeof(value) * 3 + 3]; auto len = std::sprintf(tmp, fmt, value); return sstring(tmp, len); } template <typename string_type = sstring> inline string_type to_sstring(int value, void* = nullptr) { return to_sstring_sprintf(value, "%d"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned value, void* = nullptr) { return to_sstring_sprintf(value, "%u"); } template <typename string_type = sstring> inline string_type to_sstring(long value, void* = nullptr) { return to_sstring_sprintf(value, "%ld"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned long value, void* = nullptr) { return to_sstring_sprintf(value, "%lu"); } template <typename string_type = sstring> inline string_type to_sstring(long long value, void* = nullptr) { return to_sstring_sprintf(value, "%lld"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned long long value, void* = nullptr) { return to_sstring_sprintf(value, "%llu"); } template <typename string_type = sstring> inline string_type to_sstring(const char* value, void* = nullptr) { return string_type(value); } template <typename string_type = sstring> inline string_type to_sstring(sstring value, void* = nullptr) { return value; } template <typename string_type = sstring> static string_type to_sstring(const temporary_buffer<char>& buf) { return string_type(buf.get(), buf.size()); } template <typename T> inline std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { bool first = true; os << "{"; for (auto&& elem : v) { if (!first) { os << ", "; } else { first = false; } os << elem; } os << "}"; return os; } #endif /* SSTRING_HH_ */ <commit_msg>sstring: fix character type<commit_after>/* * Copyright 2014 Cloudius Systems */ #ifndef SSTRING_HH_ #define SSTRING_HH_ #include <stdint.h> #include <algorithm> #include <string> #include <cstring> #include <stdexcept> #include <initializer_list> #include <iostream> #include <functional> #include <cstdio> #include <experimental/string_view> #include "core/temporary_buffer.hh" template <typename char_type, typename size_type, size_type max_size> class basic_sstring { union contents { struct external_type { char_type* str; size_type size; int8_t pad; } external; struct internal_type { char_type str[max_size]; int8_t size; } internal; static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small"); static_assert(max_size <= 127, "max_size too large"); } u; bool is_internal() const noexcept { return u.internal.size >= 0; } bool is_external() const noexcept { return !is_internal(); } const char_type* str() const { return is_internal() ? u.internal.str : u.external.str; } char_type* str() { return is_internal() ? u.internal.str : u.external.str; } public: struct initialized_later {}; basic_sstring() noexcept { u.internal.size = 0; u.internal.str[0] = '\0'; } basic_sstring(const basic_sstring& x) { if (x.is_internal()) { u.internal = x.u.internal; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char_type*>(std::malloc(x.u.external.size + 1)); if (!u.external.str) { throw std::bad_alloc(); } std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str); u.external.size = x.u.external.size; } } basic_sstring(basic_sstring&& x) noexcept { u = x.u; x.u.internal.size = 0; x.u.internal.str[0] = '\0'; } basic_sstring(initialized_later, size_t size) { if (size_type(size) != size) { throw std::overflow_error("sstring overflow"); } if (size + 1 <= sizeof(u.internal.str)) { u.internal.str[size] = '\0'; u.internal.size = size; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1)); if (!u.external.str) { throw std::bad_alloc(); } u.external.size = size; u.external.str[size] = '\0'; } } basic_sstring(const char_type* x, size_t size) { if (size_type(size) != size) { throw std::overflow_error("sstring overflow"); } if (size + 1 <= sizeof(u.internal.str)) { std::copy(x, x + size, u.internal.str); u.internal.str[size] = '\0'; u.internal.size = size; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1)); if (!u.external.str) { throw std::bad_alloc(); } u.external.size = size; std::copy(x, x + size, u.external.str); u.external.str[size] = '\0'; } } basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {} basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {} basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {} basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {} basic_sstring(const std::basic_string<char_type>& s) : basic_sstring(s.data(), s.size()) {} ~basic_sstring() noexcept { if (is_external()) { std::free(u.external.str); } } basic_sstring& operator=(const basic_sstring& x) { basic_sstring tmp(x); swap(tmp); return *this; } basic_sstring& operator=(basic_sstring&& x) noexcept { if (this != &x) { swap(x); x.reset(); } return *this; } operator std::string() const { return { str(), size() }; } size_t size() const noexcept { return is_internal() ? u.internal.size : u.external.size; } bool empty() const noexcept { return u.internal.size == 0; } void reset() noexcept { if (is_external()) { std::free(u.external.str); } u.internal.size = 0; u.internal.str[0] = '\0'; } temporary_buffer<char_type> release() && { if (is_external()) { auto ptr = u.external.str; auto size = u.external.size; u.external.str = nullptr; u.external.size = 0; return temporary_buffer<char_type>(ptr, size, make_free_deleter(ptr)); } else { auto buf = temporary_buffer<char_type>(u.internal.size); std::copy(u.internal.str, u.internal.str + u.internal.size, buf.get_write()); u.internal.size = 0; u.internal.str[0] = '\0'; return buf; } } void swap(basic_sstring& x) noexcept { contents tmp; tmp = x.u; x.u = u; u = tmp; } const char_type* c_str() const { return str(); } const char_type* begin() const { return str(); } const char_type* end() const { return str() + size(); } char_type* begin() { return str(); } char_type* end() { return str() + size(); } bool operator==(const basic_sstring& x) const { return size() == x.size() && std::equal(begin(), end(), x.begin()); } bool operator!=(const basic_sstring& x) const { return !operator==(x); } basic_sstring operator+(const basic_sstring& x) const { basic_sstring ret(initialized_later(), size() + x.size()); std::copy(begin(), end(), ret.begin()); std::copy(x.begin(), x.end(), ret.begin() + size()); return ret; } basic_sstring& operator+=(const basic_sstring& x) { return *this = *this + x; } operator std::experimental::string_view() const { return std::experimental::string_view(str(), size()); } }; template <size_t N> static inline size_t str_len(const char(&s)[N]) { return N - 1; } template <size_t N> static inline const char* str_begin(const char(&s)[N]) { return s; } template <size_t N> static inline const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); } template <typename char_type, typename size_type, size_type max_size> static inline const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); } template <typename char_type, typename size_type, size_type max_size> static inline const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); } template <typename char_type, typename size_type, size_type max_size> static inline size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); } template <typename First, typename Second, typename... Tail> static inline const size_t str_len(const First& first, const Second& second, const Tail&... tail) { return str_len(first) + str_len(second, tail...); } template <typename char_type, typename size_type, size_type max_size> inline void swap(basic_sstring<char_type, size_type, max_size>& x, basic_sstring<char_type, size_type, max_size>& y) noexcept { return x.swap(y); } template <typename char_type, typename size_type, size_type max_size, typename char_traits> inline std::basic_ostream<char_type, char_traits>& operator<<(std::basic_ostream<char_type, char_traits>& os, const basic_sstring<char_type, size_type, max_size>& s) { return os.write(s.begin(), s.size()); } namespace std { template <typename char_type, typename size_type, size_type max_size> struct hash<basic_sstring<char_type, size_type, max_size>> { size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const { return std::hash<std::experimental::string_view>()(s); } }; } using sstring = basic_sstring<char, uint32_t, 15>; static inline char* copy_str_to(char* dst) { return dst; } template <typename Head, typename... Tail> static inline char* copy_str_to(char* dst, const Head& head, const Tail&... tail) { return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...); } template <typename String = sstring, typename... Args> static String make_sstring(Args&&... args) { String ret(sstring::initialized_later(), str_len(args...)); copy_str_to(ret.begin(), args...); return ret; } template <typename T, typename String = sstring, typename for_enable_if = void*> String to_sstring(T value, for_enable_if); template <typename T> inline sstring to_sstring_sprintf(T value, const char* fmt) { char tmp[sizeof(value) * 3 + 3]; auto len = std::sprintf(tmp, fmt, value); return sstring(tmp, len); } template <typename string_type = sstring> inline string_type to_sstring(int value, void* = nullptr) { return to_sstring_sprintf(value, "%d"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned value, void* = nullptr) { return to_sstring_sprintf(value, "%u"); } template <typename string_type = sstring> inline string_type to_sstring(long value, void* = nullptr) { return to_sstring_sprintf(value, "%ld"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned long value, void* = nullptr) { return to_sstring_sprintf(value, "%lu"); } template <typename string_type = sstring> inline string_type to_sstring(long long value, void* = nullptr) { return to_sstring_sprintf(value, "%lld"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned long long value, void* = nullptr) { return to_sstring_sprintf(value, "%llu"); } template <typename string_type = sstring> inline string_type to_sstring(const char* value, void* = nullptr) { return string_type(value); } template <typename string_type = sstring> inline string_type to_sstring(sstring value, void* = nullptr) { return value; } template <typename string_type = sstring> static string_type to_sstring(const temporary_buffer<char>& buf) { return string_type(buf.get(), buf.size()); } template <typename T> inline std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { bool first = true; os << "{"; for (auto&& elem : v) { if (!first) { os << ", "; } else { first = false; } os << elem; } os << "}"; return os; } #endif /* SSTRING_HH_ */ <|endoftext|>
<commit_before>// Convert a non-negative integer to its english words representation. Given // input is guaranteed to be less than 231 - 1. // For example, // 123 -> "One Hundred Twenty Three" // 12345 -> "Twelve Thousand Three Hundred Forty Five" // 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty // Seven" class Solution { public: string numberToWords(int num) { std::array<int> vals = {1e9, 1e6, 1e3, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; std::array<string> words = { "Billion", "Million", "Thousand", "Hundred", "Ninety", "Eighty", "Seventy", "Sixty", "Fifty", "Forty", "Thirty", "Twenty", "Nineteen", "Eighteen", "Seventeen", "Sixteen", "Fifteen", "Fourteen", "Thirteen", "Twelve", "Eleven", "Ten", "Nine", "Eight", "Seven", "Six", "Five", "Four", "Three", "Two", "One"}; } };<commit_msg>update 273<commit_after>// Convert a non-negative integer to its english words representation. Given // input is guaranteed to be less than 231 - 1. // For example, // 123 -> "One Hundred Twenty Three" // 12345 -> "Twelve Thousand Three Hundred Forty Five" // 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty // Seven" class Solution { string smallNumToWords(int num) { vector<string> less20 = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; vector<string> tens = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; int t = 0; string result; // assume 123 if ((t = num / 100) > 0) { // t = 1 result += less20[t - 1] + " Hundred"; } if ((t = num % 100) > 19) { if (!result.empty()) result += " "; // t = 23, 23 / 10 - 2 = 0 result += tens[t / 10 - 2]; if (t % 10 > 0) result += " " + less20[t % 10 - 1]; } else if ((t = num % 20) > 0) { if (!result.empty()) result += " "; // t = 3 result += less20[t - 1]; } return result; } public: string numberToWords(int num) { if (!num) return "Zero"; string result; if (num >= 1000000000) result += smallNumToWords(num / 1000000000) + " Billion"; num %= 1000000000; if (num >= 1000000) { if (!result.empty()) result += " "; result += smallNumToWords(num / 1000000) + " Million"; } num %= 1000000; if (num >= 1000) { if (!result.empty()) result += " "; result += smallNumToWords(num / 1000) + " Thousand"; } num %= 1000; if (!result.empty() && num) result += " "; result += smallNumToWords(num); return result; } };<|endoftext|>
<commit_before>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" #if defined(HOST_OS_FUCHSIA) #include "vm/os.h" #include <errno.h> #include <lib/fdio/util.h> #include <zircon/process.h> #include <zircon/syscalls.h> #include <zircon/syscalls/object.h> #include <zircon/types.h> #include <fuchsia/timezone/cpp/fidl.h> #include "lib/component/cpp/startup_context.h" #include "lib/svc/cpp/services.h" #include "platform/assert.h" #include "vm/zone.h" namespace dart { #ifndef PRODUCT DEFINE_FLAG(bool, generate_perf_events_symbols, false, "Generate events symbols for profiling with perf"); #endif // !PRODUCT const char* OS::Name() { return "fuchsia"; } intptr_t OS::ProcessId() { return static_cast<intptr_t>(getpid()); } // TODO(FL-98): Change this to talk to fuchsia.dart to get timezone service to // directly get timezone. // // Putting this hack right now due to CP-120 as I need to remove // component:ConnectToEnvironmentServices and this is the only thing that is // blocking it and FL-98 will take time. static fuchsia::timezone::TimezoneSyncPtr tz; static zx_status_t GetLocalAndDstOffsetInSeconds(int64_t seconds_since_epoch, int32_t* local_offset, int32_t* dst_offset) { zx_status_t status = tz->GetTimezoneOffsetMinutes(seconds_since_epoch * 1000, local_offset, dst_offset); if (status != ZX_OK) { return status; } *local_offset *= 60; *dst_offset *= 60; return ZX_OK; } const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) { // TODO(abarth): Handle time zone changes. static const auto* tz_name = new std::string([] { #ifdef USE_STD_FOR_NON_NULLABLE_FIDL_FIELDS std::string result; tz->GetTimezoneId(&result); return result; #else fidl::StringPtr result; tz->GetTimezoneId(&result); return *result; #endif }()); return tz_name->c_str(); } int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) { int32_t local_offset, dst_offset; zx_status_t status = GetLocalAndDstOffsetInSeconds( seconds_since_epoch, &local_offset, &dst_offset); return status == ZX_OK ? local_offset + dst_offset : 0; } int OS::GetLocalTimeZoneAdjustmentInSeconds() { int32_t local_offset, dst_offset; zx_status_t status = GetLocalAndDstOffsetInSeconds( zx_clock_get(ZX_CLOCK_UTC) / ZX_SEC(1), &local_offset, &dst_offset); return status == ZX_OK ? local_offset : 0; } int64_t OS::GetCurrentTimeMillis() { return GetCurrentTimeMicros() / 1000; } int64_t OS::GetCurrentTimeMicros() { return zx_clock_get(ZX_CLOCK_UTC) / kNanosecondsPerMicrosecond; } int64_t OS::GetCurrentMonotonicTicks() { return zx_clock_get(ZX_CLOCK_MONOTONIC); } int64_t OS::GetCurrentMonotonicFrequency() { return kNanosecondsPerSecond; } int64_t OS::GetCurrentMonotonicMicros() { int64_t ticks = GetCurrentMonotonicTicks(); ASSERT(GetCurrentMonotonicFrequency() == kNanosecondsPerSecond); return ticks / kNanosecondsPerMicrosecond; } int64_t OS::GetCurrentThreadCPUMicros() { return zx_clock_get(ZX_CLOCK_THREAD) / kNanosecondsPerMicrosecond; } // TODO(5411554): May need to hoist these architecture dependent code // into a architecture specific file e.g: os_ia32_fuchsia.cc intptr_t OS::ActivationFrameAlignment() { #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) || \ defined(TARGET_ARCH_ARM64) const int kMinimumAlignment = 16; #elif defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_DBC) const int kMinimumAlignment = 8; #else #error Unsupported architecture. #endif intptr_t alignment = kMinimumAlignment; // TODO(5411554): Allow overriding default stack alignment for // testing purposes. // Flags::DebugIsInt("stackalign", &alignment); ASSERT(Utils::IsPowerOfTwo(alignment)); ASSERT(alignment >= kMinimumAlignment); return alignment; } intptr_t OS::PreferredCodeAlignment() { #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) || \ defined(TARGET_ARCH_ARM64) || defined(TARGET_ARCH_DBC) const int kMinimumAlignment = 32; #elif defined(TARGET_ARCH_ARM) const int kMinimumAlignment = 16; #else #error Unsupported architecture. #endif intptr_t alignment = kMinimumAlignment; // TODO(5411554): Allow overriding default code alignment for // testing purposes. // Flags::DebugIsInt("codealign", &alignment); ASSERT(Utils::IsPowerOfTwo(alignment)); ASSERT(alignment >= kMinimumAlignment); ASSERT(alignment <= OS::kMaxPreferredCodeAlignment); return alignment; } int OS::NumberOfAvailableProcessors() { return sysconf(_SC_NPROCESSORS_CONF); } void OS::Sleep(int64_t millis) { SleepMicros(millis * kMicrosecondsPerMillisecond); } void OS::SleepMicros(int64_t micros) { zx_nanosleep(zx_deadline_after(micros * kNanosecondsPerMicrosecond)); } void OS::DebugBreak() { UNIMPLEMENTED(); } DART_NOINLINE uintptr_t OS::GetProgramCounter() { return reinterpret_cast<uintptr_t>( __builtin_extract_return_addr(__builtin_return_address(0))); } void OS::Print(const char* format, ...) { va_list args; va_start(args, format); VFPrint(stdout, format, args); va_end(args); } void OS::VFPrint(FILE* stream, const char* format, va_list args) { vfprintf(stream, format, args); fflush(stream); } char* OS::SCreate(Zone* zone, const char* format, ...) { va_list args; va_start(args, format); char* buffer = VSCreate(zone, format, args); va_end(args); return buffer; } char* OS::VSCreate(Zone* zone, const char* format, va_list args) { // Measure. va_list measure_args; va_copy(measure_args, args); intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args); va_end(measure_args); char* buffer; if (zone) { buffer = zone->Alloc<char>(len + 1); } else { buffer = reinterpret_cast<char*>(malloc(len + 1)); } ASSERT(buffer != NULL); // Print. va_list print_args; va_copy(print_args, args); Utils::VSNPrint(buffer, len + 1, format, print_args); va_end(print_args); return buffer; } bool OS::StringToInt64(const char* str, int64_t* value) { ASSERT(str != NULL && strlen(str) > 0 && value != NULL); int32_t base = 10; char* endptr; int i = 0; if (str[0] == '-') { i = 1; } else if (str[0] == '+') { i = 1; } if ((str[i] == '0') && (str[i + 1] == 'x' || str[i + 1] == 'X') && (str[i + 2] != '\0')) { base = 16; } errno = 0; if (base == 16) { // Unsigned 64-bit hexadecimal integer literals are allowed but // immediately interpreted as signed 64-bit integers. *value = static_cast<int64_t>(strtoull(str, &endptr, base)); } else { *value = strtoll(str, &endptr, base); } return ((errno == 0) && (endptr != str) && (*endptr == 0)); } void OS::RegisterCodeObservers() { #ifndef PRODUCT if (FLAG_generate_perf_events_symbols) { UNIMPLEMENTED(); } #endif // !PRODUCT } void OS::PrintErr(const char* format, ...) { va_list args; va_start(args, format); VFPrint(stderr, format, args); va_end(args); } void OS::Init() { auto environment_services = std::make_shared<component::Services>(); auto env_service_root = component::subtle::CreateStaticServiceRootHandle(); environment_services->Bind(std::move(env_service_root)); environment_services->ConnectToService(tz.NewRequest()); } void OS::Cleanup() {} void OS::Abort() { abort(); } void OS::Exit(int code) { exit(code); } } // namespace dart #endif // defined(HOST_OS_FUCHSIA) <commit_msg>[fuchsia] Clean-up after the FIDL string/vector types transition<commit_after>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" #if defined(HOST_OS_FUCHSIA) #include "vm/os.h" #include <errno.h> #include <lib/fdio/util.h> #include <zircon/process.h> #include <zircon/syscalls.h> #include <zircon/syscalls/object.h> #include <zircon/types.h> #include <fuchsia/timezone/cpp/fidl.h> #include "lib/component/cpp/startup_context.h" #include "lib/svc/cpp/services.h" #include "platform/assert.h" #include "vm/zone.h" namespace dart { #ifndef PRODUCT DEFINE_FLAG(bool, generate_perf_events_symbols, false, "Generate events symbols for profiling with perf"); #endif // !PRODUCT const char* OS::Name() { return "fuchsia"; } intptr_t OS::ProcessId() { return static_cast<intptr_t>(getpid()); } // TODO(FL-98): Change this to talk to fuchsia.dart to get timezone service to // directly get timezone. // // Putting this hack right now due to CP-120 as I need to remove // component:ConnectToEnvironmentServices and this is the only thing that is // blocking it and FL-98 will take time. static fuchsia::timezone::TimezoneSyncPtr tz; static zx_status_t GetLocalAndDstOffsetInSeconds(int64_t seconds_since_epoch, int32_t* local_offset, int32_t* dst_offset) { zx_status_t status = tz->GetTimezoneOffsetMinutes(seconds_since_epoch * 1000, local_offset, dst_offset); if (status != ZX_OK) { return status; } *local_offset *= 60; *dst_offset *= 60; return ZX_OK; } const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) { // TODO(abarth): Handle time zone changes. static const auto* tz_name = new std::string([] { std::string result; tz->GetTimezoneId(&result); return result; }()); return tz_name->c_str(); } int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) { int32_t local_offset, dst_offset; zx_status_t status = GetLocalAndDstOffsetInSeconds( seconds_since_epoch, &local_offset, &dst_offset); return status == ZX_OK ? local_offset + dst_offset : 0; } int OS::GetLocalTimeZoneAdjustmentInSeconds() { int32_t local_offset, dst_offset; zx_status_t status = GetLocalAndDstOffsetInSeconds( zx_clock_get(ZX_CLOCK_UTC) / ZX_SEC(1), &local_offset, &dst_offset); return status == ZX_OK ? local_offset : 0; } int64_t OS::GetCurrentTimeMillis() { return GetCurrentTimeMicros() / 1000; } int64_t OS::GetCurrentTimeMicros() { return zx_clock_get(ZX_CLOCK_UTC) / kNanosecondsPerMicrosecond; } int64_t OS::GetCurrentMonotonicTicks() { return zx_clock_get(ZX_CLOCK_MONOTONIC); } int64_t OS::GetCurrentMonotonicFrequency() { return kNanosecondsPerSecond; } int64_t OS::GetCurrentMonotonicMicros() { int64_t ticks = GetCurrentMonotonicTicks(); ASSERT(GetCurrentMonotonicFrequency() == kNanosecondsPerSecond); return ticks / kNanosecondsPerMicrosecond; } int64_t OS::GetCurrentThreadCPUMicros() { return zx_clock_get(ZX_CLOCK_THREAD) / kNanosecondsPerMicrosecond; } // TODO(5411554): May need to hoist these architecture dependent code // into a architecture specific file e.g: os_ia32_fuchsia.cc intptr_t OS::ActivationFrameAlignment() { #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) || \ defined(TARGET_ARCH_ARM64) const int kMinimumAlignment = 16; #elif defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_DBC) const int kMinimumAlignment = 8; #else #error Unsupported architecture. #endif intptr_t alignment = kMinimumAlignment; // TODO(5411554): Allow overriding default stack alignment for // testing purposes. // Flags::DebugIsInt("stackalign", &alignment); ASSERT(Utils::IsPowerOfTwo(alignment)); ASSERT(alignment >= kMinimumAlignment); return alignment; } intptr_t OS::PreferredCodeAlignment() { #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) || \ defined(TARGET_ARCH_ARM64) || defined(TARGET_ARCH_DBC) const int kMinimumAlignment = 32; #elif defined(TARGET_ARCH_ARM) const int kMinimumAlignment = 16; #else #error Unsupported architecture. #endif intptr_t alignment = kMinimumAlignment; // TODO(5411554): Allow overriding default code alignment for // testing purposes. // Flags::DebugIsInt("codealign", &alignment); ASSERT(Utils::IsPowerOfTwo(alignment)); ASSERT(alignment >= kMinimumAlignment); ASSERT(alignment <= OS::kMaxPreferredCodeAlignment); return alignment; } int OS::NumberOfAvailableProcessors() { return sysconf(_SC_NPROCESSORS_CONF); } void OS::Sleep(int64_t millis) { SleepMicros(millis * kMicrosecondsPerMillisecond); } void OS::SleepMicros(int64_t micros) { zx_nanosleep(zx_deadline_after(micros * kNanosecondsPerMicrosecond)); } void OS::DebugBreak() { UNIMPLEMENTED(); } DART_NOINLINE uintptr_t OS::GetProgramCounter() { return reinterpret_cast<uintptr_t>( __builtin_extract_return_addr(__builtin_return_address(0))); } void OS::Print(const char* format, ...) { va_list args; va_start(args, format); VFPrint(stdout, format, args); va_end(args); } void OS::VFPrint(FILE* stream, const char* format, va_list args) { vfprintf(stream, format, args); fflush(stream); } char* OS::SCreate(Zone* zone, const char* format, ...) { va_list args; va_start(args, format); char* buffer = VSCreate(zone, format, args); va_end(args); return buffer; } char* OS::VSCreate(Zone* zone, const char* format, va_list args) { // Measure. va_list measure_args; va_copy(measure_args, args); intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args); va_end(measure_args); char* buffer; if (zone) { buffer = zone->Alloc<char>(len + 1); } else { buffer = reinterpret_cast<char*>(malloc(len + 1)); } ASSERT(buffer != NULL); // Print. va_list print_args; va_copy(print_args, args); Utils::VSNPrint(buffer, len + 1, format, print_args); va_end(print_args); return buffer; } bool OS::StringToInt64(const char* str, int64_t* value) { ASSERT(str != NULL && strlen(str) > 0 && value != NULL); int32_t base = 10; char* endptr; int i = 0; if (str[0] == '-') { i = 1; } else if (str[0] == '+') { i = 1; } if ((str[i] == '0') && (str[i + 1] == 'x' || str[i + 1] == 'X') && (str[i + 2] != '\0')) { base = 16; } errno = 0; if (base == 16) { // Unsigned 64-bit hexadecimal integer literals are allowed but // immediately interpreted as signed 64-bit integers. *value = static_cast<int64_t>(strtoull(str, &endptr, base)); } else { *value = strtoll(str, &endptr, base); } return ((errno == 0) && (endptr != str) && (*endptr == 0)); } void OS::RegisterCodeObservers() { #ifndef PRODUCT if (FLAG_generate_perf_events_symbols) { UNIMPLEMENTED(); } #endif // !PRODUCT } void OS::PrintErr(const char* format, ...) { va_list args; va_start(args, format); VFPrint(stderr, format, args); va_end(args); } void OS::Init() { auto environment_services = std::make_shared<component::Services>(); auto env_service_root = component::subtle::CreateStaticServiceRootHandle(); environment_services->Bind(std::move(env_service_root)); environment_services->ConnectToService(tz.NewRequest()); } void OS::Cleanup() {} void OS::Abort() { abort(); } void OS::Exit(int code) { exit(code); } } // namespace dart #endif // defined(HOST_OS_FUCHSIA) <|endoftext|>
<commit_before>/** * * \file example8.cc * \remark This file is part of VITA. * \details Building blocks run test. * * Copyright (C) 2011-2013 EOS di Manlio Morini. * * 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 <cstdlib> #include <iostream> #include <fstream> #include "adf.h" #include "distribution.h" #include "environment.h" #include "interpreter.h" #include "primitive/factory.h" int main(int argc, char *argv[]) { using namespace vita; environment env(true); env.code_length = argc > 1 ? atoi(argv[1]) : 5; const unsigned n(argc > 2 ? atoi(argv[2]) : 1); symbol_factory &factory(symbol_factory::instance()); env.insert(factory.make(d_double, -200, 200)); env.insert(factory.make("FADD")); env.insert(factory.make("FSUB")); env.insert(factory.make("FMUL")); env.insert(factory.make("FIFL")); env.insert(factory.make("FIFE")); env.insert(factory.make("FABS")); env.insert(factory.make("FLN")); for (unsigned k(0); k < n; ++k) { // We build, by repeated trials, an individual with an effective size // greater than 4. individual base(env, true); size_t base_es(base.eff_size()); while (base_es < 5) { base = individual(env, true); base_es = base.eff_size(); } std::cout << std::string(40, '-') << std::endl << "BASE" << std::endl; base.list(std::cout); std::cout << std::endl; std::list<locus> bl(base.blocks()); for (auto i(bl.begin()); i != bl.end(); ++i) { individual blk(base.get_block(*i)); std::cout << std::endl << "BLOCK at locus " << *i << std::endl; blk.list(std::cout); const any val(interpreter(blk).run()); if (val.empty()) std::cout << "Incorrect output."; else std::cout << "Output: " << interpreter::to_string(val); std::cout << std::endl; if (blk.eff_size() <= 20) { std::vector<locus> replaced; individual blk2(blk.generalize(2, &replaced)); std::vector<index_t> positions(replaced.size()); std::vector<category_t> categories(replaced.size()); for (size_t j(0); j < replaced.size(); ++j) { positions[j] = replaced[j][locus_index]; categories[j] = replaced[j][locus_category]; } symbol_ptr f(new adf(blk2, categories, 100)); env.insert(f); std::cout << std::endl << f->display() << std::endl; blk2.list(std::cout); individual blk3(blk.replace({{f, positions}})); std::cout << std::endl; blk3.list(std::cout); const any val3(interpreter(blk3).run()); if (val3.empty()) std::cout << "Incorrect output."; else std::cout << "Output: " << interpreter::to_string(val3); std::cout << std::endl << std::endl; if (val.empty() != val3.empty() || (!val.empty() && !val3.empty() && interpreter::to_string(val) != interpreter::to_string(val3))) { std::cout << "ADF EVAL ERROR." << std::endl; return EXIT_FAILURE; } } else std::cout << "Skipping block at line " << *i << std::endl; } } return EXIT_SUCCESS; } <commit_msg>[cleanup] example8.cc<commit_after>/** * * \file example8.cc * \remark This file is part of VITA. * \details Building blocks run test. * * Copyright (C) 2011-2013 EOS di Manlio Morini. * * 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 <cstdlib> #include <iostream> #include <fstream> #include "adf.h" #include "distribution.h" #include "environment.h" #include "interpreter.h" #include "primitive/factory.h" int main(int argc, char *argv[]) { using namespace vita; environment env(true); env.code_length = argc > 1 ? atoi(argv[1]) : 5; const unsigned n(argc > 2 ? atoi(argv[2]) : 1); symbol_factory &factory(symbol_factory::instance()); env.insert(factory.make(d_double, -200, 200)); env.insert(factory.make("FADD")); env.insert(factory.make("FSUB")); env.insert(factory.make("FMUL")); env.insert(factory.make("FIFL")); env.insert(factory.make("FIFE")); env.insert(factory.make("FABS")); env.insert(factory.make("FLN")); for (unsigned k(0); k < n; ++k) { // We build, by repeated trials, an individual with an effective size // greater than 4. individual base(env, true); size_t base_es(base.eff_size()); while (base_es < 5) { base = individual(env, true); base_es = base.eff_size(); } std::cout << std::string(40, '-') << std::endl << "BASE" << std::endl; base.list(std::cout); std::cout << std::endl; std::list<locus> bl(base.blocks()); for (const locus &l : bl) { individual blk(base.get_block(l)); std::cout << std::endl << "BLOCK at locus " << l << std::endl; blk.list(std::cout); const any val(interpreter(blk).run()); if (val.empty()) std::cout << "Empty output."; else std::cout << "Output: " << interpreter::to_string(val); std::cout << std::endl; if (blk.eff_size() <= 20) { std::vector<locus> replaced; individual blk2(blk.generalize(2, &replaced)); std::vector<index_t> positions(replaced.size()); std::vector<category_t> categories(replaced.size()); for (size_t j(0); j < replaced.size(); ++j) { positions[j] = replaced[j][locus_index]; categories[j] = replaced[j][locus_category]; } symbol_ptr f(std::make_shared<adf>(blk2, categories, 100)); env.insert(f); std::cout << std::endl << f->display() << std::endl; blk2.list(std::cout); individual blk3(blk.replace({{f, positions}})); std::cout << std::endl; blk3.list(std::cout); const any val3(interpreter(blk3).run()); if (val3.empty()) std::cout << "Empty output."; else std::cout << "Output: " << interpreter::to_string(val3); std::cout << std::endl << std::endl; if (val.empty() != val3.empty() || (!val.empty() && !val3.empty() && interpreter::to_string(val) != interpreter::to_string(val3))) { std::cerr << "ADF EVAL ERROR." << std::endl; return EXIT_FAILURE; } } else std::cout << "Skipping block at line " << l << std::endl; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright 2015 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore #include "ninja.h" #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <memory> #include <string> #include <unordered_set> #include "command.h" #include "dep.h" #include "eval.h" #include "log.h" #include "string_piece.h" #include "stringprintf.h" #include "strutil.h" #include "var.h" static StringPiece FindCommandLineFlagWithArg(StringPiece cmd, StringPiece name) { size_t index = cmd.find(name); if (index == string::npos) return StringPiece(); StringPiece val = TrimLeftSpace(cmd.substr(index + name.size())); index = val.find(name); while (index != string::npos) { val = TrimLeftSpace(val.substr(index + name.size())); index = val.find(name); } index = val.find(' '); CHECK(index != string::npos); return val.substr(0, index); } static bool StripPrefix(StringPiece p, StringPiece* s) { if (!HasPrefix(*s, p)) return false; *s = s->substr(p.size()); return true; } static bool IsAndroidCompileCommand(StringPiece cmd) { if (!StripPrefix("prebuilts/", &cmd)) return false; if (!StripPrefix("gcc/", &cmd) && !StripPrefix("clang/", &cmd)) return false; size_t index = cmd.find(' '); if (index == string::npos) return false; StringPiece cc = cmd.substr(0, index); if (!HasSuffix(cc, "gcc") && !HasSuffix(cc, "g++") && !HasSuffix(cc, "clang") && !HasSuffix(cc, "clang++")) { return false; } cmd = cmd.substr(index); return cmd.find(" -c ") != string::npos; } static bool GetDepfileFromCommandImpl(StringPiece cmd, string* out) { if (cmd.find(StringPiece(" -MD ")) == string::npos && cmd.find(StringPiece(" -MMD ")) == string::npos) { return false; } StringPiece mf = FindCommandLineFlagWithArg(cmd, StringPiece(" -MF ")); if (!mf.empty()) { mf.AppendToString(out); return true; } StringPiece o = FindCommandLineFlagWithArg(cmd, StringPiece(" -o ")); if (o.empty()) { ERROR("Cannot find the depfile in %s", cmd.as_string().c_str()); return false; } StripExt(o).AppendToString(out); *out += ".d"; return true; } bool GetDepfileFromCommand(StringPiece cmd, string* out) { CHECK(cmd.get(cmd.size()-1) == ' '); if (!GetDepfileFromCommandImpl(cmd, out)) return false; // A hack for Android - llvm-rs-cc seems not to emit a dep file. if (cmd.find("bin/llvm-rs-cc ") != string::npos) { return false; } // TODO: A hack for Makefiles generated by automake. // A hack for Android to get .P files instead of .d. string p; StripExt(*out).AppendToString(&p); p += ".P"; if (cmd.find(p) != string::npos) { *out = p; return true; } // A hack for Android. For .s files, GCC does not use C // preprocessor, so it ignores -MF flag. string as = "/"; StripExt(Basename(*out)).AppendToString(&as); as += ".s"; if (cmd.find(as) != string::npos) { return false; } return true; } class NinjaGenerator { public: explicit NinjaGenerator(Evaluator* ev) : ce_(ev), ev_(ev), fp_(NULL), rule_id_(0) { ev_->set_avoid_io(true); if (g_goma_dir) gomacc_ = StringPrintf("%s/gomacc ", g_goma_dir); } ~NinjaGenerator() { ev_->set_avoid_io(false); } void Generate(const vector<DepNode*>& nodes) { GenerateShell(); GenerateNinja(nodes); } private: string GenRuleName() { return StringPrintf("rule%d", rule_id_++); } StringPiece TranslateCommand(const char* in) { const size_t orig_size = cmd_buf_.size(); bool prev_backslash = false; char quote = 0; bool done = false; for (; *in && !done; in++) { switch (*in) { case '#': if (quote == 0 && !prev_backslash) { done = true; break; } case '\'': case '"': case '`': if (quote) { if (quote == *in) quote = 0; } else if (!prev_backslash) { quote = *in; } cmd_buf_ += *in; break; case '$': cmd_buf_ += "$$"; break; case '\t': cmd_buf_ += ' '; break; case '\n': if (prev_backslash) { cmd_buf_[cmd_buf_.size()-1] = ' '; } else { cmd_buf_ += ' '; } break; case '\\': prev_backslash = !prev_backslash; cmd_buf_ += '\\'; break; default: cmd_buf_ += *in; prev_backslash = false; } } while (true) { char c = cmd_buf_[cmd_buf_.size()-1]; if (!isspace(c) && c != ';') break; cmd_buf_.resize(cmd_buf_.size() - 1); } return StringPiece(cmd_buf_.data() + orig_size, cmd_buf_.size() - orig_size); } bool GenShellScript(const vector<Command*>& commands) { bool use_gomacc = false; bool should_ignore_error = false; cmd_buf_.clear(); for (const Command* c : commands) { if (!cmd_buf_.empty()) { if (should_ignore_error) { cmd_buf_ += " ; "; } else { cmd_buf_ += " && "; } } should_ignore_error = c->ignore_error; const char* in = c->cmd->c_str(); while (isspace(*in)) in++; bool needs_subshell = commands.size() > 1; if (*in == '(') { needs_subshell = false; } if (needs_subshell) cmd_buf_ += '('; size_t cmd_start = cmd_buf_.size(); StringPiece translated = TranslateCommand(in); if (translated.empty()) { cmd_buf_ += "true"; } else if (g_goma_dir && IsAndroidCompileCommand(translated)) { cmd_buf_.insert(cmd_start, gomacc_); use_gomacc = true; } if (c == commands.back() && c->ignore_error) { cmd_buf_ += " ; true"; } if (needs_subshell) cmd_buf_ += ')'; } return g_goma_dir && !use_gomacc; } void EmitDepfile() { cmd_buf_ += ' '; string depfile; bool result = GetDepfileFromCommand(cmd_buf_, &depfile); cmd_buf_.resize(cmd_buf_.size()-1); if (!result) return; fprintf(fp_, " depfile = %s\n", depfile.c_str()); } void EmitNode(DepNode* node) { auto p = done_.insert(node->output); if (!p.second) return; if (node->cmds.empty() && node->deps.empty() && !node->is_phony) return; vector<Command*> commands; ce_.Eval(node, &commands); string rule_name = "phony"; bool use_local_pool = false; if (!commands.empty()) { rule_name = GenRuleName(); fprintf(fp_, "rule %s\n", rule_name.c_str()); fprintf(fp_, " description = build $out\n"); use_local_pool |= GenShellScript(commands); EmitDepfile(); // It seems Linux is OK with ~130kB. // TODO: Find this number automatically. if (cmd_buf_.size() > 100 * 1000) { fprintf(fp_, " rspfile = $out.rsp\n"); fprintf(fp_, " rspfile_content = %s\n", cmd_buf_.c_str()); fprintf(fp_, " command = sh $out.rsp\n"); } else { fprintf(fp_, " command = %s\n", cmd_buf_.c_str()); } } EmitBuild(node, rule_name); if (use_local_pool) fprintf(fp_, " pool = local_pool\n"); for (DepNode* d : node->deps) { EmitNode(d); } } void EmitBuild(DepNode* node, const string& rule_name) { fprintf(fp_, "build %s: %s", node->output.c_str(), rule_name.c_str()); vector<Symbol> order_onlys; for (DepNode* d : node->deps) { fprintf(fp_, " %s", d->output.c_str()); } if (!node->order_onlys.empty()) { fprintf(fp_, " ||"); for (DepNode* d : node->order_onlys) { fprintf(fp_, " %s", d->output.c_str()); } } fprintf(fp_, "\n"); } void GenerateNinja(const vector<DepNode*>& nodes) { fp_ = fopen("build.ninja", "wb"); if (fp_ == NULL) PERROR("fopen(build.ninja) failed"); fprintf(fp_, "# Generated by kati\n"); fprintf(fp_, "\n"); if (g_goma_dir) { fprintf(fp_, "pool local_pool\n"); // TODO: Decide the appropriate number based on the number of cores. fprintf(fp_, " depth = %d\n", 32); } for (DepNode* node : nodes) { EmitNode(node); } fclose(fp_); } void GenerateShell() { FILE* fp = fopen("ninja.sh", "wb"); if (fp == NULL) PERROR("fopen(ninja.sh) failed"); shared_ptr<string> shell = ev_->EvalVar(kShellSym); if (shell->empty()) shell = make_shared<string>("/bin/sh"); fprintf(fp, "#!%s\n", shell->c_str()); for (const auto& p : ev_->exports()) { if (p.second) { shared_ptr<string> val = ev_->EvalVar(p.first); fprintf(fp, "export %s=%s\n", p.first.c_str(), val->c_str()); } else { fprintf(fp, "unset %s\n", p.first.c_str()); } } if (g_goma_dir) { fprintf(fp, "exec ninja -j300 \"$@\"\n"); } else { fprintf(fp, "exec ninja \"$@\"\n"); } if (chmod("ninja.sh", 0755) != 0) PERROR("chmod ninja.sh failed"); } CommandEvaluator ce_; Evaluator* ev_; FILE* fp_; unordered_set<Symbol> done_; int rule_id_; string cmd_buf_; string gomacc_; }; void GenerateNinja(const vector<DepNode*>& nodes, Evaluator* ev) { NinjaGenerator ng(ev); ng.Generate(nodes); } <commit_msg>[C++] Emit nodes referenced as order-only<commit_after>// Copyright 2015 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore #include "ninja.h" #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <memory> #include <string> #include <unordered_set> #include "command.h" #include "dep.h" #include "eval.h" #include "log.h" #include "string_piece.h" #include "stringprintf.h" #include "strutil.h" #include "var.h" static StringPiece FindCommandLineFlagWithArg(StringPiece cmd, StringPiece name) { size_t index = cmd.find(name); if (index == string::npos) return StringPiece(); StringPiece val = TrimLeftSpace(cmd.substr(index + name.size())); index = val.find(name); while (index != string::npos) { val = TrimLeftSpace(val.substr(index + name.size())); index = val.find(name); } index = val.find(' '); CHECK(index != string::npos); return val.substr(0, index); } static bool StripPrefix(StringPiece p, StringPiece* s) { if (!HasPrefix(*s, p)) return false; *s = s->substr(p.size()); return true; } static bool IsAndroidCompileCommand(StringPiece cmd) { if (!StripPrefix("prebuilts/", &cmd)) return false; if (!StripPrefix("gcc/", &cmd) && !StripPrefix("clang/", &cmd)) return false; size_t index = cmd.find(' '); if (index == string::npos) return false; StringPiece cc = cmd.substr(0, index); if (!HasSuffix(cc, "gcc") && !HasSuffix(cc, "g++") && !HasSuffix(cc, "clang") && !HasSuffix(cc, "clang++")) { return false; } cmd = cmd.substr(index); return cmd.find(" -c ") != string::npos; } static bool GetDepfileFromCommandImpl(StringPiece cmd, string* out) { if (cmd.find(StringPiece(" -MD ")) == string::npos && cmd.find(StringPiece(" -MMD ")) == string::npos) { return false; } StringPiece mf = FindCommandLineFlagWithArg(cmd, StringPiece(" -MF ")); if (!mf.empty()) { mf.AppendToString(out); return true; } StringPiece o = FindCommandLineFlagWithArg(cmd, StringPiece(" -o ")); if (o.empty()) { ERROR("Cannot find the depfile in %s", cmd.as_string().c_str()); return false; } StripExt(o).AppendToString(out); *out += ".d"; return true; } bool GetDepfileFromCommand(StringPiece cmd, string* out) { CHECK(cmd.get(cmd.size()-1) == ' '); if (!GetDepfileFromCommandImpl(cmd, out)) return false; // A hack for Android - llvm-rs-cc seems not to emit a dep file. if (cmd.find("bin/llvm-rs-cc ") != string::npos) { return false; } // TODO: A hack for Makefiles generated by automake. // A hack for Android to get .P files instead of .d. string p; StripExt(*out).AppendToString(&p); p += ".P"; if (cmd.find(p) != string::npos) { *out = p; return true; } // A hack for Android. For .s files, GCC does not use C // preprocessor, so it ignores -MF flag. string as = "/"; StripExt(Basename(*out)).AppendToString(&as); as += ".s"; if (cmd.find(as) != string::npos) { return false; } return true; } class NinjaGenerator { public: explicit NinjaGenerator(Evaluator* ev) : ce_(ev), ev_(ev), fp_(NULL), rule_id_(0) { ev_->set_avoid_io(true); if (g_goma_dir) gomacc_ = StringPrintf("%s/gomacc ", g_goma_dir); } ~NinjaGenerator() { ev_->set_avoid_io(false); } void Generate(const vector<DepNode*>& nodes) { GenerateShell(); GenerateNinja(nodes); } private: string GenRuleName() { return StringPrintf("rule%d", rule_id_++); } StringPiece TranslateCommand(const char* in) { const size_t orig_size = cmd_buf_.size(); bool prev_backslash = false; char quote = 0; bool done = false; for (; *in && !done; in++) { switch (*in) { case '#': if (quote == 0 && !prev_backslash) { done = true; break; } case '\'': case '"': case '`': if (quote) { if (quote == *in) quote = 0; } else if (!prev_backslash) { quote = *in; } cmd_buf_ += *in; break; case '$': cmd_buf_ += "$$"; break; case '\t': cmd_buf_ += ' '; break; case '\n': if (prev_backslash) { cmd_buf_[cmd_buf_.size()-1] = ' '; } else { cmd_buf_ += ' '; } break; case '\\': prev_backslash = !prev_backslash; cmd_buf_ += '\\'; break; default: cmd_buf_ += *in; prev_backslash = false; } } while (true) { char c = cmd_buf_[cmd_buf_.size()-1]; if (!isspace(c) && c != ';') break; cmd_buf_.resize(cmd_buf_.size() - 1); } return StringPiece(cmd_buf_.data() + orig_size, cmd_buf_.size() - orig_size); } bool GenShellScript(const vector<Command*>& commands) { bool use_gomacc = false; bool should_ignore_error = false; cmd_buf_.clear(); for (const Command* c : commands) { if (!cmd_buf_.empty()) { if (should_ignore_error) { cmd_buf_ += " ; "; } else { cmd_buf_ += " && "; } } should_ignore_error = c->ignore_error; const char* in = c->cmd->c_str(); while (isspace(*in)) in++; bool needs_subshell = commands.size() > 1; if (*in == '(') { needs_subshell = false; } if (needs_subshell) cmd_buf_ += '('; size_t cmd_start = cmd_buf_.size(); StringPiece translated = TranslateCommand(in); if (translated.empty()) { cmd_buf_ += "true"; } else if (g_goma_dir && IsAndroidCompileCommand(translated)) { cmd_buf_.insert(cmd_start, gomacc_); use_gomacc = true; } if (c == commands.back() && c->ignore_error) { cmd_buf_ += " ; true"; } if (needs_subshell) cmd_buf_ += ')'; } return g_goma_dir && !use_gomacc; } void EmitDepfile() { cmd_buf_ += ' '; string depfile; bool result = GetDepfileFromCommand(cmd_buf_, &depfile); cmd_buf_.resize(cmd_buf_.size()-1); if (!result) return; fprintf(fp_, " depfile = %s\n", depfile.c_str()); } void EmitNode(DepNode* node) { auto p = done_.insert(node->output); if (!p.second) return; if (node->cmds.empty() && node->deps.empty() && !node->is_phony) return; vector<Command*> commands; ce_.Eval(node, &commands); string rule_name = "phony"; bool use_local_pool = false; if (!commands.empty()) { rule_name = GenRuleName(); fprintf(fp_, "rule %s\n", rule_name.c_str()); fprintf(fp_, " description = build $out\n"); use_local_pool |= GenShellScript(commands); EmitDepfile(); // It seems Linux is OK with ~130kB. // TODO: Find this number automatically. if (cmd_buf_.size() > 100 * 1000) { fprintf(fp_, " rspfile = $out.rsp\n"); fprintf(fp_, " rspfile_content = %s\n", cmd_buf_.c_str()); fprintf(fp_, " command = sh $out.rsp\n"); } else { fprintf(fp_, " command = %s\n", cmd_buf_.c_str()); } } EmitBuild(node, rule_name); if (use_local_pool) fprintf(fp_, " pool = local_pool\n"); for (DepNode* d : node->deps) { EmitNode(d); } for (DepNode* d : node->order_onlys) { EmitNode(d); } } void EmitBuild(DepNode* node, const string& rule_name) { fprintf(fp_, "build %s: %s", node->output.c_str(), rule_name.c_str()); vector<Symbol> order_onlys; for (DepNode* d : node->deps) { fprintf(fp_, " %s", d->output.c_str()); } if (!node->order_onlys.empty()) { fprintf(fp_, " ||"); for (DepNode* d : node->order_onlys) { fprintf(fp_, " %s", d->output.c_str()); } } fprintf(fp_, "\n"); } void GenerateNinja(const vector<DepNode*>& nodes) { fp_ = fopen("build.ninja", "wb"); if (fp_ == NULL) PERROR("fopen(build.ninja) failed"); fprintf(fp_, "# Generated by kati\n"); fprintf(fp_, "\n"); if (g_goma_dir) { fprintf(fp_, "pool local_pool\n"); // TODO: Decide the appropriate number based on the number of cores. fprintf(fp_, " depth = %d\n", 32); } for (DepNode* node : nodes) { EmitNode(node); } fclose(fp_); } void GenerateShell() { FILE* fp = fopen("ninja.sh", "wb"); if (fp == NULL) PERROR("fopen(ninja.sh) failed"); shared_ptr<string> shell = ev_->EvalVar(kShellSym); if (shell->empty()) shell = make_shared<string>("/bin/sh"); fprintf(fp, "#!%s\n", shell->c_str()); for (const auto& p : ev_->exports()) { if (p.second) { shared_ptr<string> val = ev_->EvalVar(p.first); fprintf(fp, "export %s=%s\n", p.first.c_str(), val->c_str()); } else { fprintf(fp, "unset %s\n", p.first.c_str()); } } if (g_goma_dir) { fprintf(fp, "exec ninja -j300 \"$@\"\n"); } else { fprintf(fp, "exec ninja \"$@\"\n"); } if (chmod("ninja.sh", 0755) != 0) PERROR("chmod ninja.sh failed"); } CommandEvaluator ce_; Evaluator* ev_; FILE* fp_; unordered_set<Symbol> done_; int rule_id_; string cmd_buf_; string gomacc_; }; void GenerateNinja(const vector<DepNode*>& nodes, Evaluator* ev) { NinjaGenerator ng(ev); ng.Generate(nodes); } <|endoftext|>
<commit_before>// Copyright 2010 The RE2 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 "re2/set.h" #include <stddef.h> #include <algorithm> #include <memory> #include "util/util.h" #include "util/logging.h" #include "re2/pod_array.h" #include "re2/prog.h" #include "re2/re2.h" #include "re2/regexp.h" #include "re2/stringpiece.h" namespace re2 { RE2::Set::Set(const RE2::Options& options, RE2::Anchor anchor) { options_.Copy(options); options_.set_never_capture(true); // might unblock some optimisations anchor_ = anchor; prog_ = NULL; compiled_ = false; size_ = 0; } RE2::Set::~Set() { for (size_t i = 0; i < elem_.size(); i++) elem_[i].second->Decref(); delete prog_; } int RE2::Set::Add(const StringPiece& pattern, std::string* error) { if (compiled_) { LOG(DFATAL) << "RE2::Set::Add() called after compiling"; return -1; } Regexp::ParseFlags pf = static_cast<Regexp::ParseFlags>( options_.ParseFlags()); RegexpStatus status; re2::Regexp* re = Regexp::Parse(pattern, pf, &status); if (re == NULL) { if (error != NULL) *error = status.Text(); if (options_.log_errors()) LOG(ERROR) << "Error parsing '" << pattern << "': " << status.Text(); return -1; } // Concatenate with match index and push on vector. int n = static_cast<int>(elem_.size()); re2::Regexp* m = re2::Regexp::HaveMatch(n, pf); if (re->op() == kRegexpConcat) { int nsub = re->nsub(); PODArray<re2::Regexp*> sub(nsub + 1); for (int i = 0; i < nsub; i++) sub[i] = re->sub()[i]->Incref(); sub[nsub] = m; re->Decref(); re = re2::Regexp::Concat(sub.data(), nsub + 1, pf); } else { re2::Regexp* sub[2]; sub[0] = re; sub[1] = m; re = re2::Regexp::Concat(sub, 2, pf); } elem_.emplace_back(std::string(pattern), re); return n; } bool RE2::Set::Compile() { if (compiled_) { LOG(DFATAL) << "RE2::Set::Compile() called more than once"; return false; } compiled_ = true; size_ = static_cast<int>(elem_.size()); // Sort the elements by their patterns. This is good enough for now // until we have a Regexp comparison function. (Maybe someday...) std::sort(elem_.begin(), elem_.end(), [](const Elem& a, const Elem& b) -> bool { return a.first < b.first; }); PODArray<re2::Regexp*> sub(size_); for (int i = 0; i < size_; i++) sub[i] = elem_[i].second; elem_.clear(); elem_.shrink_to_fit(); Regexp::ParseFlags pf = static_cast<Regexp::ParseFlags>( options_.ParseFlags()); re2::Regexp* re = re2::Regexp::Alternate(sub.data(), size_, pf); prog_ = Prog::CompileSet(re, anchor_, options_.max_mem()); re->Decref(); return prog_ != NULL; } bool RE2::Set::Match(const StringPiece& text, std::vector<int>* v) const { return Match(text, v, NULL); } bool RE2::Set::Match(const StringPiece& text, std::vector<int>* v, ErrorInfo* error_info) const { if (!compiled_) { LOG(DFATAL) << "RE2::Set::Match() called before compiling"; if (error_info != NULL) error_info->kind = kNotCompiled; return false; } bool dfa_failed = false; std::unique_ptr<SparseSet> matches; if (v != NULL) { matches.reset(new SparseSet(size_)); v->clear(); } bool ret = prog_->SearchDFA(text, text, Prog::kAnchored, Prog::kManyMatch, NULL, &dfa_failed, matches.get()); if (dfa_failed) { if (options_.log_errors()) LOG(ERROR) << "DFA out of memory: " << "program size " << prog->size() << ", " << "list count " << prog->list_count() << ", " << "bytemap range " << prog->bytemap_range(); if (error_info != NULL) error_info->kind = kOutOfMemory; return false; } if (ret == false) { if (error_info != NULL) error_info->kind = kNoError; return false; } if (v != NULL) { if (matches->empty()) { LOG(DFATAL) << "RE2::Set::Match() matched, but no matches returned?!"; if (error_info != NULL) error_info->kind = kInconsistent; return false; } v->assign(matches->begin(), matches->end()); } if (error_info != NULL) error_info->kind = kNoError; return true; } } // namespace re2 <commit_msg>Aiieee. Add a missing underscore.<commit_after>// Copyright 2010 The RE2 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 "re2/set.h" #include <stddef.h> #include <algorithm> #include <memory> #include "util/util.h" #include "util/logging.h" #include "re2/pod_array.h" #include "re2/prog.h" #include "re2/re2.h" #include "re2/regexp.h" #include "re2/stringpiece.h" namespace re2 { RE2::Set::Set(const RE2::Options& options, RE2::Anchor anchor) { options_.Copy(options); options_.set_never_capture(true); // might unblock some optimisations anchor_ = anchor; prog_ = NULL; compiled_ = false; size_ = 0; } RE2::Set::~Set() { for (size_t i = 0; i < elem_.size(); i++) elem_[i].second->Decref(); delete prog_; } int RE2::Set::Add(const StringPiece& pattern, std::string* error) { if (compiled_) { LOG(DFATAL) << "RE2::Set::Add() called after compiling"; return -1; } Regexp::ParseFlags pf = static_cast<Regexp::ParseFlags>( options_.ParseFlags()); RegexpStatus status; re2::Regexp* re = Regexp::Parse(pattern, pf, &status); if (re == NULL) { if (error != NULL) *error = status.Text(); if (options_.log_errors()) LOG(ERROR) << "Error parsing '" << pattern << "': " << status.Text(); return -1; } // Concatenate with match index and push on vector. int n = static_cast<int>(elem_.size()); re2::Regexp* m = re2::Regexp::HaveMatch(n, pf); if (re->op() == kRegexpConcat) { int nsub = re->nsub(); PODArray<re2::Regexp*> sub(nsub + 1); for (int i = 0; i < nsub; i++) sub[i] = re->sub()[i]->Incref(); sub[nsub] = m; re->Decref(); re = re2::Regexp::Concat(sub.data(), nsub + 1, pf); } else { re2::Regexp* sub[2]; sub[0] = re; sub[1] = m; re = re2::Regexp::Concat(sub, 2, pf); } elem_.emplace_back(std::string(pattern), re); return n; } bool RE2::Set::Compile() { if (compiled_) { LOG(DFATAL) << "RE2::Set::Compile() called more than once"; return false; } compiled_ = true; size_ = static_cast<int>(elem_.size()); // Sort the elements by their patterns. This is good enough for now // until we have a Regexp comparison function. (Maybe someday...) std::sort(elem_.begin(), elem_.end(), [](const Elem& a, const Elem& b) -> bool { return a.first < b.first; }); PODArray<re2::Regexp*> sub(size_); for (int i = 0; i < size_; i++) sub[i] = elem_[i].second; elem_.clear(); elem_.shrink_to_fit(); Regexp::ParseFlags pf = static_cast<Regexp::ParseFlags>( options_.ParseFlags()); re2::Regexp* re = re2::Regexp::Alternate(sub.data(), size_, pf); prog_ = Prog::CompileSet(re, anchor_, options_.max_mem()); re->Decref(); return prog_ != NULL; } bool RE2::Set::Match(const StringPiece& text, std::vector<int>* v) const { return Match(text, v, NULL); } bool RE2::Set::Match(const StringPiece& text, std::vector<int>* v, ErrorInfo* error_info) const { if (!compiled_) { LOG(DFATAL) << "RE2::Set::Match() called before compiling"; if (error_info != NULL) error_info->kind = kNotCompiled; return false; } bool dfa_failed = false; std::unique_ptr<SparseSet> matches; if (v != NULL) { matches.reset(new SparseSet(size_)); v->clear(); } bool ret = prog_->SearchDFA(text, text, Prog::kAnchored, Prog::kManyMatch, NULL, &dfa_failed, matches.get()); if (dfa_failed) { if (options_.log_errors()) LOG(ERROR) << "DFA out of memory: " << "program size " << prog_->size() << ", " << "list count " << prog_->list_count() << ", " << "bytemap range " << prog_->bytemap_range(); if (error_info != NULL) error_info->kind = kOutOfMemory; return false; } if (ret == false) { if (error_info != NULL) error_info->kind = kNoError; return false; } if (v != NULL) { if (matches->empty()) { LOG(DFATAL) << "RE2::Set::Match() matched, but no matches returned?!"; if (error_info != NULL) error_info->kind = kInconsistent; return false; } v->assign(matches->begin(), matches->end()); } if (error_info != NULL) error_info->kind = kNoError; return true; } } // namespace re2 <|endoftext|>
<commit_before>/* silence.cpp - LV2 Toolkit API Demonstration Plugin Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /** @file silence.cpp Demonstrates LV2 URID mapping, Log, and State Save/Restore */ #include <iostream> #include <vector> #include <cstdlib> #include <lvtk/plugin.hpp> #include "silence.h" using namespace lvtk; using std::vector; #define LVTK_SILENCE_URI "http://lvtoolkit.org/plugins/silence" #define LVTK_SILENCE_PREFIX LVTK_SILENCE_URI "#" #define LVTK_SILENCE_MSG LVTK_SILENCE_PREFIX "msg" class Silence : public Plugin<Silence, URID<true>, State<true> > { public: Silence (double rate) : Plugin<Silence, URID<true>, State<true> > (1) { urids.atom_String = map (LV2_ATOM__String); urids.silence_msg = map (LVTK_SILENCE_MSG); urids.midi_type = map (LV2_MIDI__MidiEvent); } void run(uint32_t nframes) { float *out = p(0); check_midi(); for (int i = 0; i < nframes; i++) { out[i] = 0.0f; } } StateStatus save (StateStore &store, uint32_t flags, const FeatureVec &features) { const char* msg = "Sorry I can't hear you. Please speak up"; return store (urids.silence_msg, (void*)msg, strlen(msg), urids.atom_String, STATE_IS_POD | STATE_IS_PORTABLE); } StateStatus restore (StateRetrieve &retrieve, uint32_t flags, const FeatureVec &features) { size_t size; uint32_t type,fs; const void *message = retrieve (urids.silence_msg, &size, &type, &fs); if (message) { std::cout << "[silence] " << (char*)message << std::endl; return STATE_SUCCESS; } return STATE_ERR_UNKNOWN; } private: void check_midi () { const LV2_Atom_Sequence* midiseq = p<LV2_Atom_Sequence> (p_midi); LV2_ATOM_SEQUENCE_FOREACH(midiseq, ev) { uint32_t frame_offset = ev->time.frames; if (ev->body.type == urids.midi_type) { std::cout << "MIDI\n"; } } } struct SilenceURIs { LV2_URID atom_String; LV2_URID silence_msg; LV2_URID midi_type; } urids; }; static int _ = Silence::register_class (LVTK_SILENCE_URI); <commit_msg>Code style<commit_after>/* silence.cpp - LV2 Toolkit API Demonstration Plugin Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /** @file silence.cpp Demonstrates LV2 URID mapping, Log, and State Save/Restore */ #include <iostream> #include <vector> #include <cstdlib> #include <lvtk/plugin.hpp> #include "silence.h" using namespace lvtk; using std::vector; #define LVTK_SILENCE_URI "http://lvtoolkit.org/plugins/silence" #define LVTK_SILENCE_PREFIX LVTK_SILENCE_URI "#" #define LVTK_SILENCE_MSG LVTK_SILENCE_PREFIX "msg" class Silence : public Plugin<Silence, URID<true>, State<true> > { public: Silence (double rate) : Plugin<Silence, URID<true>, State<true> > (1) { urids.atom_String = map (LV2_ATOM__String); urids.silence_msg = map (LVTK_SILENCE_MSG); urids.midi_type = map (LV2_MIDI__MidiEvent); } void run(uint32_t nframes) { float *out = p(0); check_midi(); for (int i = 0; i < nframes; i++) { out[i] = 0.0f; } } StateStatus save (StateStore &store, uint32_t flags, const FeatureVec &features) { const char* msg = "Sorry I can't hear you. Please speak up"; return store (urids.silence_msg, (void*)msg, strlen(msg), urids.atom_String, STATE_IS_POD | STATE_IS_PORTABLE); } StateStatus restore (StateRetrieve &retrieve, uint32_t flags, const FeatureVec &features) { size_t size; uint32_t type,fs; const void *message = retrieve (urids.silence_msg, &size, &type, &fs); if (message) { std::cout << "[silence] " << (char*)message << std::endl; return STATE_SUCCESS; } return STATE_ERR_UNKNOWN; } private: void check_midi () { const LV2_Atom_Sequence* midiseq = p<LV2_Atom_Sequence> (p_midi); LV2_ATOM_SEQUENCE_FOREACH(midiseq, ev) { uint32_t frame_offset = ev->time.frames; if (ev->body.type == urids.midi_type) { std::cout << "MIDI\n"; } } } struct SilenceURIs { LV2_URID atom_String; LV2_URID silence_msg; LV2_URID midi_type; } urids; }; static int _ = Silence::register_class (LVTK_SILENCE_URI); <|endoftext|>
<commit_before>#include <Patcher/Maj.hpp> #include <QObject> #include <QUrl> #include <QFile> #include <QNetworkRequest> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QEventLoop> namespace patcher { Maj::Maj(Config& conf,int action,std::string filename,std::string url): action(action), filename(filename), url(url),config(conf), done(false) { } bool Maj::apply() { bool ok = true; switch(action) { case 1: //new { ok = download(); if (ok) write(); }break; case 2: //maj { ok = replace(); }break; case 3: //delete { ok = erase(); }break; default: //unknow { ok = false; }break; } done = ok; return ok; } bool Maj::download() { std::cout<<"[patcher] download file \""<<filename<<"\" from "<<url<<" "<<std::flush; QUrl base_url(config.getUrl().c_str()); QUrl relative_url(url.c_str()); QUrl url = base_url.resolved(relative_url); QNetworkRequest request; request.setUrl(url); QNetworkAccessManager networkManager; QNetworkReply* reply = networkManager.get(request); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); //open file QFile localFile(("download/"+filename).c_str()); if (!localFile.open(QIODevice::WriteOnly)) { std::cout<<"Failed"<<std::endl; return false; } //write in it localFile.write(reply->readAll()); localFile.close(); delete reply; std::cout<<"Ok"<<std::endl; return true; } bool Maj::erase() { bool ok = true; return ok; } bool Maj::replace() { bool ok = download(); if(ok) { erase(); ok = write(); } return ok; } bool Maj::write() { bool ok = true; return ok; } std::ostream& operator<<(std::ostream& output,const Maj& self) { output<<"{action:"<<self.action <<",\nfilename:"<<self.filename <<",\nurl:"<<self.url <<",\ndone:"<<self.done <<"}"; return output; } } <commit_msg>add exe right on exe<commit_after>#include <Patcher/Maj.hpp> #include <QObject> #include <QUrl> #include <QFile> #include <QNetworkRequest> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QEventLoop> #include <stdio.h> namespace patcher { Maj::Maj(Config& conf,int action,std::string filename,std::string url): action(action), filename(filename), url(url),config(conf), done(false) { } bool Maj::apply() { bool ok = true; switch(action) { case 1: //new { ok = download(); if (ok) write(); }break; case 2: //maj { ok = replace(); }break; case 3: //delete { ok = erase(); }break; default: //unknow { ok = false; }break; } done = ok; return ok; } bool Maj::download() { std::cout<<"[patcher] download file \""<<filename<<"\" from "<<url<<" "<<std::flush; QUrl base_url(config.getUrl().c_str()); QUrl relative_url(url.c_str()); QUrl url = base_url.resolved(relative_url); QNetworkRequest request; request.setUrl(url); QNetworkAccessManager networkManager; QNetworkReply* reply = networkManager.get(request); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); //open file QFile localFile(("download/"+filename).c_str()); if (!localFile.open(QIODevice::WriteOnly)) { std::cout<<"Failed"<<std::endl; return false; } //write in it localFile.write(reply->readAll()); localFile.close(); delete reply; std::cout<<"Ok"<<std::endl; return true; } bool Maj::erase() { return QFile::remove(filename.c_str()); } bool Maj::replace() { bool ok = download(); if(ok) { erase(); ok = write(); } return ok; } bool Maj::write() { bool ok = ::rename(("download/"+filename).c_str(),filename.c_str()) == 0; if (filename == Config::softname) QFile::setPermissions(filename.c_str(), QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner |QFile::ReadGroup|QFile::ExeGroup |QFile::ReadOther|QFile::ExeOther ); return ok; } std::ostream& operator<<(std::ostream& output,const Maj& self) { output<<"{action:"<<self.action <<",\nfilename:"<<self.filename <<",\nurl:"<<self.url <<",\ndone:"<<self.done <<"}"; return output; } } <|endoftext|>
<commit_before> #include "PitWizard.h" #include <iostream> #include <fstream> #include <chrono> #include <Physfs/physfs.h> #include "s3e.h" //#include <Photon-cpp/inc/PhotonPeer.h> #include <GG/GameLayer.h> #include <GG/Graphics.h> #include <GG/Core.h> #include <GG/Input.h> #include <GG/EntitySystem.h> #include <GG/Resources/ResourceManager.h> using namespace GG; PitWizard::PitWizard() : _deviceWidth(0), _deviceHeight(0) { } PitWizard::~PitWizard() { } void PitWizard::init(int argc, char** argv) { _setupLoggers(); s3eSurfaceSetup(S3E_SURFACE_PIXEL_TYPE_RGB888); //Initialise graphics system(s) if(!IwGLInit()) { TRACE_ERROR("IwGLInit failed"); return; } IwGLSwapBuffers(); s3eDeviceYield(0); _deviceWidth = IwGLGetInt(IW_GL_WIDTH); _deviceHeight = IwGLGetInt(IW_GL_HEIGHT); _gameStateManager.addGameState( "Intro", nullptr ); _gameStateManager.addGameState( "MainMenu", nullptr ); _gameStateManager.addGameState( "SinglePlayer", nullptr ); _gameStateManager.addGameState( "SinglePlayerEndScreen", nullptr ); _gameStateManager.addGameState( "MultiPlayer", nullptr ); _gameStateManager.addGameState( "MultiPlayerEndScreen", nullptr ); json config = JsonFromFile("configs/input_config.json"); inputSystem = std::unique_ptr<InputSystem>(new InputSystem(_deviceWidth, _deviceHeight)); inputSystem->init(config); RenderState::GetInstance()->setRenderSize(_deviceWidth, _deviceHeight); const char * argv0 = (argc > 0) ? argv[0] : nullptr; FileSystem::Init(argv0); FileSystem::Mount("rom://", "/", true); FileSystem::Mount("ram://", "/", true); FileSystem::Mount("/", "/", true); FileSystem::SetWriteDirectory("ram://"); ResourceManager::GetInstance()->registerType<Texture2D>(new Texture2DLoader()); ResourceManager::GetInstance()->registerType<Shader>(new ShaderLoader()); ResourceManager::GetInstance()->registerType<Material>(new MaterialLoader()); FileStream stream("resources/TestGroup.group", OpenMode::OPEN_READ); ResourceGroup* group = ResourceManager::GetInstance()->createGroup(&stream); group->loadAllAssets(); } void PitWizard::shutdown() { inputSystem->shutdown(); ResourceManager::ShutDown(); Log::Shutdown(); IwGLTerminate(); FileSystem::Shutdown(); } void PitWizard::doGameLoop() { ResourceManager * rm = ResourceManager::GetInstance(); ResourceH<Material> gridMat = rm->getResource<Material>("marble"); Model gridModel; gridModel.setVertexProperties(POSITIONS | TEXCOORDS | NORMALS | TANGENTS | BITANGENTS); ObjLoader::loadFromFile("./resources/environments/forest_road/models/grid.obj", gridModel); Model groundModel; groundModel.setVertexProperties(POSITIONS | TEXCOORDS | NORMALS | TANGENTS | BITANGENTS); ObjLoader::loadFromFile("./resources/environments/forest_road/models/groundPlane.obj", groundModel); Model playerModel; playerModel.setVertexProperties(POSITIONS | TEXCOORDS | NORMALS | TANGENTS | BITANGENTS); ObjLoader::loadFromFile("./resources/environments/forest_road/models/player.obj", playerModel); ResourceHandle<Material> tempHolder = rm->getResource<Material>("marble"); World* worldPtr = new World(new BasicSceneGraph(1000)); std::unique_ptr<World> world(worldPtr); float aspect = (float)_deviceWidth / (float)_deviceHeight; GG::Entity * box_1 = world->createEntity("Box_1"); GG::Mesh * boxMesh_1 = world->addComponent<Mesh>(box_1); boxMesh_1->geometry = &playerModel; boxMesh_1->material = gridMat.get(); SceneNode * boxNode_1 = box_1->getSceneNode(); boxNode_1->setPosition(Vector3(0, 1, 0)); GG::Entity * box_2 = world->createEntity("Box_2"); GG::Mesh * boxMesh_2 = world->addComponent<Mesh>(box_2); boxMesh_2->geometry = &playerModel; boxMesh_2->material = gridMat.get(); SceneNode * boxNode_2 = box_2->getSceneNode(); boxNode_2->setPosition(Vector3(0, 0, 3)); boxNode_2->setParent(boxNode_1); GG::Camera * cam = world->createCamera("Camera_1"); cam->setPerspective(Angle::FromDegrees(80.0f), aspect, 0.1f, 300.0f); cam->setViewport(0, 0, 1, 1); cam->setClearMode(RenderState::ClearMode::CM_DEPTH | RenderState::ClearMode::CM_COLOR); cam->setClearColor(GG::Vector4(0.43f, 0.48f, 0.67f, 1.0f)); GG::SceneNode * camNode_1 = cam->getEntity()->getSceneNode(); camNode_1->setPosition(Vector3(0.0f, 3.0f, -7.0f)); camNode_1->lookAt(boxNode_1); Entity * gridEntity = world->createEntity("GridMesh"); Mesh * gridMeshInstance = world->addComponent<Mesh>(gridEntity); gridMeshInstance->geometry = &gridModel; gridMeshInstance->material = gridMat.get(); Entity * groundEntity = world->createEntity("GroundMesh"); Mesh * groundMeshInstance = world->addComponent<Mesh>(groundEntity); groundMeshInstance->geometry = &groundModel; groundMeshInstance->material = gridMat.get(); const float camSpeed = 5.0f; Time clock; // Loop forever, until the user or the OS performs some action to quit the app while(!s3eDeviceCheckQuitRequest()) { clock.update(); float deltaTime = clock.getDeltaTime(); //Update the input systems inputSystem->update(); // TEMP RESOURCE RELOADING!!! -Julian if(s3eKeyboardGetState(s3eKeyR) & S3E_KEY_STATE_RELEASED) { /*ResourceHandle<Shader> shader = rm->getResource<Shader>(STRING_ID("cookTorrence")); shader->setState(IResource::State::UNLOADED); */ rm->findGroup(STRING_ID("default"))->reloadAllAssets(); } if(s3eKeyboardGetState(s3eKeyLeft) & S3E_KEY_STATE_DOWN) { boxNode_1->rotate(Angle::FromDegrees(3.0f), Vector::up()); } else if(s3eKeyboardGetState(s3eKeyRight) & S3E_KEY_STATE_DOWN) { boxNode_1->rotate(Angle::FromDegrees(-3.0f), Vector::up()); } if(s3eKeyboardGetState(s3eKeyUp) & S3E_KEY_STATE_DOWN) { boxNode_1->translate(boxNode_1->forward() * 0.1f); } else if(s3eKeyboardGetState(s3eKeyDown) & S3E_KEY_STATE_DOWN) { boxNode_1->translate(boxNode_1->forward() * -0.1f); } if(s3eKeyboardGetState(s3eKeyP) & S3E_KEY_STATE_RELEASED) { bool hasParent = boxNode_2->getParent() != nullptr; boxNode_2->setParent(hasParent ? nullptr : boxNode_1); } if(s3eKeyboardGetState(s3eKeyZ) & S3E_KEY_STATE_DOWN) { camNode_1->translate(Vector::down() * camSpeed * deltaTime); } else if(s3eKeyboardGetState(s3eKeyX) & S3E_KEY_STATE_DOWN) { camNode_1->translate(Vector::up() * camSpeed * deltaTime); } camNode_1->rotate(Angle::FromDegrees(70.0f) * inputSystem->getAxis( "RotateX" ), Vector::right() ); float walk = inputSystem->getAxis( "Walk" ); float strafe = inputSystem->getAxis( "Strafe" ); Vector3 move = (Vector::forward() * walk) + (camNode_1->right() * strafe); move = glm::length2(move) > 0.001f ? glm::normalize(move): move; camNode_1->translate(move * camSpeed * deltaTime); world->update(1.0f / 60.0f); world->renderOneFrame(); // Sleep for 0ms to allow the OS to process events etc. s3eDeviceYield( 0 ); } } void PitWizard::_setupLoggers() { const std::string filePath = _getFileLogName(); Log::GetInstance()->registerLogger( new FileLogger( filePath ) ); Log::GetInstance()->registerLogger( new ConsoleLogger() ); } const std::string PitWizard::_getFileLogName() const { auto now = std::chrono::system_clock::now(); const std::time_t now_time = std::chrono::system_clock::to_time_t( now ); auto t = localtime( &now_time ); std::string logFilename; GG::StringHelper::Format( logFilename, "ram://logs/log_%d-%d-%d_%dh-%dm-%ds.txt", t->tm_mon + 1, t->tm_hour + 1, t->tm_year + 1900, t->tm_hour, t->tm_min, t->tm_sec ); return logFilename; } <commit_msg>Setup file system earlier in init<commit_after> #include "PitWizard.h" #include <iostream> #include <fstream> #include <chrono> #include <Physfs/physfs.h> #include "s3e.h" //#include <Photon-cpp/inc/PhotonPeer.h> #include <GG/GameLayer.h> #include <GG/Graphics.h> #include <GG/Core.h> #include <GG/Input.h> #include <GG/EntitySystem.h> #include <GG/Resources/ResourceManager.h> using namespace GG; PitWizard::PitWizard() : _deviceWidth(0), _deviceHeight(0) { } PitWizard::~PitWizard() { } void PitWizard::init(int argc, char** argv) { _setupLoggers(); const char * argv0 = (argc > 0) ? argv[0] : nullptr; FileSystem::Init(argv0); FileSystem::Mount("rom://", "/", true); FileSystem::Mount("ram://", "/", true); FileSystem::Mount("/", "/", true); FileSystem::SetWriteDirectory("ram://"); s3eSurfaceSetup(S3E_SURFACE_PIXEL_TYPE_RGB888); //Initialise graphics system(s) if(!IwGLInit()) { TRACE_ERROR("IwGLInit failed"); return; } IwGLSwapBuffers(); s3eDeviceYield(0); _deviceWidth = IwGLGetInt(IW_GL_WIDTH); _deviceHeight = IwGLGetInt(IW_GL_HEIGHT); _gameStateManager.addGameState( "Intro", nullptr ); _gameStateManager.addGameState( "MainMenu", nullptr ); _gameStateManager.addGameState( "SinglePlayer", nullptr ); _gameStateManager.addGameState( "SinglePlayerEndScreen", nullptr ); _gameStateManager.addGameState( "MultiPlayer", nullptr ); _gameStateManager.addGameState( "MultiPlayerEndScreen", nullptr ); json config = JsonFromFile("configs/input_config.json"); inputSystem = std::unique_ptr<InputSystem>(new InputSystem(_deviceWidth, _deviceHeight)); inputSystem->init(config); RenderState::GetInstance()->setRenderSize(_deviceWidth, _deviceHeight); ResourceManager::GetInstance()->registerType<Texture2D>(new Texture2DLoader()); ResourceManager::GetInstance()->registerType<Shader>(new ShaderLoader()); ResourceManager::GetInstance()->registerType<Material>(new MaterialLoader()); FileStream stream("resources/TestGroup.group", OpenMode::OPEN_READ); ResourceGroup* group = ResourceManager::GetInstance()->createGroup(&stream); group->loadAllAssets(); } void PitWizard::shutdown() { inputSystem->shutdown(); ResourceManager::ShutDown(); Log::Shutdown(); IwGLTerminate(); FileSystem::Shutdown(); } void PitWizard::doGameLoop() { ResourceManager * rm = ResourceManager::GetInstance(); ResourceH<Material> gridMat = rm->getResource<Material>("marble"); Model gridModel; gridModel.setVertexProperties(POSITIONS | TEXCOORDS | NORMALS | TANGENTS | BITANGENTS); ObjLoader::loadFromFile("./resources/environments/forest_road/models/grid.obj", gridModel); Model groundModel; groundModel.setVertexProperties(POSITIONS | TEXCOORDS | NORMALS | TANGENTS | BITANGENTS); ObjLoader::loadFromFile("./resources/environments/forest_road/models/groundPlane.obj", groundModel); Model playerModel; playerModel.setVertexProperties(POSITIONS | TEXCOORDS | NORMALS | TANGENTS | BITANGENTS); ObjLoader::loadFromFile("./resources/environments/forest_road/models/player.obj", playerModel); ResourceHandle<Material> tempHolder = rm->getResource<Material>("marble"); World* worldPtr = new World(new BasicSceneGraph(1000)); std::unique_ptr<World> world(worldPtr); float aspect = (float)_deviceWidth / (float)_deviceHeight; GG::Entity * box_1 = world->createEntity("Box_1"); GG::Mesh * boxMesh_1 = world->addComponent<Mesh>(box_1); boxMesh_1->geometry = &playerModel; boxMesh_1->material = gridMat.get(); SceneNode * boxNode_1 = box_1->getSceneNode(); boxNode_1->setPosition(Vector3(0, 1, 0)); GG::Entity * box_2 = world->createEntity("Box_2"); GG::Mesh * boxMesh_2 = world->addComponent<Mesh>(box_2); boxMesh_2->geometry = &playerModel; boxMesh_2->material = gridMat.get(); SceneNode * boxNode_2 = box_2->getSceneNode(); boxNode_2->setPosition(Vector3(0, 0, 3)); boxNode_2->setParent(boxNode_1); GG::Camera * cam = world->createCamera("Camera_1"); cam->setPerspective(Angle::FromDegrees(80.0f), aspect, 0.1f, 300.0f); cam->setViewport(0, 0, 1, 1); cam->setClearMode(RenderState::ClearMode::CM_DEPTH | RenderState::ClearMode::CM_COLOR); cam->setClearColor(GG::Vector4(0.43f, 0.48f, 0.67f, 1.0f)); GG::SceneNode * camNode_1 = cam->getEntity()->getSceneNode(); camNode_1->setPosition(Vector3(0.0f, 3.0f, -7.0f)); camNode_1->lookAt(boxNode_1); Entity * gridEntity = world->createEntity("GridMesh"); Mesh * gridMeshInstance = world->addComponent<Mesh>(gridEntity); gridMeshInstance->geometry = &gridModel; gridMeshInstance->material = gridMat.get(); Entity * groundEntity = world->createEntity("GroundMesh"); Mesh * groundMeshInstance = world->addComponent<Mesh>(groundEntity); groundMeshInstance->geometry = &groundModel; groundMeshInstance->material = gridMat.get(); const float camSpeed = 5.0f; Time clock; // Loop forever, until the user or the OS performs some action to quit the app while(!s3eDeviceCheckQuitRequest()) { clock.update(); float deltaTime = clock.getDeltaTime(); //Update the input systems inputSystem->update(); // TEMP RESOURCE RELOADING!!! -Julian if(s3eKeyboardGetState(s3eKeyR) & S3E_KEY_STATE_RELEASED) { /*ResourceHandle<Shader> shader = rm->getResource<Shader>(STRING_ID("cookTorrence")); shader->setState(IResource::State::UNLOADED); */ rm->findGroup(STRING_ID("default"))->reloadAllAssets(); } if(s3eKeyboardGetState(s3eKeyLeft) & S3E_KEY_STATE_DOWN) { boxNode_1->rotate(Angle::FromDegrees(3.0f), Vector::up()); } else if(s3eKeyboardGetState(s3eKeyRight) & S3E_KEY_STATE_DOWN) { boxNode_1->rotate(Angle::FromDegrees(-3.0f), Vector::up()); } if(s3eKeyboardGetState(s3eKeyUp) & S3E_KEY_STATE_DOWN) { boxNode_1->translate(boxNode_1->forward() * 0.1f); } else if(s3eKeyboardGetState(s3eKeyDown) & S3E_KEY_STATE_DOWN) { boxNode_1->translate(boxNode_1->forward() * -0.1f); } if(s3eKeyboardGetState(s3eKeyP) & S3E_KEY_STATE_RELEASED) { bool hasParent = boxNode_2->getParent() != nullptr; boxNode_2->setParent(hasParent ? nullptr : boxNode_1); } if(s3eKeyboardGetState(s3eKeyZ) & S3E_KEY_STATE_DOWN) { camNode_1->translate(Vector::down() * camSpeed * deltaTime); } else if(s3eKeyboardGetState(s3eKeyX) & S3E_KEY_STATE_DOWN) { camNode_1->translate(Vector::up() * camSpeed * deltaTime); } camNode_1->rotate(Angle::FromDegrees(70.0f) * inputSystem->getAxis( "RotateX" ), Vector::right() ); float walk = inputSystem->getAxis( "Walk" ); float strafe = inputSystem->getAxis( "Strafe" ); Vector3 move = (Vector::forward() * walk) + (camNode_1->right() * strafe); move = glm::length2(move) > 0.001f ? glm::normalize(move): move; camNode_1->translate(move * camSpeed * deltaTime); world->update(1.0f / 60.0f); world->renderOneFrame(); // Sleep for 0ms to allow the OS to process events etc. s3eDeviceYield( 0 ); } } void PitWizard::_setupLoggers() { const std::string filePath = _getFileLogName(); Log::GetInstance()->registerLogger( new FileLogger( filePath ) ); Log::GetInstance()->registerLogger( new ConsoleLogger() ); } const std::string PitWizard::_getFileLogName() const { auto now = std::chrono::system_clock::now(); const std::time_t now_time = std::chrono::system_clock::to_time_t( now ); auto t = localtime( &now_time ); std::string logFilename; GG::StringHelper::Format( logFilename, "ram://logs/log_%d-%d-%d_%dh-%dm-%ds.txt", t->tm_mon + 1, t->tm_hour + 1, t->tm_year + 1900, t->tm_hour, t->tm_min, t->tm_sec ); return logFilename; } <|endoftext|>
<commit_before>// Vertex.hpp /* * (C) Copyright 2015 Noah Roth * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #pragma once #include "stdafx.hpp" namespace RCT3Asset { struct Vector2 { float X; float Y; Vector2() : X(0.0f), Y(0.0f) { } }; struct Vector3 { float X; float Y; float Z; Vector3() : X(0.0f), Y(0.0f), Z(0.0f) { } }; struct Vertex { Vector3 Position; Vector3 Normal; unsigned int Color; //float U; //float V; Vector2 UVCoords; }; struct WeightedVertex { Vector3 Position; Vector3 Normal; signed char Bone[4]; unsigned char BoneWeight[4]; unsigned int Color; Vector2 UVCoords; }; struct Triangle { unsigned int A; unsigned int B; unsigned int C; }; struct Matrix4x4 { union { float M[4][4]; struct { float A1, A2, A3, A4; float B1, B2, B3, B4; float C1, C2, C3, C4; float D1, D2, D3, D4; }; }; }; struct GameColor { unsigned int Color1; unsigned int Color2; unsigned int Color3; GameColor() : Color1(0), Color2(0), Color3(0) { } }; struct BGRAColor { unsigned char B; unsigned char G; unsigned char R; unsigned char A; BGRAColor() : B(0), G(0), R(0), A(0) { } }; // For use with libsquish struct U8Color { squish::u8 R; squish::u8 G; squish::u8 B; squish::u8 A; U8Color() : R(0), G(0), B(0), A(0) { } }; }<commit_msg>added keyframe<commit_after>// Vertex.hpp /* * (C) Copyright 2015 Noah Roth * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #pragma once #include "stdafx.hpp" namespace RCT3Asset { struct Vector2 { float X; float Y; Vector2() : X(0.0f), Y(0.0f) { } }; struct Vector3 { float X; float Y; float Z; Vector3() : X(0.0f), Y(0.0f), Z(0.0f) { } }; struct Vertex { Vector3 Position; Vector3 Normal; unsigned int Color; //float U; //float V; Vector2 UVCoords; }; struct WeightedVertex { Vector3 Position; Vector3 Normal; signed char Bone[4]; unsigned char BoneWeight[4]; unsigned int Color; Vector2 UVCoords; }; struct Triangle { unsigned int A; unsigned int B; unsigned int C; }; struct Matrix4x4 { union { float M[4][4]; struct { float A1, A2, A3, A4; float B1, B2, B3, B4; float C1, C2, C3, C4; float D1, D2, D3, D4; }; }; }; struct KeyFrame { float Time; Vector3 TranslateRotate; }; struct GameColor { unsigned int Color1; unsigned int Color2; unsigned int Color3; GameColor() : Color1(0), Color2(0), Color3(0) { } }; struct BGRAColor { unsigned char B; unsigned char G; unsigned char R; unsigned char A; BGRAColor() : B(0), G(0), R(0), A(0) { } }; // For use with libsquish struct U8Color { squish::u8 R; squish::u8 G; squish::u8 B; squish::u8 A; U8Color() : R(0), G(0), B(0), A(0) { } }; }<|endoftext|>
<commit_before>/* * daemon-tools.node *** A node.JS addon that allows creating Unix/Linux Daemons in pure Javascript. *** Copyright 2010 (c) <arthur@norgic.com> * Under MIT License. See LICENSE file. * Updated by Daniel Bartlett 2011 <dan@f-box.org> */ #include <v8.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <ev.h> #include <pwd.h> #define PID_MAXLEN 10 using namespace v8; // Go through special routines to become a daemon. // if successful, returns daemon's PID Handle<Value> Start(const Arguments& args) { pid_t pid, sid; int do_cd_root; if (args.Length() < 1) { return ThrowException(Exception::TypeError( String::New("Must have one argument true/false as to if we cd /"))); } do_cd_root = args[0]->Int32Value(); pid = fork(); if(pid > 0) exit(0); if(pid < 0) exit(1); ev_default_fork(); // Can be changed after with process.umaks umask(0); sid = setsid(); if(sid < 0) exit(1); // Can be changed with process.chdir if (do_cd_root == 1) { chdir("/"); } return Integer::New(getpid()); } // Close Standard IN/OUT/ERR Streams Handle<Value> CloseIO(const Arguments& args) { freopen("/dev/null", "r", stdin); freopen("/dev/null", "w", stdout); freopen("/dev/null", "w", stderr); } // File-lock to make sure that only one instance of daemon is running.. also for storing PID /* lock ( filename ) *** filename: a path to a lock-file. *** Note: if filename doesn't exist, it will be created when function is called. */ Handle<Value> LockD(const Arguments& args) { if(!args[0]->IsString()) return Boolean::New(false); String::Utf8Value data(args[0]->ToString()); char pid_str[PID_MAXLEN+1]; int lfp = open(*data, O_RDWR | O_CREAT, 0640); if(lfp < 0) exit(1); if(lockf(lfp, F_TLOCK, 0) < 0) exit(0); int len = snprintf(pid_str, PID_MAXLEN, "%d", getpid()); write(lfp, pid_str, len); return Boolean::New(true); } const char* ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } /* chroot ( folder ) * folder: The new root */ Handle<Value> Chroot(const Arguments& args) { if (args.Length() < 1) { return ThrowException(Exception::TypeError( String::New("Must have one argument; a string of the folder to chroot to.") )); } uid_t uid; int rv; uid = getuid(); if (uid != 0) { return ThrowException(Exception::Error( String::New("You must be root in order to use chroot.") )); } String::Utf8Value folderUtf8(args[0]->ToString()); const char *folder = ToCString(folderUtf8); rv = chroot(folder); if (rv != 0) { return ThrowException(Exception::Error( String::New("Failed do chroot to the folder.") )); } chdir("/"); return Boolean::New(true); } // Allow changing the real and effective user ID of this process so a root process // can become unprivileged Handle<Value> SetREUID(const Arguments& args) { if(args.Length() == 0 || !args[0]->IsString()) return ThrowException(Exception::Error( String::New("Must give a username to become") )); String::AsciiValue username(args[0]); struct passwd* pwd_entry = getpwnam(*username); if(pwd_entry) { setreuid(pwd_entry->pw_uid, pwd_entry->pw_uid); } else { return ThrowException(Exception::Error( String::New("User not found") )); } } extern "C" void init(Handle<Object> target) { HandleScope scope; target->Set(String::New("start"), FunctionTemplate::New(Start)->GetFunction()); target->Set(String::New("lock"), FunctionTemplate::New(LockD)->GetFunction()); target->Set(String::New("closeIO"), FunctionTemplate::New(CloseIO)->GetFunction()); target->Set(String::New("chroot"), FunctionTemplate::New(Chroot)->GetFunction()); target->Set(String::New("setreuid"), FunctionTemplate::New(SetREUID)->GetFunction()); } <commit_msg>Adding setreuid_username and setreuid<commit_after>/* * daemon-tools.node *** A node.JS addon that allows creating Unix/Linux Daemons in pure Javascript. *** Copyright 2010 (c) <arthur@norgic.com> * Under MIT License. See LICENSE file. * Updated by Daniel Bartlett 2011 <dan@f-box.org> */ #include <v8.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <ev.h> #include <pwd.h> #define PID_MAXLEN 10 using namespace v8; // Go through special routines to become a daemon. // if successful, returns daemon's PID Handle<Value> Start(const Arguments& args) { pid_t pid, sid; int do_cd_root; if (args.Length() < 1) { return ThrowException(Exception::TypeError( String::New("Must have one argument true/false as to if we cd /"))); } do_cd_root = args[0]->Int32Value(); pid = fork(); if(pid > 0) exit(0); if(pid < 0) exit(1); ev_default_fork(); // Can be changed after with process.umaks umask(0); sid = setsid(); if(sid < 0) exit(1); // Can be changed with process.chdir if (do_cd_root == 1) { chdir("/"); } return Integer::New(getpid()); } // Close Standard IN/OUT/ERR Streams Handle<Value> CloseIO(const Arguments& args) { freopen("/dev/null", "r", stdin); freopen("/dev/null", "w", stdout); freopen("/dev/null", "w", stderr); } // File-lock to make sure that only one instance of daemon is running.. also for storing PID /* lock ( filename ) *** filename: a path to a lock-file. *** Note: if filename doesn't exist, it will be created when function is called. */ Handle<Value> LockD(const Arguments& args) { if(!args[0]->IsString()) return Boolean::New(false); String::Utf8Value data(args[0]->ToString()); char pid_str[PID_MAXLEN+1]; int lfp = open(*data, O_RDWR | O_CREAT, 0640); if(lfp < 0) exit(1); if(lockf(lfp, F_TLOCK, 0) < 0) exit(0); int len = snprintf(pid_str, PID_MAXLEN, "%d", getpid()); write(lfp, pid_str, len); return Boolean::New(true); } const char* ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } /* chroot ( folder ) * folder: The new root */ Handle<Value> Chroot(const Arguments& args) { if (args.Length() < 1) { return ThrowException(Exception::TypeError( String::New("Must have one argument; a string of the folder to chroot to.") )); } uid_t uid; int rv; uid = getuid(); if (uid != 0) { return ThrowException(Exception::Error( String::New("You must be root in order to use chroot.") )); } String::Utf8Value folderUtf8(args[0]->ToString()); const char *folder = ToCString(folderUtf8); rv = chroot(folder); if (rv != 0) { return ThrowException(Exception::Error( String::New("Failed do chroot to the folder.") )); } chdir("/"); return Boolean::New(true); } // Allow changing the real and effective user ID of this process so a root process // can become unprivileged Handle<Value> SetREUID(const Arguments& args) { uid_t uid; if(args.Length() == 0) return ThrowException(Exception::Error( String::New("Must give a uid to become") )); uid = args[0]->Int32Value(); setreuid(uid, uid); } // Allow changing the real and effective user ID of this process so a root process // can become unprivileged Handle<Value> SetREUID_username(const Arguments& args) { if(args.Length() == 0 || !args[0]->IsString()) return ThrowException(Exception::Error( String::New("Must give a username to become") )); String::AsciiValue username(args[0]); struct passwd* pwd_entry = getpwnam(*username); if(pwd_entry) { setreuid(pwd_entry->pw_uid, pwd_entry->pw_uid); } else { return ThrowException(Exception::Error( String::New("User not found") )); } } extern "C" void init(Handle<Object> target) { HandleScope scope; target->Set(String::New("start"), FunctionTemplate::New(Start)->GetFunction()); target->Set(String::New("lock"), FunctionTemplate::New(LockD)->GetFunction()); target->Set(String::New("closeIO"), FunctionTemplate::New(CloseIO)->GetFunction()); target->Set(String::New("chroot"), FunctionTemplate::New(Chroot)->GetFunction()); target->Set(String::New("setreuid_username"), FunctionTemplate::New(SetREUID_username)->GetFunction()); target->Set(String::New("setreuid"), FunctionTemplate::New(SetREUID)->GetFunction()); } <|endoftext|>
<commit_before>#include "./core.hpp" #include "./darwin/darwin.hpp" #include <cstdlib> darwin::pixel pencil; darwin::sync_clock dclock(30); void init(){ cov_basic::storage.add_var("darwin_loadmodule",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ darwin::runtime.load(args.at(0).val<std::string>()); return 0; })); cov_basic::storage.add_var("darwin_fitwindow",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ darwin::runtime.fit_drawable(); return 0; })); cov_basic::storage.add_var("darwin_updatepaint",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ darwin::runtime.update_drawable(); dclock.sync(); dclock.reset(); return 0; })); cov_basic::storage.add_var("darwin_clearpaint",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ darwin::runtime.get_drawable()->clear(); return 0; })); cov_basic::storage.add_var("darwin_fillpaint",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ darwin::runtime.get_drawable()->fill(pencil); return 0; })); cov_basic::storage.add_var("darwin_windowheight",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ return darwin::runtime.get_drawable()->get_height(); })); cov_basic::storage.add_var("darwin_windowwidth",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ return darwin::runtime.get_drawable()->get_width(); })); cov_basic::storage.add_var("darwin_drawpoint",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ darwin::runtime.get_drawable()->draw_pixel(args.at(0).val<cov_basic::number>(),args.at(1).val<cov_basic::number>(),pencil); return 0; })); cov_basic::storage.add_var("darwin_drawline",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ darwin::runtime.get_drawable()->draw_line(args.at(0).val<cov_basic::number>(),args.at(1).val<cov_basic::number>(),args.at(2).val<cov_basic::number>(),args.at(3).val<cov_basic::number>(),pencil); return 0; })); cov_basic::storage.add_var("darwin_setpencil",cov_basic::native_interface([](const std::deque<cov::any>& args)->cov_basic::number{ char ch=args.at(0).val<std::string>().at(0); bool bright=args.at(1).val<bool>(); bool underline=args.at(2).val<bool>(); darwin::colors fc,bc; switch(int(args.at(3).val<cov_basic::number>())) { case 0: fc=darwin::colors::black; break; case 1: fc=darwin::colors::white; break; case 2: fc=darwin::colors::red; break; case 3: fc=darwin::colors::green; break; case 4: fc=darwin::colors::blue; break; case 5: fc=darwin::colors::pink; break; case 6: fc=darwin::colors::yellow; break; case 7: fc=darwin::colors::cyan; break; } switch(int(args.at(4).val<cov_basic::number>())) { case 0: bc=darwin::colors::black; break; case 1: bc=darwin::colors::white; break; case 2: bc=darwin::colors::red; break; case 3: bc=darwin::colors::green; break; case 4: bc=darwin::colors::blue; break; case 5: bc=darwin::colors::pink; break; case 6: bc=darwin::colors::yellow; break; case 7: bc=darwin::colors::cyan; break; } pencil=darwin::pixel(ch,bright,underline,fc,bc); return 0; })); }<commit_msg>Delete darwin_core.hpp<commit_after><|endoftext|>
<commit_before>#ifndef __Data_course__ #define __Data_course__ #include "data-general.hpp" #include "data-major.hpp" #include "data-department.hpp" using namespace std; class Course { protected: string ID; int number; string title; string description; char section; vector<Major> majors; Department* department; string concentrations; string conversations; string professor; int half_semester; bool pass_fail; float credits; string location; bool lab; GenEd* geneds; bool days[7]; float time[7]; public: Course(istream &is) { if (!is) return; string tmpLine; getline(is, tmpLine); // remove the extra data of course status vector<string> record = split(tmpLine, ','); for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) *i=removeAllQuotes(*i); // Ignore the first column; record.at(0); // Second column has the course ID, //number = stringToInt(record.at(1)); ID = record.at(1); number = parseID(ID); // Third column has the section, section = record.at(2)[0]; // Fourth holds the lab boolean, if (record.at(3).empty()) lab = false; else lab = true; // while Fifth contains the title of the course; title = record.at(4); // Sixth hands over the length (half semester or not) // it's actually an int that tells us how many times the course is offered per semester. half_semester = stringToInt(record.at(5)); // Seventh tells us the number of credits, credits = stringToFloat(record.at(6)); // Eighth shows us if it can be taken pass/no-pass, if (record.at(7) == "Y") pass_fail = true; else pass_fail = false; // while Nine gives us the GEs of the course, // GEreqs = record.at(9); // and Ten spits out the days and times; // Times = record.at(10); // Eleven holds the location, location = record.at(11); // and Twelve knows who teaches. professor = record.at(12); } void parseID(string str) { unsigned int foundLoc = str.find('/'); string tempDept = str.substr(0,str.find(' ')-1); if (foundLoc != str.npos) { string dept1 = tempDept.substr(0,2); department.push_back(Department(dept1)); string dept2 = tempDept.substr(2,2); department.push_back(Department(dept2)); } else { department.push_back(Department(tempDept)); } } void updateID() { string dept; for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) dept += i->getName(); ID = dept + tostring(number) + section; } string getID() { return ID; } ostream& getData(ostream &os) { os << ID << section << " - "; os << title << " | "; // os << professor << endl; return os; } void display(); }; ostream &operator<<(ostream &os, Course &item) { return item.getData(os); } void Course::display() { if(this==0) cout << *this << endl; } #endif <commit_msg>Switch to a vector of departments<commit_after>#ifndef __Data_course__ #define __Data_course__ #include "data-general.hpp" #include "data-major.hpp" #include "data-department.hpp" using namespace std; class Course { protected: string ID; int number; string title; string description; char section; vector<Major> majors; vector<Department> department; string concentrations; string conversations; string professor; int half_semester; bool pass_fail; float credits; string location; bool lab; GenEd* geneds; bool days[7]; float time[7]; public: Course(istream &is) { if (!is) return; string tmpLine; getline(is, tmpLine); // remove the extra data of course status vector<string> record = split(tmpLine, ','); for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) *i=removeAllQuotes(*i); // Ignore the first column; record.at(0); // Second column has the course ID, //number = stringToInt(record.at(1)); ID = record.at(1); number = parseID(ID); // Third column has the section, section = record.at(2)[0]; // Fourth holds the lab boolean, if (record.at(3).empty()) lab = false; else lab = true; // while Fifth contains the title of the course; title = record.at(4); // Sixth hands over the length (half semester or not) // it's actually an int that tells us how many times the course is offered per semester. half_semester = stringToInt(record.at(5)); // Seventh tells us the number of credits, credits = stringToFloat(record.at(6)); // Eighth shows us if it can be taken pass/no-pass, if (record.at(7) == "Y") pass_fail = true; else pass_fail = false; // while Nine gives us the GEs of the course, // GEreqs = record.at(9); // and Ten spits out the days and times; // Times = record.at(10); // Eleven holds the location, location = record.at(11); // and Twelve knows who teaches. professor = record.at(12); } void parseID(string str) { unsigned int foundLoc = str.find('/'); string tempDept = str.substr(0,str.find(' ')-1); if (foundLoc != str.npos) { string dept1 = tempDept.substr(0,2); department.push_back(Department(dept1)); string dept2 = tempDept.substr(2,2); department.push_back(Department(dept2)); } else { department.push_back(Department(tempDept)); } } void updateID() { string dept; for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) dept += i->getName(); ID = dept + tostring(number) + section; } string getID() { return ID; } ostream& getData(ostream &os) { os << ID << section << " - "; os << title << " | "; // os << professor << endl; return os; } void display(); }; ostream &operator<<(ostream &os, Course &item) { return item.getData(os); } void Course::display() { if(this==0) cout << *this << endl; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 "sandbox/src/win_utils.h" #include <map> #include "base/logging.h" #include "base/scoped_ptr.h" #include "sandbox/src/internal_types.h" #include "sandbox/src/nt_internals.h" namespace { // Holds the information about a known registry key. struct KnownReservedKey { const wchar_t* name; HKEY key; }; // Contains all the known registry key by name and by handle. const KnownReservedKey kKnownKey[] = { { L"HKEY_CLASSES_ROOT", HKEY_CLASSES_ROOT }, { L"HKEY_CURRENT_USER", HKEY_CURRENT_USER }, { L"HKEY_LOCAL_MACHINE", HKEY_LOCAL_MACHINE}, { L"HKEY_USERS", HKEY_USERS}, { L"HKEY_PERFORMANCE_DATA", HKEY_PERFORMANCE_DATA}, { L"HKEY_PERFORMANCE_TEXT", HKEY_PERFORMANCE_TEXT}, { L"HKEY_PERFORMANCE_NLSTEXT", HKEY_PERFORMANCE_NLSTEXT}, { L"HKEY_CURRENT_CONFIG", HKEY_CURRENT_CONFIG}, { L"HKEY_DYN_DATA", HKEY_DYN_DATA} }; } // namespace namespace sandbox { HKEY GetReservedKeyFromName(const std::wstring& name) { for (size_t i = 0; i < arraysize(kKnownKey); ++i) { if (name == kKnownKey[i].name) return kKnownKey[i].key; } return NULL; } bool ResolveRegistryName(std::wstring name, std::wstring* resolved_name) { for (size_t i = 0; i < arraysize(kKnownKey); ++i) { if (name.find(kKnownKey[i].name) == 0) { HKEY key; DWORD disposition; if (ERROR_SUCCESS != ::RegCreateKeyEx(kKnownKey[i].key, L"", 0, NULL, 0, MAXIMUM_ALLOWED, NULL, &key, &disposition)) return false; bool result = GetPathFromHandle(key, resolved_name); ::RegCloseKey(key); if (!result) return false; *resolved_name += name.substr(wcslen(kKnownKey[i].name)); return true; } } return false; } DWORD IsReparsePoint(const std::wstring& full_path, bool* result) { std::wstring path = full_path; // Remove the nt prefix. if (0 == path.compare(0, kNTPrefixLen, kNTPrefix)) path = path.substr(kNTPrefixLen); // Check if it's a pipe. We can't query the attributes of a pipe. const wchar_t kPipe[] = L"pipe\\"; if (0 == path.compare(0, arraysize(kPipe) - 1, kPipe)) { *result = FALSE; return ERROR_SUCCESS; } std::wstring::size_type last_pos = std::wstring::npos; do { path = path.substr(0, last_pos); DWORD attributes = ::GetFileAttributes(path.c_str()); if (INVALID_FILE_ATTRIBUTES == attributes) { DWORD error = ::GetLastError(); if (error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND && error != ERROR_INVALID_NAME) { // Unexpected error. NOTREACHED(); return error; } } else if (FILE_ATTRIBUTE_REPARSE_POINT & attributes) { // This is a reparse point. *result = true; return ERROR_SUCCESS; } last_pos = path.rfind(L'\\'); } while (last_pos != std::wstring::npos); *result = false; return ERROR_SUCCESS; } bool ConvertToLongPath(const std::wstring& short_path, std::wstring* long_path) { // Check if the path is a NT path. bool is_nt_path = false; std::wstring path = short_path; if (0 == path.compare(0, kNTPrefixLen, kNTPrefix)) { path = path.substr(kNTPrefixLen); is_nt_path = true; } DWORD size = MAX_PATH; scoped_array<wchar_t> long_path_buf(new wchar_t[size]); DWORD return_value = ::GetLongPathName(path.c_str(), long_path_buf.get(), size); while (return_value >= size) { size *= 2; long_path_buf.reset(new wchar_t[size]); return_value = ::GetLongPathName(path.c_str(), long_path_buf.get(), size); } DWORD last_error = ::GetLastError(); if (0 == return_value && (ERROR_FILE_NOT_FOUND == last_error || ERROR_PATH_NOT_FOUND == last_error || ERROR_INVALID_NAME == last_error)) { // The file does not exist, but maybe a sub path needs to be expanded. std::wstring::size_type last_slash = path.rfind(L'\\'); if (std::wstring::npos == last_slash) return false; std::wstring begin = path.substr(0, last_slash); std::wstring end = path.substr(last_slash); if (!ConvertToLongPath(begin, &begin)) return false; // Ok, it worked. Let's reset the return value. path = begin + end; return_value = 1; } else if (0 != return_value) { path = long_path_buf.get(); } if (return_value != 0) { if (is_nt_path) { *long_path = kNTPrefix; *long_path += path; } else { *long_path = path; } return true; } return false; } bool GetPathFromHandle(HANDLE handle, std::wstring* path) { NtQueryObjectFunction NtQueryObject = NULL; ResolveNTFunctionPtr("NtQueryObject", &NtQueryObject); OBJECT_NAME_INFORMATION* name = NULL; ULONG size = 0; // Query the name information a first time to get the size of the name. NTSTATUS status = NtQueryObject(handle, ObjectNameInformation, name, size, &size); scoped_ptr<OBJECT_NAME_INFORMATION> name_ptr; if (size) { name = reinterpret_cast<OBJECT_NAME_INFORMATION*>(new BYTE[size]); name_ptr.reset(name); // Query the name information a second time to get the name of the // object referenced by the handle. status = NtQueryObject(handle, ObjectNameInformation, name, size, &size); } if (STATUS_SUCCESS != status) return false; path->assign(name->ObjectName.Buffer, name->ObjectName.Length / sizeof(name->ObjectName.Buffer[0])); return true; } }; // namespace sandbox // TODO(cpu): Revert this change to use a map to speed up the function once // this has been deployed in the dev channel for a week. See bug 11789. void ResolveNTFunctionPtr(const char* name, void* ptr) { static HMODULE ntdll = ::GetModuleHandle(sandbox::kNtdllName); FARPROC* function_ptr = reinterpret_cast<FARPROC*>(ptr); *function_ptr = ::GetProcAddress(ntdll, name); CHECK(*function_ptr) << "Failed to resolve NTDLL function"; } <commit_msg>Change again the way we do ResolveNTFunctionPtr - This version is different from last two<commit_after>// Copyright (c) 2006-2008 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 "sandbox/src/win_utils.h" #include <map> #include "base/logging.h" #include "base/scoped_ptr.h" #include "sandbox/src/internal_types.h" #include "sandbox/src/nt_internals.h" namespace { // Holds the information about a known registry key. struct KnownReservedKey { const wchar_t* name; HKEY key; }; // Contains all the known registry key by name and by handle. const KnownReservedKey kKnownKey[] = { { L"HKEY_CLASSES_ROOT", HKEY_CLASSES_ROOT }, { L"HKEY_CURRENT_USER", HKEY_CURRENT_USER }, { L"HKEY_LOCAL_MACHINE", HKEY_LOCAL_MACHINE}, { L"HKEY_USERS", HKEY_USERS}, { L"HKEY_PERFORMANCE_DATA", HKEY_PERFORMANCE_DATA}, { L"HKEY_PERFORMANCE_TEXT", HKEY_PERFORMANCE_TEXT}, { L"HKEY_PERFORMANCE_NLSTEXT", HKEY_PERFORMANCE_NLSTEXT}, { L"HKEY_CURRENT_CONFIG", HKEY_CURRENT_CONFIG}, { L"HKEY_DYN_DATA", HKEY_DYN_DATA} }; } // namespace namespace sandbox { HKEY GetReservedKeyFromName(const std::wstring& name) { for (size_t i = 0; i < arraysize(kKnownKey); ++i) { if (name == kKnownKey[i].name) return kKnownKey[i].key; } return NULL; } bool ResolveRegistryName(std::wstring name, std::wstring* resolved_name) { for (size_t i = 0; i < arraysize(kKnownKey); ++i) { if (name.find(kKnownKey[i].name) == 0) { HKEY key; DWORD disposition; if (ERROR_SUCCESS != ::RegCreateKeyEx(kKnownKey[i].key, L"", 0, NULL, 0, MAXIMUM_ALLOWED, NULL, &key, &disposition)) return false; bool result = GetPathFromHandle(key, resolved_name); ::RegCloseKey(key); if (!result) return false; *resolved_name += name.substr(wcslen(kKnownKey[i].name)); return true; } } return false; } DWORD IsReparsePoint(const std::wstring& full_path, bool* result) { std::wstring path = full_path; // Remove the nt prefix. if (0 == path.compare(0, kNTPrefixLen, kNTPrefix)) path = path.substr(kNTPrefixLen); // Check if it's a pipe. We can't query the attributes of a pipe. const wchar_t kPipe[] = L"pipe\\"; if (0 == path.compare(0, arraysize(kPipe) - 1, kPipe)) { *result = FALSE; return ERROR_SUCCESS; } std::wstring::size_type last_pos = std::wstring::npos; do { path = path.substr(0, last_pos); DWORD attributes = ::GetFileAttributes(path.c_str()); if (INVALID_FILE_ATTRIBUTES == attributes) { DWORD error = ::GetLastError(); if (error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND && error != ERROR_INVALID_NAME) { // Unexpected error. NOTREACHED(); return error; } } else if (FILE_ATTRIBUTE_REPARSE_POINT & attributes) { // This is a reparse point. *result = true; return ERROR_SUCCESS; } last_pos = path.rfind(L'\\'); } while (last_pos != std::wstring::npos); *result = false; return ERROR_SUCCESS; } bool ConvertToLongPath(const std::wstring& short_path, std::wstring* long_path) { // Check if the path is a NT path. bool is_nt_path = false; std::wstring path = short_path; if (0 == path.compare(0, kNTPrefixLen, kNTPrefix)) { path = path.substr(kNTPrefixLen); is_nt_path = true; } DWORD size = MAX_PATH; scoped_array<wchar_t> long_path_buf(new wchar_t[size]); DWORD return_value = ::GetLongPathName(path.c_str(), long_path_buf.get(), size); while (return_value >= size) { size *= 2; long_path_buf.reset(new wchar_t[size]); return_value = ::GetLongPathName(path.c_str(), long_path_buf.get(), size); } DWORD last_error = ::GetLastError(); if (0 == return_value && (ERROR_FILE_NOT_FOUND == last_error || ERROR_PATH_NOT_FOUND == last_error || ERROR_INVALID_NAME == last_error)) { // The file does not exist, but maybe a sub path needs to be expanded. std::wstring::size_type last_slash = path.rfind(L'\\'); if (std::wstring::npos == last_slash) return false; std::wstring begin = path.substr(0, last_slash); std::wstring end = path.substr(last_slash); if (!ConvertToLongPath(begin, &begin)) return false; // Ok, it worked. Let's reset the return value. path = begin + end; return_value = 1; } else if (0 != return_value) { path = long_path_buf.get(); } if (return_value != 0) { if (is_nt_path) { *long_path = kNTPrefix; *long_path += path; } else { *long_path = path; } return true; } return false; } bool GetPathFromHandle(HANDLE handle, std::wstring* path) { NtQueryObjectFunction NtQueryObject = NULL; ResolveNTFunctionPtr("NtQueryObject", &NtQueryObject); OBJECT_NAME_INFORMATION* name = NULL; ULONG size = 0; // Query the name information a first time to get the size of the name. NTSTATUS status = NtQueryObject(handle, ObjectNameInformation, name, size, &size); scoped_ptr<OBJECT_NAME_INFORMATION> name_ptr; if (size) { name = reinterpret_cast<OBJECT_NAME_INFORMATION*>(new BYTE[size]); name_ptr.reset(name); // Query the name information a second time to get the name of the // object referenced by the handle. status = NtQueryObject(handle, ObjectNameInformation, name, size, &size); } if (STATUS_SUCCESS != status) return false; path->assign(name->ObjectName.Buffer, name->ObjectName.Length / sizeof(name->ObjectName.Buffer[0])); return true; } }; // namespace sandbox // TODO(cpu): This is not the final code we want here but we are yet // to understand what is going on. See bug 11789. void ResolveNTFunctionPtr(const char* name, void* ptr) { static HMODULE ntdll = ::GetModuleHandle(sandbox::kNtdllName); FARPROC* function_ptr = reinterpret_cast<FARPROC*>(ptr); *function_ptr = ::GetProcAddress(ntdll, name); if (*function_ptr) return; // We have data that re-trying helps. *function_ptr = ::GetProcAddress(ntdll, name); CHECK(*function_ptr); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: BiasCorrector.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <string> #include <vector> #include <vnl/vnl_math.h> #include "mydefs.h" #include "imageutils.h" #include "OptionList.h" #include "itkMRIBiasFieldCorrectionFilter.h" void print_usage() { print_line("MRIBiasCorrection 1.0 (21.June.2001)"); print_line("usage: BiasCorrector --input file" ) ; print_line(" --output file") ; print_line(" --class-mean mean(1) ... mean(i)" ) ; print_line(" --class-sigma sigma(1) ... sigma(i)" ) ; print_line(" --use-log [yes|no]") ; print_line(" [--input-mask file]" ) ; print_line(" [--output-mask file]" ) ; print_line(" [--degree int] ") ; print_line(" [--growth double] [--shrink double] [--max-iteration int]"); print_line(" [--init-step-size double] "); print_line(" [--use-slab-identification [yes|no]]") ; print_line(" [--slice-direction [0-2]]" ) ; print_line(""); print_line("--input file") ; print_line(" input image file name [meta image format]" ); print_line("--output file") ; print_line(" output image file name [meta image format]" ); print_line("--class-mean mean(1),...,mean(i)" ) ; print_line(" intensity means of the differen i tissue classes") ; print_line("--class-sigma sig(1),...,sig(i)" ) ; print_line(" intensity sigmas of the different i tissue clases") ; print_line(" NOTE: The sigmas should be listed in the SAME ORDER") ; print_line(" of means"); print_line(" and each value should be SEPERATED BY A SPACE)") ; print_line("--input-mask file" ) ; print_line(" mask input with file [meta image format]"); print_line("--output-mask file" ) ; print_line(" mask output with file [meta image format]"); print_line("--degree int") ; print_line(" degree of legendre polynomial used for the") ; print_line(" approximation of the bias field" ); print_line("--use-log [yes|no]") ; print_line(" if yes, assume a multiplicative bias field") ; print_line(" (use log of image, class-mean, class-sigma,") ; print_line(" and init-step-size)" ); print_line("--growth double") ; print_line(" stepsize growth factor. must be greater than 1.0") ; print_line(" [default 1.05]" ) ; print_line("--shrink double") ; print_line(" stepsize shrink factor ") ; print_line(" [default growth^(-0.25)]" ) ; print_line("--max-iteration int") ; print_line(" maximal number of iterations") ; print_line(" [default 20]" ) ; print_line("--init-step-size double") ; print_line(" inital step size [default 1.02]" ); print_line("--use-slab-identification [yes|no]") ; print_line(" if yes, the bias correction will first identify slabs,") ; print_line(" and then apply the bias correction to each slab") ; print_line("--slice-direction [0-2]" ) ; print_line(" slice creation direction ( 0 - x axis, 1 - y axis") ; print_line(" 2 - z axis) [default 2]") ; print_line(""); print_line("example: BiasCorrector --input sample.mhd") ; print_line(" --output sample.corrected.mhd") ; print_line(" --class-mean 1500 570") ; print_line(" --class-sigma 100 70 --use-log yes"); print_line(" --input-mask sample.mask.mhd ") ; print_line(" --output-mask sample.mask2.mhd ") ; print_line(" --degree 3 --growth 1.05 --shrink 0.9"); print_line(" --max-iteration 2000 --init-step-size 1.1") ; print_line(" --use-slab-identification no") ; print_line(" --slice-direction 2") ; } int main(int argc, char* argv[]) { if (argc <= 1) { print_usage() ; exit(0) ; } OptionList options(argc, argv) ; typedef itk::MRIBiasFieldCorrectionFilter<ImageType, ImageType> Corrector ; Corrector::Pointer filter = Corrector::New() ; std::string inputFileName ; std::string outputFileName ; std::string inputMaskFileName = "" ; std::string outputMaskFileName = "" ; bool useLog ; int degree ; int sliceDirection ; vnl_vector<double> coefficientVector ; itk::Array<double> classMeans ; itk::Array<double> classSigmas ; int maximumIteration ; double initialRadius ; double growth ; double shrink ; bool usingSlabIdentification ; try { // get image file options options.GetStringOption("input", &inputFileName, true) ; options.GetStringOption("output", &outputFileName, true) ; options.GetStringOption("input-mask", &inputMaskFileName, false) ; options.GetStringOption("output-mask", &outputMaskFileName, false) ; // get bias field options useLog = options.GetBooleanOption("use-log", true, true) ; degree = options.GetIntOption("degree", 3, false) ; sliceDirection = options.GetIntOption("slice-direction", 2, false) ; // get energyfunction options options.GetMultiDoubleOption("class-mean", &classMeans, true) ; options.GetMultiDoubleOption("class-sigma", &classSigmas, true) ; // get optimizer options maximumIteration = options.GetIntOption("max-iteration", 20, false) ; growth = options.GetDoubleOption("growth", 1.05, false) ; shrink = pow(growth, -0.25) ; shrink = options.GetDoubleOption("shrink", shrink, false) ; initialRadius = options.GetDoubleOption("init-step-size", 1.02, false) ; // get the filter operation option usingSlabIdentification = options.GetBooleanOption("use-slab-identification", false, false) ; } catch(OptionList::RequiredOptionMissing e) { std::cout << "Error: The '" << e.OptionTag << "' option is required but missing." << std::endl ; } // load images ImagePointer input = ImageType::New() ; MaskPointer inputMask = MaskType::New() ; MaskPointer outputMask = MaskType::New() ; try { std::cout << "Loading images..." << std::endl ; loadImage(inputFileName, input) ; filter->SetInput(input) ; std::cout << "Input image loaded." << std::endl ; if (inputMaskFileName != "") { loadMask(inputMaskFileName, inputMask) ; filter->SetInputMask(inputMask) ; std::cout << "Input mask image loaded." << std::endl ; } if (outputMaskFileName != "") { loadMask(outputMaskFileName, outputMask) ; filter->SetOutputMask(outputMask) ; std::cout << "Output mask image loaded." << std::endl ; } std::cout << "Images loaded." << std::endl ; } catch (ImageIOError e) { std::cout << "Error: " << e.Operation << " file name:" << e.FileName << std::endl ; exit(0) ; } ImagePointer output = ImageType::New() ; output->SetLargestPossibleRegion(input->GetLargestPossibleRegion()) ; output->SetRequestedRegion(input->GetLargestPossibleRegion()) ; filter->SetOutput(output) ; filter->IsBiasFieldMultiplicative(useLog) ; filter->SetTissueClassStatistics(classMeans, classSigmas) ; filter->SetOptimizerGrowthFactor(growth) ; filter->SetOptimizerShrinkFactor(shrink) ; filter->SetOptimizerMaximumIteration(maximumIteration) ; filter->SetOptimizerInitialRadius(initialRadius) ; filter->SetBiasFieldDegree(degree) ; filter->SetUsingSlabIdentification(usingSlabIdentification) ; filter->SetSlicingDirection(sliceDirection) ; filter->Update() ; std::cout << "Writing the output image..." << std::endl ; try { writeImage(outputFileName, output) ; } catch (ImageIOError e) { std::cout << "Error: " << e.Operation << " file name:" << e.FileName << std::endl ; exit(0) ; } return 0 ; } <commit_msg>ERR: warnings about possible uninitialized variables.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: BiasCorrector.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <string> #include <vector> #include <vnl/vnl_math.h> #include "mydefs.h" #include "imageutils.h" #include "OptionList.h" #include "itkMRIBiasFieldCorrectionFilter.h" void print_usage() { print_line("MRIBiasCorrection 1.0 (21.June.2001)"); print_line("usage: BiasCorrector --input file" ) ; print_line(" --output file") ; print_line(" --class-mean mean(1) ... mean(i)" ) ; print_line(" --class-sigma sigma(1) ... sigma(i)" ) ; print_line(" --use-log [yes|no]") ; print_line(" [--input-mask file]" ) ; print_line(" [--output-mask file]" ) ; print_line(" [--degree int] ") ; print_line(" [--growth double] [--shrink double] [--max-iteration int]"); print_line(" [--init-step-size double] "); print_line(" [--use-slab-identification [yes|no]]") ; print_line(" [--slice-direction [0-2]]" ) ; print_line(""); print_line("--input file") ; print_line(" input image file name [meta image format]" ); print_line("--output file") ; print_line(" output image file name [meta image format]" ); print_line("--class-mean mean(1),...,mean(i)" ) ; print_line(" intensity means of the differen i tissue classes") ; print_line("--class-sigma sig(1),...,sig(i)" ) ; print_line(" intensity sigmas of the different i tissue clases") ; print_line(" NOTE: The sigmas should be listed in the SAME ORDER") ; print_line(" of means"); print_line(" and each value should be SEPERATED BY A SPACE)") ; print_line("--input-mask file" ) ; print_line(" mask input with file [meta image format]"); print_line("--output-mask file" ) ; print_line(" mask output with file [meta image format]"); print_line("--degree int") ; print_line(" degree of legendre polynomial used for the") ; print_line(" approximation of the bias field" ); print_line("--use-log [yes|no]") ; print_line(" if yes, assume a multiplicative bias field") ; print_line(" (use log of image, class-mean, class-sigma,") ; print_line(" and init-step-size)" ); print_line("--growth double") ; print_line(" stepsize growth factor. must be greater than 1.0") ; print_line(" [default 1.05]" ) ; print_line("--shrink double") ; print_line(" stepsize shrink factor ") ; print_line(" [default growth^(-0.25)]" ) ; print_line("--max-iteration int") ; print_line(" maximal number of iterations") ; print_line(" [default 20]" ) ; print_line("--init-step-size double") ; print_line(" inital step size [default 1.02]" ); print_line("--use-slab-identification [yes|no]") ; print_line(" if yes, the bias correction will first identify slabs,") ; print_line(" and then apply the bias correction to each slab") ; print_line("--slice-direction [0-2]" ) ; print_line(" slice creation direction ( 0 - x axis, 1 - y axis") ; print_line(" 2 - z axis) [default 2]") ; print_line(""); print_line("example: BiasCorrector --input sample.mhd") ; print_line(" --output sample.corrected.mhd") ; print_line(" --class-mean 1500 570") ; print_line(" --class-sigma 100 70 --use-log yes"); print_line(" --input-mask sample.mask.mhd ") ; print_line(" --output-mask sample.mask2.mhd ") ; print_line(" --degree 3 --growth 1.05 --shrink 0.9"); print_line(" --max-iteration 2000 --init-step-size 1.1") ; print_line(" --use-slab-identification no") ; print_line(" --slice-direction 2") ; } int main(int argc, char* argv[]) { if (argc <= 1) { print_usage() ; exit(0) ; } OptionList options(argc, argv) ; typedef itk::MRIBiasFieldCorrectionFilter<ImageType, ImageType> Corrector ; Corrector::Pointer filter = Corrector::New() ; std::string inputFileName ; std::string outputFileName ; std::string inputMaskFileName = "" ; std::string outputMaskFileName = "" ; bool useLog = true; int degree = 3; int sliceDirection = 2; vnl_vector<double> coefficientVector ; itk::Array<double> classMeans ; itk::Array<double> classSigmas ; int maximumIteration = 20; double initialRadius ; double growth = 1.05; double shrink = 0.0; bool usingSlabIdentification = false; try { // get image file options options.GetStringOption("input", &inputFileName, true) ; options.GetStringOption("output", &outputFileName, true) ; options.GetStringOption("input-mask", &inputMaskFileName, false) ; options.GetStringOption("output-mask", &outputMaskFileName, false) ; // get bias field options useLog = options.GetBooleanOption("use-log", true, true) ; degree = options.GetIntOption("degree", 3, false) ; sliceDirection = options.GetIntOption("slice-direction", 2, false) ; // get energyfunction options options.GetMultiDoubleOption("class-mean", &classMeans, true) ; options.GetMultiDoubleOption("class-sigma", &classSigmas, true) ; // get optimizer options maximumIteration = options.GetIntOption("max-iteration", 20, false) ; growth = options.GetDoubleOption("growth", 1.05, false) ; shrink = pow(growth, -0.25) ; shrink = options.GetDoubleOption("shrink", shrink, false) ; initialRadius = options.GetDoubleOption("init-step-size", 1.02, false) ; // get the filter operation option usingSlabIdentification = options.GetBooleanOption("use-slab-identification", false, false) ; } catch(OptionList::RequiredOptionMissing e) { std::cout << "Error: The '" << e.OptionTag << "' option is required but missing." << std::endl ; } // load images ImagePointer input = ImageType::New() ; MaskPointer inputMask = MaskType::New() ; MaskPointer outputMask = MaskType::New() ; try { std::cout << "Loading images..." << std::endl ; loadImage(inputFileName, input) ; filter->SetInput(input) ; std::cout << "Input image loaded." << std::endl ; if (inputMaskFileName != "") { loadMask(inputMaskFileName, inputMask) ; filter->SetInputMask(inputMask) ; std::cout << "Input mask image loaded." << std::endl ; } if (outputMaskFileName != "") { loadMask(outputMaskFileName, outputMask) ; filter->SetOutputMask(outputMask) ; std::cout << "Output mask image loaded." << std::endl ; } std::cout << "Images loaded." << std::endl ; } catch (ImageIOError e) { std::cout << "Error: " << e.Operation << " file name:" << e.FileName << std::endl ; exit(0) ; } ImagePointer output = ImageType::New() ; output->SetLargestPossibleRegion(input->GetLargestPossibleRegion()) ; output->SetRequestedRegion(input->GetLargestPossibleRegion()) ; filter->SetOutput(output) ; filter->IsBiasFieldMultiplicative(useLog) ; filter->SetTissueClassStatistics(classMeans, classSigmas) ; filter->SetOptimizerGrowthFactor(growth) ; filter->SetOptimizerShrinkFactor(shrink) ; filter->SetOptimizerMaximumIteration(maximumIteration) ; filter->SetOptimizerInitialRadius(initialRadius) ; filter->SetBiasFieldDegree(degree) ; filter->SetUsingSlabIdentification(usingSlabIdentification) ; filter->SetSlicingDirection(sliceDirection) ; filter->Update() ; std::cout << "Writing the output image..." << std::endl ; try { writeImage(outputFileName, output) ; } catch (ImageIOError e) { std::cout << "Error: " << e.Operation << " file name:" << e.FileName << std::endl ; exit(0) ; } return 0 ; } <|endoftext|>
<commit_before>/* * (c) 2015 Raghavendra Nayak, All Rights Reserved. * www.openguru.com/ */ #include <iostream> #include <string> // Window is the abstract base for all concrete Window implementations class Window { public: Window() { } virtual ~Window() { } virtual void draw() = 0; }; // MainWindow is a type of Window class MainWindow : public Window { int height; int width; std::string windowName; public: MainWindow(const std::string& name, int height, int width) : height(height), width(width), windowName(name) { } ~MainWindow() { } std::string name() { return windowName; } virtual void draw() { std::cout << "Rendering the MainWindow: " << name() << " with height: " << height << ", width: " << width << std::endl; } }; // SimpleWindow does not have any name class SimpleWindow : public Window { int height; int width; public: SimpleWindow(int height, int width) : height(height), width(width) { } ~SimpleWindow() { } virtual void draw() { std::cout << "Rendering the SimpleWindow: " << " with height: " << height << ", width: " << width << std::endl; } }; // Below class is a decorator or wrapper class WindowDecorator : public Window { // Here we store the reference Window& decoratedWindow; public: // Constructor WindowDecorator(Window& window) : decoratedWindow(window) { } virtual ~WindowDecorator() { } // Call our wrapper object's function virtual void draw() { decoratedWindow.draw(); } }; class MenubarDecorator : public WindowDecorator { void drawMenuBar() { std::cout << "Drawing the Menu bar. " << std::endl; } public: MenubarDecorator(Window& decoratedWindow) : WindowDecorator(decoratedWindow) { } ~MenubarDecorator() { } virtual void draw() { // Draw Wrapped Window first as it is in the background WindowDecorator::draw(); // Now draw the actual menu bar drawMenuBar(); } }; class StatusbarDecorator : public WindowDecorator { void drawStatusbar() { std::cout << "Drawing the Status bar." << std::endl; } public: StatusbarDecorator(Window& decoratedWindow) : WindowDecorator(decoratedWindow) { } ~StatusbarDecorator() { } virtual void draw() { // Draw Wrapped Window first as it is in the background WindowDecorator::draw(); // Now draw the actual menu bar drawStatusbar(); } }; int main(int argc, char **argv) { // Draw a MainWindow MainWindow mainWindow("simple window", 1024, 768); mainWindow.draw(); // Now for the same MainWindow we can add the menubar // via MenubarDecorator MenubarDecorator windowWithMenubar(mainWindow); windowWithMenubar.draw(); // Now we can add Statusbar via StatusbarDecorator StatusbarDecorator windowWithMenubarAndStatusBar(windowWithMenubar); windowWithMenubarAndStatusBar.draw(); // Draw a simpleWindow SimpleWindow simpleWindow(1024, 768); simpleWindow.draw(); // Now lets decorate SimpleWindow with Menubar MenubarDecorator simpleWindowWithMenubar(simpleWindow); simpleWindowWithMenubar.draw(); return 0; }<commit_msg>Modified to improve the clarity.<commit_after>/* * (c) 2015 Raghavendra Nayak, All Rights Reserved. * www.openguru.com/ */ #include <iostream> #include <string> // Window is the abstract base for all concrete Window implementations class Window { std::string windowName; public: Window(const std::string& windowName) : windowName(windowName) { } Window() { } virtual ~Window() { } virtual std::string name() { return windowName; } virtual void draw() = 0; }; // MainWindow is a type of Window class MainWindow : public Window { int height; int width; public: MainWindow(const std::string& windowName, int height, int width) : Window(windowName), height(height), width(width) { } ~MainWindow() { } virtual void draw() { std::cout << "Rendering the MainWindow: [" << name() << "] with height: " << height << ", width: " << width << std::endl; } }; // SquareWindow have same height & width class SquareWindow : public Window { int dimension; public: SquareWindow(const std::string& windowName, int dimension) : Window(windowName), dimension(dimension) { } ~SquareWindow() { } virtual void draw() { std::cout << "Rendering the SquareWindow: [" << name() << "] with dimensions: " << dimension << std::endl; } }; // Below class is a decorator or wrapper class WindowDecorator : public Window { // Here we store the reference Window& decoratedWindow; public: // Constructor WindowDecorator(Window& window) : decoratedWindow(window) { } virtual ~WindowDecorator() { } // Call our wrapper object's function virtual std::string name() { return decoratedWindow.name(); } // Call our wrapper object's function virtual void draw() { decoratedWindow.draw(); } }; class MenubarDecorator : public WindowDecorator { void drawMenuBar() { std::cout << "Drawing the Menu bar for [" << WindowDecorator::name() << "]" << std::endl; } public: MenubarDecorator(Window& decoratedWindow) : WindowDecorator(decoratedWindow) { } ~MenubarDecorator() { } virtual std::string name() { return WindowDecorator::name(); } virtual void draw() { // Draw Wrapped Window first as it is in the background WindowDecorator::draw(); // Now draw the actual menu bar drawMenuBar(); } }; class StatusbarDecorator : public WindowDecorator { void drawStatusbar() { std::cout << "Drawing the Status bar for [" << WindowDecorator::name() << "]" << std::endl; } public: StatusbarDecorator(Window& decoratedWindow) : WindowDecorator(decoratedWindow) { } ~StatusbarDecorator() { } virtual std::string name() { return WindowDecorator::name(); } virtual void draw() { // Draw Wrapped Window first as it is in the background WindowDecorator::draw(); // Now draw the actual menu bar drawStatusbar(); } }; int main(int argc, char **argv) { // Draw a MainWindow MainWindow mainWindow("Main window", 1024, 768); mainWindow.draw(); // Now for the same MainWindow we can add the menubar // via MenubarDecorator MenubarDecorator windowWithMenubar(mainWindow); windowWithMenubar.draw(); // Now we can add Statusbar via StatusbarDecorator StatusbarDecorator windowWithMenubarAndStatusBar(windowWithMenubar); windowWithMenubarAndStatusBar.draw(); // Draw a squareWindow SquareWindow squareWindow("Square Window", 1024); squareWindow.draw(); // Now lets decorate SquareWindow with Menubar MenubarDecorator squareWindowWithMenubar(squareWindow); squareWindowWithMenubar.draw(); return 0; }<|endoftext|>
<commit_before>// Copyright (c) 2020 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_UTILS_CONCURRENT_PERIODIC_TASK_HPP #define IOX_UTILS_CONCURRENT_PERIODIC_TASK_HPP #include "iceoryx_utils/cxx/string.hpp" #include "iceoryx_utils/internal/units/duration.hpp" #include "iceoryx_utils/posix_wrapper/semaphore.hpp" #include "iceoryx_utils/posix_wrapper/thread.hpp" #include <thread> namespace iox { namespace concurrent { /// @brief This class periodically executes a callable specified by the template parameter. /// This can be a struct with a `operator()()` overload, a `cxx::function_ref<void()>` or `std::fuction<void()>` /// @tparam T is a callable type without function parameters template <typename T> class PeriodicTask { public: /// @brief Creates a periodic task. The specified callable is stored but not executed. /// To run the task, `void start(const units::Duration interval)` must be called. /// @tparam Args are variadic template parameter for which are forwarded to the underlying callable object /// @param[in] taskName will be set as thread name /// @param[in] args are forwarded to the underlying callable object template <typename... Args> PeriodicTask(const posix::ThreadName_t taskName, Args&&... args) noexcept; /// @brief Creates a periodic task by spawning a thread. The specified callable is executed immediately on creation /// and then periodically after the interval duration. /// @tparam Args are variadic template parameter for which are forwarded to the underlying callable object /// @param[in] interval is the time the thread waits between two invocations of the callable /// @param[in] taskName will be set as thread name /// @param[in] args are forwarded to the underlying callable object template <typename... Args> PeriodicTask(const units::Duration interval, const posix::ThreadName_t taskName, Args&&... args) noexcept; /// @brief Stops and joins the thread spawned by the constructor. /// @note This is blocking and the blocking time depends on the callable. ~PeriodicTask() noexcept; PeriodicTask(const PeriodicTask&) = delete; PeriodicTask(PeriodicTask&&) = delete; PeriodicTask& operator=(const PeriodicTask&) = delete; PeriodicTask& operator=(PeriodicTask&&) = delete; /// @brief Spawns a thread and immediately executes the callable specified with the constructor. /// The execution is repeated after the specified interval is passed. /// @param[in] interval is the time the thread waits between two invocations of the callable /// @attention If the PeriodicTask instance has already a running thread, this will be stopped and started again /// with the new interval. This might take some time if a slow task is executing during this call. void start(const units::Duration interval) noexcept; /// @brief This stops the thread if it's running, otherwise does nothing. When this method returns, the thread is /// stopped. /// @attention This might take some time if a slow task is executing during this call. void stop() noexcept; /// @brief This method check if a thread is spawned and running, potentially executing a task. /// @return true if the thread is running, false otherwise. bool isActive() const noexcept; private: void run() noexcept; private: T m_callable; posix::ThreadName_t m_taskName; units::Duration m_interval{units::Duration::milliseconds<long double>(0.0)}; /// @todo use a refactored posix::Timer object once available posix::Semaphore m_stop{posix::Semaphore::create(posix::CreateUnnamedSingleProcessSemaphore, 0U).value()}; std::thread m_taskExecutor; }; } // namespace concurrent } // namespace iox #include "iceoryx_utils/internal/concurrent/periodic_task.inl" #endif // IOX_UTILS_CONCURRENT_PERIODIC_TASK_HPP <commit_msg>iox-#489 Update PeriodicTask documentation<commit_after>// Copyright (c) 2020 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_UTILS_CONCURRENT_PERIODIC_TASK_HPP #define IOX_UTILS_CONCURRENT_PERIODIC_TASK_HPP #include "iceoryx_utils/cxx/string.hpp" #include "iceoryx_utils/internal/units/duration.hpp" #include "iceoryx_utils/posix_wrapper/semaphore.hpp" #include "iceoryx_utils/posix_wrapper/thread.hpp" #include <thread> namespace iox { namespace concurrent { /// @brief This class periodically executes a callable specified by the template parameter. /// This can be a struct with a `operator()()` overload, a `cxx::function_ref<void()>` or `std::fuction<void()>`. /// @note Currently execution time of the callable is added to the interval. /// @tparam T is a callable type without function parameters template <typename T> class PeriodicTask { public: /// @brief Creates a periodic task. The specified callable is stored but not executed. /// To run the task, `void start(const units::Duration interval)` must be called. /// @tparam Args are variadic template parameter for which are forwarded to the underlying callable object /// @param[in] taskName will be set as thread name /// @param[in] args are forwarded to the underlying callable object template <typename... Args> PeriodicTask(const posix::ThreadName_t taskName, Args&&... args) noexcept; /// @brief Creates a periodic task by spawning a thread. The specified callable is executed immediately on creation /// and then periodically after the interval duration. /// @tparam Args are variadic template parameter for which are forwarded to the underlying callable object /// @param[in] interval is the time the thread waits between two invocations of the callable /// @param[in] taskName will be set as thread name /// @param[in] args are forwarded to the underlying callable object template <typename... Args> PeriodicTask(const units::Duration interval, const posix::ThreadName_t taskName, Args&&... args) noexcept; /// @brief Stops and joins the thread spawned by the constructor. /// @note This is blocking and the blocking time depends on the callable. ~PeriodicTask() noexcept; PeriodicTask(const PeriodicTask&) = delete; PeriodicTask(PeriodicTask&&) = delete; PeriodicTask& operator=(const PeriodicTask&) = delete; PeriodicTask& operator=(PeriodicTask&&) = delete; /// @brief Spawns a thread and immediately executes the callable specified with the constructor. /// The execution is repeated after the specified interval is passed. /// @param[in] interval is the time the thread waits between two invocations of the callable /// @attention If the PeriodicTask instance has already a running thread, this will be stopped and started again /// with the new interval. This might take some time if a slow task is executing during this call. void start(const units::Duration interval) noexcept; /// @brief This stops the thread if it's running, otherwise does nothing. When this method returns, the thread is /// stopped. /// @attention This might take some time if a slow task is executing during this call. void stop() noexcept; /// @brief This method check if a thread is spawned and running, potentially executing a task. /// @return true if the thread is running, false otherwise. bool isActive() const noexcept; private: void run() noexcept; private: T m_callable; posix::ThreadName_t m_taskName; units::Duration m_interval{units::Duration::milliseconds<long double>(0.0)}; /// @todo use a refactored posix::Timer object once available posix::Semaphore m_stop{posix::Semaphore::create(posix::CreateUnnamedSingleProcessSemaphore, 0U).value()}; std::thread m_taskExecutor; }; } // namespace concurrent } // namespace iox #include "iceoryx_utils/internal/concurrent/periodic_task.inl" #endif // IOX_UTILS_CONCURRENT_PERIODIC_TASK_HPP <|endoftext|>
<commit_before><commit_msg>Displaying results.<commit_after><|endoftext|>
<commit_before>#include "stdafx.h" #include <graphics/dynamictexture.h> #include "fogrenderer.h" #include <temple/dll.h> #include <common.h> using namespace gfx; #pragma pack(push, 1) struct FogOfWarVertex { XMFLOAT3 pos; XMFLOAT2 uv; }; #pragma pack(pop) FogOfWarRenderer::FogOfWarRenderer(MdfMaterialFactory& mdfFactory, RenderingDevice& device) : mMdfFactory(mdfFactory), mDevice(device), mNumSubtilesX(temple::GetRef<uint32_t>(0x10820458)), mNumSubtilesY(temple::GetRef<uint32_t>(0x10824490)) { mBlurredFogWidth = (mNumSubtilesX / 32) * 32 + 32; // Has to be a multiple of 4 mBlurredFogHeight = (mNumSubtilesY / 32) * 32 + 32; mBlurredFogTexture = mDevice.CreateDynamicTexture(D3DFMT_A8, mBlurredFogWidth, mBlurredFogHeight); mBlurredFog.resize(mBlurredFogWidth * mBlurredFogHeight); auto vs = device.GetShaders().LoadVertexShader("fogofwar_vs"); auto ps = device.GetShaders().LoadPixelShader("fogofwar_ps"); BlendState blendState; blendState.blendEnable = true; blendState.srcBlend = D3DBLEND_SRCALPHA; blendState.destBlend = D3DBLEND_INVSRCALPHA; DepthStencilState depthStencilState; depthStencilState.depthEnable = false; RasterizerState rasterizerState; // rasterizerState.cullMode = D3DCULL_NONE; SamplerState samplerState; samplerState.addressU = D3DTADDRESS_CLAMP; samplerState.addressV = D3DTADDRESS_CLAMP; std::vector<MaterialSamplerBinding> samplers{ MaterialSamplerBinding(mBlurredFogTexture, samplerState) }; mMaterial = std::make_unique<Material>(blendState, depthStencilState, rasterizerState, samplers, vs, ps); uint16_t indices[6] { 0, 2, 1, 2, 0, 3 }; mIndexBuffer = device.CreateIndexBuffer(indices); mVertexBuffer = device.CreateEmptyVertexBuffer(sizeof(FogOfWarVertex) * 4); mBufferBinding.AddBuffer(mVertexBuffer, 0, sizeof(FogOfWarVertex)) .AddElement(VertexElementType::Float3, VertexElementSemantic::Position) .AddElement(VertexElementType::Float2, VertexElementSemantic::TexCoord); } struct FogBlurKernel { // 4 kernels (shifted by 0,1,2,3 pixels right), each has // 5 rows with 8 columns (for shift-compensation) uint8_t patterns[4][5][8]; // [xShift][y][x] FogBlurKernel() { memset(patterns, 0, sizeof(patterns)); } static FogBlurKernel Create(uint8_t totalPatternValue); }; void FogOfWarRenderer::Render() { static auto& sFoggingEnabled = temple::GetRef<uint32_t>(0x108254A0); if (!(sFoggingEnabled & 1)) { return; } // Reset the blurred buffer std::fill(mBlurredFog.begin(), mBlurredFog.end(), 0); static auto sOpaquePattern = FogBlurKernel::Create(0xFF); static auto sHalfTransparentPattern = FogBlurKernel::Create(0xA0); static auto& fogCheckData = temple::GetRef<uint8_t*>(0x108A5498); // Get [1,1] of the subtile data auto fogCheckSubtile = &fogCheckData[mNumSubtilesX + 1]; for (size_t y = 1; y < mNumSubtilesY - 1; y++) { for (size_t x = 1; x < mNumSubtilesX - 1; x++) { auto fogState = *fogCheckSubtile; // Bit 2 -> Currently in LoS of the party if (!(fogState & 2)) { uint8_t* patternSrc; // Bit 3 -> Explored if (fogState & 4) { patternSrc = &sHalfTransparentPattern.patterns[x & 3][0][0]; } else { patternSrc = &sOpaquePattern.patterns[x & 3][0][0]; } // Now we copy 5 rows of 2 dwords each, to apply // the filter-kernel to the blurred fog map for (auto row = 0; row < 5; ++row) { auto src = (uint64_t*) &patternSrc[row * 8]; auto roundedDownX = (x / 4) * 4; auto dest = (uint64_t*) &mBlurredFog[(y + row) * mBlurredFogWidth + roundedDownX]; // Due to how the kernel is layed out, the individual bytes in this 8-byte addition will never carry // over to the next higher byte, thus this is equivalent to 8 separate 1-byte additions *dest += *src; } } ++fogCheckSubtile; } // Skips the last subtile of the row and the first of the next row fogCheckSubtile += 2; } static auto& fogMinX = temple::GetRef<uint64_t>(0x10824468); static auto& fogMinY = temple::GetRef<uint64_t>(0x108EC4C8); auto mFogOriginX = (uint32_t) fogMinX; auto mFogOriginY = (uint32_t) fogMinY; mBlurredFogTexture->Update<uint8_t>({&mBlurredFog[0], mBlurredFog.size()}); FogOfWarVertex mVertices[4]; mVertices[0].pos.x = (mFogOriginX * 3) * INCH_PER_SUBTILE; mVertices[0].pos.y = 0; mVertices[0].pos.z = (mFogOriginY * 3) * INCH_PER_SUBTILE; mVertices[0].uv = {0, 0}; mVertices[1].pos.x = (mFogOriginX * 3 + mBlurredFogWidth) * INCH_PER_SUBTILE; mVertices[1].pos.y = 0; mVertices[1].pos.z = (mFogOriginY * 3) * INCH_PER_SUBTILE; mVertices[1].uv = {1, 0}; mVertices[2].pos.x = (mFogOriginX * 3 + mBlurredFogWidth) * INCH_PER_SUBTILE; mVertices[2].pos.y = 0; mVertices[2].pos.z = (mFogOriginY * 3 + mBlurredFogHeight) * INCH_PER_SUBTILE; mVertices[2].uv = {1, 1}; mVertices[3].pos.x = (mFogOriginX * 3) * INCH_PER_SUBTILE; mVertices[3].pos.y = 0; mVertices[3].pos.z = (mFogOriginY * 3 + mBlurredFogHeight) * INCH_PER_SUBTILE; mVertices[3].uv = {0, 1}; mVertexBuffer->Update<FogOfWarVertex>(mVertices); mBufferBinding.Bind(); mDevice.GetDevice()->SetIndices(mIndexBuffer->GetBuffer()); mDevice.SetMaterial(*mMaterial); mDevice.SetVertexShaderConstant(0, StandardSlotSemantic::ViewProjMatrix); mDevice.GetDevice()->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 4, 0, 2); } FogBlurKernel FogBlurKernel::Create(uint8_t totalPatternValue) { FogBlurKernel result; // Precompute 5x5 inverted blur kernel for distributing the total pattern value float weights[5][5]; auto weightSum = 0.0f; auto weightOut = &weights[0][0]; for (auto y = -2; y <= 2; y++) { for (auto x = -2; x <= 2; x++) { auto strength = 3.0f - sqrtf((float)(x * x + y * y)); *weightOut++ = strength; weightSum += strength; } } // Now use the computed weights to calculate the actual pattern based on the requested total value auto patternSum = 0; for (auto y = 0; y < 5; ++y) { for (auto x = 0; x < 5; ++x) { auto pixelValue = (uint8_t)(weights[y][x] / weightSum * totalPatternValue); result.patterns[0][y][x] = pixelValue; patternSum += pixelValue; } } // This assigns any remainder of the total pattern value (loss due to rounding down above) // to the center pixel of the 5x5 kernel result.patterns[0][2][2] += totalPatternValue - patternSum; // Now create 3 versions of the pattern that are shifted by 1-3 pixels to the right // This is for optimization reasons since addition is done using 32-bit (4 bytes) addition // and the resulting patterns are in reality 8 pixels wide for (auto xShift = 1; xShift <= 3; ++xShift) { for (auto y = 0; y < 5; ++y) { for (auto x = 0; x < 5; ++x) { // Output here is shifted by {1,2,3} pixels right result.patterns[xShift][y][x + xShift] = result.patterns[0][y][x]; } } } return result; } <commit_msg>Possible fix for flashing unexplored tiles when rendering fog.<commit_after>#include "stdafx.h" #include <graphics/dynamictexture.h> #include "fogrenderer.h" #include <temple/dll.h> #include <common.h> using namespace gfx; #pragma pack(push, 1) struct FogOfWarVertex { XMFLOAT3 pos; XMFLOAT2 uv; }; #pragma pack(pop) FogOfWarRenderer::FogOfWarRenderer(MdfMaterialFactory& mdfFactory, RenderingDevice& device) : mMdfFactory(mdfFactory), mDevice(device), mNumSubtilesX(temple::GetRef<uint32_t>(0x10820458)), mNumSubtilesY(temple::GetRef<uint32_t>(0x10824490)) { mBlurredFogWidth = (mNumSubtilesX / 4) * 4 + 8; mBlurredFogHeight = (mNumSubtilesY / 4) * 4 + 8; mBlurredFogTexture = mDevice.CreateDynamicTexture(D3DFMT_A8, mBlurredFogWidth, mBlurredFogHeight); mBlurredFog.resize(mBlurredFogWidth * mBlurredFogHeight); auto vs = device.GetShaders().LoadVertexShader("fogofwar_vs"); auto ps = device.GetShaders().LoadPixelShader("fogofwar_ps"); BlendState blendState; blendState.blendEnable = true; blendState.srcBlend = D3DBLEND_SRCALPHA; blendState.destBlend = D3DBLEND_INVSRCALPHA; DepthStencilState depthStencilState; depthStencilState.depthEnable = false; RasterizerState rasterizerState; SamplerState samplerState; samplerState.addressU = D3DTADDRESS_CLAMP; samplerState.addressV = D3DTADDRESS_CLAMP; samplerState.magFilter = D3DTEXF_LINEAR; samplerState.minFilter = D3DTEXF_LINEAR; std::vector<MaterialSamplerBinding> samplers{ MaterialSamplerBinding(mBlurredFogTexture, samplerState) }; mMaterial = std::make_unique<Material>(blendState, depthStencilState, rasterizerState, samplers, vs, ps); uint16_t indices[6]{0, 2, 1, 2, 0, 3}; mIndexBuffer = device.CreateIndexBuffer(indices); mVertexBuffer = device.CreateEmptyVertexBuffer(sizeof(FogOfWarVertex) * 4); mBufferBinding.AddBuffer(mVertexBuffer, 0, sizeof(FogOfWarVertex)) .AddElement(VertexElementType::Float3, VertexElementSemantic::Position) .AddElement(VertexElementType::Float2, VertexElementSemantic::TexCoord); } struct FogBlurKernel { // 4 kernels (shifted by 0,1,2,3 pixels right), each has // 5 rows with 8 columns (for shift-compensation) uint8_t patterns[4][5][8]; // [xShift][y][x] FogBlurKernel() { memset(patterns, 0, sizeof(patterns)); } static FogBlurKernel Create(uint8_t totalPatternValue); }; void FogOfWarRenderer::Render() { static auto& sFoggingEnabled = temple::GetRef<uint32_t>(0x108254A0); if (!(sFoggingEnabled & 1)) { return; } // Reset the blurred buffer std::fill(mBlurredFog.begin(), mBlurredFog.end(), 0); static auto sOpaquePattern = FogBlurKernel::Create(0xFF); static auto sHalfTransparentPattern = FogBlurKernel::Create(0xA0); static auto& fogCheckData = temple::GetRef<uint8_t*>(0x108A5498); // Get [0,0] of the subtile data auto fogCheckSubtile = &fogCheckData[0]; for (size_t y = 0; y < mNumSubtilesY; y++) { for (size_t x = 0; x < mNumSubtilesX; x++) { auto fogState = *fogCheckSubtile; // Bit 2 -> Currently in LoS of the party if (!(fogState & 2)) { uint8_t* patternSrc; // Bit 3 -> Explored if (fogState & 4) { patternSrc = &sHalfTransparentPattern.patterns[x & 3][0][0]; } else { patternSrc = &sOpaquePattern.patterns[x & 3][0][0]; } // Now we copy 5 rows of 2 dwords each, to apply // the filter-kernel to the blurred fog map for (auto row = 0; row < 5; ++row) { auto src = (uint64_t*) &patternSrc[row * 8]; auto roundedDownX = (x / 4) * 4; auto dest = (uint64_t*) &mBlurredFog[(y + row) * mBlurredFogWidth + roundedDownX]; // Due to how the kernel is layed out, the individual bytes in this 8-byte addition will never carry // over to the next higher byte, thus this is equivalent to 8 separate 1-byte additions *dest += *src; } } ++fogCheckSubtile; } // Skips the last subtile of the row and the first of the next row // fogCheckSubtile += 2; } static auto& fogMinX = temple::GetRef<uint64_t>(0x10824468); static auto& fogMinY = temple::GetRef<uint64_t>(0x108EC4C8); auto mFogOriginX = (uint32_t) fogMinX; auto mFogOriginY = (uint32_t) fogMinY; mBlurredFogTexture->Update<uint8_t>({&mBlurredFog[0], mBlurredFog.size()}); // Use only the relevant subportion of the texture auto umin = 2.5f / (float)mBlurredFogWidth; auto vmin = 2.5f / (float)mBlurredFogHeight; auto umax = mNumSubtilesX / (float)mBlurredFogWidth; auto vmax = mNumSubtilesY / (float)mBlurredFogHeight; FogOfWarVertex mVertices[4]; mVertices[0].pos.x = (mFogOriginX * 3) * INCH_PER_SUBTILE; mVertices[0].pos.y = 0; mVertices[0].pos.z = (mFogOriginY * 3) * INCH_PER_SUBTILE; mVertices[0].uv = {umin, vmin}; mVertices[1].pos.x = (mFogOriginX * 3 + mNumSubtilesX) * INCH_PER_SUBTILE; mVertices[1].pos.y = 0; mVertices[1].pos.z = (mFogOriginY * 3) * INCH_PER_SUBTILE; mVertices[1].uv = {umax, vmin}; mVertices[2].pos.x = (mFogOriginX * 3 + mNumSubtilesX) * INCH_PER_SUBTILE; mVertices[2].pos.y = 0; mVertices[2].pos.z = (mFogOriginY * 3 + mNumSubtilesY) * INCH_PER_SUBTILE; mVertices[2].uv = {umax, vmax}; mVertices[3].pos.x = (mFogOriginX * 3) * INCH_PER_SUBTILE; mVertices[3].pos.y = 0; mVertices[3].pos.z = (mFogOriginY * 3 + mNumSubtilesY) * INCH_PER_SUBTILE; mVertices[3].uv = {umin, vmax}; mVertexBuffer->Update<FogOfWarVertex>(mVertices); mBufferBinding.Bind(); mDevice.GetDevice()->SetIndices(mIndexBuffer->GetBuffer()); mDevice.SetMaterial(*mMaterial); mDevice.SetVertexShaderConstant(0, StandardSlotSemantic::ViewProjMatrix); mDevice.GetDevice()->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 4, 0, 2); } FogBlurKernel FogBlurKernel::Create(uint8_t totalPatternValue) { FogBlurKernel result; // Precompute 5x5 inverted blur kernel for distributing the total pattern value float weights[5][5]; auto weightSum = 0.0f; auto weightOut = &weights[0][0]; for (auto y = -2; y <= 2; y++) { for (auto x = -2; x <= 2; x++) { auto strength = 3.0f - sqrtf((float)(x * x + y * y)); *weightOut++ = strength; weightSum += strength; } } // Now use the computed weights to calculate the actual pattern based on the requested total value auto patternSum = 0; for (auto y = 0; y < 5; ++y) { for (auto x = 0; x < 5; ++x) { auto pixelValue = (uint8_t)(weights[y][x] / weightSum * totalPatternValue); result.patterns[0][y][x] = pixelValue; patternSum += pixelValue; } } // This assigns any remainder of the total pattern value (loss due to rounding down above) // to the center pixel of the 5x5 kernel result.patterns[0][2][2] += totalPatternValue - patternSum; // Now create 3 versions of the pattern that are shifted by 1-3 pixels to the right // This is for optimization reasons since addition is done using 32-bit (4 bytes) addition // and the resulting patterns are in reality 8 pixels wide for (auto xShift = 1; xShift <= 3; ++xShift) { for (auto y = 0; y < 5; ++y) { for (auto x = 0; x < 5; ++x) { // Output here is shifted by {1,2,3} pixels right result.patterns[xShift][y][x + xShift] = result.patterns[0][y][x]; } } } return result; } <|endoftext|>
<commit_before>// // Name: SceneGraphDlg.cpp // // Copyright (c) 2001-2004 Virtual Terrain Project // Free for all uses, see license.txt for details. // #ifdef __GNUG__ #pragma implementation "SceneGraphDlg.cpp" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/treectrl.h" #include "wx/image.h" #include "vtlib/vtlib.h" #include "vtlib/core/Engine.h" #include "vtui/wxString2.h" #include "SceneGraphDlg.h" #include <typeinfo> using namespace std; #if defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXMAC__) # include "icon1.xpm" # include "icon2.xpm" # include "icon3.xpm" # include "icon4.xpm" # include "icon5.xpm" # include "icon6.xpm" # include "icon7.xpm" # include "icon8.xpm" # include "icon9.xpm" # include "icon10.xpm" #endif ///////////////////////////// class MyTreeItemData : public wxTreeItemData { public: MyTreeItemData(vtNodeBase *pNode, vtEngine *pEngine) { m_pNode = pNode; m_pEngine = pEngine; } vtNodeBase *m_pNode; vtEngine *m_pEngine; }; // WDR: class implementations //---------------------------------------------------------------------------- // SceneGraphDlg //---------------------------------------------------------------------------- // WDR: event table for SceneGraphDlg BEGIN_EVENT_TABLE(SceneGraphDlg,wxDialog) EVT_INIT_DIALOG (SceneGraphDlg::OnInitDialog) EVT_TREE_SEL_CHANGED( ID_SCENETREE, SceneGraphDlg::OnTreeSelChanged ) EVT_CHECKBOX( ID_ENABLED, SceneGraphDlg::OnEnabled ) EVT_BUTTON( ID_ZOOMTO, SceneGraphDlg::OnZoomTo ) EVT_BUTTON( ID_REFRESH, SceneGraphDlg::OnRefresh ) END_EVENT_TABLE() SceneGraphDlg::SceneGraphDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : wxDialog( parent, id, title, position, size, style ) { SceneGraphFunc( this, TRUE ); m_pZoomTo = GetZoomto(); m_pEnabled = GetEnabled(); m_pTree = GetScenetree(); m_pZoomTo->Enable(false); m_imageListNormal = NULL; CreateImageList(16); } SceneGraphDlg::~SceneGraphDlg() { delete m_imageListNormal; } /////////// void SceneGraphDlg::CreateImageList(int size) { delete m_imageListNormal; if ( size == -1 ) { m_imageListNormal = NULL; return; } // Make an image list containing small icons m_imageListNormal = new wxImageList(size, size, TRUE); wxIcon icons[10]; icons[0] = wxICON(icon1); icons[1] = wxICON(icon2); icons[2] = wxICON(icon3); icons[3] = wxICON(icon4); icons[4] = wxICON(icon5); icons[5] = wxICON(icon6); icons[6] = wxICON(icon7); icons[7] = wxICON(icon8); icons[8] = wxICON(icon9); icons[9] = wxICON(icon10); int sizeOrig = icons[0].GetWidth(); for ( size_t i = 0; i < WXSIZEOF(icons); i++ ) { if ( size == sizeOrig ) m_imageListNormal->Add(icons[i]); else m_imageListNormal->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size))); } m_pTree->SetImageList(m_imageListNormal); } void SceneGraphDlg::RefreshTreeContents() { vtScene* scene = vtGetScene(); if (!scene) return; // start with a blank slate m_pTree->DeleteAllItems(); // Fill in the tree with nodes m_bFirst = true; vtNode *pRoot = scene->GetRoot(); if (pRoot) AddNodeItemsRecursively(wxTreeItemId(), pRoot, 0); wxTreeItemId hRoot = m_pTree->GetRootItem(); wxTreeItemId hEngRoot = m_pTree->AppendItem(hRoot, _("Engines"), 7, 7); vtEngine *pEngine = scene->GetRootEngine(); if (pEngine) AddEnginesRecursively(hEngRoot, pEngine, 0); m_pTree->Expand(hEngRoot); m_pSelectedEngine = NULL; m_pSelectedNode = NULL; } void SceneGraphDlg::AddNodeItemsRecursively(wxTreeItemId hParentItem, vtNodeBase *pNode, int depth) { wxString str; int nImage; wxTreeItemId hNewItem; if (!pNode) return; if (dynamic_cast<vtLight*>(pNode)) { str = _("Light"); nImage = 4; } else if (dynamic_cast<vtGeom*>(pNode)) { str = _("Geometry"); nImage = 2; } else if (dynamic_cast<vtLOD*>(pNode)) { str = _T("LOD"); nImage = 5; } else if (dynamic_cast<vtTransform*>(pNode)) { str = _T("XForm"); nImage = 9; } else if (dynamic_cast<vtGroupBase*>(pNode)) { // must be just a group for grouping's sake str = _("Group"); nImage = 3; } else { // must be something else str = _("Other"); nImage = 8; } if (pNode->GetName2()) { str += _T(" \""); str += wxString::FromAscii(pNode->GetName2()); str += _T("\""); } if (m_bFirst) { hNewItem = m_pTree->AddRoot(str); m_bFirst = false; } else hNewItem = m_pTree->AppendItem(hParentItem, str, nImage, nImage); const std::type_info &t1 = typeid(*pNode); if (t1 == typeid(vtGeom)) { vtGeom *pGeom = dynamic_cast<vtGeom*>(pNode); int num_mesh = pGeom->GetNumMeshes(); wxTreeItemId hGeomItem; for (int i = 0; i < num_mesh; i++) { vtMesh *pMesh = pGeom->GetMesh(i); if (pMesh) { int iNumPrim = pMesh->GetNumPrims(); int iNumVert = pMesh->GetNumVertices(); GLenum pt = pMesh->GetPrimType(); const char *mtype=""; switch (pt) { case GL_POINTS: mtype = "Points"; break; case GL_LINES: mtype = "Lines"; break; case GL_LINE_LOOP: mtype = "LineLoop"; break; case GL_LINE_STRIP: mtype = "LineStrip"; break; case GL_TRIANGLES: mtype = "Triangles"; break; case GL_TRIANGLE_STRIP: mtype = "TriStrip"; break; case GL_TRIANGLE_FAN: mtype = "TriFan"; break; case GL_QUADS: mtype = "Quads"; break; case GL_QUAD_STRIP: mtype = "QuadStrip"; break; case GL_POLYGON: mtype = "Polygon"; break; } str.Printf(_("Mesh %d, %hs, %d verts, %d prims"), i, mtype, iNumVert, iNumPrim); hGeomItem = m_pTree->AppendItem(hNewItem, str, 6, 6); } else hGeomItem = m_pTree->AppendItem(hNewItem, _("Text Mesh"), 6, 6); } } m_pTree->SetItemData(hNewItem, new MyTreeItemData(pNode, NULL)); wxTreeItemId hSubItem; vtGroupBase *pGroup = dynamic_cast<vtGroupBase*>(pNode); if (pGroup) { int num_children = pGroup->GetNumChildren(); if (num_children > 200) { str.Printf(_("(%d children)"), num_children); hSubItem = m_pTree->AppendItem(hNewItem, str, 8, 8); } else { for (int i = 0; i < num_children; i++) { vtNode *pChild = pGroup->GetChild(i); if (pChild) AddNodeItemsRecursively(hNewItem, pChild, depth+1); else hSubItem = m_pTree->AppendItem(hNewItem, _("(internal node)"), 8, 8); } } } // expand a bit so that the tree is initially partially exposed if (depth < 2) m_pTree->Expand(hNewItem); } void SceneGraphDlg::AddEnginesRecursively(wxTreeItemId hParentItem, vtEngine *pEng, int depth) { wxTreeItemId hNewItem; if (!pEng) return; wxString2 str = pEng->GetName2(); if (str == "") str = "unnamed"; int targets = pEng->NumTargets(); vtTarget *target = pEng->GetTarget(); if (target) { str += _T(" -> "); vtNodeBase *node = dynamic_cast<vtNodeBase*>(target); if (node) { str += _T("\""); str += wxString::FromAscii(node->GetName2()); str += _T("\""); } else str += _("(non-node)"); } if (targets > 1) { wxString2 plus; plus.Printf(_(" (%d targets total)"), targets); str += plus; } hNewItem = m_pTree->AppendItem(hParentItem, str, 1, 1); m_pTree->SetItemData(hNewItem, new MyTreeItemData(NULL, pEng)); for (unsigned int i = 0; i < pEng->NumChildren(); i++) { vtEngine *pChild = pEng->GetChild(i); AddEnginesRecursively(hNewItem, pChild, depth+1); } // always expand engines m_pTree->Expand(hNewItem); } // WDR: handler implementations for SceneGraphDlg void SceneGraphDlg::OnRefresh( wxCommandEvent &event ) { RefreshTreeContents(); } void SceneGraphDlg::OnZoomTo( wxCommandEvent &event ) { if (m_pSelectedNode) { FSphere sph; m_pSelectedNode->GetBoundSphere(sph, true); // global bounds // a bit back to make sure whole volume of bounding sphere is in view vtCamera *pCam = vtGetScene()->GetCamera(); float smallest = min(pCam->GetFOV(), pCam->GetVertFOV()); float alpha = smallest / 2.0f; float distance = sph.radius / tanf(alpha); sph.radius = distance; pCam->ZoomToSphere(sph); } } void SceneGraphDlg::OnEnabled( wxCommandEvent &event ) { if (m_pSelectedEngine) m_pSelectedEngine->SetEnabled(m_pEnabled->GetValue()); if (m_pSelectedNode) m_pSelectedNode->SetEnabled(m_pEnabled->GetValue()); } void SceneGraphDlg::OnTreeSelChanged( wxTreeEvent &event ) { wxTreeItemId item = event.GetItem(); MyTreeItemData *data = (MyTreeItemData *)m_pTree->GetItemData(item); m_pEnabled->Enable(data != NULL); m_pSelectedEngine = NULL; m_pSelectedNode = NULL; if (data && data->m_pEngine) { m_pSelectedEngine = data->m_pEngine; m_pEnabled->SetValue(m_pSelectedEngine->GetEnabled()); } if (data && data->m_pNode) { m_pSelectedNode = data->m_pNode; m_pEnabled->SetValue(m_pSelectedNode->GetEnabled()); m_pZoomTo->Enable(true); } else m_pZoomTo->Enable(false); } void SceneGraphDlg::OnInitDialog(wxInitDialogEvent& event) { RefreshTreeContents(); wxWindow::OnInitDialog(event); } <commit_msg>unicode build fix<commit_after>// // Name: SceneGraphDlg.cpp // // Copyright (c) 2001-2004 Virtual Terrain Project // Free for all uses, see license.txt for details. // #ifdef __GNUG__ #pragma implementation "SceneGraphDlg.cpp" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/treectrl.h" #include "wx/image.h" #include "vtlib/vtlib.h" #include "vtlib/core/Engine.h" #include "vtui/wxString2.h" #include "SceneGraphDlg.h" #include <typeinfo> using namespace std; #if defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXMAC__) # include "icon1.xpm" # include "icon2.xpm" # include "icon3.xpm" # include "icon4.xpm" # include "icon5.xpm" # include "icon6.xpm" # include "icon7.xpm" # include "icon8.xpm" # include "icon9.xpm" # include "icon10.xpm" #endif ///////////////////////////// class MyTreeItemData : public wxTreeItemData { public: MyTreeItemData(vtNodeBase *pNode, vtEngine *pEngine) { m_pNode = pNode; m_pEngine = pEngine; } vtNodeBase *m_pNode; vtEngine *m_pEngine; }; // WDR: class implementations //---------------------------------------------------------------------------- // SceneGraphDlg //---------------------------------------------------------------------------- // WDR: event table for SceneGraphDlg BEGIN_EVENT_TABLE(SceneGraphDlg,wxDialog) EVT_INIT_DIALOG (SceneGraphDlg::OnInitDialog) EVT_TREE_SEL_CHANGED( ID_SCENETREE, SceneGraphDlg::OnTreeSelChanged ) EVT_CHECKBOX( ID_ENABLED, SceneGraphDlg::OnEnabled ) EVT_BUTTON( ID_ZOOMTO, SceneGraphDlg::OnZoomTo ) EVT_BUTTON( ID_REFRESH, SceneGraphDlg::OnRefresh ) END_EVENT_TABLE() SceneGraphDlg::SceneGraphDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : wxDialog( parent, id, title, position, size, style ) { SceneGraphFunc( this, TRUE ); m_pZoomTo = GetZoomto(); m_pEnabled = GetEnabled(); m_pTree = GetScenetree(); m_pZoomTo->Enable(false); m_imageListNormal = NULL; CreateImageList(16); } SceneGraphDlg::~SceneGraphDlg() { delete m_imageListNormal; } /////////// void SceneGraphDlg::CreateImageList(int size) { delete m_imageListNormal; if ( size == -1 ) { m_imageListNormal = NULL; return; } // Make an image list containing small icons m_imageListNormal = new wxImageList(size, size, TRUE); wxIcon icons[10]; icons[0] = wxICON(icon1); icons[1] = wxICON(icon2); icons[2] = wxICON(icon3); icons[3] = wxICON(icon4); icons[4] = wxICON(icon5); icons[5] = wxICON(icon6); icons[6] = wxICON(icon7); icons[7] = wxICON(icon8); icons[8] = wxICON(icon9); icons[9] = wxICON(icon10); int sizeOrig = icons[0].GetWidth(); for ( size_t i = 0; i < WXSIZEOF(icons); i++ ) { if ( size == sizeOrig ) m_imageListNormal->Add(icons[i]); else m_imageListNormal->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size))); } m_pTree->SetImageList(m_imageListNormal); } void SceneGraphDlg::RefreshTreeContents() { vtScene* scene = vtGetScene(); if (!scene) return; // start with a blank slate m_pTree->DeleteAllItems(); // Fill in the tree with nodes m_bFirst = true; vtNode *pRoot = scene->GetRoot(); if (pRoot) AddNodeItemsRecursively(wxTreeItemId(), pRoot, 0); wxTreeItemId hRoot = m_pTree->GetRootItem(); wxTreeItemId hEngRoot = m_pTree->AppendItem(hRoot, _("Engines"), 7, 7); vtEngine *pEngine = scene->GetRootEngine(); if (pEngine) AddEnginesRecursively(hEngRoot, pEngine, 0); m_pTree->Expand(hEngRoot); m_pSelectedEngine = NULL; m_pSelectedNode = NULL; } void SceneGraphDlg::AddNodeItemsRecursively(wxTreeItemId hParentItem, vtNodeBase *pNode, int depth) { wxString str; int nImage; wxTreeItemId hNewItem; if (!pNode) return; if (dynamic_cast<vtLight*>(pNode)) { str = _("Light"); nImage = 4; } else if (dynamic_cast<vtGeom*>(pNode)) { str = _("Geometry"); nImage = 2; } else if (dynamic_cast<vtLOD*>(pNode)) { str = _T("LOD"); nImage = 5; } else if (dynamic_cast<vtTransform*>(pNode)) { str = _T("XForm"); nImage = 9; } else if (dynamic_cast<vtGroupBase*>(pNode)) { // must be just a group for grouping's sake str = _("Group"); nImage = 3; } else { // must be something else str = _("Other"); nImage = 8; } if (pNode->GetName2()) { str += _T(" \""); str += wxString::FromAscii(pNode->GetName2()); str += _T("\""); } if (m_bFirst) { hNewItem = m_pTree->AddRoot(str); m_bFirst = false; } else hNewItem = m_pTree->AppendItem(hParentItem, str, nImage, nImage); const std::type_info &t1 = typeid(*pNode); if (t1 == typeid(vtGeom)) { vtGeom *pGeom = dynamic_cast<vtGeom*>(pNode); int num_mesh = pGeom->GetNumMeshes(); wxTreeItemId hGeomItem; for (int i = 0; i < num_mesh; i++) { vtMesh *pMesh = pGeom->GetMesh(i); if (pMesh) { int iNumPrim = pMesh->GetNumPrims(); int iNumVert = pMesh->GetNumVertices(); GLenum pt = pMesh->GetPrimType(); const char *mtype=""; switch (pt) { case GL_POINTS: mtype = "Points"; break; case GL_LINES: mtype = "Lines"; break; case GL_LINE_LOOP: mtype = "LineLoop"; break; case GL_LINE_STRIP: mtype = "LineStrip"; break; case GL_TRIANGLES: mtype = "Triangles"; break; case GL_TRIANGLE_STRIP: mtype = "TriStrip"; break; case GL_TRIANGLE_FAN: mtype = "TriFan"; break; case GL_QUADS: mtype = "Quads"; break; case GL_QUAD_STRIP: mtype = "QuadStrip"; break; case GL_POLYGON: mtype = "Polygon"; break; } str.Printf(_("Mesh %d, %hs, %d verts, %d prims"), i, mtype, iNumVert, iNumPrim); hGeomItem = m_pTree->AppendItem(hNewItem, str, 6, 6); } else hGeomItem = m_pTree->AppendItem(hNewItem, _("Text Mesh"), 6, 6); } } m_pTree->SetItemData(hNewItem, new MyTreeItemData(pNode, NULL)); wxTreeItemId hSubItem; vtGroupBase *pGroup = dynamic_cast<vtGroupBase*>(pNode); if (pGroup) { int num_children = pGroup->GetNumChildren(); if (num_children > 200) { str.Printf(_("(%d children)"), num_children); hSubItem = m_pTree->AppendItem(hNewItem, str, 8, 8); } else { for (int i = 0; i < num_children; i++) { vtNode *pChild = pGroup->GetChild(i); if (pChild) AddNodeItemsRecursively(hNewItem, pChild, depth+1); else hSubItem = m_pTree->AppendItem(hNewItem, _("(internal node)"), 8, 8); } } } // expand a bit so that the tree is initially partially exposed if (depth < 2) m_pTree->Expand(hNewItem); } void SceneGraphDlg::AddEnginesRecursively(wxTreeItemId hParentItem, vtEngine *pEng, int depth) { wxTreeItemId hNewItem; if (!pEng) return; wxString2 str = pEng->GetName2(); if (str == wxString2("")) str = "unnamed"; int targets = pEng->NumTargets(); vtTarget *target = pEng->GetTarget(); if (target) { str += _T(" -> "); vtNodeBase *node = dynamic_cast<vtNodeBase*>(target); if (node) { str += _T("\""); str += wxString::FromAscii(node->GetName2()); str += _T("\""); } else str += _("(non-node)"); } if (targets > 1) { wxString2 plus; plus.Printf(_(" (%d targets total)"), targets); str += plus; } hNewItem = m_pTree->AppendItem(hParentItem, str, 1, 1); m_pTree->SetItemData(hNewItem, new MyTreeItemData(NULL, pEng)); for (unsigned int i = 0; i < pEng->NumChildren(); i++) { vtEngine *pChild = pEng->GetChild(i); AddEnginesRecursively(hNewItem, pChild, depth+1); } // always expand engines m_pTree->Expand(hNewItem); } // WDR: handler implementations for SceneGraphDlg void SceneGraphDlg::OnRefresh( wxCommandEvent &event ) { RefreshTreeContents(); } void SceneGraphDlg::OnZoomTo( wxCommandEvent &event ) { if (m_pSelectedNode) { FSphere sph; m_pSelectedNode->GetBoundSphere(sph, true); // global bounds // a bit back to make sure whole volume of bounding sphere is in view vtCamera *pCam = vtGetScene()->GetCamera(); float smallest = min(pCam->GetFOV(), pCam->GetVertFOV()); float alpha = smallest / 2.0f; float distance = sph.radius / tanf(alpha); sph.radius = distance; pCam->ZoomToSphere(sph); } } void SceneGraphDlg::OnEnabled( wxCommandEvent &event ) { if (m_pSelectedEngine) m_pSelectedEngine->SetEnabled(m_pEnabled->GetValue()); if (m_pSelectedNode) m_pSelectedNode->SetEnabled(m_pEnabled->GetValue()); } void SceneGraphDlg::OnTreeSelChanged( wxTreeEvent &event ) { wxTreeItemId item = event.GetItem(); MyTreeItemData *data = (MyTreeItemData *)m_pTree->GetItemData(item); m_pEnabled->Enable(data != NULL); m_pSelectedEngine = NULL; m_pSelectedNode = NULL; if (data && data->m_pEngine) { m_pSelectedEngine = data->m_pEngine; m_pEnabled->SetValue(m_pSelectedEngine->GetEnabled()); } if (data && data->m_pNode) { m_pSelectedNode = data->m_pNode; m_pEnabled->SetValue(m_pSelectedNode->GetEnabled()); m_pZoomTo->Enable(true); } else m_pZoomTo->Enable(false); } void SceneGraphDlg::OnInitDialog(wxInitDialogEvent& event) { RefreshTreeContents(); wxWindow::OnInitDialog(event); } <|endoftext|>
<commit_before>/* MAX1464 library for Arduino Copyright (C) 2016 Giacomo Mazzamuto <gmazzamuto@gmail.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, see <http://www.gnu.org/licenses/>. */ #include "MAX1464.h" MAX1464::MAX1464(int chipSelect) : AbstractMAX1464(chipSelect) { settings = SPISettings(4000000, LSBFIRST, SPI_MODE0); } void MAX1464::begin() { SPI.begin(); enable4WireModeDataTransfer(); } void MAX1464::byteShiftOut(uint8_t b) { #ifdef SERIALDEBUG if(debugMsg == NULL) debugMsg = ""; Serial.println(debugMsg); debugMsg = NULL; #endif SPI.beginTransaction(settings); digitalWrite(_chipSelect, LOW); SPI.transfer(b); digitalWrite(_chipSelect, HIGH); SPI.endTransaction(); } uint16_t MAX1464::wordShiftIn() { uint16_t w = 0; SPI.beginTransaction(settings); digitalWrite(_chipSelect, LOW); w = SPI.transfer16(0x0000); digitalWrite(_chipSelect, HIGH); SPI.endTransaction(); // reverse bits uint8_t newVal = 0; if (w & 0x1) newVal |= 0x8000; if (w & 0x2) newVal |= 0x4000; if (w & 0x4) newVal |= 0x2000; if (w & 0x8) newVal |= 0x1000; if (w & 0x10) newVal |= 0x800; if (w & 0x20) newVal |= 0x400; if (w & 0x40) newVal |= 0x200; if (w & 0x80) newVal |= 0x100; if (w & 0x100) newVal |= 0x80; if (w & 0x200) newVal |= 0x40; if (w & 0x400) newVal |= 0x20; if (w & 0x800) newVal |= 0x10; if (w & 0x1000) newVal |= 0x8; if (w & 0x2000) newVal |= 0x4; if (w & 0x4000) newVal |= 0x2; if (w & 0x8000) newVal |= 0x1; return newVal; } <commit_msg>MAX1464: fix bug in byteShiftOut (wrong 8 bit type)<commit_after>/* MAX1464 library for Arduino Copyright (C) 2016 Giacomo Mazzamuto <gmazzamuto@gmail.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, see <http://www.gnu.org/licenses/>. */ #include "MAX1464.h" MAX1464::MAX1464(int chipSelect) : AbstractMAX1464(chipSelect) { settings = SPISettings(4000000, LSBFIRST, SPI_MODE0); } void MAX1464::begin() { SPI.begin(); enable4WireModeDataTransfer(); } void MAX1464::byteShiftOut(uint8_t b) { #ifdef SERIALDEBUG if(debugMsg == NULL) debugMsg = ""; Serial.println(debugMsg); debugMsg = NULL; #endif SPI.beginTransaction(settings); digitalWrite(_chipSelect, LOW); SPI.transfer(b); digitalWrite(_chipSelect, HIGH); SPI.endTransaction(); } uint16_t MAX1464::wordShiftIn() { uint16_t w = 0; SPI.beginTransaction(settings); digitalWrite(_chipSelect, LOW); w = SPI.transfer16(0x0000); digitalWrite(_chipSelect, HIGH); SPI.endTransaction(); // reverse bits uint16_t newVal = 0; if (w & 0x1) newVal |= 0x8000; if (w & 0x2) newVal |= 0x4000; if (w & 0x4) newVal |= 0x2000; if (w & 0x8) newVal |= 0x1000; if (w & 0x10) newVal |= 0x800; if (w & 0x20) newVal |= 0x400; if (w & 0x40) newVal |= 0x200; if (w & 0x80) newVal |= 0x100; if (w & 0x100) newVal |= 0x80; if (w & 0x200) newVal |= 0x40; if (w & 0x400) newVal |= 0x20; if (w & 0x800) newVal |= 0x10; if (w & 0x1000) newVal |= 0x8; if (w & 0x2000) newVal |= 0x4; if (w & 0x4000) newVal |= 0x2; if (w & 0x8000) newVal |= 0x1; return newVal; } <|endoftext|>
<commit_before>#include "Ubidots.h" /** * Constructor. */ Ubidots::Ubidots(char* token, char* dsName) { _token = token; currentValue = 0; val = (Value *)malloc(MAX_VALUES*sizeof(Value)); _dsName = dsName; } /** * This function is to get value from the Ubidots API * @arg id the id where you will get the data * @return num the data that you get from the Ubidots API */ float Ubidots::getValueWithDatasource(char* dsName, char* idName) { float num; int i = 0; char* allData = (char *) malloc(sizeof(char) * 300); String response; uint8_t bodyPosinit; sprintf(allData, "Particle|LV|%s|%s:%s|end", _token, _dsName, idName); while (!_client.connected() && i < 6) { i++; _client.connect(SERVER, PORT); } if (_client.connected()) { // Connect to the server #ifdef DEBUG_UBIDOTS Serial.println("Client connected"); Serial.println(allData); #endif _client.println(allData); _client.flush(); } i = 50000; while (!_client.available()|| i == 0) { i--; } while (_client.available()) { char c = _client.read(); response += c; } bodyPosinit = 3 + response.indexOf("OK|"); response = response.substring(bodyPosinit); num = response.toFloat(); currentValue = 0; _client.stop(); free(allData); _client.stop(); return num; } /** * Add a value of variable to save * @arg variable_id variable id to save in a struct * @arg value variable value to save in a struct */ void Ubidots::add(char *variable_id, double value) { add(variable_id, value, NULL); } /** * Add a value of variable to save * @arg variable_id variable id to save in a struct * @arg value variable value to save in a struct */ void Ubidots::add(char *variable_id, double value, char *ctext1) { (val+currentValue)->idName = variable_id; (val+currentValue)->idValue = value; (val+currentValue)->contextOne = ctext1; currentValue++; if (currentValue > MAX_VALUES) { Serial.println(F("You are sending more than 10 consecutives variables, you just could send 5 variables. Then other variables will be deleted!")); currentValue = MAX_VALUES; } } /** * Send all data of all variables that you saved * @reutrn true upon success, false upon error. */ bool Ubidots::sendAll() { int i; char* allData = (char *) malloc(sizeof(char) * 700); sprintf(allData, "Particle|POST|%s|%s=>", _token, _dsName); for (i = 0; i < currentValue; ) { sprintf(allData, "%s%s:%f", allData, (val + i)->idName, (val + i)->idValue); if ((val + i)->contextOne != NULL) { sprintf(allData, "%s$%s", allData, (val + i)->contextOne); } i++; if (i < currentValue) { sprintf(allData, "%s,", allData); } } sprintf(allData, "%s|end", allData); #ifdef DEBUG_UBIDOTS Serial.println(allData); #endif while (!_client.connected() && i < 6) { i++; _client.connect(SERVER, PORT); } if (_client.connected()) { // Connect to the server #ifdef DEBUG_UBIDOTS Serial.println("Client connected"); #endif _client.println(allData); _client.flush(); } i = 50000; while (!_client.available() || i == 0) { i--; } while (_client.available()) { char c = _client.read(); #ifdef DEBUG_UBIDOTS Serial.write(c); #endif } currentValue = 0; _client.stop(); free(allData); return true; } <commit_msg>changed the version and the message of maximum variables<commit_after>#include "Ubidots.h" /** * Constructor. */ Ubidots::Ubidots(char* token, char* dsName) { _token = token; currentValue = 0; val = (Value *)malloc(MAX_VALUES*sizeof(Value)); _dsName = dsName; } /** * This function is to get value from the Ubidots API * @arg id the id where you will get the data * @return num the data that you get from the Ubidots API */ float Ubidots::getValueWithDatasource(char* dsName, char* idName) { float num; int i = 0; char* allData = (char *) malloc(sizeof(char) * 300); String response; uint8_t bodyPosinit; sprintf(allData, "Particle|LV|%s|%s:%s|end", _token, _dsName, idName); while (!_client.connected() && i < 6) { i++; _client.connect(SERVER, PORT); } if (_client.connected()) { // Connect to the server #ifdef DEBUG_UBIDOTS Serial.println("Client connected"); Serial.println(allData); #endif _client.println(allData); _client.flush(); } i = 50000; while (!_client.available()|| i == 0) { i--; } while (_client.available()) { char c = _client.read(); response += c; } bodyPosinit = 3 + response.indexOf("OK|"); response = response.substring(bodyPosinit); num = response.toFloat(); currentValue = 0; _client.stop(); free(allData); _client.stop(); return num; } /** * Add a value of variable to save * @arg variable_id variable id to save in a struct * @arg value variable value to save in a struct */ void Ubidots::add(char *variable_id, double value) { add(variable_id, value, NULL); } /** * Add a value of variable to save * @arg variable_id variable id to save in a struct * @arg value variable value to save in a struct */ void Ubidots::add(char *variable_id, double value, char *ctext1) { (val+currentValue)->idName = variable_id; (val+currentValue)->idValue = value; (val+currentValue)->contextOne = ctext1; currentValue++; if (currentValue > MAX_VALUES) { Serial.println(F("You are sending more than the maximum of consecutive variables")); currentValue = MAX_VALUES; } } /** * Send all data of all variables that you saved * @reutrn true upon success, false upon error. */ bool Ubidots::sendAll() { int i; char* allData = (char *) malloc(sizeof(char) * 700); sprintf(allData, "Particle/1.0|POST|%s|%s=>", _token, _dsName); for (i = 0; i < currentValue; ) { sprintf(allData, "%s%s:%f", allData, (val + i)->idName, (val + i)->idValue); if ((val + i)->contextOne != NULL) { sprintf(allData, "%s$%s", allData, (val + i)->contextOne); } i++; if (i < currentValue) { sprintf(allData, "%s,", allData); } } sprintf(allData, "%s|end", allData); #ifdef DEBUG_UBIDOTS Serial.println(allData); #endif while (!_client.connected() && i < 6) { i++; _client.connect(SERVER, PORT); } if (_client.connected()) { // Connect to the server #ifdef DEBUG_UBIDOTS Serial.println("Client connected"); #endif _client.println(allData); _client.flush(); } i = 50000; while (!_client.available() || i == 0) { i--; } while (_client.available()) { char c = _client.read(); #ifdef DEBUG_UBIDOTS Serial.write(c); #endif } currentValue = 0; _client.stop(); free(allData); return true; } <|endoftext|>
<commit_before>// FILE: dataperf.cpp // // DESCRIPTION: // // Compare relative performance of data types in SystemC // by creating long loops and performing arithmetic. // // LICENSE: // // Copyright 2014 David C Black // // 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 "require_cxx11.h" #include <cstdint> #include <cmath> #include <cassert> #include <systemc> #include <iostream> #include <iomanip> #include <sstream> #include <chrono> #include <ctime> #include <string> #include <cstddef> using namespace std; using namespace sc_dt; namespace { chrono::time_point<chrono::system_clock> start, current; chrono::duration<double> elapsed_seconds; time_t end_time; size_t loop_count = 1e8; } template<typename T> void truncate(T& val) { val = T(uint32_t(val)); // Truncate to 32 bits } template<> void truncate<sc_bigint<32>>(sc_bigint<32>& val) { } template<typename T> void dataperf(void) { cout << "Testing " << typeid(T).name() << " with loop_count=" << loop_count << " " << flush; T result = 1; T A = 1103515245; // Linear congruential constants for 32 bit pseudo-random of max length T C = 12345; // result = (A*result + C) & 0xFFFF_FFFF start = chrono::system_clock::now(); for (size_t loop=loop_count; loop!=0; --loop) { result = A * result + C; // Computation truncate<T>(result); } cout << "result=" << fixed << setprecision(0) << result << " " << flush; // Ensure compiler doesn't optimize loop out current = chrono::system_clock::now(); elapsed_seconds = current - start; end_time = chrono::system_clock::to_time_t(current); cout << "elapsed time " << setprecision(6) << elapsed_seconds.count() << "s" << endl; } int sc_main(int argc, char* argv[]) { for (int i=1; i<argc; ++i) { // Process command-line string arg(argv[i]); if (arg.length()>1 and string("-help").find(arg) == 0) { cout << "SYNOPSIS\n" << " " << argv[0] << " [LOOP_COUNT]\n" << "EXAMPLES\n" << " " << argv[0] << "1e7\n" << endl ; return 0; } else if (arg.find_first_not_of("0123456789e") == string::npos) { istringstream is(arg); double d; is >> d; loop_count = d; assert(loop_count != 0); }//endif } dataperf<int32_t>(); dataperf<sc_int<32>>(); dataperf<sc_bigint<32>>(); dataperf<double>(); dataperf<sc_fixed_fast<32,32>>(); dataperf<sc_fixed<32,32>>(); cout << "\nCompleted all tests" << endl; return 0; } //End of file <commit_msg>formatting<commit_after>// FILE: dataperf.cpp // // DESCRIPTION: // // Compare relative performance of data types in SystemC // by creating long loops and performing operations on the data. // // LICENSE: // // Copyright 2014,2015 David C Black // // 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 "require_cxx11.h" #include <cstdint> #include <cmath> #include <cassert> #include <systemc> #include <iostream> #include <iomanip> #include <sstream> #include <chrono> #include <ctime> #include <string> #include <cstddef> using namespace std; using namespace sc_dt; namespace { chrono::time_point<chrono::system_clock> start, current; chrono::duration<double> elapsed_seconds; time_t end_time; size_t loop_count = 1e8; } template<typename T> void truncate(T& val) { val = T(uint32_t(val)); // Truncate to 32 bits } template<> void truncate<sc_bigint<32>>(sc_bigint<32>& val) { } template<typename T> void arithperf(void) { cout << "Testing arithmetic " << typeid(T).name() << " occupies " << sizeof(T) << " bytes with loop_count=" << loop_count << " " << flush; T result = 1; T A = 1103515245; // Linear congruential constants for 32 bit pseudo-random of max length T C = 12345; // result = (A*result + C) & 0xFFFF_FFFF start = chrono::system_clock::now(); for (size_t loop=loop_count; loop!=0; --loop) { // Compute result = A * result + C; truncate<T>(result); } cout << "result=" << fixed << setprecision(0) << result << " " << flush; // Ensure compiler doesn't optimize loop out current = chrono::system_clock::now(); elapsed_seconds = current - start; end_time = chrono::system_clock::to_time_t(current); cout << "elapsed time " << setprecision(6) << elapsed_seconds.count() << "s" << endl; } template<typename T> void logicperf(void) { cout << "Testing logic " << typeid(T).name() << " occupies " << sizeof(T) << " bytes with loop_count=" << loop_count << " " << flush; size_t tbits = 8*sizeof(T); size_t rbits = 17; size_t lbits = tbits - rbits; T val = 1; T A = 1103515245; // Linear congruential constants for 32 bit pseudo-random of max length T C = 12345; // val = (A^ror(val,rbits) ^ C) & 0xFFFF_FFFF T rhs, lhs; start = chrono::system_clock::now(); for (size_t loop=loop_count; loop!=0; --loop) { // Compute rhs = (val >> rbits); lhs = ((rhs << rbits)^val); val = A ^ ((lhs<<lbits)|rhs) ^ C; } cout << "result=" << fixed << setprecision(0) << val << " " << flush; // Ensure compiler doesn't optimize loop out current = chrono::system_clock::now(); elapsed_seconds = current - start; end_time = chrono::system_clock::to_time_t(current); cout << "elapsed time " << setprecision(6) << elapsed_seconds.count() << "s" << endl; } int sc_main(int argc, char* argv[]) { for (int i=1; i<argc; ++i) { // Process command-line string arg(argv[i]); if (arg.length()>1 and string("-help").find(arg) == 0) { cout << "SYNOPSIS\n" << " " << argv[0] << " [LOOP_COUNT]\n" << "EXAMPLES\n" << " " << argv[0] << "1e7\n" << endl ; return 0; } else if (arg.find_first_not_of("0123456789e") == string::npos) { istringstream is(arg); double d; is >> d; loop_count = d; assert(loop_count != 0); }//endif } arithperf<int32_t>(); arithperf<sc_int<32>>(); arithperf<sc_bigint<32>>(); arithperf<double>(); arithperf<sc_fixed_fast<32,32>>(); arithperf<sc_fixed<32,32>>(); cout << endl; logicperf<int32_t>(); logicperf<sc_int<32>>(); logicperf<sc_bigint<32>>(); logicperf<sc_lv<32>>(); logicperf<sc_bv<32>>(); cout << "\nCompleted all tests" << endl; return 0; } //End of file <|endoftext|>
<commit_before>/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MacAddress.h" #include "folly/Exception.h" #include "folly/IPAddressV6.h" using std::invalid_argument; using std::string; namespace folly { const MacAddress MacAddress::BROADCAST{Endian::big(0xffffffffffffU)}; const MacAddress MacAddress::ZERO; MacAddress::MacAddress(StringPiece str) { memset(&bytes_, 0, 8); parse(str); } MacAddress MacAddress::createMulticast(IPAddressV6 v6addr) { // This method should only be used for multicast addresses. DCHECK(v6addr.isMulticast()); uint8_t bytes[SIZE]; bytes[0] = 0x33; bytes[1] = 0x33; memcpy(bytes + 2, v6addr.bytes() + 12, 4); return fromBinary(ByteRange(bytes, SIZE)); } string MacAddress::toString() const { static const char hexValues[] = "0123456789abcdef"; string result; result.resize(17); result[0] = hexValues[getByte(0) >> 4]; result[1] = hexValues[getByte(0) & 0xf]; result[2] = ':'; result[3] = hexValues[getByte(1) >> 4]; result[4] = hexValues[getByte(1) & 0xf]; result[5] = ':'; result[6] = hexValues[getByte(2) >> 4]; result[7] = hexValues[getByte(2) & 0xf]; result[8] = ':'; result[9] = hexValues[getByte(3) >> 4]; result[10] = hexValues[getByte(3) & 0xf]; result[11] = ':'; result[12] = hexValues[getByte(4) >> 4]; result[13] = hexValues[getByte(4) & 0xf]; result[14] = ':'; result[15] = hexValues[getByte(5) >> 4]; result[16] = hexValues[getByte(5) & 0xf]; return result; } void MacAddress::parse(StringPiece str) { // Helper function to convert a single hex char into an integer auto unhex = [](char c) -> int { return c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1; }; auto isSeparatorChar = [](char c) { return c == ':' || c == '-'; }; uint8_t parsed[SIZE]; auto p = str.begin(); for (unsigned int byteIndex = 0; byteIndex < SIZE; ++byteIndex) { if (p == str.end()) { throw invalid_argument(to<string>("invalid MAC address \"", str, "\": not enough digits")); } // Skip over ':' or '-' separators between bytes if (byteIndex != 0 && isSeparatorChar(*p)) { ++p; if (p == str.end()) { throw invalid_argument(to<string>("invalid MAC address \"", str, "\": not enough digits")); } } // Parse the upper nibble int upper = unhex(*p); if (upper < 0) { throw invalid_argument(to<string>("invalid MAC address \"", str, "\": contains non-hex digit")); } ++p; // Parse the lower nibble int lower; if (p == str.end()) { lower = upper; upper = 0; } else { lower = unhex(*p); if (lower < 0) { // Also accept ':', '-', or '\0', to handle the case where one // of the bytes was represented by just a single digit. if (isSeparatorChar(*p)) { lower = upper; upper = 0; } else { throw invalid_argument(to<string>("invalid MAC address \"", str, "\": contains non-hex digit")); } } ++p; } // Update parsed with the newly parsed byte parsed[byteIndex] = ((upper << 4) | lower); } if (p != str.end()) { // String is too long to be a MAC address throw invalid_argument(to<string>("invalid MAC address \"", str, "\": found trailing characters")); } // Only update now that we have successfully parsed the entire // string. This way we remain unchanged on error. setFromBinary(ByteRange(parsed, SIZE)); } void MacAddress::setFromBinary(ByteRange value) { if (value.size() != SIZE) { throw invalid_argument(to<string>("MAC address must be 6 bytes " "long, got ", value.size())); } memcpy(bytes_ + 2, value.begin(), SIZE); } std::ostream& operator<<(std::ostream& os, MacAddress address) { os << address.toString(); return os; } } // folly <commit_msg>Be explicit about what we're passing to Endian::big<commit_after>/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MacAddress.h" #include "folly/Exception.h" #include "folly/IPAddressV6.h" using std::invalid_argument; using std::string; namespace folly { const MacAddress MacAddress::BROADCAST{Endian::big(uint64_t(0xffffffffffffU))}; const MacAddress MacAddress::ZERO; MacAddress::MacAddress(StringPiece str) { memset(&bytes_, 0, 8); parse(str); } MacAddress MacAddress::createMulticast(IPAddressV6 v6addr) { // This method should only be used for multicast addresses. DCHECK(v6addr.isMulticast()); uint8_t bytes[SIZE]; bytes[0] = 0x33; bytes[1] = 0x33; memcpy(bytes + 2, v6addr.bytes() + 12, 4); return fromBinary(ByteRange(bytes, SIZE)); } string MacAddress::toString() const { static const char hexValues[] = "0123456789abcdef"; string result; result.resize(17); result[0] = hexValues[getByte(0) >> 4]; result[1] = hexValues[getByte(0) & 0xf]; result[2] = ':'; result[3] = hexValues[getByte(1) >> 4]; result[4] = hexValues[getByte(1) & 0xf]; result[5] = ':'; result[6] = hexValues[getByte(2) >> 4]; result[7] = hexValues[getByte(2) & 0xf]; result[8] = ':'; result[9] = hexValues[getByte(3) >> 4]; result[10] = hexValues[getByte(3) & 0xf]; result[11] = ':'; result[12] = hexValues[getByte(4) >> 4]; result[13] = hexValues[getByte(4) & 0xf]; result[14] = ':'; result[15] = hexValues[getByte(5) >> 4]; result[16] = hexValues[getByte(5) & 0xf]; return result; } void MacAddress::parse(StringPiece str) { // Helper function to convert a single hex char into an integer auto unhex = [](char c) -> int { return c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1; }; auto isSeparatorChar = [](char c) { return c == ':' || c == '-'; }; uint8_t parsed[SIZE]; auto p = str.begin(); for (unsigned int byteIndex = 0; byteIndex < SIZE; ++byteIndex) { if (p == str.end()) { throw invalid_argument(to<string>("invalid MAC address \"", str, "\": not enough digits")); } // Skip over ':' or '-' separators between bytes if (byteIndex != 0 && isSeparatorChar(*p)) { ++p; if (p == str.end()) { throw invalid_argument(to<string>("invalid MAC address \"", str, "\": not enough digits")); } } // Parse the upper nibble int upper = unhex(*p); if (upper < 0) { throw invalid_argument(to<string>("invalid MAC address \"", str, "\": contains non-hex digit")); } ++p; // Parse the lower nibble int lower; if (p == str.end()) { lower = upper; upper = 0; } else { lower = unhex(*p); if (lower < 0) { // Also accept ':', '-', or '\0', to handle the case where one // of the bytes was represented by just a single digit. if (isSeparatorChar(*p)) { lower = upper; upper = 0; } else { throw invalid_argument(to<string>("invalid MAC address \"", str, "\": contains non-hex digit")); } } ++p; } // Update parsed with the newly parsed byte parsed[byteIndex] = ((upper << 4) | lower); } if (p != str.end()) { // String is too long to be a MAC address throw invalid_argument(to<string>("invalid MAC address \"", str, "\": found trailing characters")); } // Only update now that we have successfully parsed the entire // string. This way we remain unchanged on error. setFromBinary(ByteRange(parsed, SIZE)); } void MacAddress::setFromBinary(ByteRange value) { if (value.size() != SIZE) { throw invalid_argument(to<string>("MAC address must be 6 bytes " "long, got ", value.size())); } memcpy(bytes_ + 2, value.begin(), SIZE); } std::ostream& operator<<(std::ostream& os, MacAddress address) { os << address.toString(); return os; } } // folly <|endoftext|>
<commit_before>/* ___ _ ___ __ _ ___ _ / _ \_ __ ___ ___ ___ ___ ___ __ _ _ __ ___ ___ _ __ | |_ ___ / _ \_ __ __ _ / _(_) ___ ___ / _ \ /_\ / /_)/ '__/ _ \ / __/ _ \/ __/ __|/ _` | '_ ` _ \ / _ \ '_ \| __/ _ \ / /_\/ '__/ _` | |_| |/ __/ _ \ _____ / /_\///_\\ / ___/| | | (_) | (_| __/\__ \__ \ (_| | | | | | | __/ | | | || (_) | / /_\\| | | (_| | _| | (_| (_) | |_____| / /_\\/ _ \ \/ |_| \___/ \___\___||___/___/\__,_|_| |_| |_|\___|_| |_|\__\___/ \____/|_| \__,_|_| |_|\___\___/ \____/\_/ \_/ Unisinos 2016 - Vinicius Pegorini Arnhold e Reni Steffenon */ #pragma once #include <Windows.h> #include <GL/gl.h> #include <GL/glut.h> #include <stdio.h> #include <stdlib.h> #include "Image.h" #include "PTMReader.h" #include <iostream> #include "Layer.h" #include "Animation.h" #pragma warning( disable : 4244)//Conversao sempre estara no range using namespace std; vector<Layer *> layers; vector<Animation *> animations; Image *scene, *backup; char *zBuffer, *zBuffer2; //Sprites int numSpritesLargura = 4; int numSpritesAltura = 4; int widthSprites = 0; int heightSprites = 0; int xSprite = 0; int ySprite = 0; Image imagem; Image sprite; void updateScene(int value) { Image impressao = imagem.clone(); widthSprites = floor(sprite.getWidth() / numSpritesLargura); heightSprites = floor(sprite.getHeight() / numSpritesAltura); Image personagem1(64, 64); sprite.subImage(&personagem1, xSprite*widthSprites, ySprite*heightSprites); impressao.plot(personagem1, 50, 50); if (ySprite == numSpritesAltura - 1 && xSprite == numSpritesLargura - 1) { ySprite = 0; xSprite = 0; } else if (xSprite == numSpritesLargura - 1) { xSprite = 0; ySprite++; } else { xSprite++; } cout << xSprite << " " << ySprite << endl << widthSprites << " " << heightSprites << endl; glClearColor(0.0, 0.0, 0.0, 0.0); glDrawPixels(impressao.getWidth(), impressao.getHeight(), GL_BGRA_EXT, GL_UNSIGNED_BYTE, impressao.getPixels()); glFlush(); glutTimerFunc(500, updateScene, 1); } void display(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glDrawPixels(imagem.getWidth(), imagem.getHeight(), GL_BGRA_EXT, GL_UNSIGNED_BYTE, imagem.getPixels()); glFlush(); } void keyboard(int key, int x, int y) { switch (key) { case GLUT_KEY_RIGHT: for each (Layer* layer in layers) { layer->scroll(true); } break; case GLUT_KEY_LEFT: for each (Layer* layer in layers) { layer->scroll(false); } break; default: break; } } void init(void) { /* select clearing (background) color */ glClearColor(0.0, 0.0, 0.0, 0.0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); /* 1) carregar imagens das camadas */ PTMReader leitorFundo = PTMReader(); leitorFundo.ler("C:\\Users\Administrador\Documents\ProcessamentoGrafico\Imagens\montanhas.ptm"); imagem = leitorFundo.getImage(); /* 2) Inicializar Layers, para cada layer da cena */ Layer cena1 = Layer(0,0); cena1.setBackground(&imagem); /* 3) Carregar animaes objetos do jogo */ PTMReader leitorPersonagem = PTMReader(); leitorPersonagem.ler("C:\\Users\Administrador\Documents\ProcessamentoGrafico\Imagens\T-rex.ptm"); sprite = leitorPersonagem.getImage(); GameObject personagemDireita = GameObject(); GameObject personagemEsquerda = GameObject(); Animation animacaoPersonagemDireita = Animation(); Animation animacaoPersonagemEsquerda = Animation(); for (int x = 0; x < sprite.getHeight()+1; x += 242) { for (int y = 0; y < sprite.getWidth()/2+1; y += 126) { if (x = 242) { Image aux = Image(242, 126); Image *p = &aux; sprite.subImage(p, x, y); animacaoPersonagemDireita.addFrame(&aux); delete p; } else { Image aux = Image(242, 126); Image *p = &aux; sprite.subImage(p, x, y); animacaoPersonagemEsquerda.addFrame(&aux); delete p; } } } personagemDireita.setSprite(animacaoPersonagemDireita); personagemEsquerda.setSprite(animacaoPersonagemEsquerda); /* 4) Inicializar scene, backup, zBuffer e zBuffer2 */ scene = &imagem; Image imagemBackup = imagem; backup = &imagemBackup; int tamanhox = scene->getHeight(); char buffer[1600*900]; char buffer2[1600*900]; //zBuffer = &buffer; //zBuffer2 = &buffer2; } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); init(); glutInitWindowSize(imagem.getWidth(), imagem.getHeight()); glutInitWindowPosition(100, 100); glutCreateWindow("Processamento Grafico - GA"); glutDisplayFunc(display); updateScene(1); glutMainLoop(); return 0; /* ISO C requires main to return int. */ //TODO Deletar Ponteiros Criados }<commit_msg>Fix NullPointers<commit_after>/* ___ _ ___ __ _ ___ _ / _ \_ __ ___ ___ ___ ___ ___ __ _ _ __ ___ ___ _ __ | |_ ___ / _ \_ __ __ _ / _(_) ___ ___ / _ \ /_\ / /_)/ '__/ _ \ / __/ _ \/ __/ __|/ _` | '_ ` _ \ / _ \ '_ \| __/ _ \ / /_\/ '__/ _` | |_| |/ __/ _ \ _____ / /_\///_\\ / ___/| | | (_) | (_| __/\__ \__ \ (_| | | | | | | __/ | | | || (_) | / /_\\| | | (_| | _| | (_| (_) | |_____| / /_\\/ _ \ \/ |_| \___/ \___\___||___/___/\__,_|_| |_| |_|\___|_| |_|\__\___/ \____/|_| \__,_|_| |_|\___\___/ \____/\_/ \_/ Unisinos 2016 - Vinicius Pegorini Arnhold e Reni Steffenon */ #pragma once #include <Windows.h> #include <GL/gl.h> #include <GL/glut.h> #include <stdio.h> #include <stdlib.h> #include "Image.h" #include "PTMReader.h" #include <iostream> #include "Layer.h" #include "Animation.h" #pragma warning( disable : 4244)//Conversao sempre estara no range using namespace std; vector<Layer *> layers; vector<Animation *> animations; Image *scene, *backup; char *zBuffer, *zBuffer2; //Sprites int numSpritesLargura = 4; int numSpritesAltura = 4; int widthSprites = 0; int heightSprites = 0; int xSprite = 0; int ySprite = 0; Image imagem; Image sprite; void updateScene(int value) { Image impressao = imagem.clone(); widthSprites = floor(sprite.getWidth() / numSpritesLargura); heightSprites = floor(sprite.getHeight() / numSpritesAltura); Image personagem1(64, 64); sprite.subImage(&personagem1, xSprite*widthSprites, ySprite*heightSprites); impressao.plot(personagem1, 50, 50); if (ySprite == numSpritesAltura - 1 && xSprite == numSpritesLargura - 1) { ySprite = 0; xSprite = 0; } else if (xSprite == numSpritesLargura - 1) { xSprite = 0; ySprite++; } else { xSprite++; } cout << xSprite << " " << ySprite << endl << widthSprites << " " << heightSprites << endl; glClearColor(0.0, 0.0, 0.0, 0.0); glDrawPixels(impressao.getWidth(), impressao.getHeight(), GL_BGRA_EXT, GL_UNSIGNED_BYTE, impressao.getPixels()); glFlush(); glutTimerFunc(500, updateScene, 1); } void display(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glDrawPixels(imagem.getWidth(), imagem.getHeight(), GL_BGRA_EXT, GL_UNSIGNED_BYTE, imagem.getPixels()); glFlush(); } void keyboard(int key, int x, int y) { switch (key) { case GLUT_KEY_RIGHT: for each (Layer* layer in layers) { layer->scroll(true); } break; case GLUT_KEY_LEFT: for each (Layer* layer in layers) { layer->scroll(false); } break; default: break; } } void init(void) { /* select clearing (background) color */ glClearColor(0.0, 0.0, 0.0, 0.0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); /* 1) carregar imagens das camadas */ PTMReader leitorFundo = PTMReader(); leitorFundo.ler("C:\\Users\Administrador\Documents\ProcessamentoGrafico\Imagens\montanhas.ptm"); imagem = leitorFundo.getImage(); /* 2) Inicializar Layers, para cada layer da cena */ Layer cena1 = Layer(0,0); cena1.setBackground(&imagem); /* 3) Carregar anima��es objetos do jogo */ PTMReader leitorPersonagem = PTMReader(); leitorPersonagem.ler("C:\\Users\Administrador\Documents\ProcessamentoGrafico\Imagens\T-rex.ptm"); sprite = leitorPersonagem.getImage(); GameObject personagemDireita = GameObject(); GameObject personagemEsquerda = GameObject(); Animation animacaoPersonagemDireita = Animation(); Animation animacaoPersonagemEsquerda = Animation(); for (int x = 0; x < sprite.getHeight()+1; x += 242) { for (int y = 0; y < sprite.getWidth()/2+1; y += 126) { if (x = 242) { Image aux = Image(242, 126); Image *p = &aux; sprite.subImage(p, x, y); animacaoPersonagemDireita.addFrame(&aux); delete p; } else { Image aux = Image(242, 126); Image *p = &aux; sprite.subImage(p, x, y); animacaoPersonagemEsquerda.addFrame(&aux); delete p; } } } personagemDireita.setSprite(animacaoPersonagemDireita); personagemEsquerda.setSprite(animacaoPersonagemEsquerda); /* 4) Inicializar scene, backup, zBuffer e zBuffer2 */ scene = &imagem; Image imagemBackup = imagem; backup = &imagemBackup; int tamanhox = scene->getHeight(); char buffer[1600*900]; char buffer2[1600*900]; zBuffer2 = buffer2; zBuffer = buffer; } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); init(); glutInitWindowSize(imagem.getWidth(), imagem.getHeight()); glutInitWindowPosition(100, 100); glutCreateWindow("Processamento Grafico - GA"); glutDisplayFunc(display); updateScene(1); glutMainLoop(); return 0; /* ISO C requires main to return int. */ //TODO Deletar Ponteiros Criados }<|endoftext|>
<commit_before>// // Created by Per Lange Laursen on 08/03/16. // #include "Pathfinding.h" void Pathfinding::addState(int x1, int y1, std::string roadName, int x2, int y2) { Heureka::Point point1(x1, y1); Heureka::State temp1; temp1.point = point1; temp1.distanceFromStart = std::numeric_limits<double>::max(); temp1.heuristic_distance = std::numeric_limits<double>::max(); Heureka::Point point2(x2, y2); Heureka::State temp2; temp2.point = point2; temp2.distanceFromStart = std::numeric_limits<double>::max(); temp2.heuristic_distance = std::numeric_limits<double>::max(); int index1 = checkIfStateExists(temp1); int index2 = checkIfStateExists(temp2); states[index1].neighbors.push_back(std::make_pair(index2, roadName)); } void Pathfinding::aStar(Heureka::State start, Heureka::State goal) { start.distanceFromStart = 0; start.heuristic_distance = start.point.calcEuclideanDistance(goal.point); openSet.push_back(start); double tempDistanceFromStart; std::list<Heureka::State>::iterator iterator; while (!openSet.empty()) { std::sort(openSet.begin(), openSet.end()); Heureka::State current = openSet.front(); if (current == goal) { reconstructPath(goal); openSet.clear(); break; } openSet.pop_front(); for(std::pair<int, std::string> neighbor : current.neighbors) { if (states[neighbor.first].visited) { continue; } tempDistanceFromStart = current.distanceFromStart + current.point.calcEuclideanDistance(states[neighbor.first].point); if (tempDistanceFromStart >= states[neighbor.first].distanceFromStart) { continue; } states[neighbor.first].cameFrom = getIndex(current); states[neighbor.first].distanceFromStart = tempDistanceFromStart; states[neighbor.first].heuristic_distance = states[neighbor.first].point.calcEuclideanDistance(goal.point); iterator = std::find(openSet.begin(), openSet.end(), states[neighbor.first]); if(iterator != openSet.end()) { (*iterator).cameFrom = states[neighbor.first].cameFrom; (*iterator).distanceFromStart = states[neighbor.first].distanceFromStart; (*iterator).heuristic_distance = states[neighbor.first].heuristic_distance; } else { openSet.push_front(states[neighbor.first]); } } } } void Pathfinding::reconstructPath(Heureka::State goal) { std::vector<std::string> path; int currentIndex = getIndex(goal); std::vector<std::pair<int, std::string>>::iterator iterator; while (currentIndex != -1) { iterator = std::find_if(goal.neighbors.begin(), goal.neighbors.end(), [](const std::pair<int, std::string>& element) { return element.first == goal.cameFrom; }); currentIndex = (*iterator).first; path.insert(path.begin(), (*iterator).second); } std::copy(path.begin(), path.end(), std::ostream_iterator<std::string>(std::cout, "\n")); } int Pathfinding::checkIfStateExists(Heureka::State state) { bool inSet = false; int i = 0; for(Heureka::State s : states) { if(state == s) { inSet = true; } } if(!inSet) { states.push_back(state); i = (int) (states.size() - 1); } return i; } void Pathfinding::aStar(int startIndex, int goalIndex) { Heureka::State start = states[startIndex]; Heureka::State goal = states[goalIndex]; aStar(start, goal); } int Pathfinding::getIndex(Heureka::State s) { int i = 0; for(auto state : states) { if (state == s) return i; ++i; } return -1; } <commit_msg>AStar ready for testing + code cleanup<commit_after>// // Created by Per Lange Laursen on 08/03/16. // #include "Pathfinding.h" void Pathfinding::addState(int x1, int y1, std::string roadName, int x2, int y2) { Heureka::Point point1(x1, y1); Heureka::State temp1; temp1.point = point1; temp1.distanceFromStart = std::numeric_limits<double>::max(); temp1.heuristic_distance = std::numeric_limits<double>::max(); states.push_back(temp1); Heureka::Point point2(x2, y2); Heureka::State temp2; temp2.point = point2; temp2.distanceFromStart = std::numeric_limits<double>::max(); temp2.heuristic_distance = std::numeric_limits<double>::max(); states.push_back(temp2); int index1 = checkIfStateExists(temp1); int index2 = checkIfStateExists(temp2); states[index1].neighbors.push_back(std::make_pair(index2, roadName)); } void Pathfinding::aStar(Heureka::State start, Heureka::State goal) { start.distanceFromStart = 0; start.heuristic_distance = start.point.calcEuclideanDistance(goal.point); openSet.push_back(start); double tempDistanceFromStart; std::list<Heureka::State>::iterator iterator; while (!openSet.empty()) { std::sort(openSet.begin(), openSet.end()); Heureka::State current = openSet.front(); if (current == goal) { reconstructPath(goal); openSet.clear(); break; } openSet.pop_front(); for(std::pair<int, std::string> neighbor : current.neighbors) { if (states[neighbor.first].visited) { continue; } tempDistanceFromStart = current.distanceFromStart + current.point.calcEuclideanDistance(states[neighbor.first].point); if (tempDistanceFromStart >= states[neighbor.first].distanceFromStart) { continue; } states[neighbor.first].cameFrom = getIndex(current); states[neighbor.first].distanceFromStart = tempDistanceFromStart; states[neighbor.first].heuristic_distance = states[neighbor.first].point.calcEuclideanDistance(goal.point); iterator = std::find(openSet.begin(), openSet.end(), states[neighbor.first]); if(iterator != openSet.end()) { (*iterator).cameFrom = states[neighbor.first].cameFrom; (*iterator).distanceFromStart = states[neighbor.first].distanceFromStart; (*iterator).heuristic_distance = states[neighbor.first].heuristic_distance; } else { openSet.push_front(states[neighbor.first]); } } } } void Pathfinding::reconstructPath(Heureka::State goal) { std::vector<std::string> path; int currentIndex = getIndex(goal); std::vector<std::pair<int, std::string>>::iterator iterator; while (currentIndex != -1) { iterator = std::find_if(goal.neighbors.begin(), goal.neighbors.end(), [](const std::pair<int, std::string>& element) { return element.first == goal.cameFrom; }); currentIndex = (*iterator).first; path.insert(path.begin(), (*iterator).second); } std::copy(path.begin(), path.end(), std::ostream_iterator<std::string>(std::cout, "\n")); } int Pathfinding::checkIfStateExists(Heureka::State state) { bool inSet = false; int i = 0; for(Heureka::State s : states) { if(state == s) { inSet = true; } } if(!inSet) { states.push_back(state); i = (int) (states.size() - 1); } return i; } void Pathfinding::aStar(int startIndex, int goalIndex) { Heureka::State start = states[startIndex]; Heureka::State goal = states[goalIndex]; aStar(start, goal); } int Pathfinding::getIndex(Heureka::State s) { int i = 0; for(auto state : states) { if (state == s) return i; ++i; } return -1; } <|endoftext|>
<commit_before>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // CodeEmitterGen uses the descriptions of instructions and their fields to // construct an automated code emitter: a function that, given a MachineInstr, // returns the (currently, 32-bit unsigned) value of the instruction. // //===----------------------------------------------------------------------===// #include "CodeEmitterGen.h" #include "CodeGenTarget.h" #include "Record.h" #include "Support/Debug.h" using namespace llvm; void CodeEmitterGen::run(std::ostream &o) { CodeGenTarget Target; std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); EmitSourceFileHeader("Machine Code Emitter", o); std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::"; //const std::string &Namespace = Inst->getValue("Namespace")->getName(); o << "unsigned " << Target.getName() << "CodeEmitter::" << "getBinaryCodeForInstr(MachineInstr &MI) {\n" << " unsigned Value = 0;\n" << " DEBUG(std::cerr << MI);\n" << " switch (MI.getOpcode()) {\n"; for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end(); I != E; ++I) { Record *R = *I; o << " case " << Namespace << R->getName() << ": {\n" << " DEBUG(std::cerr << \"Emitting " << R->getName() << "\\n\");\n"; BitsInit *BI = R->getValueAsBitsInit("Inst"); unsigned Value = 0; const std::vector<RecordVal> &Vals = R->getValues(); DEBUG(o << " // prefilling: "); // Start by filling in fixed values... for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) { Value |= B->getValue() << (e-i-1); DEBUG(o << B->getValue()); } else { DEBUG(o << "0"); } } DEBUG(o << "\n"); DEBUG(o << " // " << *R->getValue("Inst") << "\n"); o << " Value = " << Value << "U;\n\n"; // Loop over all of the fields in the instruction determining which are the // operands to the instruction. // unsigned op = 0; std::map<std::string, unsigned> OpOrder; std::map<std::string, bool> OpContinuous; for (unsigned i = 0, e = Vals.size(); i != e; ++i) { if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) { // Is the operand continuous? If so, we can just mask and OR it in // instead of doing it bit-by-bit, saving a lot in runtime cost. const BitsInit *InstInit = BI; int beginBitInVar = -1, endBitInVar = -1; int beginBitInInst = -1, endBitInInst = -1; bool continuous = true; for (int bit = InstInit->getNumBits()-1; bit >= 0; --bit) { if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(InstInit->getBit(bit))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // only process the current variable if (VI->getName() != Vals[i].getName()) continue; if (beginBitInVar == -1) beginBitInVar = VBI->getBitNum(); if (endBitInVar == -1) endBitInVar = VBI->getBitNum(); else { if (endBitInVar == (int)VBI->getBitNum() + 1) endBitInVar = VBI->getBitNum(); else { continuous = false; break; } } if (beginBitInInst == -1) beginBitInInst = bit; if (endBitInInst == -1) endBitInInst = bit; else { if (endBitInInst == bit + 1) endBitInInst = bit; else { continuous = false; break; } } // maintain same distance between bits in field and bits in // instruction. if the relative distances stay the same // throughout, if (beginBitInVar - (int)VBI->getBitNum() != beginBitInInst - bit) { continuous = false; break; } } } } // If we have found no bit in "Inst" which comes from this field, then // this is not an operand!! if (beginBitInInst != -1) { o << " // op" << op << ": " << Vals[i].getName() << "\n" << " int64_t op" << op <<" = getMachineOpValue(MI, MI.getOperand("<<op<<"));\n"; //<< " MachineOperand &op" << op <<" = MI.getOperand("<<op<<");\n"; OpOrder[Vals[i].getName()] = op++; DEBUG(o << " // Var: begin = " << beginBitInVar << ", end = " << endBitInVar << "; Inst: begin = " << beginBitInInst << ", end = " << endBitInInst << "\n"); if (continuous) { DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()] << "\n"); // Mask off the right bits // Low mask (ie. shift, if necessary) assert(endBitInVar >= 0 && "Negative shift amount in masking!"); if (endBitInVar != 0) { o << " op" << OpOrder[Vals[i].getName()] << " >>= " << endBitInVar << ";\n"; beginBitInVar -= endBitInVar; endBitInVar = 0; } // High mask o << " op" << OpOrder[Vals[i].getName()] << " &= (1<<" << beginBitInVar+1 << ") - 1;\n"; // Shift the value to the correct place (according to place in inst) assert(endBitInInst >= 0 && "Negative shift amount!"); if (endBitInInst != 0) o << " op" << OpOrder[Vals[i].getName()] << " <<= " << endBitInInst << ";\n"; // Just OR in the result o << " Value |= op" << OpOrder[Vals[i].getName()] << ";\n"; } // otherwise, will be taken care of in the loop below using this // value: OpContinuous[Vals[i].getName()] = continuous; } } } for (unsigned f = 0, e = Vals.size(); f != e; ++f) { if (Vals[f].getPrefix()) { BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue(); // Scan through the field looking for bit initializers of the current // variable... for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) { Init *I = FieldInitializer->getBit(i); if (BitInit *BI = dynamic_cast<BitInit*>(I)) { DEBUG(o << " // bit init: f: " << f << ", i: " << i << "\n"); } else if (UnsetInit *UI = dynamic_cast<UnsetInit*>(I)) { DEBUG(o << " // unset init: f: " << f << ", i: " << i << "\n"); } else if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(I)) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // If the bits of the field are laid out consecutively in the // instruction, then instead of separately ORing in bits, just // mask and shift the entire field for efficiency. if (OpContinuous[VI->getName()]) { // already taken care of in the loop above, thus there is no // need to individually OR in the bits // for debugging, output the regular version anyway, commented DEBUG(o << " // Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"); } else { o << " Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"; } } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) { // FIXME: implement this! o << "FIELD INIT not implemented yet!\n"; } else { o << "Error: UNIMPLEMENTED\n"; } } } } } o << " break;\n" << " }\n"; } o << " default:\n" << " std::cerr << \"Not supported instr: \" << MI << \"\\n\";\n" << " abort();\n" << " }\n" << " return Value;\n" << "}\n"; EmitSourceFileTail(o); } <commit_msg>Deleted commented-out code as we now get namespace directly, add comments<commit_after>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // CodeEmitterGen uses the descriptions of instructions and their fields to // construct an automated code emitter: a function that, given a MachineInstr, // returns the (currently, 32-bit unsigned) value of the instruction. // //===----------------------------------------------------------------------===// #include "CodeEmitterGen.h" #include "CodeGenTarget.h" #include "Record.h" #include "Support/Debug.h" using namespace llvm; void CodeEmitterGen::run(std::ostream &o) { CodeGenTarget Target; std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); EmitSourceFileHeader("Machine Code Emitter", o); std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::"; // Emit function declaration o << "unsigned " << Target.getName() << "CodeEmitter::" << "getBinaryCodeForInstr(MachineInstr &MI) {\n" << " unsigned Value = 0;\n" << " DEBUG(std::cerr << MI);\n" << " switch (MI.getOpcode()) {\n"; // Emit a case statement for each opcode for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end(); I != E; ++I) { Record *R = *I; o << " case " << Namespace << R->getName() << ": {\n" << " DEBUG(std::cerr << \"Emitting " << R->getName() << "\\n\");\n"; BitsInit *BI = R->getValueAsBitsInit("Inst"); unsigned Value = 0; const std::vector<RecordVal> &Vals = R->getValues(); DEBUG(o << " // prefilling: "); // Start by filling in fixed values... for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) { Value |= B->getValue() << (e-i-1); DEBUG(o << B->getValue()); } else { DEBUG(o << "0"); } } DEBUG(o << "\n"); DEBUG(o << " // " << *R->getValue("Inst") << "\n"); o << " Value = " << Value << "U;\n\n"; // Loop over all of the fields in the instruction determining which are the // operands to the instruction. // unsigned op = 0; std::map<std::string, unsigned> OpOrder; std::map<std::string, bool> OpContinuous; for (unsigned i = 0, e = Vals.size(); i != e; ++i) { if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) { // Is the operand continuous? If so, we can just mask and OR it in // instead of doing it bit-by-bit, saving a lot in runtime cost. const BitsInit *InstInit = BI; int beginBitInVar = -1, endBitInVar = -1; int beginBitInInst = -1, endBitInInst = -1; bool continuous = true; for (int bit = InstInit->getNumBits()-1; bit >= 0; --bit) { if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(InstInit->getBit(bit))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // only process the current variable if (VI->getName() != Vals[i].getName()) continue; if (beginBitInVar == -1) beginBitInVar = VBI->getBitNum(); if (endBitInVar == -1) endBitInVar = VBI->getBitNum(); else { if (endBitInVar == (int)VBI->getBitNum() + 1) endBitInVar = VBI->getBitNum(); else { continuous = false; break; } } if (beginBitInInst == -1) beginBitInInst = bit; if (endBitInInst == -1) endBitInInst = bit; else { if (endBitInInst == bit + 1) endBitInInst = bit; else { continuous = false; break; } } // maintain same distance between bits in field and bits in // instruction. if the relative distances stay the same // throughout, if (beginBitInVar - (int)VBI->getBitNum() != beginBitInInst - bit) { continuous = false; break; } } } } // If we have found no bit in "Inst" which comes from this field, then // this is not an operand!! if (beginBitInInst != -1) { o << " // op" << op << ": " << Vals[i].getName() << "\n" << " int64_t op" << op <<" = getMachineOpValue(MI, MI.getOperand("<<op<<"));\n"; //<< " MachineOperand &op" << op <<" = MI.getOperand("<<op<<");\n"; OpOrder[Vals[i].getName()] = op++; DEBUG(o << " // Var: begin = " << beginBitInVar << ", end = " << endBitInVar << "; Inst: begin = " << beginBitInInst << ", end = " << endBitInInst << "\n"); if (continuous) { DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()] << "\n"); // Mask off the right bits // Low mask (ie. shift, if necessary) assert(endBitInVar >= 0 && "Negative shift amount in masking!"); if (endBitInVar != 0) { o << " op" << OpOrder[Vals[i].getName()] << " >>= " << endBitInVar << ";\n"; beginBitInVar -= endBitInVar; endBitInVar = 0; } // High mask o << " op" << OpOrder[Vals[i].getName()] << " &= (1<<" << beginBitInVar+1 << ") - 1;\n"; // Shift the value to the correct place (according to place in inst) assert(endBitInInst >= 0 && "Negative shift amount!"); if (endBitInInst != 0) o << " op" << OpOrder[Vals[i].getName()] << " <<= " << endBitInInst << ";\n"; // Just OR in the result o << " Value |= op" << OpOrder[Vals[i].getName()] << ";\n"; } // otherwise, will be taken care of in the loop below using this // value: OpContinuous[Vals[i].getName()] = continuous; } } } for (unsigned f = 0, e = Vals.size(); f != e; ++f) { if (Vals[f].getPrefix()) { BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue(); // Scan through the field looking for bit initializers of the current // variable... for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) { Init *I = FieldInitializer->getBit(i); if (BitInit *BI = dynamic_cast<BitInit*>(I)) { DEBUG(o << " // bit init: f: " << f << ", i: " << i << "\n"); } else if (UnsetInit *UI = dynamic_cast<UnsetInit*>(I)) { DEBUG(o << " // unset init: f: " << f << ", i: " << i << "\n"); } else if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(I)) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // If the bits of the field are laid out consecutively in the // instruction, then instead of separately ORing in bits, just // mask and shift the entire field for efficiency. if (OpContinuous[VI->getName()]) { // already taken care of in the loop above, thus there is no // need to individually OR in the bits // for debugging, output the regular version anyway, commented DEBUG(o << " // Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"); } else { o << " Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"; } } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) { // FIXME: implement this! o << "FIELD INIT not implemented yet!\n"; } else { o << "Error: UNIMPLEMENTED\n"; } } } } } o << " break;\n" << " }\n"; } o << " default:\n" << " std::cerr << \"Not supported instr: \" << MI << \"\\n\";\n" << " abort();\n" << " }\n" << " return Value;\n" << "}\n"; EmitSourceFileTail(o); } <|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetCmdParser.cpp */ #include "JPetCmdParser.h" #include <iostream> #include "../JPetCommonTools/JPetCommonTools.h" #include "../JPetLoggerInclude.h" #include "../JPetScopeConfigParser/JPetScopeConfigParser.h" #include <stdexcept> JPetCmdParser::JPetCmdParser(): fOptionsDescriptions("Allowed options") { fOptionsDescriptions.add_options() ("help,h", "Displays this help message.") ("type,t", po::value<std::string>()->required()->implicit_value(""), "Type of file: hld, zip, root or scope.") ("file,f", po::value< std::vector<std::string> >()->required()->multitoken(), "File(s) to open.") ("outputPath,o", po::value<std::string>(), "Location to which the outputFiles will be saved.") ("range,r", po::value< std::vector<int> >()->multitoken()->default_value({ -1, -1}, ""), "Range of events to process e.g. -r 1 1000 .") ("param,p", po::value<std::string>(), "xml file with TRB settings used by the unpacker program.") ("runId,i", po::value<int>(), "Run id.") ("progressBar,b", "Progress bar.") ("localDB,l", po::value<std::string>(), "The file to use as the parameter database.") ("localDBCreate,L", po::value<std::string>(), "File name to which the parameter database will be saved."); } JPetCmdParser::~JPetCmdParser() { /**/ } std::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv) { po::variables_map variablesMap; if (argc == 1) { ERROR("No options provided."); std::cerr << getOptionsDescription() << "\n"; throw std::invalid_argument("No options provided."); } po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap); /* print out help */ if (variablesMap.count("help")) { std::cout << getOptionsDescription() << "\n"; exit(0); } po::notify(variablesMap); if (!areCorrectOptions(variablesMap)) { throw std::invalid_argument("Wrong user options provided! Check the log!"); } return generateOptions(variablesMap); } bool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const { /* Parse range of events */ if (variablesMap.count("range")) { if (variablesMap["range"].as< std::vector<int> >().size() != 2) { ERROR("Wrong number of bounds in range."); std::cerr << "Wrong number of bounds in range: " << variablesMap["range"].as< std::vector<int> >().size() << std::endl; return false; } if ( variablesMap["range"].as< std::vector<int> >()[0] > variablesMap["range"].as< std::vector<int> >()[1]) { ERROR("Wrong range of events."); std::cerr << "Wrong range of events." << std::endl; return false; } } if (!isCorrectFileType(getFileType(variablesMap))) { ERROR("Wrong type of file."); std::cerr << "Wrong type of file: " << getFileType(variablesMap) << std::endl; std::cerr << "Possible options: hld, root or scope" << std::endl; return false; } if (isRunNumberSet(variablesMap)) { int l_runId = variablesMap["runId"].as<int>(); if (l_runId <= 0) { ERROR("Run id must be a number larger than 0."); std::cerr << "Run id must be a number larger than 0." << l_runId << std::endl; return false; } } if (isProgressBarSet(variablesMap)) { int l_progressBar = variablesMap["progressBar"].as<int>(); if (l_progressBar != 0 && l_progressBar != 1) { ERROR("Wrong parameter of progressbar."); std::cerr << "Wrong parameter of progressbar: " << l_progressBar << std::endl; return false; } } if (isLocalDBSet(variablesMap)) { std::string localDBName = getLocalDBName(variablesMap); if ( !JPetCommonTools::ifFileExisting(localDBName) ) { ERROR("File : " + localDBName + " does not exist."); std::cerr << "File : " << localDBName << " does not exist" << std::endl; return false; } } std::vector<std::string> fileNames(variablesMap["file"].as< std::vector<std::string> >()); for (unsigned int i = 0; i < fileNames.size(); i++) { if ( ! JPetCommonTools::ifFileExisting(fileNames[i]) ) { std::string fileName = fileNames[i]; ERROR("File : " + fileName + " does not exist."); std::cerr << "File : " << fileNames[i] << " does not exist" << std::endl; return false; } } /// The run number option is neclegted if the input file is set as "scope" if (isRunNumberSet(variablesMap)) { if (getFileType(variablesMap) == "scope") { WARNING("Run number was specified but the input file type is a scope!\n The run number will be ignored!"); } } /// Check if output path exists if (isOutputPath(variablesMap)) { auto dir = getOutputPath(variablesMap); if (!JPetCommonTools::isDirectory(dir)) { ERROR("Output directory : " + dir + " does not exist."); std::cerr << "Output directory: " << dir << " does not exist" << std::endl; return false; } } return true; } std::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const { std::map<std::string, std::string> options = JPetOptions::getDefaultOptions(); auto fileType = getFileType(optsMap); if (isCorrectFileType(fileType)) { options.at("inputFileType") = fileType; } if (isOutputPath(optsMap)) { options.at("outputPath") = JPetCommonTools::appendSlashToPathIfAbsent(getOutputPath(optsMap)); } if (isRunNumberSet(optsMap)) { options.at("runId") = std::to_string(getRunNumber(optsMap)); } if (isProgressBarSet(optsMap)) { options.at("progressBar") = "true"; } if (isLocalDBSet(optsMap)) { options["localDB"] = getLocalDBName(optsMap); } if (isLocalDBCreateSet(optsMap)) { options["localDBCreate"] = getLocalDBCreateName(optsMap); } auto firstEvent = getLowerEventBound(optsMap); auto lastEvent = getHigherEventBound(optsMap); if (firstEvent >= 0) options.at("firstEvent") = std::to_string(firstEvent); if (lastEvent >= 0) options.at("lastEvent") = std::to_string(lastEvent); auto files = getFileNames(optsMap); std::vector<JPetOptions> optionContainer; /// In case of scope there is one special input file /// which is a json config file which must be parsed. /// Based on its content the set of input directories are generated. /// The input directories contain data files. /// The config input file name also should be stored in a special option field. if (fileType == "scope") { assert(files.size() == 1); /// there should be only file which is config. auto configFileName = files.front(); options.at("scopeConfigFile") = configFileName; JPetScopeConfigParser scopeConfigParser; /// The scope module must use a fake input file name which will be used to /// produce the correct output file names by the following modules. /// At the same time, the input directory with true input files must be /// also added. The container of pairs <directory, fileName> is generated /// based on the content of the configuration file. JPetScopeConfigParser::DirFileContainer dirsAndFiles = scopeConfigParser.getInputDirectoriesAndFakeInputFiles(configFileName); for (auto dirAndFile : dirsAndFiles) { options.at("scopeInputDirectory") = dirAndFile.first; options.at("inputFile") = dirAndFile.second; optionContainer.push_back(JPetOptions(options)); } } else { /// for every single input file we create separate JPetOptions for (auto file : files) { options.at("inputFile") = file; optionContainer.push_back(JPetOptions(options)); } } return optionContainer; } //#endif /* __CINT__ */ <commit_msg>Added zip phrase to function in JPetCmdParser<commit_after>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetCmdParser.cpp */ #include "JPetCmdParser.h" #include <iostream> #include "../JPetCommonTools/JPetCommonTools.h" #include "../JPetLoggerInclude.h" #include "../JPetScopeConfigParser/JPetScopeConfigParser.h" #include <stdexcept> JPetCmdParser::JPetCmdParser(): fOptionsDescriptions("Allowed options") { fOptionsDescriptions.add_options() ("help,h", "Displays this help message.") ("type,t", po::value<std::string>()->required()->implicit_value(""), "Type of file: hld, zip, root or scope.") ("file,f", po::value< std::vector<std::string> >()->required()->multitoken(), "File(s) to open.") ("outputPath,o", po::value<std::string>(), "Location to which the outputFiles will be saved.") ("range,r", po::value< std::vector<int> >()->multitoken()->default_value({ -1, -1}, ""), "Range of events to process e.g. -r 1 1000 .") ("param,p", po::value<std::string>(), "xml file with TRB settings used by the unpacker program.") ("runId,i", po::value<int>(), "Run id.") ("progressBar,b", "Progress bar.") ("localDB,l", po::value<std::string>(), "The file to use as the parameter database.") ("localDBCreate,L", po::value<std::string>(), "File name to which the parameter database will be saved."); } JPetCmdParser::~JPetCmdParser() { /**/ } std::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv) { po::variables_map variablesMap; if (argc == 1) { ERROR("No options provided."); std::cerr << getOptionsDescription() << "\n"; throw std::invalid_argument("No options provided."); } po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap); /* print out help */ if (variablesMap.count("help")) { std::cout << getOptionsDescription() << "\n"; exit(0); } po::notify(variablesMap); if (!areCorrectOptions(variablesMap)) { throw std::invalid_argument("Wrong user options provided! Check the log!"); } return generateOptions(variablesMap); } bool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const { /* Parse range of events */ if (variablesMap.count("range")) { if (variablesMap["range"].as< std::vector<int> >().size() != 2) { ERROR("Wrong number of bounds in range."); std::cerr << "Wrong number of bounds in range: " << variablesMap["range"].as< std::vector<int> >().size() << std::endl; return false; } if ( variablesMap["range"].as< std::vector<int> >()[0] > variablesMap["range"].as< std::vector<int> >()[1]) { ERROR("Wrong range of events."); std::cerr << "Wrong range of events." << std::endl; return false; } } if (!isCorrectFileType(getFileType(variablesMap))) { ERROR("Wrong type of file."); std::cerr << "Wrong type of file: " << getFileType(variablesMap) << std::endl; std::cerr << "Possible options: hld, zip, root or scope" << std::endl; return false; } if (isRunNumberSet(variablesMap)) { int l_runId = variablesMap["runId"].as<int>(); if (l_runId <= 0) { ERROR("Run id must be a number larger than 0."); std::cerr << "Run id must be a number larger than 0." << l_runId << std::endl; return false; } } if (isProgressBarSet(variablesMap)) { int l_progressBar = variablesMap["progressBar"].as<int>(); if (l_progressBar != 0 && l_progressBar != 1) { ERROR("Wrong parameter of progressbar."); std::cerr << "Wrong parameter of progressbar: " << l_progressBar << std::endl; return false; } } if (isLocalDBSet(variablesMap)) { std::string localDBName = getLocalDBName(variablesMap); if ( !JPetCommonTools::ifFileExisting(localDBName) ) { ERROR("File : " + localDBName + " does not exist."); std::cerr << "File : " << localDBName << " does not exist" << std::endl; return false; } } std::vector<std::string> fileNames(variablesMap["file"].as< std::vector<std::string> >()); for (unsigned int i = 0; i < fileNames.size(); i++) { if ( ! JPetCommonTools::ifFileExisting(fileNames[i]) ) { std::string fileName = fileNames[i]; ERROR("File : " + fileName + " does not exist."); std::cerr << "File : " << fileNames[i] << " does not exist" << std::endl; return false; } } /// The run number option is neclegted if the input file is set as "scope" if (isRunNumberSet(variablesMap)) { if (getFileType(variablesMap) == "scope") { WARNING("Run number was specified but the input file type is a scope!\n The run number will be ignored!"); } } /// Check if output path exists if (isOutputPath(variablesMap)) { auto dir = getOutputPath(variablesMap); if (!JPetCommonTools::isDirectory(dir)) { ERROR("Output directory : " + dir + " does not exist."); std::cerr << "Output directory: " << dir << " does not exist" << std::endl; return false; } } return true; } std::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const { std::map<std::string, std::string> options = JPetOptions::getDefaultOptions(); auto fileType = getFileType(optsMap); if (isCorrectFileType(fileType)) { options.at("inputFileType") = fileType; } if (isOutputPath(optsMap)) { options.at("outputPath") = JPetCommonTools::appendSlashToPathIfAbsent(getOutputPath(optsMap)); } if (isRunNumberSet(optsMap)) { options.at("runId") = std::to_string(getRunNumber(optsMap)); } if (isProgressBarSet(optsMap)) { options.at("progressBar") = "true"; } if (isLocalDBSet(optsMap)) { options["localDB"] = getLocalDBName(optsMap); } if (isLocalDBCreateSet(optsMap)) { options["localDBCreate"] = getLocalDBCreateName(optsMap); } auto firstEvent = getLowerEventBound(optsMap); auto lastEvent = getHigherEventBound(optsMap); if (firstEvent >= 0) options.at("firstEvent") = std::to_string(firstEvent); if (lastEvent >= 0) options.at("lastEvent") = std::to_string(lastEvent); auto files = getFileNames(optsMap); std::vector<JPetOptions> optionContainer; /// In case of scope there is one special input file /// which is a json config file which must be parsed. /// Based on its content the set of input directories are generated. /// The input directories contain data files. /// The config input file name also should be stored in a special option field. if (fileType == "scope") { assert(files.size() == 1); /// there should be only file which is config. auto configFileName = files.front(); options.at("scopeConfigFile") = configFileName; JPetScopeConfigParser scopeConfigParser; /// The scope module must use a fake input file name which will be used to /// produce the correct output file names by the following modules. /// At the same time, the input directory with true input files must be /// also added. The container of pairs <directory, fileName> is generated /// based on the content of the configuration file. JPetScopeConfigParser::DirFileContainer dirsAndFiles = scopeConfigParser.getInputDirectoriesAndFakeInputFiles(configFileName); for (auto dirAndFile : dirsAndFiles) { options.at("scopeInputDirectory") = dirAndFile.first; options.at("inputFile") = dirAndFile.second; optionContainer.push_back(JPetOptions(options)); } } else { /// for every single input file we create separate JPetOptions for (auto file : files) { options.at("inputFile") = file; optionContainer.push_back(JPetOptions(options)); } } return optionContainer; } //#endif /* __CINT__ */ <|endoftext|>
<commit_before>#pragma once #include "diff_patch_common.hpp" #include "../base/assert.hpp" #include "../base/base.hpp" #include "../std/algorithm.hpp" #include "../std/unordered_map.hpp" #include "../std/vector.hpp" namespace diff { template <class PatchWriterT, typename SizeT = uint64_t> class PatchCoder { public: typedef SizeT size_type; explicit PatchCoder(PatchWriterT & patchWriter) : m_LastOperation(COPY), m_LastOpCode(0), m_PatchWriter(patchWriter) { } void Delete(size_type n) { if (n != 0) Op(DELETE, n); } void Copy(size_type n) { if (n != 0) Op(COPY, n); } template <typename TIter> void Insert(TIter it, size_type n) { if (n != 0) { Op(INSERT, n); m_PatchWriter.WriteData(it, n); } } void Finalize() { WriteLasOp(); } private: void Op(Operation op, size_type n) { if (m_LastOperation == op) { m_LastOpCode += (n << 1); return; } WriteLasOp(); m_LastOpCode = (n << 1) | ((m_LastOperation + 1) % 3 == op ? 0 : 1); m_LastOperation = op; } void WriteLasOp() { if (m_LastOpCode != 0) m_PatchWriter.WriteOperation(m_LastOpCode); else CHECK_EQUAL(m_LastOperation, COPY, ()); // "We were just initialized." } Operation m_LastOperation; size_type m_LastOpCode; PatchWriterT & m_PatchWriter; }; // Find minimal patch, with no more than maxPatchSize edited values, that transforms A into B. // Returns the length of the minimal patch, or -1 if no such patch found. // Intermediate information is saved into tmpSink and can be used later to restore // the resulting patch. template < typename TSignedWord, // Signed word, capable of storing position in text. class TSrcVector, // Source data (A). class TDstVector, // Destination data (B). class TTmpFileSink // Sink to store temporary information. > TSignedWord DiffMyersSimple(TSrcVector const & A, TDstVector const & B, TSignedWord maxPatchSize, TTmpFileSink & tmpSink) { ASSERT_GREATER(maxPatchSize, 0, ()); vector<TSignedWord> V(2 * maxPatchSize + 1); for (TSignedWord d = 0; d <= maxPatchSize; ++d) { for (TSignedWord k = -d; k <= d; k += 2) { TSignedWord x; if (k == -d || (k != d && V[maxPatchSize + k - 1] < V[maxPatchSize + k + 1])) x = V[maxPatchSize + k + 1]; else x = V[maxPatchSize + k - 1] + 1; while (x < static_cast<TSignedWord>(A.size()) && x - k < static_cast<TSignedWord>(B.size()) && A[x] == B[x - k]) ++x; V[maxPatchSize + k] = x; if (x == static_cast<TSignedWord>(A.size()) && x - k == static_cast<TSignedWord>(B.size())) return d; } tmpSink.Write(&V[maxPatchSize + d], (2 * d + 1) * sizeof(TSignedWord)); } return -1; } // Differ that just replaces old with new, with the only optimization of skipping equal values // at the beginning and at the end. class SimpleReplaceDiffer { public: template <typename SrcIterT, typename DstIterT, class PatchCoderT> void Diff(SrcIterT srcBeg, SrcIterT srcEnd, DstIterT dstBeg, DstIterT dstEnd, PatchCoderT & patchCoder) { typename PatchCoderT::size_type begCopy = 0; for (; srcBeg != srcEnd && dstBeg != dstEnd && *srcBeg == *dstBeg; ++srcBeg, ++dstBeg) ++begCopy; patchCoder.Copy(begCopy); typename PatchCoderT::size_type endCopy = 0; for (; srcBeg != srcEnd && dstBeg != dstEnd && *(srcEnd-1) == *(dstEnd-1); --srcEnd, --dstEnd) ++endCopy; patchCoder.Delete(srcEnd - srcBeg); patchCoder.Insert(dstBeg, dstEnd - dstBeg); patchCoder.Copy(endCopy); } }; // Given FineGrainedDiff and rolling Hasher, DiffWithRollingHash splits the source sequence // into chunks of size m_BlockSize, finds equal chunks in the destination sequence, using rolling // hash to find good candidates, writes info about equal chunks into patchCoder and for everything // between equal chunks, calls FineGrainedDiff::Diff(). template <class FineGrainedDiffT, class HasherT, class HashPosMultiMapT = unordered_multimap<typename HasherT::hash_type, uint64_t> > class RollingHashDiffer { public: explicit RollingHashDiffer(size_t blockSize, FineGrainedDiffT const & fineGrainedDiff = FineGrainedDiffT()) : m_FineGrainedDiff(fineGrainedDiff), m_BlockSize(blockSize) {} template <typename SrcIterT, typename DstIterT, class PatchCoderT> void Diff(SrcIterT const srcBeg, SrcIterT const srcEnd, DstIterT const dstBeg, DstIterT const dstEnd, PatchCoderT & patchCoder) { if (srcEnd - srcBeg < m_BlockSize || dstEnd - dstBeg < m_BlockSize) { m_FineGrainedDiff.Diff(srcBeg, srcEnd, dstBeg, dstEnd, patchCoder); return; } HasherT hasher; HashPosMultiMapT srcHashes; for (SrcIterT src = srcBeg; srcEnd - src >= m_BlockSize; src += m_BlockSize) srcHashes.insert(HashPosMultiMapValue(hasher.Init(src, m_BlockSize), src - srcBeg)); SrcIterT srcLastDiff = srcBeg; DstIterT dst = dstBeg, dstNext = dstBeg + m_BlockSize, dstLastDiff = dstBeg; hash_type h = hasher.Init(dst, m_BlockSize); while (dstNext != dstEnd) { pair<HashPosMultiMapIterator, HashPosMultiMapIterator> iters = srcHashes.equal_range(h); if (iters.first != iters.second) { pos_type const srcLastDiffPos = srcLastDiff - srcBeg; HashPosMultiMapIterator it = srcHashes.end(); for (HashPosMultiMapIterator i = iters.first; i != iters.second; ++i) if (i->second >= srcLastDiffPos && (it == srcHashes.end() || i->second < it->second)) it = i; if (it != srcHashes.end() && equal(srcBeg + it->second, srcBeg + it->second + m_BlockSize, dst)) { pos_type srcBlockEqualPos = it->second; m_FineGrainedDiff.Diff(srcLastDiff, srcBeg + srcBlockEqualPos, dstLastDiff, dst, patchCoder); patchCoder.Copy(m_BlockSize); srcLastDiff = srcBeg + srcBlockEqualPos + m_BlockSize; dst = dstLastDiff = dstNext; if (dstEnd - dstNext < m_BlockSize) break; dstNext = dst + m_BlockSize; h = hasher.Init(dst, m_BlockSize); continue; } } h = hasher.Scroll(*(dst++), *(dstNext++)); } if (srcLastDiff != srcEnd || dstLastDiff != dstEnd) m_FineGrainedDiff.Diff(srcLastDiff, srcEnd, dstLastDiff, dstEnd, patchCoder); } private: typedef typename HasherT::hash_type hash_type; typedef typename HashPosMultiMapT::value_type::second_type pos_type; typedef typename HashPosMultiMapT::const_iterator HashPosMultiMapIterator; typedef typename HashPosMultiMapT::value_type HashPosMultiMapValue; FineGrainedDiffT m_FineGrainedDiff; HasherT m_Hasher; size_t m_BlockSize; }; } <commit_msg>[coding] Fixed buffer-overflow in MyersSimpleDiff() algorithm.<commit_after>#pragma once #include "diff_patch_common.hpp" #include "../base/assert.hpp" #include "../base/base.hpp" #include "../std/algorithm.hpp" #include "../std/unordered_map.hpp" #include "../std/vector.hpp" namespace diff { template <class PatchWriterT, typename SizeT = uint64_t> class PatchCoder { public: typedef SizeT size_type; explicit PatchCoder(PatchWriterT & patchWriter) : m_LastOperation(COPY), m_LastOpCode(0), m_PatchWriter(patchWriter) { } void Delete(size_type n) { if (n != 0) Op(DELETE, n); } void Copy(size_type n) { if (n != 0) Op(COPY, n); } template <typename TIter> void Insert(TIter it, size_type n) { if (n != 0) { Op(INSERT, n); m_PatchWriter.WriteData(it, n); } } void Finalize() { WriteLasOp(); } private: void Op(Operation op, size_type n) { if (m_LastOperation == op) { m_LastOpCode += (n << 1); return; } WriteLasOp(); m_LastOpCode = (n << 1) | ((m_LastOperation + 1) % 3 == op ? 0 : 1); m_LastOperation = op; } void WriteLasOp() { if (m_LastOpCode != 0) m_PatchWriter.WriteOperation(m_LastOpCode); else CHECK_EQUAL(m_LastOperation, COPY, ()); // "We were just initialized." } Operation m_LastOperation; size_type m_LastOpCode; PatchWriterT & m_PatchWriter; }; // Find minimal patch, with no more than maxPatchSize edited values, that transforms A into B. // Returns the length of the minimal patch, or -1 if no such patch found. // Intermediate information is saved into tmpSink and can be used later to restore // the resulting patch. template < typename TSignedWord, // Signed word, capable of storing position in text. class TSrcVector, // Source data (A). class TDstVector, // Destination data (B). class TTmpFileSink // Sink to store temporary information. > TSignedWord DiffMyersSimple(TSrcVector const & A, TDstVector const & B, TSignedWord maxPatchSize, TTmpFileSink & tmpSink) { ASSERT_GREATER(maxPatchSize, 0, ()); vector<TSignedWord> V(2 * maxPatchSize + 1); for (TSignedWord d = 0; d <= maxPatchSize; ++d) { for (TSignedWord k = -d; k <= d; k += 2) { TSignedWord x; if (k == -d || (k != d && V[maxPatchSize + k - 1] < V[maxPatchSize + k + 1])) x = V[maxPatchSize + k + 1]; else x = V[maxPatchSize + k - 1] + 1; while (x < static_cast<TSignedWord>(A.size()) && x - k < static_cast<TSignedWord>(B.size()) && A[x] == B[x - k]) ++x; V[maxPatchSize + k] = x; if (x == static_cast<TSignedWord>(A.size()) && x - k == static_cast<TSignedWord>(B.size())) return d; } tmpSink.Write(&V[maxPatchSize - d], (2 * d + 1) * sizeof(TSignedWord)); } return -1; } // Differ that just replaces old with new, with the only optimization of skipping equal values // at the beginning and at the end. class SimpleReplaceDiffer { public: template <typename SrcIterT, typename DstIterT, class PatchCoderT> void Diff(SrcIterT srcBeg, SrcIterT srcEnd, DstIterT dstBeg, DstIterT dstEnd, PatchCoderT & patchCoder) { typename PatchCoderT::size_type begCopy = 0; for (; srcBeg != srcEnd && dstBeg != dstEnd && *srcBeg == *dstBeg; ++srcBeg, ++dstBeg) ++begCopy; patchCoder.Copy(begCopy); typename PatchCoderT::size_type endCopy = 0; for (; srcBeg != srcEnd && dstBeg != dstEnd && *(srcEnd-1) == *(dstEnd-1); --srcEnd, --dstEnd) ++endCopy; patchCoder.Delete(srcEnd - srcBeg); patchCoder.Insert(dstBeg, dstEnd - dstBeg); patchCoder.Copy(endCopy); } }; // Given FineGrainedDiff and rolling Hasher, DiffWithRollingHash splits the source sequence // into chunks of size m_BlockSize, finds equal chunks in the destination sequence, using rolling // hash to find good candidates, writes info about equal chunks into patchCoder and for everything // between equal chunks, calls FineGrainedDiff::Diff(). template <class FineGrainedDiffT, class HasherT, class HashPosMultiMapT = unordered_multimap<typename HasherT::hash_type, uint64_t> > class RollingHashDiffer { public: explicit RollingHashDiffer(size_t blockSize, FineGrainedDiffT const & fineGrainedDiff = FineGrainedDiffT()) : m_FineGrainedDiff(fineGrainedDiff), m_BlockSize(blockSize) {} template <typename SrcIterT, typename DstIterT, class PatchCoderT> void Diff(SrcIterT const srcBeg, SrcIterT const srcEnd, DstIterT const dstBeg, DstIterT const dstEnd, PatchCoderT & patchCoder) { if (srcEnd - srcBeg < m_BlockSize || dstEnd - dstBeg < m_BlockSize) { m_FineGrainedDiff.Diff(srcBeg, srcEnd, dstBeg, dstEnd, patchCoder); return; } HasherT hasher; HashPosMultiMapT srcHashes; for (SrcIterT src = srcBeg; srcEnd - src >= m_BlockSize; src += m_BlockSize) srcHashes.insert(HashPosMultiMapValue(hasher.Init(src, m_BlockSize), src - srcBeg)); SrcIterT srcLastDiff = srcBeg; DstIterT dst = dstBeg, dstNext = dstBeg + m_BlockSize, dstLastDiff = dstBeg; hash_type h = hasher.Init(dst, m_BlockSize); while (dstNext != dstEnd) { pair<HashPosMultiMapIterator, HashPosMultiMapIterator> iters = srcHashes.equal_range(h); if (iters.first != iters.second) { pos_type const srcLastDiffPos = srcLastDiff - srcBeg; HashPosMultiMapIterator it = srcHashes.end(); for (HashPosMultiMapIterator i = iters.first; i != iters.second; ++i) if (i->second >= srcLastDiffPos && (it == srcHashes.end() || i->second < it->second)) it = i; if (it != srcHashes.end() && equal(srcBeg + it->second, srcBeg + it->second + m_BlockSize, dst)) { pos_type srcBlockEqualPos = it->second; m_FineGrainedDiff.Diff(srcLastDiff, srcBeg + srcBlockEqualPos, dstLastDiff, dst, patchCoder); patchCoder.Copy(m_BlockSize); srcLastDiff = srcBeg + srcBlockEqualPos + m_BlockSize; dst = dstLastDiff = dstNext; if (dstEnd - dstNext < m_BlockSize) break; dstNext = dst + m_BlockSize; h = hasher.Init(dst, m_BlockSize); continue; } } h = hasher.Scroll(*(dst++), *(dstNext++)); } if (srcLastDiff != srcEnd || dstLastDiff != dstEnd) m_FineGrainedDiff.Diff(srcLastDiff, srcEnd, dstLastDiff, dstEnd, patchCoder); } private: typedef typename HasherT::hash_type hash_type; typedef typename HashPosMultiMapT::value_type::second_type pos_type; typedef typename HashPosMultiMapT::const_iterator HashPosMultiMapIterator; typedef typename HashPosMultiMapT::value_type HashPosMultiMapValue; FineGrainedDiffT m_FineGrainedDiff; HasherT m_Hasher; size_t m_BlockSize; }; } <|endoftext|>
<commit_before>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #define NONADAPTIVE #undef ADAPTIVE #define _WAVELETTL_USE_TBASIS 1 #define _WAVELETTL_USE_TFRAME 1 #define _DIM 2 #include <iostream> #include <utils/fixed_array1d.h> #include <utils/multiindex.h> #include <numerics/bvp.h> #include <numerics/corner_singularity.h> #include <interval/p_basis.h> #include <interval/pq_frame.h> #include <Ldomain/ldomain_frame_index.h> #include <Ldomain/ldomain_frame.h> #include <Ldomain/ldomain_frame_evaluate.h> #include <galerkin/ldomain_frame_equation.h> //#include <galerkin/cached_lproblem.h> #include <adaptive/compression.h> #include <adaptive/apply.h> #include <adaptive/cdd2.h> #include "ldomain_solutions.h" using namespace std; using namespace WaveletTL; using MathTL::FixedArray1D; class myRHS : public Function<2,double> { public: virtual ~myRHS() {}; double value(const Point<2>& p, const unsigned int component = 0) const { return 2*M_PI*M_PI*sin(M_PI*p[0])*sin(M_PI*p[1]); } void vector_value(const Point<2>& p, Vector<double>& values) const { values[0] = value(p); } }; class mySolution : public Function<2,double> { public: virtual ~mySolution() {}; double value(const Point<2>& p, const unsigned int component = 0) const { return sin(M_PI*p[0])*sin(M_PI*p[1]); } void vector_value(const Point<2>& p, Vector<double>& values) const { values[0] = value(p); } }; class mySum : public Function<2,double> { public: virtual ~mySum() {}; double value(const Point<2>& p, const unsigned int component = 0) const { return (1+2*M_PI*M_PI)*sin(M_PI*p[0])*sin(M_PI*p[1]); } void vector_value(const Point<2>& p, Vector<double>& values) const { values[0] = value(p); } }; int main(){ cout << "testing L-domain quarklet frame" << endl; const int d = 3; const int dT = 3; const int dim = 2; const int jmax = 6; const int pmax = 0; typedef PQFrame<d,dT> Frame1d; Frame1d frame1d(false,false); typedef LDomainFrame<Frame1d> Frame; typedef Frame::Index Index; //Frame frame(frame1d); Frame frame; frame.set_jpmax(jmax,pmax); //CornerSingularity uexact1(Point<2>(0,0), 0.5, 1.5); mySolution uexact1; //CornerSingularityRHS rhs1(Point<2>(0,0), 0.5, 1.5); //Fnorm=0? //Vector<double> val(1, "1.0"); //ConstantFunction<dim> rhs1(val); myRHS rhs1; PoissonBVP<dim> poisson1(&rhs1); LDomainFrameEquation<Frame1d,Frame> eq(&poisson1, false); eq.set_jpmax(jmax,pmax,false); Index testindex=frame.get_quarklet(71); #if 0 //plot rhs and exact solution Array1D<Point<dim,int> > corners; corners.resize(3); corners[0][0]=-1; corners[0][1]=0; corners[1][0]=-1; corners[1][1]=-1; corners[2][0]=0; corners[2][1]=-1; std::ofstream osrhs("rhs.m"); std::ofstream osuexact("uexact.m"); for(int i=0;i<3;i++){ Point<2> q0(corners[i][0],corners[i][1]); Point<2> q1(corners[i][0]+1,corners[i][1]+1); Grid<2> mygrid(q0,q1,100); SampledMapping<2> smrhs(mygrid, rhs1); SampledMapping<2> smuexact(mygrid, uexact1); smrhs.matlab_output(osrhs); smuexact.matlab_output(osuexact); osrhs << "surf(x,y,z)"<<endl; osuexact<<"surf(x,y,z)"<<endl; osrhs << "hold on;" << endl; osuexact<<"hold on;"<<endl; } osrhs << "view(30,55);"<<endl; osrhs << "hold off;" << endl; osuexact << "view(30,55);"<<endl; osuexact<<"hold off;"<<endl; osrhs.close(); osuexact.close(); cout << "rhs and uexact plotted" << endl; #endif #if 1 //setup index set //Vector<double> a; //a.resize(eq.frame().degrees_of_freedom(),true); //setup Index set set<Index> Lambda; MultiIndex<int,dim> p;p[0]=0;p[1]=0; Index lambda = eq.frame().first_generator(eq.frame().j0(), p); int zaehler=0; for (int l = 0; l < eq.frame().degrees_of_freedom(); l++) { //cout << lambda << " : "<<lambda.number()<< endl; //cout << lambda << " : " << eq.a(lambda,lambda) << endl; //if(multi_degree(lambda.e())<1 && lambda.patch()<4){ Lambda.insert(lambda); ++zaehler; //} if(lambda==eq.frame().last_quarklet(jmax, p)){ ++p; lambda=eq.frame().first_generator(eq.frame().j0(), p); } else //a(zaehler)=eq.a(eq.frame().get_quarklet(126),lambda); ++lambda; } //a.matlab_output("a","a"); cout << "size of Lambda: " << zaehler << endl; #endif #if 0 //test methods of ldomain_frame_equation cout << "testindex: "<<testindex<<endl; cout << "a(lambda_0,lambda_0) : "<<eq.a(testindex,testindex) << endl; cout << "f(lambda_0): "<<eq.f(testindex)<<endl; cout << "D(lambda_0): "<<eq.D(testindex)<<endl; //cout << "F_norm: "<<eq.F_norm() << endl; //cout << "normA: "<<eq.norm_A() <<endl; //cout << "normAinv: "<<eq.norm_Ainv() << endl; #endif #ifdef NONADAPTIVE //setup stiffness matrix and rhs SparseMatrix<double> A; setup_stiffness_matrix(eq,Lambda,A); cout << "setup stiffness matrix done" << endl; Vector<double> F; setup_righthand_side(eq, Lambda, F); A.compress(1e-14); F.compress(1e-14); A.matlab_output("A","A",0,A.row_dimension()-1,A.column_dimension()-1 ); F.matlab_output("F","F"); Vector<double> x(Lambda.size()); x =0; //richardson iteration unsigned int iterations; const int maxiterations = 9999; const double omega = 2.0 / (eq.norm_A() + 1.0/eq.norm_Ainv()); cout << "omega: "<<omega<<endl; Richardson(A,F,x,omega,1e-6,maxiterations,iterations); //CG(A,F,x,1e-8,maxiterations,iterations); cout << "iterations:" << iterations << endl; //plot solution InfiniteVector<double,Index> u; unsigned int i2 = 0; for (set<Index>::const_iterator it = Lambda.begin(); it != Lambda.end(); ++it, ++i2){ u.set_coefficient(*it, x[i2]); } //u.COARSE(1e-6,v); u.scale(&eq, -1); Array1D<SampledMapping<dim> > eval(3); eval=eq.frame().evaluate(u,6); std::ofstream os2("solution_na.m"); for(int i=0;i<3;i++){ eval[i].matlab_output(os2); os2 << "surf(x,y,z);" << endl; os2 << "hold on;" << endl; } os2 << "view(30,55);"<<endl; os2 << "hold off" << endl; os2.close(); #endif #if 1 //test bilinearform const int resolution=6; Index testindex1(testindex); Index testindex2=eq.frame().get_quarklet(192); Array1D<SampledMapping<dim> > eval1(3); Array1D<SampledMapping<dim> > eval2(3); eval1=frame.evaluate(testindex1,resolution); eval2=frame.evaluate(testindex2,resolution); std::ofstream os("testa.m"); os<<"Iexakt="<<eq.a(testindex1,testindex2)<<endl; os<<"I=0;"<<endl; for(int i=0;i<3;i++){ eval1[i].matlab_output(os); os<<"z1=z;"<<endl; eval2[i].matlab_output(os); os<<"z2=z;"<<endl; os<<"xx=x(1,:);"<<endl; os<<"yy=y'(1,:);"<<endl; os<<"[gx1,gy1]=gradient(z1,2^-"<<resolution<<",2^-"<<resolution<<");"<<endl; os<<"[gx2,gy2]=gradient(z2,2^-"<<resolution<<",2^-"<<resolution<<");"<<endl; os<<"L=gx1.*gx2.+gy1.*gy2;"<<endl; os<<"I=I+trapz(yy,trapz(xx,L,2)');"<<endl; } os<<"I"<<endl; os<<"relative_error=abs(I-Iexakt)/Iexakt"<<endl; os.close(); #endif #if 1 //test rhs const int resolution2=6; Index testindex3(testindex); Array1D<SampledMapping<dim> > eval3(3); eval3=frame.evaluate(testindex3, resolution2); Array1D<Point<dim,int> > corners; corners.resize(3); corners[0][0]=-1; corners[0][1]=0; corners[1][0]=-1; corners[1][1]=-1; corners[2][0]=0; corners[2][1]=-1; std::ofstream os3("testf.m"); os3<<"Iexakt="<<eq.f(testindex)<<endl; os3<<"I=0;"<<endl; for(int i=0;i<3;i++){ eval3[i].matlab_output(os3); os3<<"zalt=z;"<<endl; Point<2> q0(corners[i][0],corners[i][1]); Point<2> q1(corners[i][0]+1,corners[i][1]+1); Grid<2> mygrid(q0,q1,pow(2,resolution2)); SampledMapping<2> smf(mygrid, rhs1); smf.matlab_output(os3); os3<<"z=z.*zalt;"<<endl; os3<<"xx=x(1,:);"<<endl; os3<<"yy=y'(1,:);"<<endl; os3<<"I=I+trapz(yy,trapz(xx,z,2)');"<<endl; } os3<<"I"<<endl; os3<<"relative_error=abs(I-Iexakt)/Iexakt"<<endl; os3.close(); #endif #if 1 //plot one function Array1D<SampledMapping<dim> > evalf(3); //Index ind=frame.get_quarklet(159); //0-26:generatoren auf patches, //27-32:überlappende generatoren, indiziert mit p=3,4 //33:überlappendes wavelet //34:nicht-überlappendes wavelet cout << "evaluate quarklet with index " << testindex << endl; evalf=frame.evaluate(testindex,6); std::ofstream osf("Ldomainoutput.m"); osf << "clf;" << endl; osf << "axis([-1 1 -1 1 0 1]);" << endl; for(int i=0;i<3;i++){ evalf[i].matlab_output(osf); osf << "surf(x,y,z);" << endl; osf << "hold on;" << endl; } osf << "view(30,55);"<<endl; osf << "hold off" << endl; osf.close(); #endif return 0; }<commit_msg>added test file<commit_after>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #undef NONADAPTIVE #define ADAPTIVE #define _WAVELETTL_USE_TBASIS 1 #define _WAVELETTL_USE_TFRAME 1 #define _DIM 2 #include <iostream> #include <utils/fixed_array1d.h> #include <utils/multiindex.h> #include <numerics/bvp.h> #include <numerics/corner_singularity.h> #include <interval/p_basis.h> #include <interval/pq_frame.h> #include <Ldomain/ldomain_frame_index.h> #include <Ldomain/ldomain_frame.h> #include <Ldomain/ldomain_frame_evaluate.h> #include <galerkin/ldomain_frame_equation.h> #include <galerkin/cached_quarklet_ldomain_problem.h> #include <adaptive/compression.h> #include <adaptive/apply.h> #include <adaptive/cdd2.h> #include "ldomain_solutions.h" using namespace std; using namespace WaveletTL; using MathTL::FixedArray1D; class myRHS : public Function<2,double> { public: virtual ~myRHS() {}; double value(const Point<2>& p, const unsigned int component = 0) const { return 2*M_PI*M_PI*sin(M_PI*p[0])*sin(M_PI*p[1]); } void vector_value(const Point<2>& p, Vector<double>& values) const { values[0] = value(p); } }; class mySolution : public Function<2,double> { public: virtual ~mySolution() {}; double value(const Point<2>& p, const unsigned int component = 0) const { return sin(M_PI*p[0])*sin(M_PI*p[1]); } void vector_value(const Point<2>& p, Vector<double>& values) const { values[0] = value(p); } }; class mySum : public Function<2,double> { public: virtual ~mySum() {}; double value(const Point<2>& p, const unsigned int component = 0) const { return (1+2*M_PI*M_PI)*sin(M_PI*p[0])*sin(M_PI*p[1]); } void vector_value(const Point<2>& p, Vector<double>& values) const { values[0] = value(p); } }; int main(){ cout << "testing L-domain quarklet frame" << endl; const int d = 3; const int dT = 3; const int dim = 2; const int jmax = 6; const int pmax = 0; typedef PQFrame<d,dT> Frame1d; Frame1d frame1d(false,false); typedef LDomainFrame<Frame1d> Frame; typedef Frame::Index Index; //Frame frame(frame1d); Frame frame(frame1d); frame.set_jpmax(jmax,pmax); //CornerSingularity uexact1(Point<2>(0,0), 0.5, 1.5); mySolution uexact1; //CornerSingularityRHS rhs1(Point<2>(0,0), 0.5, 1.5); //Fnorm=0? //Vector<double> val(1, "1.0"); //ConstantFunction<dim> rhs1(val); myRHS rhs1; PoissonBVP<dim> poisson1(&rhs1); LDomainFrameEquation<Frame1d,Frame> eq(&poisson1,frame, true); eq.set_jpmax(jmax,pmax); Index testindex=frame.get_quarklet(71); #if 0 //plot rhs and exact solution Array1D<Point<dim,int> > corners; corners.resize(3); corners[0][0]=-1; corners[0][1]=0; corners[1][0]=-1; corners[1][1]=-1; corners[2][0]=0; corners[2][1]=-1; std::ofstream osrhs("rhs.m"); std::ofstream osuexact("uexact.m"); for(int i=0;i<3;i++){ Point<2> q0(corners[i][0],corners[i][1]); Point<2> q1(corners[i][0]+1,corners[i][1]+1); Grid<2> mygrid(q0,q1,100); SampledMapping<2> smrhs(mygrid, rhs1); SampledMapping<2> smuexact(mygrid, uexact1); smrhs.matlab_output(osrhs); smuexact.matlab_output(osuexact); osrhs << "surf(x,y,z)"<<endl; osuexact<<"surf(x,y,z)"<<endl; osrhs << "hold on;" << endl; osuexact<<"hold on;"<<endl; } osrhs << "view(30,55);"<<endl; osrhs << "hold off;" << endl; osuexact << "view(30,55);"<<endl; osuexact<<"hold off;"<<endl; osrhs.close(); osuexact.close(); cout << "rhs and uexact plotted" << endl; #endif #if 1 //setup index set //Vector<double> a; //a.resize(eq.frame().degrees_of_freedom(),true); //setup Index set set<Index> Lambda; MultiIndex<int,dim> p;p[0]=0;p[1]=0; Index lambda = eq.frame().first_generator(eq.frame().j0(), p); int zaehler=0; for (int l = 0; l < eq.frame().degrees_of_freedom(); l++) { //cout << lambda << " : "<<lambda.number()<< endl; //cout << lambda << " : " << eq.a(lambda,lambda) << endl; //if(multi_degree(lambda.e())<1 && lambda.patch()<4){ Lambda.insert(lambda); ++zaehler; //} if(lambda==eq.frame().last_quarklet(jmax, p)){ ++p; lambda=eq.frame().first_generator(eq.frame().j0(), p); } else //a(zaehler)=eq.a(eq.frame().get_quarklet(126),lambda); ++lambda; } //a.matlab_output("a","a"); cout << "size of Lambda: " << zaehler << endl; #endif #if 0 //test methods of ldomain_frame_equation cout << "testindex: "<<testindex<<endl; cout << "a(lambda_0,lambda_0) : "<<eq.a(testindex,testindex) << endl; cout << "f(lambda_0): "<<eq.f(testindex)<<endl; cout << "D(lambda_0): "<<eq.D(testindex)<<endl; //cout << "F_norm: "<<eq.F_norm() << endl; //cout << "normA: "<<eq.norm_A() <<endl; //cout << "normAinv: "<<eq.norm_Ainv() << endl; #endif #ifdef NONADAPTIVE //setup stiffness matrix and rhs SparseMatrix<double> A; setup_stiffness_matrix(eq,Lambda,A); cout << "setup stiffness matrix done" << endl; Vector<double> F; setup_righthand_side(eq, Lambda, F); A.compress(1e-14); F.compress(1e-14); A.matlab_output("A","A",0,A.row_dimension()-1,A.column_dimension()-1 ); F.matlab_output("F","F"); Vector<double> x(Lambda.size()); x =0; //richardson iteration unsigned int iterations; const int maxiterations = 9999; const double omega = 2.0 / (eq.norm_A() + 1.0/eq.norm_Ainv()); cout << "omega: "<<omega<<endl; Richardson(A,F,x,omega,1e-6,maxiterations,iterations); //CG(A,F,x,1e-8,maxiterations,iterations); cout << "iterations:" << iterations << endl; InfiniteVector<double,Index> u; unsigned int i2 = 0; for (set<Index>::const_iterator it = Lambda.begin(); it != Lambda.end(); ++it, ++i2){ u.set_coefficient(*it, x[i2]); } //plot solution //u.COARSE(1e-6,v); u.scale(&eq, -1); Array1D<SampledMapping<dim> > eval(3); eval=eq.frame().evaluate(u,6); std::ofstream os2("solution_na.m"); for(int i=0;i<3;i++){ eval[i].matlab_output(os2); os2 << "surf(x,y,z);" << endl; os2 << "hold on;" << endl; } os2 << "view(30,55);"<<endl; os2 << "hold off" << endl; os2.close(); #endif #ifdef ADAPTIVE CachedQuarkletLDomainProblem<LDomainFrameEquation<Frame1d,Frame> > cproblem1(&eq); InfiniteVector<double, Index> F_eta; cproblem1.RHS(1e-6, F_eta); const double nu = cproblem1.norm_Ainv() * l2_norm(F_eta); //benötigt hinreichend großes jmax double epsilon = 1e-3; InfiniteVector<double, Index> u_epsilon, v; const double a=2; const double b=2; CDD2_QUARKLET_SOLVE(cproblem1, nu, epsilon, u_epsilon, jmax, tensor_simple, pmax, a, b); //plot solution //u.COARSE(1e-6,v); u_epsilon.scale(&cproblem1, -1); Array1D<SampledMapping<dim> > eval(3); eval=cproblem1.frame().evaluate(u_epsilon,6); std::ofstream os2("solution_ad.m"); for(int i=0;i<3;i++){ eval[i].matlab_output(os2); os2 << "surf(x,y,z);" << endl; os2 << "hold on;" << endl; } os2 << "view(30,55);"<<endl; os2 << "hold off" << endl; os2.close(); #endif #if 0 //test bilinearform const int resolution=6; Index testindex1(testindex); Index testindex2=eq.frame().get_quarklet(192); Array1D<SampledMapping<dim> > eval1(3); Array1D<SampledMapping<dim> > eval2(3); eval1=frame.evaluate(testindex1,resolution); eval2=frame.evaluate(testindex2,resolution); std::ofstream os("testa.m"); os<<"Iexakt="<<eq.a(testindex1,testindex2)<<endl; os<<"I=0;"<<endl; for(int i=0;i<3;i++){ eval1[i].matlab_output(os); os<<"z1=z;"<<endl; eval2[i].matlab_output(os); os<<"z2=z;"<<endl; os<<"xx=x(1,:);"<<endl; os<<"yy=y'(1,:);"<<endl; os<<"[gx1,gy1]=gradient(z1,2^-"<<resolution<<",2^-"<<resolution<<");"<<endl; os<<"[gx2,gy2]=gradient(z2,2^-"<<resolution<<",2^-"<<resolution<<");"<<endl; os<<"L=gx1.*gx2.+gy1.*gy2;"<<endl; os<<"I=I+trapz(yy,trapz(xx,L,2)');"<<endl; } os<<"I"<<endl; os<<"relative_error=abs(I-Iexakt)/Iexakt"<<endl; os.close(); #endif #if 0 //test rhs const int resolution2=6; Index testindex3(testindex); Array1D<SampledMapping<dim> > eval3(3); eval3=frame.evaluate(testindex3, resolution2); Array1D<Point<dim,int> > corners; corners.resize(3); corners[0][0]=-1; corners[0][1]=0; corners[1][0]=-1; corners[1][1]=-1; corners[2][0]=0; corners[2][1]=-1; std::ofstream os3("testf.m"); os3<<"Iexakt="<<eq.f(testindex)<<endl; os3<<"I=0;"<<endl; for(int i=0;i<3;i++){ eval3[i].matlab_output(os3); os3<<"zalt=z;"<<endl; Point<2> q0(corners[i][0],corners[i][1]); Point<2> q1(corners[i][0]+1,corners[i][1]+1); Grid<2> mygrid(q0,q1,pow(2,resolution2)); SampledMapping<2> smf(mygrid, rhs1); smf.matlab_output(os3); os3<<"z=z.*zalt;"<<endl; os3<<"xx=x(1,:);"<<endl; os3<<"yy=y'(1,:);"<<endl; os3<<"I=I+trapz(yy,trapz(xx,z,2)');"<<endl; } os3<<"I"<<endl; os3<<"relative_error=abs(I-Iexakt)/Iexakt"<<endl; os3.close(); #endif #if 0 //plot one function Array1D<SampledMapping<dim> > evalf(3); //Index ind=frame.get_quarklet(159); //0-26:generatoren auf patches, //27-32:überlappende generatoren, indiziert mit p=3,4 //33:überlappendes wavelet //34:nicht-überlappendes wavelet cout << "evaluate quarklet with index " << testindex << endl; evalf=frame.evaluate(testindex,6); std::ofstream osf("Ldomainoutput.m"); osf << "clf;" << endl; osf << "axis([-1 1 -1 1 0 1]);" << endl; for(int i=0;i<3;i++){ evalf[i].matlab_output(osf); osf << "surf(x,y,z);" << endl; osf << "hold on;" << endl; } osf << "view(30,55);"<<endl; osf << "hold off" << endl; osf.close(); #endif return 0; }<|endoftext|>
<commit_before>#include "ManualControl.h" #include <chrono> #include <thread> ManualControl::ManualControl(ICommunicationModule *pComModule) :ConfigurableModule("ManualControl"), ThreadedClass("ManualControl") { speed = { 0, 0 }; rotation = 0; m_pComModule = pComModule; AddSetting("Turn Left", []{return "r"; }, [this] {this->rotation -= 10; }); AddSetting("Turn Right", []{return "l"; }, [this]{this->rotation += 10; }); AddSetting("Move Left", []{return "a"; }, [this] {this->speed.x -= 10; }); AddSetting("Move Right", []{return "d"; }, [this]{this->speed.x += 10; }); AddSetting("Move Forward", []{return "w"; }, [this]{this->speed.y += 10; }); AddSetting("Move Back", []{return "s"; }, [this]{this->speed.y -= 10; }); AddSetting("Stop (space)", []{return "q"; }, [this]{this->speed = cv::Point2d(0,0); }); // AddSetting("Rotate Right", []{return ""; }, [this]{this->wheels->Rotate(0, 20); }); // AddSetting("Rotate Left", []{return ""; }, [this]{this->wheels->Rotate(1, 20); }); AddSetting("Kick", []{return "k"; }, [this] {this->m_pComModule->Kick(2500); }); AddSetting("Start tribbler", []{return "z"; }, [this]{this->m_pComModule->ToggleTribbler(100); }); AddSetting("Stop tribbler", []{return "x"; }, [this]{this->m_pComModule->ToggleTribbler(0); }); //Start(); } void ManualControl::Run(){ speed = { 0, 0 }; rotation = 0; last_tick = boost::posix_time::microsec_clock::local_time(); while (!stop_thread){ m_pComModule->Drive(speed, rotation); boost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time(); double dt = (double)((time - last_tick).total_milliseconds())/1000; rotation -= sign0(rotation); speed.x -= sign0(speed.x)*dt; speed.y -= sign0(speed.y)*dt; last_tick = time; Sleep(100); } } ManualControl::~ManualControl() { } <commit_msg>Stop rotation on q<commit_after>#include "ManualControl.h" #include <chrono> #include <thread> ManualControl::ManualControl(ICommunicationModule *pComModule) :ConfigurableModule("ManualControl"), ThreadedClass("ManualControl") { speed = { 0, 0 }; rotation = 0; m_pComModule = pComModule; AddSetting("Turn Left", []{return "r"; }, [this] {this->rotation -= 10; }); AddSetting("Turn Right", []{return "l"; }, [this]{this->rotation += 10; }); AddSetting("Move Left", []{return "a"; }, [this] {this->speed.x -= 10; }); AddSetting("Move Right", []{return "d"; }, [this]{this->speed.x += 10; }); AddSetting("Move Forward", []{return "w"; }, [this]{this->speed.y += 10; }); AddSetting("Move Back", []{return "s"; }, [this]{this->speed.y -= 10; }); AddSetting("Stop (space)", []{return "q"; }, [this]{this->speed = cv::Point2d(0, 0); this->rotation = 0; }); // AddSetting("Rotate Right", []{return ""; }, [this]{this->wheels->Rotate(0, 20); }); // AddSetting("Rotate Left", []{return ""; }, [this]{this->wheels->Rotate(1, 20); }); AddSetting("Kick", []{return "k"; }, [this] {this->m_pComModule->Kick(2500); }); AddSetting("Start tribbler", []{return "z"; }, [this]{this->m_pComModule->ToggleTribbler(100); }); AddSetting("Stop tribbler", []{return "x"; }, [this]{this->m_pComModule->ToggleTribbler(0); }); //Start(); } void ManualControl::Run(){ speed = { 0, 0 }; rotation = 0; last_tick = boost::posix_time::microsec_clock::local_time(); while (!stop_thread){ m_pComModule->Drive(speed, rotation); boost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time(); double dt = (double)((time - last_tick).total_milliseconds())/1000; rotation -= sign0(rotation); speed.x -= sign0(speed.x)*dt; speed.y -= sign0(speed.y)*dt; last_tick = time; Sleep(100); } } ManualControl::~ManualControl() { } <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware 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.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // QT includes #include <QDebug> #include <QVBoxLayout> #include <QHBoxLayout> #include <QTabWidget> #include <QVariant> // CTK includes #include "ctkColorDialog.h" QList<QWidget*> ctkColorDialog::DefaultTabs; int ctkColorDialog::DefaultTab = -1; QString ctkColorDialog::LastColorName = QString(); //------------------------------------------------------------------------------ class ctkColorDialogPrivate { Q_DECLARE_PUBLIC(ctkColorDialog); protected: ctkColorDialog* const q_ptr; public: ctkColorDialogPrivate(ctkColorDialog& object); void init(); QTabWidget* LeftTabWidget; QWidget* BasicTab; QString ColorName; }; //------------------------------------------------------------------------------ ctkColorDialogPrivate::ctkColorDialogPrivate(ctkColorDialog& object) :q_ptr(&object) { this->LeftTabWidget = 0; } //------------------------------------------------------------------------------ void ctkColorDialogPrivate::init() { Q_Q(ctkColorDialog); QVBoxLayout* mainLay = qobject_cast<QVBoxLayout*>(q->layout()); QHBoxLayout* topLay = qobject_cast<QHBoxLayout*>(mainLay->itemAt(0)->layout()); QVBoxLayout* leftLay = qobject_cast<QVBoxLayout*>(topLay->takeAt(0)->layout()); leftLay->setParent(0); this->BasicTab = new QWidget(q); this->BasicTab->setLayout(leftLay); this->LeftTabWidget = new QTabWidget(q); topLay->insertWidget(0, this->LeftTabWidget); this->LeftTabWidget->addTab(this->BasicTab, QObject::tr("Basic")); // If you use a ctkColorDialog, it's probably because you have tabs to add // into. Which means that you are likely to want to resize the dialog as // well. q->setSizeGripEnabled(true); q->layout()->setSizeConstraint(QLayout::SetDefaultConstraint); QObject::connect(q, SIGNAL(currentColorChanged(QColor)), q, SLOT(resetColorName())); } //------------------------------------------------------------------------------ ctkColorDialog::ctkColorDialog(QWidget* parent) : QColorDialog(parent) , d_ptr(new ctkColorDialogPrivate(*this)) { Q_D(ctkColorDialog); d->init(); } //------------------------------------------------------------------------------ ctkColorDialog::ctkColorDialog(const QColor& initial, QWidget* parent) : QColorDialog(initial, parent) , d_ptr(new ctkColorDialogPrivate(*this)) { Q_D(ctkColorDialog); d->init(); } //------------------------------------------------------------------------------ ctkColorDialog::~ctkColorDialog() { } //------------------------------------------------------------------------------ void ctkColorDialog::insertTab(int tabIndex, QWidget* widget, const QString& label) { Q_D(ctkColorDialog); d->LeftTabWidget->insertTab(tabIndex, widget, label); } //------------------------------------------------------------------------------ void ctkColorDialog::setCurrentTab(int index) { Q_D(ctkColorDialog); d->LeftTabWidget->setCurrentIndex(index); } //------------------------------------------------------------------------------ void ctkColorDialog::removeTab(int index) { Q_D(ctkColorDialog); d->LeftTabWidget->removeTab(index); } //------------------------------------------------------------------------------ int ctkColorDialog::indexOf(QWidget* widget)const { Q_D(const ctkColorDialog); return d->LeftTabWidget->indexOf(widget); } //------------------------------------------------------------------------------ QWidget* ctkColorDialog::widget(int index)const { Q_D(const ctkColorDialog); return d->LeftTabWidget->widget(index); } //------------------------------------------------------------------------------ QColor ctkColorDialog::getColor(const QColor &initial, QWidget *parent, const QString &title, ColorDialogOptions options) { ctkColorDialog dlg(parent); if (!title.isEmpty()) { dlg.setWindowTitle(title); } dlg.setOptions(options | QColorDialog::DontUseNativeDialog); dlg.setCurrentColor(initial); foreach(QWidget* tab, ctkColorDialog::DefaultTabs) { dlg.insertTab(tab->property("tabIndex").toInt(), tab, tab->windowTitle()); if (!tab->property("colorSignal").isNull()) { QObject::connect(tab, tab->property("colorSignal").toString().toLatin1(), &dlg, SLOT(setColor(QColor))); } if (!tab->property("nameSignal").isNull()) { QObject::connect(tab, tab->property("nameSignal").toString().toLatin1(), &dlg, SLOT(setColorName(QString))); } } dlg.setCurrentTab(ctkColorDialog::DefaultTab); dlg.exec(); foreach(QWidget* tab, ctkColorDialog::DefaultTabs) { dlg.removeTab(dlg.indexOf(tab)); if (!tab->property("colorSignal").isNull()) { QObject::disconnect(tab, tab->property("colorSignal").toString().toLatin1(), &dlg, SLOT(setColor(QColor))); } if (!tab->property("nameSignal").isNull()) { QObject::disconnect(tab, tab->property("nameSignal").toString().toLatin1(), &dlg, SLOT(setColorName(QString))); } tab->setParent(0); tab->hide(); } ctkColorDialog::LastColorName = dlg.colorName(); return dlg.selectedColor(); } //------------------------------------------------------------------------------ QString ctkColorDialog::getColorName() { return ctkColorDialog::LastColorName; } //------------------------------------------------------------------------------ void ctkColorDialog::insertDefaultTab(int tabIndex, QWidget* widget, const QString& label, const char* colorSignal, const char* nameSignal) { widget->setWindowTitle(label); widget->setProperty("colorSignal", colorSignal); widget->setProperty("nameSignal", nameSignal); widget->setProperty("tabIndex", tabIndex); ctkColorDialog::DefaultTabs << widget; widget->setParent(0); } //------------------------------------------------------------------------------ void ctkColorDialog::setDefaultTab(int index) { ctkColorDialog::DefaultTab = index; } //------------------------------------------------------------------------------ void ctkColorDialog::setColor(const QColor& color) { this->QColorDialog::setCurrentColor(color); } //------------------------------------------------------------------------------ void ctkColorDialog::setColorName(const QString& name) { Q_D(ctkColorDialog); if (d->ColorName == name) { return; } d->ColorName = name; emit currentColorNameChanged(d->ColorName); } //------------------------------------------------------------------------------ QString ctkColorDialog::colorName()const { Q_D(const ctkColorDialog); return d->ColorName; } //------------------------------------------------------------------------------ void ctkColorDialog::resetColorName() { this->setColorName(QString()); } <commit_msg>BUG: Fix ctkColorDialog crash on Mac with Qt5<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware 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.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // QT includes #include <QDebug> #include <QVBoxLayout> #include <QHBoxLayout> #include <QTabWidget> #include <QVariant> // CTK includes #include "ctkColorDialog.h" QList<QWidget*> ctkColorDialog::DefaultTabs; int ctkColorDialog::DefaultTab = -1; QString ctkColorDialog::LastColorName = QString(); //------------------------------------------------------------------------------ class ctkColorDialogPrivate { Q_DECLARE_PUBLIC(ctkColorDialog); protected: ctkColorDialog* const q_ptr; public: ctkColorDialogPrivate(ctkColorDialog& object); void init(); QTabWidget* LeftTabWidget; QWidget* BasicTab; QString ColorName; }; //------------------------------------------------------------------------------ ctkColorDialogPrivate::ctkColorDialogPrivate(ctkColorDialog& object) :q_ptr(&object) { this->LeftTabWidget = 0; } //------------------------------------------------------------------------------ void ctkColorDialogPrivate::init() { Q_Q(ctkColorDialog); QVBoxLayout* mainLay = qobject_cast<QVBoxLayout*>(q->layout()); QHBoxLayout* topLay = qobject_cast<QHBoxLayout*>(mainLay->itemAt(0)->layout()); QVBoxLayout* leftLay = qobject_cast<QVBoxLayout*>(topLay->takeAt(0)->layout()); leftLay->setParent(0); this->BasicTab = new QWidget(q); this->BasicTab->setLayout(leftLay); this->LeftTabWidget = new QTabWidget(q); topLay->insertWidget(0, this->LeftTabWidget); this->LeftTabWidget->addTab(this->BasicTab, QObject::tr("Basic")); // If you use a ctkColorDialog, it's probably because you have tabs to add // into. Which means that you are likely to want to resize the dialog as // well. q->setSizeGripEnabled(true); q->layout()->setSizeConstraint(QLayout::SetDefaultConstraint); QObject::connect(q, SIGNAL(currentColorChanged(QColor)), q, SLOT(resetColorName())); } //------------------------------------------------------------------------------ ctkColorDialog::ctkColorDialog(QWidget* parent) : QColorDialog(parent) , d_ptr(new ctkColorDialogPrivate(*this)) { Q_D(ctkColorDialog); // Force using Qt's standard color dialog to support adding new widgets setOption(QColorDialog::DontUseNativeDialog); d->init(); } //------------------------------------------------------------------------------ ctkColorDialog::ctkColorDialog(const QColor& initial, QWidget* parent) : QColorDialog(initial, parent) , d_ptr(new ctkColorDialogPrivate(*this)) { Q_D(ctkColorDialog); // Force using Qt's standard color dialog to support adding new widgets setOption(QColorDialog::DontUseNativeDialog); d->init(); } //------------------------------------------------------------------------------ ctkColorDialog::~ctkColorDialog() { } //------------------------------------------------------------------------------ void ctkColorDialog::insertTab(int tabIndex, QWidget* widget, const QString& label) { Q_D(ctkColorDialog); d->LeftTabWidget->insertTab(tabIndex, widget, label); } //------------------------------------------------------------------------------ void ctkColorDialog::setCurrentTab(int index) { Q_D(ctkColorDialog); d->LeftTabWidget->setCurrentIndex(index); } //------------------------------------------------------------------------------ void ctkColorDialog::removeTab(int index) { Q_D(ctkColorDialog); d->LeftTabWidget->removeTab(index); } //------------------------------------------------------------------------------ int ctkColorDialog::indexOf(QWidget* widget)const { Q_D(const ctkColorDialog); return d->LeftTabWidget->indexOf(widget); } //------------------------------------------------------------------------------ QWidget* ctkColorDialog::widget(int index)const { Q_D(const ctkColorDialog); return d->LeftTabWidget->widget(index); } //------------------------------------------------------------------------------ QColor ctkColorDialog::getColor(const QColor &initial, QWidget *parent, const QString &title, ColorDialogOptions options) { ctkColorDialog dlg(parent); if (!title.isEmpty()) { dlg.setWindowTitle(title); } dlg.setOptions(options | QColorDialog::DontUseNativeDialog); dlg.setCurrentColor(initial); foreach(QWidget* tab, ctkColorDialog::DefaultTabs) { dlg.insertTab(tab->property("tabIndex").toInt(), tab, tab->windowTitle()); if (!tab->property("colorSignal").isNull()) { QObject::connect(tab, tab->property("colorSignal").toString().toLatin1(), &dlg, SLOT(setColor(QColor))); } if (!tab->property("nameSignal").isNull()) { QObject::connect(tab, tab->property("nameSignal").toString().toLatin1(), &dlg, SLOT(setColorName(QString))); } } dlg.setCurrentTab(ctkColorDialog::DefaultTab); dlg.exec(); foreach(QWidget* tab, ctkColorDialog::DefaultTabs) { dlg.removeTab(dlg.indexOf(tab)); if (!tab->property("colorSignal").isNull()) { QObject::disconnect(tab, tab->property("colorSignal").toString().toLatin1(), &dlg, SLOT(setColor(QColor))); } if (!tab->property("nameSignal").isNull()) { QObject::disconnect(tab, tab->property("nameSignal").toString().toLatin1(), &dlg, SLOT(setColorName(QString))); } tab->setParent(0); tab->hide(); } ctkColorDialog::LastColorName = dlg.colorName(); return dlg.selectedColor(); } //------------------------------------------------------------------------------ QString ctkColorDialog::getColorName() { return ctkColorDialog::LastColorName; } //------------------------------------------------------------------------------ void ctkColorDialog::insertDefaultTab(int tabIndex, QWidget* widget, const QString& label, const char* colorSignal, const char* nameSignal) { widget->setWindowTitle(label); widget->setProperty("colorSignal", colorSignal); widget->setProperty("nameSignal", nameSignal); widget->setProperty("tabIndex", tabIndex); ctkColorDialog::DefaultTabs << widget; widget->setParent(0); } //------------------------------------------------------------------------------ void ctkColorDialog::setDefaultTab(int index) { ctkColorDialog::DefaultTab = index; } //------------------------------------------------------------------------------ void ctkColorDialog::setColor(const QColor& color) { this->QColorDialog::setCurrentColor(color); } //------------------------------------------------------------------------------ void ctkColorDialog::setColorName(const QString& name) { Q_D(ctkColorDialog); if (d->ColorName == name) { return; } d->ColorName = name; emit currentColorNameChanged(d->ColorName); } //------------------------------------------------------------------------------ QString ctkColorDialog::colorName()const { Q_D(const ctkColorDialog); return d->ColorName; } //------------------------------------------------------------------------------ void ctkColorDialog::resetColorName() { this->setColorName(QString()); } <|endoftext|>
<commit_before>#include "objLoader.hpp" #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <numeric> #include <map> #include <set> using namespace std; using glm::vec3; // Function to read input data values template <typename T> bool readvals(stringstream &s, const int numvals, T* values) { for (int i = 0; i < numvals; i++) { s >> values[i]; if (s.fail()) { cout << "Failed reading value " << i << " will skip\n"; return false; } } return true; } //string split helper vector<string> split(string s, char delim) { vector<string> ret; ret.reserve(s.length()); auto idx0 = 0u; auto idx1 = s.find(delim); while (idx1 != string::npos) { ret.push_back(s.substr(idx0, idx1 - idx0)); idx0 = idx1 + 1; idx1 = s.find(delim, idx0); } ret.push_back(s.substr(idx0)); return ret; } // helper to push float members of a vec3 to a vector void addToVec(std::vector<const GLfloat> &c, const glm::vec3 &v) { c.push_back(v.x); c.push_back(v.y); c.push_back(v.z); } // helper to calculate averaged vertex normal void addToVec(std::vector<const GLfloat> &c, const set<Face*> &s) { vec3 average_normal; for (auto f : s) average_normal += f->normal; average_normal = glm::normalize(average_normal); c.push_back(average_normal.x); c.push_back(average_normal.y); c.push_back(average_normal.z); } void loadObj(string obj_file, Obj &obj) { // disable syncing with c stdio functions, we only need c++ streams! // improves performance of streams a lot! ifstream::sync_with_stdio(false); ifstream file(obj_file); if (file.is_open()) { auto& faces = obj.faces; auto& vertices = obj.vertices; auto count = std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n'); // jump back to beginning of file file.clear(); file.seekg(0, ios::beg); faces.clear(); faces.reserve(count); vertices.clear(); vertices.reserve(count); // for averaging vertex normals map<vec3*, set<Face*>> vtx_triangle_map; // read file line by line as long as it's good while (file.good()) { // read line string line; getline(file, line); if (line.empty()) continue; stringstream ssline(line); // extract mode (v, f, vn, ...) string mode; ssline >> mode; // erase mode from input line line = string(line.begin()+2, line.end()); ssline.str(line); // interpret mode if (mode == "#") continue; else if (mode == "v") { // read vertex data vector<float> coords(3, 0.0f); if (readvals(ssline, 3, &coords[0])) { vertices.push_back(vec3(coords[0], coords[1], coords[2])); } } else if (mode == "f") { // read triangle face, vertices are indexed beginning from 1 // strip out any normals or texture specification auto vertex_indices = split(line, ' '); auto stripped_indices = accumulate(begin(vertex_indices), end(vertex_indices), string(), [](string &left, string right) -> string { auto spl = split(right, '/'); return left + " " + spl[0]; }); ssline.str(stripped_indices); vector<int> idx(3, 0); if (readvals(ssline, 3, &idx[0])) { std::transform(begin(idx), end(idx), begin(idx), [](int i) { return --i; }); auto& v1 = vertices[idx[0]]; auto& v2 = vertices[idx[1]]; auto& v3 = vertices[idx[2]]; auto face = Face(v1, v2, v3); faces.emplace_back(face); // save the triangle for each vertex for averaging normals vtx_triangle_map[&v1].insert(&faces.back()); vtx_triangle_map[&v2].insert(&faces.back()); vtx_triangle_map[&v3].insert(&faces.back()); face.normal; } } } file.close(); // generate vertex and normal array for fast opengl rendering auto& gl_vertices = obj.gl_vertices; auto& gl_normals = obj.gl_normals; auto& gl_normals_average = obj.gl_normals_average; gl_vertices.clear(); gl_vertices.reserve(vertices.size()); for (auto& face : faces) { addToVec(gl_vertices, face.v0); addToVec(gl_vertices, face.v1); addToVec(gl_vertices, face.v2); addToVec(gl_normals, face.normal); addToVec(gl_normals, face.normal); addToVec(gl_normals, face.normal); // generate averaged vertex normals addToVec(gl_normals_average, vtx_triangle_map[&face.v0]); addToVec(gl_normals_average, vtx_triangle_map[&face.v1]); addToVec(gl_normals_average, vtx_triangle_map[&face.v2]); } } else { throw std::exception((string("Unable to open file ") + obj_file).c_str()); } }<commit_msg>performance gain for converting string to numbers (stringstreams stream operator is totally slow!)<commit_after>#include "objLoader.hpp" #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <numeric> #include <map> #include <set> using namespace std; using glm::vec3; // Function to read input data values bool readvals(stringstream &s, const int numvals, GLfloat* values) { for (int i = 0; i < numvals; i++) { string value; s >> value; try { auto v = std::stof(value); values[i] = v; } catch (std::exception) { cout << "Failed reading value " << i << " will skip\n"; return false; } } return true; } bool readvals(stringstream &s, const int numvals, int* values) { for (int i = 0; i < numvals; i++) { string value; s >> value; try { auto v = std::stoi(value); values[i] = v; } catch (std::exception) { cout << "Failed reading value " << i << " will skip\n"; return false; } } return true; } //string split helper vector<string> split(string s, char delim) { vector<string> ret; ret.reserve(s.length()); auto idx0 = 0u; auto idx1 = s.find(delim); while (idx1 != string::npos) { ret.push_back(s.substr(idx0, idx1 - idx0)); idx0 = idx1 + 1; idx1 = s.find(delim, idx0); } ret.push_back(s.substr(idx0)); return ret; } // helper to push float members of a vec3 to a vector void addToVec(std::vector<const GLfloat> &c, const glm::vec3 &v) { c.push_back(v.x); c.push_back(v.y); c.push_back(v.z); } // helper to calculate averaged vertex normal void addToVec(std::vector<const GLfloat> &c, const set<Face*> &s) { vec3 average_normal; for (auto f : s) average_normal += f->normal; average_normal = glm::normalize(average_normal); c.push_back(average_normal.x); c.push_back(average_normal.y); c.push_back(average_normal.z); } void loadObj(string obj_file, Obj &obj) { // disable syncing with c stdio functions, we only need c++ streams! // improves performance of streams a lot! ifstream::sync_with_stdio(false); ifstream file(obj_file); if (file.is_open()) { auto& faces = obj.faces; auto& vertices = obj.vertices; auto count = std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n'); // jump back to beginning of file file.clear(); file.seekg(0, ios::beg); faces.clear(); faces.reserve(count); vertices.clear(); vertices.reserve(count); // for averaging vertex normals map<vec3*, set<Face*>> vtx_triangle_map; // read file line by line as long as it's good while (file.good()) { // read line string line; getline(file, line); if (line.empty()) continue; stringstream ssline(line); // extract mode (v, f, vn, ...) string mode; ssline >> mode; // erase mode from input line line = string(line.begin()+2, line.end()); ssline.str(line); // interpret mode if (mode == "#") continue; else if (mode == "v") { // read vertex data vector<float> coords(3, 0.0f); if (readvals(ssline, 3, &coords[0])) { vertices.push_back(vec3(coords[0], coords[1], coords[2])); } } else if (mode == "f") { // read triangle face, vertices are indexed beginning from 1 // strip out any normals or texture specification auto vertex_indices = split(line, ' '); auto stripped_indices = accumulate(begin(vertex_indices), end(vertex_indices), string(), [](string &left, string right) -> string { auto spl = split(right, '/'); return left + " " + spl[0]; }); ssline.str(stripped_indices); vector<int> idx(3, 0); if (readvals(ssline, 3, &idx[0])) { std::transform(begin(idx), end(idx), begin(idx), [](int i) { return --i; }); auto& v1 = vertices[idx[0]]; auto& v2 = vertices[idx[1]]; auto& v3 = vertices[idx[2]]; auto face = Face(v1, v2, v3); faces.emplace_back(face); // save the triangle for each vertex for averaging normals vtx_triangle_map[&v1].insert(&faces.back()); vtx_triangle_map[&v2].insert(&faces.back()); vtx_triangle_map[&v3].insert(&faces.back()); face.normal; } } } file.close(); // generate vertex and normal array for fast opengl rendering auto& gl_vertices = obj.gl_vertices; auto& gl_normals = obj.gl_normals; auto& gl_normals_average = obj.gl_normals_average; gl_vertices.clear(); gl_vertices.reserve(vertices.size()); for (auto& face : faces) { addToVec(gl_vertices, face.v0); addToVec(gl_vertices, face.v1); addToVec(gl_vertices, face.v2); addToVec(gl_normals, face.normal); addToVec(gl_normals, face.normal); addToVec(gl_normals, face.normal); // generate averaged vertex normals addToVec(gl_normals_average, vtx_triangle_map[&face.v0]); addToVec(gl_normals_average, vtx_triangle_map[&face.v1]); addToVec(gl_normals_average, vtx_triangle_map[&face.v2]); } } else { throw std::exception((string("Unable to open file ") + obj_file).c_str()); } }<|endoftext|>
<commit_before>#include "QueryParams.h" #include <boost/filesystem/fstream.hpp> #include "Header.h" using namespace HTTP; QueryParams::QueryParams() : FMParseState(STATE_HEADERSTART), BoundaryParseCounter(2), CurrFileS(nullptr) { } QueryParams::QueryParams(const FileUploadParams &UploadParams) : FMParseState(STATE_HEADERSTART), BoundaryParseCounter(2), FUParams(UploadParams), CurrFileS(nullptr) { } bool QueryParams::AddURLEncoded(const char *Begin, const char *End) { enum PARSESTATE { PS_PARAM_END, PS_VALUE_END, } CurrState=PS_PARAM_END; ParseTmp.reserve(ParseTmp.size()); ParseTmp.clear(); std::string *ValStr=nullptr; std::string *TargetStr= &ParseTmp; while (Begin!=End) { char CurrVal=*Begin++; if (CurrVal=='+') TargetStr->append((std::string::size_type)1,' '); else if ((CurrVal=='%') && (End-Begin>0)) { TargetStr->append((std::string::size_type)1,(std::string::value_type)( (GetHexVal(*Begin) << 4) | GetHexVal(*(Begin+1)) ) ); Begin+=2; } else { if (CurrState==PS_PARAM_END) { if (CurrVal=='=') { Param &CurrParam=ParamMap[ParseTmp]; CurrParam.Value.clear(); ValStr=&CurrParam.Value; CurrState=PS_VALUE_END; TargetStr=ValStr; } else TargetStr->append((std::string::size_type)1,CurrVal); } else if (CurrState==PS_VALUE_END) { if (CurrVal=='&') { ValStr=nullptr; ParseTmp.reserve(ParseTmp.size()); ParseTmp.clear(); CurrState=PS_PARAM_END; TargetStr=&ParseTmp; } else TargetStr->append((std::string::size_type)1,CurrVal); } } } return true; } bool QueryParams::AppendFormMultipart(const char *Begin, const char *End) { /*Continous boundary detection: set content start to start of the input data for each input character: if the current char equals to the parse position in the boundary string: advance the parse position if the boundary string is fully matched: we have content from content start to the start of the boundary string. if the boundary string starts after the end of the input data: the bytes in [start of content, start of boundary) are content reset the parse position set content start to current position + 1 otherwise: the bytes in temporary data are content reset the parse position clear the temporary data storage save the parse position the bytes [content start, end-parse position) are content store the bytes [end-parse position, end) as temporary data*/ const char *ContentBegin=Begin; while (Begin!=End) { char CurrVal=*Begin; if (CurrVal==BoundaryStr[BoundaryParseCounter]) { if (++BoundaryParseCounter==BoundaryStr.length()) { if (!AppendToCurrentPart(ContentBegin,Begin-BoundaryParseCounter+1)) return false; ContentBegin=Begin + 1; BoundaryParseCounter=0; StartNewPart(); } } else { if (!ParseTmp.empty()) { if (!AppendToCurrentPart(ParseTmp.data(),ParseTmp.data()+ParseTmp.length())) return false; ParseTmp.clear(); } BoundaryParseCounter=0; } Begin++; } if (!AppendToCurrentPart(ContentBegin,Begin-BoundaryParseCounter)) return false; ParseTmp.append(Begin-BoundaryParseCounter,Begin); return true; } const QueryParams::Param &QueryParams::Get(const std::string &Name) const { ParamMapType::const_iterator FindI=ParamMap.find(Name); if (FindI!=ParamMap.end()) return FindI->second; else throw ParameterNotFound(); } const QueryParams::Param QueryParams::Get(const std::string &Name, const std::string &Default) const { ParamMapType::const_iterator FindI=ParamMap.find(Name); if (FindI!=ParamMap.end()) return FindI->second; else return Param(Default); } void QueryParams::DecodeURLEncoded(std::string &Target, const char *Begin, const char *End) { while (Begin!=End) { char CurrVal=*Begin++; if (CurrVal=='+') Target.append((std::string::size_type)1,' '); else if ((CurrVal=='%') && (End-Begin>0)) { Target.append((std::string::size_type)1,(std::string::value_type)( (GetHexVal(*Begin) << 4) | GetHexVal(*(Begin+1)) ) ); Begin+=2; } else Target.append((std::string::size_type)1,CurrVal); } } void QueryParams::OnBoundaryParsed() { BoundaryStr="\r\n--" + BoundaryStr; } void QueryParams::DeleteUploadedFiles() { for (FileMapType::value_type &CurrFile : FileMap) { boost::system::error_code DelErr; boost::filesystem::remove(CurrFile.second.Path,DelErr); } } void QueryParams::StartNewPart() { FMParseState=STATE_HEADERSTART; FMParseCounter=0; HeaderParseTmp.clear(); } bool QueryParams::AppendToCurrentPart(const char *Begin, const char *End) { if ((Begin>=End) || (FMParseState==STATE_FINISHED)) return true; const char *OrigBegin=Begin; while ((Begin!=End) && (FMParseState!=STATE_READ)) { char CurrVal=*Begin; switch (FMParseState) { case STATE_HEADERSTART: if (FMParseCounter==0) { if ((CurrVal=='\r') || (CurrVal=='-')) FMParseCounter++; else return false; } else if (FMParseCounter==1) { if (CurrVal=='\n') { FMParseCounter=0; FMParseState=STATE_HEADERS_END; OrigBegin=Begin + 1; } else if (CurrVal=='-') FMParseState=STATE_FINISHED; else return false; } break; case STATE_HEADERS_END: if (CurrVal=="\r\n\r\n"[FMParseCounter]) { if (++FMParseCounter==4) { //End of headers found. if (Begin-OrigBegin-4>0) HeaderParseTmp.append(OrigBegin,Begin+1); if (ParseFMHeaders(HeaderParseTmp.data(),HeaderParseTmp.data()+HeaderParseTmp.length())) { //Now, we can read the actual content until StartNewPart is called. FMParseState=STATE_READ; break; } else { HeaderParseTmp.clear(); return false; } } } else FMParseCounter=0; break; case STATE_FINISHED: if (CurrFileS) { CurrFileS->close(); delete CurrFileS; CurrFileS=nullptr; } return true; } Begin++; } if (FMParseState==STATE_READ) { if (IsCurrPartValid()) { if (IsCurrPartFile()) { CurrFileS->write(Begin,End-Begin); return !CurrFileS->fail(); } else { CurrFMPart.TargetParam->Value.append(Begin,End); return true; } } else return false; } else if (FMParseState==STATE_HEADERS_END) { HeaderParseTmp.append(OrigBegin,Begin); return true; } else return true; } bool QueryParams::ParseFMHeaders(const char *HeadersBegin, const char *HeadersEnd) { std::string Name, FileName; const char *ContentTypeVal=nullptr; const char *HBegin=HeadersBegin; while (HeadersBegin!=HeadersEnd) { char CurrVal=*HeadersBegin; if (CurrVal=='\n') { //Header in [HBegin,HeadersBegin[ . Header CurrHeader((char *)HBegin,(char *)HeadersBegin); if (CurrHeader.IntName==HN_CONTENT_DISPOSITION) CurrHeader.ParseContentDisposition(Name,FileName); else if (CurrHeader.IntName==HN_CONTENT_TYPE) ContentTypeVal=CurrHeader.Value; HBegin=HeadersBegin+1; } HeadersBegin++; } if (!Name.empty()) { if (CurrFileS) { CurrFileS->close(); delete CurrFileS; CurrFileS=nullptr; } if (ContentTypeVal) { try { boost::filesystem::path TmpFilePath= (FUParams.Root.empty() ? boost::filesystem::temp_directory_path() : FUParams.Root) / boost::filesystem::unique_path(); CurrFileS=new boost::filesystem::ofstream(TmpFilePath,std::ios_base::binary); CurrFMPart.TargetFile=&FileMap[Name]; CurrFMPart.TargetFile->MimeType=ContentTypeVal; CurrFMPart.TargetFile->OrigFileName=FileName; CurrFMPart.TargetFile->Path=TmpFilePath; } catch (...) { CurrFMPart.TargetFile=NULL; return false; } } else CurrFMPart.TargetParam=&ParamMap[Name]; return true; } else { CurrFMPart.TargetFile=NULL; return false; } } <commit_msg>QueryParams::AppendToCurrentPart: switch label warning fix<commit_after>#include "QueryParams.h" #include <boost/filesystem/fstream.hpp> #include "Header.h" using namespace HTTP; QueryParams::QueryParams() : FMParseState(STATE_HEADERSTART), BoundaryParseCounter(2), CurrFileS(nullptr) { } QueryParams::QueryParams(const FileUploadParams &UploadParams) : FMParseState(STATE_HEADERSTART), BoundaryParseCounter(2), FUParams(UploadParams), CurrFileS(nullptr) { } bool QueryParams::AddURLEncoded(const char *Begin, const char *End) { enum PARSESTATE { PS_PARAM_END, PS_VALUE_END, } CurrState=PS_PARAM_END; ParseTmp.reserve(ParseTmp.size()); ParseTmp.clear(); std::string *ValStr=nullptr; std::string *TargetStr= &ParseTmp; while (Begin!=End) { char CurrVal=*Begin++; if (CurrVal=='+') TargetStr->append((std::string::size_type)1,' '); else if ((CurrVal=='%') && (End-Begin>0)) { TargetStr->append((std::string::size_type)1,(std::string::value_type)( (GetHexVal(*Begin) << 4) | GetHexVal(*(Begin+1)) ) ); Begin+=2; } else { if (CurrState==PS_PARAM_END) { if (CurrVal=='=') { Param &CurrParam=ParamMap[ParseTmp]; CurrParam.Value.clear(); ValStr=&CurrParam.Value; CurrState=PS_VALUE_END; TargetStr=ValStr; } else TargetStr->append((std::string::size_type)1,CurrVal); } else if (CurrState==PS_VALUE_END) { if (CurrVal=='&') { ValStr=nullptr; ParseTmp.reserve(ParseTmp.size()); ParseTmp.clear(); CurrState=PS_PARAM_END; TargetStr=&ParseTmp; } else TargetStr->append((std::string::size_type)1,CurrVal); } } } return true; } bool QueryParams::AppendFormMultipart(const char *Begin, const char *End) { /*Continous boundary detection: set content start to start of the input data for each input character: if the current char equals to the parse position in the boundary string: advance the parse position if the boundary string is fully matched: we have content from content start to the start of the boundary string. if the boundary string starts after the end of the input data: the bytes in [start of content, start of boundary) are content reset the parse position set content start to current position + 1 otherwise: the bytes in temporary data are content reset the parse position clear the temporary data storage save the parse position the bytes [content start, end-parse position) are content store the bytes [end-parse position, end) as temporary data*/ const char *ContentBegin=Begin; while (Begin!=End) { char CurrVal=*Begin; if (CurrVal==BoundaryStr[BoundaryParseCounter]) { if (++BoundaryParseCounter==BoundaryStr.length()) { if (!AppendToCurrentPart(ContentBegin,Begin-BoundaryParseCounter+1)) return false; ContentBegin=Begin + 1; BoundaryParseCounter=0; StartNewPart(); } } else { if (!ParseTmp.empty()) { if (!AppendToCurrentPart(ParseTmp.data(),ParseTmp.data()+ParseTmp.length())) return false; ParseTmp.clear(); } BoundaryParseCounter=0; } Begin++; } if (!AppendToCurrentPart(ContentBegin,Begin-BoundaryParseCounter)) return false; ParseTmp.append(Begin-BoundaryParseCounter,Begin); return true; } const QueryParams::Param &QueryParams::Get(const std::string &Name) const { ParamMapType::const_iterator FindI=ParamMap.find(Name); if (FindI!=ParamMap.end()) return FindI->second; else throw ParameterNotFound(); } const QueryParams::Param QueryParams::Get(const std::string &Name, const std::string &Default) const { ParamMapType::const_iterator FindI=ParamMap.find(Name); if (FindI!=ParamMap.end()) return FindI->second; else return Param(Default); } void QueryParams::DecodeURLEncoded(std::string &Target, const char *Begin, const char *End) { while (Begin!=End) { char CurrVal=*Begin++; if (CurrVal=='+') Target.append((std::string::size_type)1,' '); else if ((CurrVal=='%') && (End-Begin>0)) { Target.append((std::string::size_type)1,(std::string::value_type)( (GetHexVal(*Begin) << 4) | GetHexVal(*(Begin+1)) ) ); Begin+=2; } else Target.append((std::string::size_type)1,CurrVal); } } void QueryParams::OnBoundaryParsed() { BoundaryStr="\r\n--" + BoundaryStr; } void QueryParams::DeleteUploadedFiles() { for (FileMapType::value_type &CurrFile : FileMap) { boost::system::error_code DelErr; boost::filesystem::remove(CurrFile.second.Path,DelErr); } } void QueryParams::StartNewPart() { FMParseState=STATE_HEADERSTART; FMParseCounter=0; HeaderParseTmp.clear(); } bool QueryParams::AppendToCurrentPart(const char *Begin, const char *End) { if ((Begin>=End) || (FMParseState==STATE_FINISHED)) return true; const char *OrigBegin=Begin; while ((Begin!=End) && (FMParseState!=STATE_READ)) { char CurrVal=*Begin; switch (FMParseState) { case STATE_HEADERSTART: if (FMParseCounter==0) { if ((CurrVal=='\r') || (CurrVal=='-')) FMParseCounter++; else return false; } else if (FMParseCounter==1) { if (CurrVal=='\n') { FMParseCounter=0; FMParseState=STATE_HEADERS_END; OrigBegin=Begin + 1; } else if (CurrVal=='-') FMParseState=STATE_FINISHED; else return false; } break; case STATE_HEADERS_END: if (CurrVal=="\r\n\r\n"[FMParseCounter]) { if (++FMParseCounter==4) { //End of headers found. if (Begin-OrigBegin-4>0) HeaderParseTmp.append(OrigBegin,Begin+1); if (ParseFMHeaders(HeaderParseTmp.data(),HeaderParseTmp.data()+HeaderParseTmp.length())) { //Now, we can read the actual content until StartNewPart is called. FMParseState=STATE_READ; break; } else { HeaderParseTmp.clear(); return false; } } } else FMParseCounter=0; break; case STATE_FINISHED: if (CurrFileS) { CurrFileS->close(); delete CurrFileS; CurrFileS=nullptr; } return true; default: break; } Begin++; } if (FMParseState==STATE_READ) { if (IsCurrPartValid()) { if (IsCurrPartFile()) { CurrFileS->write(Begin,End-Begin); return !CurrFileS->fail(); } else { CurrFMPart.TargetParam->Value.append(Begin,End); return true; } } else return false; } else if (FMParseState==STATE_HEADERS_END) { HeaderParseTmp.append(OrigBegin,Begin); return true; } else return true; } bool QueryParams::ParseFMHeaders(const char *HeadersBegin, const char *HeadersEnd) { std::string Name, FileName; const char *ContentTypeVal=nullptr; const char *HBegin=HeadersBegin; while (HeadersBegin!=HeadersEnd) { char CurrVal=*HeadersBegin; if (CurrVal=='\n') { //Header in [HBegin,HeadersBegin[ . Header CurrHeader((char *)HBegin,(char *)HeadersBegin); if (CurrHeader.IntName==HN_CONTENT_DISPOSITION) CurrHeader.ParseContentDisposition(Name,FileName); else if (CurrHeader.IntName==HN_CONTENT_TYPE) ContentTypeVal=CurrHeader.Value; HBegin=HeadersBegin+1; } HeadersBegin++; } if (!Name.empty()) { if (CurrFileS) { CurrFileS->close(); delete CurrFileS; CurrFileS=nullptr; } if (ContentTypeVal) { try { boost::filesystem::path TmpFilePath= (FUParams.Root.empty() ? boost::filesystem::temp_directory_path() : FUParams.Root) / boost::filesystem::unique_path(); CurrFileS=new boost::filesystem::ofstream(TmpFilePath,std::ios_base::binary); CurrFMPart.TargetFile=&FileMap[Name]; CurrFMPart.TargetFile->MimeType=ContentTypeVal; CurrFMPart.TargetFile->OrigFileName=FileName; CurrFMPart.TargetFile->Path=TmpFilePath; } catch (...) { CurrFMPart.TargetFile=NULL; return false; } } else CurrFMPart.TargetParam=&ParamMap[Name]; return true; } else { CurrFMPart.TargetFile=NULL; return false; } } <|endoftext|>
<commit_before>/*! @file @author Albert Semenov @date 04/2009 @module */ /* This file is part of MyGUI. MyGUI 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. MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #include "MyGUI_Precompiled.h" #include "MyGUI_Timer.h" #if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32 #include <windows.h> #pragma comment(lib, "winmm.lib") #endif namespace MyGUI { void Timer::reset() { mTimeStart = getCurrentMilliseconds(); } unsigned long Timer::getMilliseconds() { return getCurrentMilliseconds() - mTimeStart; } unsigned long Timer::getCurrentMilliseconds() { #if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32 /* We do this because clock() is not affected by timeBeginPeriod on Win32. QueryPerformanceCounter is a little overkill for the amount of precision that I consider acceptable. If someone submits a patch that replaces this code with QueryPerformanceCounter, I wouldn't complain. Until then, timeGetTime gets the results I'm after. -EMS See: http://www.geisswerks.com/ryan/FAQS/timing.html And: http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q274323& */ return timeGetTime(); #else return ( unsigned long )(( float )( clock() ) / (( float )CLOCKS_PER_SEC / 1000.0 ) ); #endif } } // namespace MyGUI <commit_msg>little fix in Timer for code blocks<commit_after>/*! @file @author Albert Semenov @date 04/2009 @module */ /* This file is part of MyGUI. MyGUI 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. MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #include "MyGUI_Precompiled.h" #include "MyGUI_Timer.h" #if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32 # include <windows.h> # ifndef __MINGW32__ # pragma comment(lib, "winmm.lib") # else # pragma comment(lib, "libwinmm.a") # endif #endif namespace MyGUI { void Timer::reset() { mTimeStart = getCurrentMilliseconds(); } unsigned long Timer::getMilliseconds() { return getCurrentMilliseconds() - mTimeStart; } unsigned long Timer::getCurrentMilliseconds() { #if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32 /* We do this because clock() is not affected by timeBeginPeriod on Win32. QueryPerformanceCounter is a little overkill for the amount of precision that I consider acceptable. If someone submits a patch that replaces this code with QueryPerformanceCounter, I wouldn't complain. Until then, timeGetTime gets the results I'm after. -EMS See: http://www.geisswerks.com/ryan/FAQS/timing.html And: http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q274323& */ return timeGetTime(); #else return ( unsigned long )(( float )( clock() ) / (( float )CLOCKS_PER_SEC / 1000.0 ) ); #endif } } // namespace MyGUI <|endoftext|>
<commit_before>/* openDCM, dimensional constraint manager Copyright (C) 2012 Stefan Troeger <stefantroeger@gmx.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef GCM_SYSTEM_H #define GCM_SYSTEM_H #include <boost/mpl/vector.hpp> #include <boost/mpl/vector/vector0.hpp> #include <boost/mpl/map.hpp> #include <boost/mpl/fold.hpp> #include <boost/mpl/insert.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/count.hpp> #include <boost/mpl/or.hpp> #include <boost/mpl/less_equal.hpp> #include <boost/mpl/print.hpp> #include <boost/mpl/and.hpp> #include <boost/graph/adjacency_list.hpp> #include <iostream> #include "property.hpp" #include "clustergraph.hpp" #include "sheduler.hpp" #include "logging.hpp" #include "traits.hpp" namespace mpl = boost::mpl; namespace dcm { struct No_Identifier {}; struct Unspecified_Identifier {}; namespace details { template<typename seq, typename state> struct vector_fold : mpl::fold< seq, state, mpl::push_back<mpl::_1,mpl::_2> > {}; template<typename seq, typename state> struct edge_fold : mpl::fold< seq, state, mpl::if_< is_edge_property<mpl::_2>, mpl::push_back<mpl::_1,mpl::_2>, mpl::_1 > > {}; template<typename seq, typename state> struct vertex_fold : mpl::fold< seq, state, mpl::if_< is_vertex_property<mpl::_2>, mpl::push_back<mpl::_1,mpl::_2>, mpl::_1 > > {}; template<typename seq, typename state> struct cluster_fold : mpl::fold< seq, state, mpl::if_< is_cluster_property<mpl::_2>, mpl::push_back<mpl::_1,mpl::_2>, mpl::_1 > > {}; template<typename seq, typename state, typename obj> struct obj_fold : mpl::fold< seq, state, mpl::if_< mpl::or_< boost::is_same< details::property_kind<mpl::_2>, obj>, is_object_property<mpl::_2> >, mpl::push_back<mpl::_1,mpl::_2>, mpl::_1 > > {}; template<typename objects, typename properties> struct property_map { typedef typename mpl::fold< objects, mpl::map<>, mpl::insert< mpl::_1, mpl::pair< mpl::_2, details::obj_fold<properties, mpl::vector<>, mpl::_2 > > > >::type type; }; template<typename T> struct get_identifier { typedef typename T::Identifier type; }; template<typename seq, typename state> struct map_fold : mpl::fold< seq, state, mpl::insert<mpl::_1,mpl::_2> > {}; struct nothing {}; template<int v> struct EmptyModule { template<typename T> struct type { struct inheriter {}; typedef mpl::vector<> properties; typedef mpl::vector<> objects; typedef Unspecified_Identifier Identifier; static void system_init(T& sys) {}; static void system_copy(const T& from, T& into) {}; }; }; template <class T> struct is_shared_ptr : boost::mpl::false_ {}; template <class T> struct is_shared_ptr<boost::shared_ptr<T> > : boost::mpl::true_ {}; } template< typename KernelType, typename T1 = details::EmptyModule<1>, typename T2 = details::EmptyModule<2>, typename T3 = details::EmptyModule<3> > class System : public T1::template type< System<KernelType,T1,T2,T3> >::inheriter, public T2::template type< System<KernelType,T1,T2,T3> >::inheriter, public T3::template type< System<KernelType,T1,T2,T3> >::inheriter { typedef System<KernelType,T1,T2,T3> BaseType; public: typedef typename T1::template type< BaseType > Type1; typedef typename T2::template type< BaseType > Type2; typedef typename T3::template type< BaseType > Type3; typedef mpl::vector3<Type1, Type2, Type3> TypeVector; //Check if all Identifiers are the same and find out which type it is typedef typename mpl::fold<TypeVector, mpl::vector<>, mpl::if_<boost::is_same<details::get_identifier<mpl::_2>, Unspecified_Identifier>, mpl::_1, mpl::push_back<mpl::_1, details::get_identifier<mpl::_2> > > >::type Identifiers; BOOST_MPL_ASSERT((mpl::or_< mpl::less_equal<typename mpl::size<Identifiers>::type, mpl::int_<1> >, mpl::equal< typename mpl::count<Identifiers, typename mpl::at_c<Identifiers,0> >::type, typename mpl::size<Identifiers>::type > >)); typedef typename mpl::if_< mpl::empty<Identifiers>, No_Identifier, typename mpl::at_c<Identifiers, 0>::type >::type Identifier; public: //get all module objects and properties typedef typename details::vector_fold<typename Type3::objects, typename details::vector_fold<typename Type2::objects, typename details::vector_fold<typename Type1::objects, mpl::vector<> >::type >::type>::type objects; typedef typename details::vector_fold<typename Type3::properties, typename details::vector_fold<typename Type2::properties, typename details::vector_fold<typename Type1::properties, mpl::vector<id_prop<Identifier> > >::type >::type>::type properties; //make the subcomponent lists of objects and properties typedef typename details::edge_fold< properties, mpl::vector<> >::type edge_properties; typedef typename details::vertex_fold< properties, mpl::vector<> >::type vertex_properties; typedef typename details::cluster_fold< properties, mpl::vector<changed_prop, type_prop> >::type cluster_properties; typedef typename details::property_map<objects, properties>::type object_properties; protected: //object storage typedef typename mpl::transform<objects, boost::shared_ptr<mpl::_1> >::type sp_objects; typedef typename mpl::fold< sp_objects, mpl::vector<>, mpl::push_back<mpl::_1, std::vector<mpl::_2> > >::type object_vectors; typedef typename fusion::result_of::as_vector<object_vectors>::type Storage; template<typename FT1, typename FT2, typename FT3> friend struct Object; struct clearer { template<typename T> void operator()(T& vector) const { vector.clear(); }; }; #ifdef USE_LOGGING boost::shared_ptr< sink_t > sink; #endif public: typedef ClusterGraph<edge_properties, vertex_properties, cluster_properties, objects> Cluster; typedef Sheduler< BaseType > Shedule; typedef KernelType Kernel; public: System() : m_cluster(new Cluster) #ifdef USE_LOGGING , sink(init_log()) #endif { Type1::system_init(*this); Type2::system_init(*this); Type3::system_init(*this); }; ~System() { #ifdef USE_LOGGING stop_log(sink); #endif }; void clear() { m_cluster->clearClusters(); m_cluster->clear(); fusion::for_each(m_storage, clearer()); }; template<typename Object> typename std::vector< boost::shared_ptr<Object> >::iterator begin() { typedef typename mpl::find<objects, Object>::type iterator; typedef typename mpl::distance<typename mpl::begin<objects>::type, iterator>::type distance; BOOST_MPL_ASSERT((mpl::not_<boost::is_same<iterator, typename mpl::end<objects>::type > >)); return fusion::at<distance>(m_storage).begin(); }; template<typename Object> typename std::vector< boost::shared_ptr<Object> >::iterator end() { typedef typename mpl::find<objects, Object>::type iterator; typedef typename mpl::distance<typename mpl::begin<objects>::type, iterator>::type distance; BOOST_MPL_ASSERT((mpl::not_<boost::is_same<iterator, typename mpl::end<objects>::type > >)); return fusion::at<distance>(m_storage).end(); }; template<typename Object> std::vector< boost::shared_ptr<Object> >& objectVector() { typedef typename mpl::find<objects, Object>::type iterator; typedef typename mpl::distance<typename mpl::begin<objects>::type, iterator>::type distance; BOOST_MPL_ASSERT((mpl::not_<boost::is_same<iterator, typename mpl::end<objects>::type > >)); return fusion::at<distance>(m_storage); }; template<typename Object> void push_back(boost::shared_ptr<Object> ptr) { objectVector<Object>().push_back(ptr); }; template<typename Object> void erase(boost::shared_ptr<Object> ptr) { std::vector< boost::shared_ptr<Object> >& vec = objectVector<Object>(); vec.erase(std::remove(vec.begin(), vec.end(), ptr), vec.end()); }; void solve() { clock_t start = clock(); m_sheduler.execute(*this); clock_t end = clock(); double ms = (double(end-start)* 1000.) / double(CLOCKS_PER_SEC); //Base::Console().Message("overall solving time in ms: %f\n", ms); }; private: struct cloner { System& newSys; cloner(System& ns) : newSys(ns) {}; template<typename T> struct test : mpl::and_<details::is_shared_ptr<T>, mpl::not_<boost::is_same<T, boost::shared_ptr<typename System::Cluster> > > > {}; template<typename T> typename boost::enable_if< test<T>, void>::type operator()(T& p) const { p = p->clone(newSys); newSys.push_back(p); }; template<typename T> typename boost::enable_if< mpl::not_<test<T> >, void>::type operator()(const T& p) const {}; }; public: void copyInto(System& into) const { //copy the clustergraph and clone all objects while at it. They are also pushed to the storage cloner cl(into); m_cluster->copyInto(into.m_cluster, cl); //notify all modules that they are copied Type1::system_copy(*this, into); Type2::system_copy(*this, into); Type3::system_copy(*this, into); }; System* clone() const { System* ns = new System(); this->copyInto(*ns); return ns; }; boost::shared_ptr<Cluster> m_cluster; Shedule m_sheduler; Kernel m_kernel; Storage m_storage; }; } #endif //GCM_SYSTEM_H <commit_msg>aloow shared object storage<commit_after>/* openDCM, dimensional constraint manager Copyright (C) 2012 Stefan Troeger <stefantroeger@gmx.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef GCM_SYSTEM_H #define GCM_SYSTEM_H #include <boost/mpl/vector.hpp> #include <boost/mpl/vector/vector0.hpp> #include <boost/mpl/map.hpp> #include <boost/mpl/fold.hpp> #include <boost/mpl/insert.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/count.hpp> #include <boost/mpl/or.hpp> #include <boost/mpl/less_equal.hpp> #include <boost/mpl/print.hpp> #include <boost/mpl/and.hpp> #include <boost/graph/adjacency_list.hpp> #include <iostream> #include "property.hpp" #include "clustergraph.hpp" #include "sheduler.hpp" #include "logging.hpp" #include "traits.hpp" namespace mpl = boost::mpl; namespace dcm { struct No_Identifier {}; struct Unspecified_Identifier {}; namespace details { template<typename seq, typename state> struct vector_fold : mpl::fold< seq, state, mpl::push_back<mpl::_1,mpl::_2> > {}; template<typename seq, typename state> struct edge_fold : mpl::fold< seq, state, mpl::if_< is_edge_property<mpl::_2>, mpl::push_back<mpl::_1,mpl::_2>, mpl::_1 > > {}; template<typename seq, typename state> struct vertex_fold : mpl::fold< seq, state, mpl::if_< is_vertex_property<mpl::_2>, mpl::push_back<mpl::_1,mpl::_2>, mpl::_1 > > {}; template<typename seq, typename state> struct cluster_fold : mpl::fold< seq, state, mpl::if_< is_cluster_property<mpl::_2>, mpl::push_back<mpl::_1,mpl::_2>, mpl::_1 > > {}; template<typename seq, typename state, typename obj> struct obj_fold : mpl::fold< seq, state, mpl::if_< mpl::or_< boost::is_same< details::property_kind<mpl::_2>, obj>, is_object_property<mpl::_2> >, mpl::push_back<mpl::_1,mpl::_2>, mpl::_1 > > {}; template<typename objects, typename properties> struct property_map { typedef typename mpl::fold< objects, mpl::map<>, mpl::insert< mpl::_1, mpl::pair< mpl::_2, details::obj_fold<properties, mpl::vector<>, mpl::_2 > > > >::type type; }; template<typename T> struct get_identifier { typedef typename T::Identifier type; }; template<typename seq, typename state> struct map_fold : mpl::fold< seq, state, mpl::insert<mpl::_1,mpl::_2> > {}; struct nothing {}; template<int v> struct EmptyModule { template<typename T> struct type { struct inheriter {}; typedef mpl::vector<> properties; typedef mpl::vector<> objects; typedef Unspecified_Identifier Identifier; static void system_init(T& sys) {}; static void system_copy(const T& from, T& into) {}; }; }; template <class T> struct is_shared_ptr : boost::mpl::false_ {}; template <class T> struct is_shared_ptr<boost::shared_ptr<T> > : boost::mpl::true_ {}; } template< typename KernelType, typename T1 = details::EmptyModule<1>, typename T2 = details::EmptyModule<2>, typename T3 = details::EmptyModule<3> > class System : public T1::template type< System<KernelType,T1,T2,T3> >::inheriter, public T2::template type< System<KernelType,T1,T2,T3> >::inheriter, public T3::template type< System<KernelType,T1,T2,T3> >::inheriter { typedef System<KernelType,T1,T2,T3> BaseType; public: typedef typename T1::template type< BaseType > Type1; typedef typename T2::template type< BaseType > Type2; typedef typename T3::template type< BaseType > Type3; typedef mpl::vector3<Type1, Type2, Type3> TypeVector; //Check if all Identifiers are the same and find out which type it is typedef typename mpl::fold<TypeVector, mpl::vector<>, mpl::if_<boost::is_same<details::get_identifier<mpl::_2>, Unspecified_Identifier>, mpl::_1, mpl::push_back<mpl::_1, details::get_identifier<mpl::_2> > > >::type Identifiers; BOOST_MPL_ASSERT((mpl::or_< mpl::less_equal<typename mpl::size<Identifiers>::type, mpl::int_<1> >, mpl::equal< typename mpl::count<Identifiers, typename mpl::at_c<Identifiers,0> >::type, typename mpl::size<Identifiers>::type > >)); typedef typename mpl::if_< mpl::empty<Identifiers>, No_Identifier, typename mpl::at_c<Identifiers, 0>::type >::type Identifier; public: //get all module objects and properties typedef typename details::vector_fold<typename Type3::objects, typename details::vector_fold<typename Type2::objects, typename details::vector_fold<typename Type1::objects, mpl::vector<> >::type >::type>::type objects; typedef typename details::vector_fold<typename Type3::properties, typename details::vector_fold<typename Type2::properties, typename details::vector_fold<typename Type1::properties, mpl::vector<id_prop<Identifier> > >::type >::type>::type properties; //make the subcomponent lists of objects and properties typedef typename details::edge_fold< properties, mpl::vector<> >::type edge_properties; typedef typename details::vertex_fold< properties, mpl::vector<> >::type vertex_properties; typedef typename details::cluster_fold< properties, mpl::vector<changed_prop, type_prop> >::type cluster_properties; typedef typename details::property_map<objects, properties>::type object_properties; protected: //object storage typedef typename mpl::transform<objects, boost::shared_ptr<mpl::_1> >::type sp_objects; typedef typename mpl::fold< sp_objects, mpl::vector<>, mpl::push_back<mpl::_1, std::vector<mpl::_2> > >::type object_vectors; typedef typename fusion::result_of::as_vector<object_vectors>::type Storage; template<typename FT1, typename FT2, typename FT3> friend struct Object; struct clearer { template<typename T> void operator()(T& vector) const { vector.clear(); }; }; #ifdef USE_LOGGING boost::shared_ptr< sink_t > sink; #endif public: typedef ClusterGraph<edge_properties, vertex_properties, cluster_properties, objects> Cluster; typedef Sheduler< BaseType > Shedule; typedef KernelType Kernel; public: System() : m_cluster(new Cluster), m_storage(new Storage) #ifdef USE_LOGGING , sink(init_log()) #endif { Type1::system_init(*this); Type2::system_init(*this); Type3::system_init(*this); }; ~System() { #ifdef USE_LOGGING stop_log(sink); #endif }; void clear() { m_cluster->clearClusters(); m_cluster->clear(); fusion::for_each(*m_storage, clearer()); }; template<typename Object> typename std::vector< boost::shared_ptr<Object> >::iterator begin() { typedef typename mpl::find<objects, Object>::type iterator; typedef typename mpl::distance<typename mpl::begin<objects>::type, iterator>::type distance; BOOST_MPL_ASSERT((mpl::not_<boost::is_same<iterator, typename mpl::end<objects>::type > >)); return fusion::at<distance>(*m_storage).begin(); }; template<typename Object> typename std::vector< boost::shared_ptr<Object> >::iterator end() { typedef typename mpl::find<objects, Object>::type iterator; typedef typename mpl::distance<typename mpl::begin<objects>::type, iterator>::type distance; BOOST_MPL_ASSERT((mpl::not_<boost::is_same<iterator, typename mpl::end<objects>::type > >)); return fusion::at<distance>(*m_storage).end(); }; template<typename Object> std::vector< boost::shared_ptr<Object> >& objectVector() { typedef typename mpl::find<objects, Object>::type iterator; typedef typename mpl::distance<typename mpl::begin<objects>::type, iterator>::type distance; BOOST_MPL_ASSERT((mpl::not_<boost::is_same<iterator, typename mpl::end<objects>::type > >)); return fusion::at<distance>(*m_storage); }; template<typename Object> void push_back(boost::shared_ptr<Object> ptr) { objectVector<Object>().push_back(ptr); }; template<typename Object> void erase(boost::shared_ptr<Object> ptr) { std::vector< boost::shared_ptr<Object> >& vec = objectVector<Object>(); vec.erase(std::remove(vec.begin(), vec.end(), ptr), vec.end()); }; void solve() { clock_t start = clock(); m_sheduler.execute(*this); clock_t end = clock(); double ms = (double(end-start)* 1000.) / double(CLOCKS_PER_SEC); //Base::Console().Message("overall solving time in ms: %f\n", ms); }; private: struct cloner { System& newSys; cloner(System& ns) : newSys(ns) {}; template<typename T> struct test : mpl::and_<details::is_shared_ptr<T>, mpl::not_<boost::is_same<T, boost::shared_ptr<typename System::Cluster> > > > {}; template<typename T> typename boost::enable_if< test<T>, void>::type operator()(T& p) const { p = p->clone(newSys); newSys.push_back(p); }; template<typename T> typename boost::enable_if< mpl::not_<test<T> >, void>::type operator()(const T& p) const {}; }; public: void copyInto(System& into) const { //copy the clustergraph and clone all objects while at it. They are also pushed to the storage cloner cl(into); m_cluster->copyInto(into.m_cluster, cl); //notify all modules that they are copied Type1::system_copy(*this, into); Type2::system_copy(*this, into); Type3::system_copy(*this, into); }; System* clone() const { System* ns = new System(); this->copyInto(*ns); return ns; }; boost::shared_ptr<Cluster> m_cluster; boost::shared_ptr<Storage> m_storage; Shedule m_sheduler; Kernel m_kernel; }; } #endif //GCM_SYSTEM_H <|endoftext|>
<commit_before>// Copyright (c) 2020 The Orbit 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 "Track.h" #include "Capture.h" #include "CoreMath.h" #include "GlCanvas.h" #include "TimeGraphLayout.h" #include "absl/strings/str_format.h" //----------------------------------------------------------------------------- Track::Track(TimeGraph* time_graph) : time_graph_(time_graph), collapse_toggle_( TriangleToggle::State::kExpanded, [this](TriangleToggle::State state) { OnCollapseToggle(state); }, time_graph) { m_MousePos[0] = m_MousePos[1] = Vec2(0, 0); m_Pos = Vec2(0, 0); m_Size = Vec2(0, 0); m_PickingOffset = Vec2(0, 0); m_Picked = false; m_Moving = false; m_Canvas = nullptr; } //----------------------------------------------------------------------------- std::vector<Vec2> GetRoundedCornerMask(float radius, uint32_t num_sides) { std::vector<Vec2> points; points.emplace_back(0.f, 0.f); points.emplace_back(0.f, radius); float increment_radians = 0.5f * kPiFloat / static_cast<float>(num_sides); for (uint32_t i = 1; i < num_sides; ++i) { float angle = kPiFloat + static_cast<float>(i) * increment_radians; points.emplace_back(radius * cosf(angle) + radius, radius * sinf(angle) + radius); } points.emplace_back(radius, 0.f); return points; } //----------------------------------------------------------------------------- std::vector<Vec2> RotatePoints(const std::vector<Vec2>& points, float rotation) { float cos_r = cosf(kPiFloat * rotation / 180.f); float sin_r = sinf(kPiFloat * rotation / 180.f); std::vector<Vec2> result; for (const Vec2 point : points) { float x_rotated = cos_r * point[0] - sin_r * point[1]; float y_rotated = sin_r * point[0] + cos_r * point[1]; result.push_back(Vec2(x_rotated, y_rotated)); } return result; } //----------------------------------------------------------------------------- void DrawTriangleFan(Batcher* batcher, const std::vector<Vec2>& points, const Vec2& pos, const Color& color, float rotation, float z) { if (points.size() < 3) { return; } std::vector<Vec2> rotated_points = RotatePoints(points, rotation); Vec3 position(pos[0], pos[1], z); Vec3 pivot = position + Vec3(rotated_points[0][0], rotated_points[0][1], z); Vec3 vertices[2]; vertices[0] = position + Vec3(rotated_points[1][0], rotated_points[1][1], z); for (size_t i = 1; i < rotated_points.size() - 1; ++i) { vertices[i % 2] = position + Vec3(rotated_points[i + 1][0], rotated_points[i + 1][1], z); Triangle triangle(pivot, vertices[i % 2], vertices[(i + 1) % 2]); batcher->AddTriangle(triangle, color, PickingID::PICKABLE); } } //----------------------------------------------------------------------------- void Track::Draw(GlCanvas* canvas, bool picking) { Batcher* batcher = canvas->GetBatcher(); const TimeGraphLayout& layout = time_graph_->GetLayout(); Color picking_color = canvas->GetPickingManager().GetPickableColor( this, PickingID::BatcherId::UI); const Color kTabColor(50, 50, 50, 255); Color color = picking ? picking_color : kTabColor; glColor4ubv(&color[0]); float x0 = m_Pos[0]; float x1 = x0 + m_Size[0]; float y0 = m_Pos[1]; float y1 = y0 - m_Size[1]; float track_z = layout.GetTrackZ(); float text_z = layout.GetTextZ(); float top_margin = layout.GetTrackTopMargin(); // Draw track background. if (!picking) { if (layout.GetDrawTrackBackground()) { Box box(Vec2(x0, y0 + top_margin), Vec2(m_Size[0], -m_Size[1] - top_margin), track_z); batcher->AddBox(box, color, PickingID::PICKABLE); } } // Draw tab. float label_height = layout.GetTrackTabHeight(); float half_label_height = 0.5f * label_height; float label_width = layout.GetTrackTabWidth(); float tab_x0 = x0 + layout.GetTrackTabOffset(); Box box(Vec2(tab_x0, y0), Vec2(label_width, label_height), track_z); batcher->AddBox(box, color, PickingID::PICKABLE, std::make_shared<PickingUserData>(nullptr, [&](PickingID id) { return GetGenericTooltip(id); }) ); // Draw rounded corners. if (!picking) { float vertical_margin = time_graph_->GetVerticalMargin(); const Color kBackgroundColor(70, 70, 70, 255); float radius = std::min(layout.GetRoundingRadius(), half_label_height); uint32_t sides = static_cast<uint32_t>(layout.GetRoundingNumSides() + 0.5f); auto rounded_corner = GetRoundedCornerMask(radius, sides); Vec2 bottom_left(x0, y1); Vec2 bottom_right(tab_x0 + label_width, y0 + top_margin); Vec2 top_right(tab_x0 + label_width, y0 + label_height); Vec2 top_left(tab_x0, y0 + label_height); Vec2 end_bottom(x1 - vertical_margin, y1); Vec2 end_top(x1 - vertical_margin, y0 + top_margin); float z = GlCanvas::Z_VALUE_BOX_ACTIVE + 0.001f; DrawTriangleFan(batcher, rounded_corner, bottom_left, kBackgroundColor, 0, z); DrawTriangleFan(batcher, rounded_corner, bottom_right, color, 0, z); DrawTriangleFan(batcher, rounded_corner, top_right, kBackgroundColor, 180.f, z); DrawTriangleFan(batcher, rounded_corner, top_left, kBackgroundColor, -90.f, z); DrawTriangleFan(batcher, rounded_corner, end_bottom, kBackgroundColor, 90.f, z); DrawTriangleFan(batcher, rounded_corner, end_top, kBackgroundColor, 180.f, z); // Collapse toggle state management. if (!this->IsCollapsable()) { collapse_toggle_.SetState(TriangleToggle::State::kInactive); } else if (collapse_toggle_.IsInactive()) { collapse_toggle_.ResetToInitialState(); } // Draw collapsing triangle. float button_offset = layout.GetCollapseButtonOffset(); Vec2 toggle_pos = Vec2(tab_x0 + button_offset, m_Pos[1] + half_label_height); collapse_toggle_.SetPos(toggle_pos); collapse_toggle_.Draw(canvas, picking); // Draw label. float label_offset_x = layout.GetTrackLabelOffsetX(); float label_offset_y = layout.GetTrackLabelOffsetY(); const Color kTextWhite(255, 255, 255, 255); canvas->AddText(label_.c_str(), tab_x0 + label_offset_x, y1 + label_offset_y + m_Size[1], text_z, kTextWhite, label_width - label_offset_x); } m_Canvas = canvas; } //----------------------------------------------------------------------------- void Track::UpdatePrimitives(uint64_t /*t_min*/, uint64_t /*t_max*/) {} //----------------------------------------------------------------------------- void Track::SetPos(float a_X, float a_Y) { if (!m_Moving) { m_Pos = Vec2(a_X, a_Y); } } //----------------------------------------------------------------------------- void Track::SetY(float y) { if (!m_Moving) { m_Pos[1] = y; } } //----------------------------------------------------------------------------- void Track::SetSize(float a_SizeX, float a_SizeY) { m_Size = Vec2(a_SizeX, a_SizeY); } //----------------------------------------------------------------------------- void Track::OnCollapseToggle(TriangleToggle::State /*state*/) { time_graph_->NeedsUpdate(); time_graph_->NeedsRedraw(); } std::string Track::GetGenericTooltip(PickingID _) const { return std::string("Displays all hooked functions executed from thread ") + GetLabel(); } //----------------------------------------------------------------------------- void Track::OnPick(int a_X, int a_Y) { if (!m_PickingEnabled) return; Vec2& mousePos = m_MousePos[0]; m_Canvas->ScreenToWorld(a_X, a_Y, mousePos[0], mousePos[1]); m_PickingOffset = mousePos - m_Pos; m_MousePos[1] = m_MousePos[0]; m_Picked = true; } //----------------------------------------------------------------------------- void Track::OnRelease() { if (!m_PickingEnabled) return; m_Picked = false; m_Moving = false; time_graph_->NeedsUpdate(); } //----------------------------------------------------------------------------- void Track::OnDrag(int a_X, int a_Y) { if (!m_PickingEnabled) return; m_Moving = true; float x = 0.f; m_Canvas->ScreenToWorld(a_X, a_Y, x, m_Pos[1]); m_MousePos[1] = m_Pos; m_Pos[1] -= m_PickingOffset[1]; time_graph_->NeedsUpdate(); } <commit_msg>Collapse triangle is rendered into picking again, was falsely removed<commit_after>// Copyright (c) 2020 The Orbit 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 "Track.h" #include "Capture.h" #include "CoreMath.h" #include "GlCanvas.h" #include "TimeGraphLayout.h" #include "absl/strings/str_format.h" //----------------------------------------------------------------------------- Track::Track(TimeGraph* time_graph) : time_graph_(time_graph), collapse_toggle_( TriangleToggle::State::kExpanded, [this](TriangleToggle::State state) { OnCollapseToggle(state); }, time_graph) { m_MousePos[0] = m_MousePos[1] = Vec2(0, 0); m_Pos = Vec2(0, 0); m_Size = Vec2(0, 0); m_PickingOffset = Vec2(0, 0); m_Picked = false; m_Moving = false; m_Canvas = nullptr; } //----------------------------------------------------------------------------- std::vector<Vec2> GetRoundedCornerMask(float radius, uint32_t num_sides) { std::vector<Vec2> points; points.emplace_back(0.f, 0.f); points.emplace_back(0.f, radius); float increment_radians = 0.5f * kPiFloat / static_cast<float>(num_sides); for (uint32_t i = 1; i < num_sides; ++i) { float angle = kPiFloat + static_cast<float>(i) * increment_radians; points.emplace_back(radius * cosf(angle) + radius, radius * sinf(angle) + radius); } points.emplace_back(radius, 0.f); return points; } //----------------------------------------------------------------------------- std::vector<Vec2> RotatePoints(const std::vector<Vec2>& points, float rotation) { float cos_r = cosf(kPiFloat * rotation / 180.f); float sin_r = sinf(kPiFloat * rotation / 180.f); std::vector<Vec2> result; for (const Vec2 point : points) { float x_rotated = cos_r * point[0] - sin_r * point[1]; float y_rotated = sin_r * point[0] + cos_r * point[1]; result.push_back(Vec2(x_rotated, y_rotated)); } return result; } //----------------------------------------------------------------------------- void DrawTriangleFan(Batcher* batcher, const std::vector<Vec2>& points, const Vec2& pos, const Color& color, float rotation, float z) { if (points.size() < 3) { return; } std::vector<Vec2> rotated_points = RotatePoints(points, rotation); Vec3 position(pos[0], pos[1], z); Vec3 pivot = position + Vec3(rotated_points[0][0], rotated_points[0][1], z); Vec3 vertices[2]; vertices[0] = position + Vec3(rotated_points[1][0], rotated_points[1][1], z); for (size_t i = 1; i < rotated_points.size() - 1; ++i) { vertices[i % 2] = position + Vec3(rotated_points[i + 1][0], rotated_points[i + 1][1], z); Triangle triangle(pivot, vertices[i % 2], vertices[(i + 1) % 2]); batcher->AddTriangle(triangle, color, PickingID::PICKABLE); } } //----------------------------------------------------------------------------- void Track::Draw(GlCanvas* canvas, bool picking) { Batcher* batcher = canvas->GetBatcher(); const TimeGraphLayout& layout = time_graph_->GetLayout(); Color picking_color = canvas->GetPickingManager().GetPickableColor( this, PickingID::BatcherId::UI); const Color kTabColor(50, 50, 50, 255); Color color = picking ? picking_color : kTabColor; glColor4ubv(&color[0]); float x0 = m_Pos[0]; float x1 = x0 + m_Size[0]; float y0 = m_Pos[1]; float y1 = y0 - m_Size[1]; float track_z = layout.GetTrackZ(); float text_z = layout.GetTextZ(); float top_margin = layout.GetTrackTopMargin(); // Draw track background. if (!picking) { if (layout.GetDrawTrackBackground()) { Box box(Vec2(x0, y0 + top_margin), Vec2(m_Size[0], -m_Size[1] - top_margin), track_z); batcher->AddBox(box, color, PickingID::PICKABLE); } } // Draw tab. float label_height = layout.GetTrackTabHeight(); float half_label_height = 0.5f * label_height; float label_width = layout.GetTrackTabWidth(); float tab_x0 = x0 + layout.GetTrackTabOffset(); Box box(Vec2(tab_x0, y0), Vec2(label_width, label_height), track_z); batcher->AddBox(box, color, PickingID::PICKABLE, std::make_shared<PickingUserData>(nullptr, [&](PickingID id) { return GetGenericTooltip(id); })); // Draw rounded corners. if (!picking) { float vertical_margin = time_graph_->GetVerticalMargin(); const Color kBackgroundColor(70, 70, 70, 255); float radius = std::min(layout.GetRoundingRadius(), half_label_height); uint32_t sides = static_cast<uint32_t>(layout.GetRoundingNumSides() + 0.5f); auto rounded_corner = GetRoundedCornerMask(radius, sides); Vec2 bottom_left(x0, y1); Vec2 bottom_right(tab_x0 + label_width, y0 + top_margin); Vec2 top_right(tab_x0 + label_width, y0 + label_height); Vec2 top_left(tab_x0, y0 + label_height); Vec2 end_bottom(x1 - vertical_margin, y1); Vec2 end_top(x1 - vertical_margin, y0 + top_margin); float z = GlCanvas::Z_VALUE_BOX_ACTIVE + 0.001f; DrawTriangleFan(batcher, rounded_corner, bottom_left, kBackgroundColor, 0, z); DrawTriangleFan(batcher, rounded_corner, bottom_right, color, 0, z); DrawTriangleFan(batcher, rounded_corner, top_right, kBackgroundColor, 180.f, z); DrawTriangleFan(batcher, rounded_corner, top_left, kBackgroundColor, -90.f, z); DrawTriangleFan(batcher, rounded_corner, end_bottom, kBackgroundColor, 90.f, z); DrawTriangleFan(batcher, rounded_corner, end_top, kBackgroundColor, 180.f, z); } // Collapse toggle state management. if (!this->IsCollapsable()) { collapse_toggle_.SetState(TriangleToggle::State::kInactive); } else if (collapse_toggle_.IsInactive()) { collapse_toggle_.ResetToInitialState(); } // Draw collapsing triangle. float button_offset = layout.GetCollapseButtonOffset(); Vec2 toggle_pos = Vec2(tab_x0 + button_offset, m_Pos[1] + half_label_height); collapse_toggle_.SetPos(toggle_pos); collapse_toggle_.Draw(canvas, picking); if (!picking) { // Draw label. float label_offset_x = layout.GetTrackLabelOffsetX(); float label_offset_y = layout.GetTrackLabelOffsetY(); const Color kTextWhite(255, 255, 255, 255); canvas->AddText(label_.c_str(), tab_x0 + label_offset_x, y1 + label_offset_y + m_Size[1], text_z, kTextWhite, label_width - label_offset_x); } m_Canvas = canvas; } //----------------------------------------------------------------------------- void Track::UpdatePrimitives(uint64_t /*t_min*/, uint64_t /*t_max*/) {} //----------------------------------------------------------------------------- void Track::SetPos(float a_X, float a_Y) { if (!m_Moving) { m_Pos = Vec2(a_X, a_Y); } } //----------------------------------------------------------------------------- void Track::SetY(float y) { if (!m_Moving) { m_Pos[1] = y; } } //----------------------------------------------------------------------------- void Track::SetSize(float a_SizeX, float a_SizeY) { m_Size = Vec2(a_SizeX, a_SizeY); } //----------------------------------------------------------------------------- void Track::OnCollapseToggle(TriangleToggle::State /*state*/) { time_graph_->NeedsUpdate(); time_graph_->NeedsRedraw(); } std::string Track::GetGenericTooltip(PickingID _) const { return std::string("Displays all hooked functions executed from thread ") + GetLabel(); } //----------------------------------------------------------------------------- void Track::OnPick(int a_X, int a_Y) { if (!m_PickingEnabled) return; Vec2& mousePos = m_MousePos[0]; m_Canvas->ScreenToWorld(a_X, a_Y, mousePos[0], mousePos[1]); m_PickingOffset = mousePos - m_Pos; m_MousePos[1] = m_MousePos[0]; m_Picked = true; } //----------------------------------------------------------------------------- void Track::OnRelease() { if (!m_PickingEnabled) return; m_Picked = false; m_Moving = false; time_graph_->NeedsUpdate(); } //----------------------------------------------------------------------------- void Track::OnDrag(int a_X, int a_Y) { if (!m_PickingEnabled) return; m_Moving = true; float x = 0.f; m_Canvas->ScreenToWorld(a_X, a_Y, x, m_Pos[1]); m_MousePos[1] = m_Pos; m_Pos[1] -= m_PickingOffset[1]; time_graph_->NeedsUpdate(); } <|endoftext|>
<commit_before>// Copyright (c) The University of Cincinnati. // All rights reserved. // UC MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF // THE SOFTWARE, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE, OR NON-INFRINGEMENT. UC SHALL NOT BE LIABLE // FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, // RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS // DERIVATIVES. // By using or copying this Software, Licensee agrees to abide by the // intellectual property laws, and all other applicable laws of the // U.S., and the terms of this license. //Authors: Xinyu Guo guox2@mail.uc.edu // Philip A. Wilsey phil.wilsey@uc.edu #include "Iscas85Application.h" #include "LogicEvent.h" #include "FileReaderWriter.h" #include "NInputAndGate.h" #include "NInputXorGate.h" #include "NInputOrGate.h" #include "NInputNandGate.h" #include "NInputNorGate.h" #include "NotGate.h" #include <warped/PartitionInfo.h> #include <warped/RoundRobinPartitioner.h> #include <warped/DeserializerManager.h> #include <utils/ArgumentParser.h> #include "vector" #include "iostream" #include "fstream" #include "stdlib.h" using namespace std; Iscas85Application::Iscas85Application() :inputFileName( "" ), testCaseFileName(""), numObjects( 0 ){} int Iscas85Application::initialize( vector<string> &arguments ){ string path="circuitsimulationmodels/iscas85/iscas85Sim/"; getArgumentParser().checkArgs( arguments ); if( inputFileName.empty() ){ std::cerr << "A smmpSim configuration file must be specified using -simulate"<<std::endl; abort(); } return 0; } int Iscas85Application::finalize(){ return 0; } int Iscas85Application::getNumberOfSimulationObjects(int mgrId) const { return numObjects; } const PartitionInfo* Iscas85Application::getPartitionInfo(unsigned int numberOfProcessorsAvailable){ const PartitionInfo *retval = 0; Partitioner *myPartitioner = new RoundRobinPartitioner(); int numFileObjects; string fileName; int numOfGates; string type; int desPort; string desGateName; int maxLines; ifstream configfile; configfile.open(inputFileName.c_str()); if(configfile.fail()){ cerr<<"Could not open file!:'"<<inputFileName<<"'"<<endl; cerr<<"Terminating simulation."<<endl; abort(); } vector<SimulationObject *> *objects = new vector<SimulationObject *>; string filePath;// int totalGates; // total gates number in the circuit configfile>>filePath;// configfile>>numFileObjects; configfile>>totalGates; for(int i=0; i < numFileObjects; i++){ configfile>>fileName>>numOfGates>>type; vector<int> *desPortId = new vector<int>; vector<string> *desGatesNames = new vector<string>; if(0==numOfGates){ configfile>>desPort; //cout<<"numOfGates is:"<<numOfGates<<endl; //cout<<"desPort Value is:"<<desPort<<endl; desPortId->push_back(desPort); configfile>>desGateName; //cout<<"numOfGates is:"<<numOfGates<<endl; //cout<<"desPort Value is:"<<desPort<<endl; desGatesNames->push_back(desGateName); } else{ for(int j= 0;j<numOfGates;j++){ configfile>>desPort; //cout<<"numOfGates is:"<<numOfGates<<endl; //cout<<"desPort Value is:"<<desPort<<endl; desPortId->push_back(desPort); } for(int j= 0;j<numOfGates;j++){ configfile>>desGateName; desGatesNames->push_back(desGateName); } } configfile>>maxLines; fileName = filePath+fileName;//the absolute path of the file SimulationObject *newObject = new FileReaderWriter(fileName,numOfGates,type,desPortId,desGatesNames,maxLines); objects->push_back(newObject); //cout<<"construct FileReaderWriter object!"<<endl; } // int totalGates; // total gates number in the circuit string myObjName; // object name int numberOfInputs; // the number of inputs of the object int numberOfOutputs; // the number of objects connected to the object string destObjName; // the name of the gate which receives the object output int desInputPort; // pin id of the gate which receives the object output int delay; // the delay between event receiving and event sending // configfile >> totalGates; for(int i = 0; i < totalGates; i++){ configfile >> myObjName >> numberOfInputs >> numberOfOutputs;// >> destObjName >> desInputPort; vector<string> *outputObjectNames = new vector<string>; vector<int> *destinationPorts = new vector<int>; for(int i = 0; i < numberOfOutputs; i++){ configfile >> destObjName; //cout<<"object name is "<< destObjName<<endl; outputObjectNames -> push_back(destObjName); } for(int i =0; i < numberOfOutputs; i++){ configfile >> desInputPort; destinationPorts->push_back(desInputPort); } configfile >> delay; string gate= myObjName.substr(0,1); string gate1 = myObjName.substr(0,3); if("A"==gate){ SimulationObject *newObject = new NInputAndGate(myObjName, numberOfInputs, numberOfOutputs, outputObjectNames, destinationPorts, delay); objects->push_back(newObject); // cout << "building object with R !"<<endl; // cout << "the address of the object is " << newObject<<endl; } else if ("X"==gate){ SimulationObject *newObject = new NInputXorGate(myObjName, numberOfInputs, numberOfOutputs, outputObjectNames, destinationPorts, delay); objects->push_back(newObject); // cout << "building object with R !"<<endl; // cout << "the address of the object is " << newObject<<endl; } else if ("O"==gate){ SimulationObject *newObject = new NInputOrGate(myObjName, numberOfInputs, numberOfOutputs, outputObjectNames, destinationPorts, delay); objects->push_back(newObject); // cout << "building object with R !"<<endl; // cout << "the address of the object is " << newObject<<endl; } else { if("NOT"==gate1){ SimulationObject *newObject = new NotGate(myObjName, numberOfInputs,numberOfOutputs,outputObjectNames, destinationPorts,delay); objects->push_back(newObject); } if("NAN"==gate1){ SimulationObject *newObject = new NotGate(myObjName, numberOfInputs,numberOfOutputs,outputObjectNames, destinationPorts,delay); objects->push_back(newObject); } if("NOR"==gate1){ SimulationObject *newObject = new NotGate(myObjName, numberOfInputs,numberOfOutputs,outputObjectNames, destinationPorts,delay); objects->push_back(newObject); } } } // cout<<"objects size is"<<objects->size()<<endl; retval = myPartitioner->partition( objects, numberOfProcessorsAvailable ); delete objects; return retval; } void Iscas85Application::registerDeserializers(){ DeserializerManager::instance()->registerDeserializer(LogicEvent::getLogicEventDataType(),&LogicEvent::deserialize); } ArgumentParser & Iscas85Application::getArgumentParser(){ static ArgumentParser::ArgRecord args[] = { {"-simulate", "input file name", &inputFileName, ArgumentParser::STRING,false}, {"","",0 } }; static ArgumentParser *myArgParser = new ArgumentParser(args); return *myArgParser; } <commit_msg>change the Iscas85 models configuration file input manner<commit_after>// Copyright (c) The University of Cincinnati. // All rights reserved. // UC MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF // THE SOFTWARE, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE, OR NON-INFRINGEMENT. UC SHALL NOT BE LIABLE // FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, // RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS // DERIVATIVES. // By using or copying this Software, Licensee agrees to abide by the // intellectual property laws, and all other applicable laws of the // U.S., and the terms of this license. //Authors: Xinyu Guo guox2@mail.uc.edu // Philip A. Wilsey phil.wilsey@uc.edu #include "Iscas85Application.h" #include "LogicEvent.h" #include "FileReaderWriter.h" #include "NInputAndGate.h" #include "NInputXorGate.h" #include "NInputOrGate.h" #include "NInputNandGate.h" #include "NInputNorGate.h" #include "NotGate.h" #include <warped/PartitionInfo.h> #include <warped/RoundRobinPartitioner.h> #include <warped/DeserializerManager.h> #include <utils/ArgumentParser.h> #include "vector" #include "iostream" #include "fstream" #include "stdlib.h" using namespace std; Iscas85Application::Iscas85Application() :inputFileName( "" ), testCaseFileName(""), numObjects( 0 ){} int Iscas85Application::initialize( vector<string> &arguments ){ string path="circuitsimulationmodels/iscas85/iscas85Sim/"; arguments[2] = path+arguments[2]+"/"+arguments[2]+"config"; getArgumentParser().checkArgs( arguments ); if( inputFileName.empty() ){ std::cerr << "A smmpSim configuration file must be specified using -simulate"<<std::endl; abort(); } return 0; } int Iscas85Application::finalize(){ return 0; } int Iscas85Application::getNumberOfSimulationObjects(int mgrId) const { return numObjects; } const PartitionInfo* Iscas85Application::getPartitionInfo(unsigned int numberOfProcessorsAvailable){ const PartitionInfo *retval = 0; Partitioner *myPartitioner = new RoundRobinPartitioner(); int numFileObjects; string fileName; int numOfGates; string type; int desPort; string desGateName; int maxLines; ifstream configfile; configfile.open(inputFileName.c_str()); if(configfile.fail()){ cerr<<"Could not open file!:'"<<inputFileName<<"'"<<endl; cerr<<"Terminating simulation."<<endl; abort(); } vector<SimulationObject *> *objects = new vector<SimulationObject *>; string filePath;// int totalGates; // total gates number in the circuit configfile>>filePath;// configfile>>numFileObjects; configfile>>totalGates; for(int i=0; i < numFileObjects; i++){ configfile>>fileName>>numOfGates>>type; vector<int> *desPortId = new vector<int>; vector<string> *desGatesNames = new vector<string>; if(0==numOfGates){ configfile>>desPort; //cout<<"numOfGates is:"<<numOfGates<<endl; //cout<<"desPort Value is:"<<desPort<<endl; desPortId->push_back(desPort); configfile>>desGateName; //cout<<"numOfGates is:"<<numOfGates<<endl; //cout<<"desPort Value is:"<<desPort<<endl; desGatesNames->push_back(desGateName); } else{ for(int j= 0;j<numOfGates;j++){ configfile>>desPort; //cout<<"numOfGates is:"<<numOfGates<<endl; //cout<<"desPort Value is:"<<desPort<<endl; desPortId->push_back(desPort); } for(int j= 0;j<numOfGates;j++){ configfile>>desGateName; desGatesNames->push_back(desGateName); } } configfile>>maxLines; fileName = filePath+fileName;//the absolute path of the file SimulationObject *newObject = new FileReaderWriter(fileName,numOfGates,type,desPortId,desGatesNames,maxLines); objects->push_back(newObject); //cout<<"construct FileReaderWriter object!"<<endl; } // int totalGates; // total gates number in the circuit string myObjName; // object name int numberOfInputs; // the number of inputs of the object int numberOfOutputs; // the number of objects connected to the object string destObjName; // the name of the gate which receives the object output int desInputPort; // pin id of the gate which receives the object output int delay; // the delay between event receiving and event sending // configfile >> totalGates; for(int i = 0; i < totalGates; i++){ configfile >> myObjName >> numberOfInputs >> numberOfOutputs;// >> destObjName >> desInputPort; vector<string> *outputObjectNames = new vector<string>; vector<int> *destinationPorts = new vector<int>; for(int i = 0; i < numberOfOutputs; i++){ configfile >> destObjName; //cout<<"object name is "<< destObjName<<endl; outputObjectNames -> push_back(destObjName); } for(int i =0; i < numberOfOutputs; i++){ configfile >> desInputPort; destinationPorts->push_back(desInputPort); } configfile >> delay; string gate= myObjName.substr(0,1); string gate1 = myObjName.substr(0,3); if("A"==gate){ SimulationObject *newObject = new NInputAndGate(myObjName, numberOfInputs, numberOfOutputs, outputObjectNames, destinationPorts, delay); objects->push_back(newObject); // cout << "building object with R !"<<endl; // cout << "the address of the object is " << newObject<<endl; } else if ("X"==gate){ SimulationObject *newObject = new NInputXorGate(myObjName, numberOfInputs, numberOfOutputs, outputObjectNames, destinationPorts, delay); objects->push_back(newObject); // cout << "building object with R !"<<endl; // cout << "the address of the object is " << newObject<<endl; } else if ("O"==gate){ SimulationObject *newObject = new NInputOrGate(myObjName, numberOfInputs, numberOfOutputs, outputObjectNames, destinationPorts, delay); objects->push_back(newObject); // cout << "building object with R !"<<endl; // cout << "the address of the object is " << newObject<<endl; } else { if("NOT"==gate1){ SimulationObject *newObject = new NotGate(myObjName, numberOfInputs,numberOfOutputs,outputObjectNames, destinationPorts,delay); objects->push_back(newObject); } if("NAN"==gate1){ SimulationObject *newObject = new NotGate(myObjName, numberOfInputs,numberOfOutputs,outputObjectNames, destinationPorts,delay); objects->push_back(newObject); } if("NOR"==gate1){ SimulationObject *newObject = new NotGate(myObjName, numberOfInputs,numberOfOutputs,outputObjectNames, destinationPorts,delay); objects->push_back(newObject); } } } // cout<<"objects size is"<<objects->size()<<endl; retval = myPartitioner->partition( objects, numberOfProcessorsAvailable ); delete objects; return retval; } void Iscas85Application::registerDeserializers(){ DeserializerManager::instance()->registerDeserializer(LogicEvent::getLogicEventDataType(),&LogicEvent::deserialize); } ArgumentParser & Iscas85Application::getArgumentParser(){ static ArgumentParser::ArgRecord args[] = { {"-simulate", "input file name", &inputFileName, ArgumentParser::STRING,false}, {"","",0 } }; static ArgumentParser *myArgParser = new ArgumentParser(args); return *myArgParser; } <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/Attic/CTabWidget.cpp,v $ // $Revision: 1.16 $ // $Name: $ // $Author: shoops $ // $Date: 2008/06/03 13:58:56 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <qtabwidget.h> #include <qlayout.h> #include "CTabWidget.h" #include "ModelWidget.h" #include "MIRIAMUI/CQMiriamWidget.h" #include "MIRIAMUI/CQRDFListViewWidget.h" /* * Constructs a CTabWidget as a child of 'parent', with the * name 'name' and widget flags set to 'f'. label is the first * tab name. */ CTabWidget::CTabWidget(const QString & label, CopasiWidget * pCopasiWidget, QWidget* parent, const char* name, WFlags f) : CopasiWidget(parent, name, f) { if (!name) CopasiWidget::setName("CTabWidget"); QHBoxLayout* tabLayout = new QHBoxLayout(this, 0, 0, "tabLayout"); mTabWidget = new QTabWidget (this, "mTabWidget"); tabLayout->addWidget(mTabWidget); mPages.push_back(pCopasiWidget); mTabWidget->addTab(pCopasiWidget, label); CQMiriamWidget* pMIRIAMWidget = new CQMiriamWidget(mTabWidget); mPages.push_back(pMIRIAMWidget); mTabWidget->addTab(mPages[1], "Annotation"); CQRDFListViewWidget* pRDFListViewWidget = new CQRDFListViewWidget(mTabWidget); mPages.push_back(pRDFListViewWidget); mTabWidget->addTab(mPages[2], "RDF Browser"); pRDFListViewWidget->setMIRIAMInfo(&pMIRIAMWidget->getMIRIAMInfo()); } /* * Destroys the object and frees any allocated resources */ CTabWidget::~CTabWidget() { // no need to delete child widgets, Qt does it all for us } bool CTabWidget::leave() { std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) (*it)->leave(); return true; } bool CTabWidget::enter(const std::string & key) { std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) (*it)->enter(key); return true; } <commit_msg>Removed obsolete call to CRDFListViewWidget::setMIRIAMInfo.<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/Attic/CTabWidget.cpp,v $ // $Revision: 1.17 $ // $Name: $ // $Author: shoops $ // $Date: 2008/06/10 20:30:32 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <qtabwidget.h> #include <qlayout.h> #include "CTabWidget.h" #include "ModelWidget.h" #include "MIRIAMUI/CQMiriamWidget.h" #include "MIRIAMUI/CQRDFListViewWidget.h" /* * Constructs a CTabWidget as a child of 'parent', with the * name 'name' and widget flags set to 'f'. label is the first * tab name. */ CTabWidget::CTabWidget(const QString & label, CopasiWidget * pCopasiWidget, QWidget* parent, const char* name, WFlags f) : CopasiWidget(parent, name, f) { if (!name) CopasiWidget::setName("CTabWidget"); QHBoxLayout* tabLayout = new QHBoxLayout(this, 0, 0, "tabLayout"); mTabWidget = new QTabWidget (this, "mTabWidget"); tabLayout->addWidget(mTabWidget); mPages.push_back(pCopasiWidget); mTabWidget->addTab(pCopasiWidget, label); CQMiriamWidget* pMIRIAMWidget = new CQMiriamWidget(mTabWidget); mPages.push_back(pMIRIAMWidget); mTabWidget->addTab(mPages[1], "Annotation"); CQRDFListViewWidget* pRDFListViewWidget = new CQRDFListViewWidget(mTabWidget); mPages.push_back(pRDFListViewWidget); mTabWidget->addTab(mPages[2], "RDF Browser"); } /* * Destroys the object and frees any allocated resources */ CTabWidget::~CTabWidget() { // no need to delete child widgets, Qt does it all for us } bool CTabWidget::leave() { std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) (*it)->leave(); return true; } bool CTabWidget::enter(const std::string & key) { std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) (*it)->enter(key); return true; } <|endoftext|>
<commit_before>#include "RooFitCore/RooFit.hh" #include "Rtypes.h" #include "Rtypes.h" #include "Riostream.h" // -- CLASS DESCRIPTION [AUX] -- // Print banner message when RooFit library is loaded const char* VTAG="2.06" ; Int_t doBanner() { cout << endl << "\033[1mRooFit v" << VTAG << " -- Developed by Wouter Verkerke and David Kirkby\033[0m " << endl << " Copyright (C) 2000-2005 NIKHEF, University of California & Stanford University" << endl << " All rights reserved, please read http://roofit.sourceforge.net/license.txt" << endl << endl ; return 0 ; } static Int_t dummy = doBanner() ; <commit_msg><commit_after>#include "RooFitCore/RooFit.hh" #include "Rtypes.h" #include "Rtypes.h" #include "Riostream.h" // -- CLASS DESCRIPTION [AUX] -- // Print banner message when RooFit library is loaded const char* VTAG="2.07" ; Int_t doBanner() { cout << endl << "\033[1mRooFit v" << VTAG << " -- Developed by Wouter Verkerke and David Kirkby\033[0m " << endl << " Copyright (C) 2000-2005 NIKHEF, University of California & Stanford University" << endl << " All rights reserved, please read http://roofit.sourceforge.net/license.txt" << endl << endl ; return 0 ; } static Int_t dummy = doBanner() ; <|endoftext|>
<commit_before>/** Copyright (c) 2013, Philip Deegan. 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 Philip Deegan 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. */ #ifndef _KUL_PROC_HPP_ #define _KUL_PROC_HPP_ #include <string> #include <tchar.h> #include <stdio.h> #include <sstream> #include <strsafe.h> #include <Windows.h> #include "kul/os.hpp" #include "kul/def.hpp" #include "kul/log.hpp" #include "kul/string.hpp" #include "kul/proc.base.hpp" // extern char **environ; #include <iostream> namespace kul{ namespace this_proc{ inline int32_t id(){ return GetCurrentProcessId(); } inline void kill(const int32_t& e){ TerminateProcess(OpenProcess(PROCESS_TERMINATE, 0, kul::this_proc::id()), 128+e); } } class Process : public kul::AProcess{ private: static ULONG PIPE_ID(){ static ULONG p = 999; p++; return p; } HANDLE g_hChildStd_OUT_Rd = NULL; HANDLE g_hChildStd_OUT_Wr = NULL; HANDLE g_hChildStd_ERR_Rd = NULL; HANDLE g_hChildStd_ERR_Wr = NULL; HANDLE revent = CreateEvent(0, 1, 0, 0); public: Process(const std::string& cmd, const bool& wfe = true) : kul::AProcess(cmd, wfe) {} Process(const std::string& cmd, const std::string& path, const bool& wfe = true): kul::AProcess(cmd, path, wfe){} ~Process(){ tearDown(); } bool kill(int16_t k = 6){ if(!started()) return 0; DWORD dwDesiredAccess = PROCESS_TERMINATE; bool bInheritHandle = 0; HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, pid()); if (hProcess == NULL) return 0; bool r = TerminateProcess(hProcess, 128+k); CloseHandle(hProcess); setFinished(); return r; } protected: void tearDown(){ CloseHandle(g_hChildStd_OUT_Rd); CloseHandle(g_hChildStd_ERR_Rd); } void run() throw (kul::Exception){ SECURITY_ATTRIBUTES sa; ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES)); // Set the bInheritHandle flag so pipe handles are inherited. sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; std::stringstream ss; ss << this; const ULONG& pipeID = PIPE_ID(); std::string pipeOut = "\\\\.\\Pipe\\kul_proc_out."+std::to_string(this_proc::id())+"."+ss.str()+"."+std::to_string(pipeID); std::string pipeErr = "\\\\.\\Pipe\\kul_proc_err."+std::to_string(this_proc::id())+"."+ss.str()+"."+std::to_string(pipeID); std::string pipeIn = "\\\\.\\Pipe\\kul_proc_in." +std::to_string(this_proc::id())+"."+ss.str()+"."+std::to_string(pipeID); LPSTR lPipeOut = _strdup(pipeOut.c_str()); g_hChildStd_OUT_Wr = ::CreateNamedPipeA(lPipeOut, PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, __KUL_PROCESS_BUFFER__, __KUL_PROCESS_BUFFER__, 0, &sa); if(!g_hChildStd_OUT_Wr) error(__LINE__, "CreatePipe failed"); g_hChildStd_OUT_Rd = ::CreateFileA(lPipeOut, GENERIC_READ, 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0); if(!g_hChildStd_OUT_Rd) error(__LINE__, "CreatePipe failed"); if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) error(__LINE__, "SetHandleInformation failed"); LPSTR lPipeErr = _strdup(pipeErr.c_str()); g_hChildStd_ERR_Wr = ::CreateNamedPipeA(lPipeErr, PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, __KUL_PROCESS_BUFFER__, __KUL_PROCESS_BUFFER__, 0, &sa); if(!g_hChildStd_ERR_Wr) error(__LINE__, "CreatePipe failed"); g_hChildStd_ERR_Rd = ::CreateFileA(lPipeErr, GENERIC_READ, 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0); if(!g_hChildStd_ERR_Rd) error(__LINE__, "CreatePipe failed"); if (!SetHandleInformation(g_hChildStd_ERR_Rd, HANDLE_FLAG_INHERIT, 0)) error(__LINE__, "SetHandleInformation failed"); bool bSuccess = FALSE; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.dwFlags = STARTF_USESTDHANDLES; siStartInfo.hStdError = g_hChildStd_ERR_Wr; siStartInfo.hStdOutput = g_hChildStd_OUT_Wr; siStartInfo.wShowWindow = SW_HIDE; siStartInfo.lpDesktop = NULL; siStartInfo.lpReserved = NULL; siStartInfo.lpTitle = NULL; siStartInfo.cbReserved2 = 0; siStartInfo.lpReserved2 = NULL; unsigned flags = CREATE_UNICODE_ENVIRONMENT; HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (cons == INVALID_HANDLE_VALUE) { flags |= DETACHED_PROCESS; } else { CloseHandle(cons); } preStart(); LPTSTR lpszVariable; LPCH lpvEnv; lpvEnv = GetEnvironmentStrings(); if (lpvEnv == NULL) error(__LINE__, "GetEnvironmentStrings() failed."); kul::hash::map::S2S env; for (lpszVariable = (LPTSTR) lpvEnv; *lpszVariable; lpszVariable++){ std::stringstream ss; while (*lpszVariable) ss << *lpszVariable++; std::string var = ss.str(); if(var.find(":") != std::string::npos) env.insert(var.substr(0, var.find(":")), var.substr(var.find(":") + 1)); else env.insert(var, ""); } if(FreeEnvironmentStrings(lpvEnv) == 0) error(__LINE__, "FreeEnvironmentStrings() failed"); const char* dir = directory().empty() ? 0 : directory().c_str(); LPSTR szCmdline = _strdup(toString().c_str()); if(vars().size()){ TCHAR chNewEnv[__KUL_PROCESS_ENV_BUFFER__]; LPTSTR lpszCurrentVariable; lpszCurrentVariable = (LPTSTR) chNewEnv; for(auto& evs : vars()){ if(FAILED(StringCchCopy(lpszCurrentVariable, __KUL_PROCESS_ENV_BUFFER__, TEXT(std::string(evs.first + "=" + evs.second).c_str())))) error(__LINE__, "String copy failed"); lpszCurrentVariable += lstrlen(lpszCurrentVariable) + 1; } for(auto& evs : env){ if(vars().count(evs.first)) continue; if(FAILED(StringCchCopy(lpszCurrentVariable, __KUL_PROCESS_ENV_BUFFER__, TEXT(std::string(evs.first + "=" + evs.second).c_str())))) error(__LINE__, "String copy failed"); lpszCurrentVariable += lstrlen(lpszCurrentVariable) + 1; } *lpszCurrentVariable = (TCHAR)0; bSuccess = CreateProcess(NULL, szCmdline, NULL, NULL, TRUE, flags, chNewEnv, dir, &siStartInfo, &piProcInfo); }else bSuccess = CreateProcess(NULL, szCmdline, NULL, NULL, TRUE, flags, NULL, dir, &siStartInfo, &piProcInfo); if(!bSuccess) error(__LINE__, "CreateProcess failed with last error: " + GetLastError()); pid(piProcInfo.dwProcessId); CloseHandle(g_hChildStd_OUT_Wr); CloseHandle(g_hChildStd_ERR_Wr); if(this->waitForExit()){ OVERLAPPED il = { 0 }; memset(&il, 0, sizeof(il)); il.hEvent = revent; OVERLAPPED ol = { 0 }; memset(&ol, 0, sizeof(ol)); ol.hEvent = revent; OVERLAPPED el = { 0 }; memset(&el, 0, sizeof(el)); el.hEvent = revent; DWORD dwRead; CHAR chBuf[__KUL_PROCESS_BUFFER__ + 1]; bSuccess = FALSE; bool alive = true; do{ alive = WaitForSingleObject(piProcInfo.hProcess, 11) == WAIT_TIMEOUT; for (;;) { dwRead = 0; bSuccess = ::ReadFile( g_hChildStd_OUT_Rd, chBuf, __KUL_PROCESS_BUFFER__, &dwRead, &ol); while(!bSuccess && (GetLastError() == ERROR_IO_PENDING || GetLastError() == ERROR_IO_INCOMPLETE)){ WaitForSingleObject(ol.hEvent, 11); bSuccess = GetOverlappedResult(g_hChildStd_OUT_Rd, &ol, &dwRead, 0); } if(!bSuccess || dwRead == 0) break; chBuf[dwRead] = '\0'; out(std::string(chBuf, dwRead)); } for (;;) { dwRead = 0; bSuccess = ::ReadFile( g_hChildStd_ERR_Rd, chBuf, __KUL_PROCESS_BUFFER__, &dwRead, &el); if (GetLastError() == ERROR_IO_PENDING) { WaitForSingleObject(el.hEvent, 11); bSuccess = GetOverlappedResult(g_hChildStd_OUT_Rd, &el, &dwRead, 0); } if(!bSuccess || dwRead == 0) break; chBuf[dwRead] = '\0'; err(std::string(chBuf, dwRead)); } }while(alive); } tearDown(); if(this->waitForExit()){ DWORD ec = 0; if (FALSE == GetExitCodeProcess(piProcInfo.hProcess, &ec)) KEXCEPT(kul::proc::Exception, "GetExitCodeProcess failure"); exitCode(ec); finish(); setFinished(); } CloseHandle(piProcInfo.hThread); CloseHandle(piProcInfo.hProcess); } }; } #endif /* _KUL_PROC_HPP_ */ <commit_msg>wstring in win proc for env vars<commit_after>/** Copyright (c) 2013, Philip Deegan. 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 Philip Deegan 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. */ #ifndef _KUL_PROC_HPP_ #define _KUL_PROC_HPP_ #include <string> #include <tchar.h> #include <stdio.h> #include <sstream> #include <strsafe.h> #include <Windows.h> #include "kul/os.hpp" #include "kul/def.hpp" #include "kul/log.hpp" #include "kul/string.hpp" #include "kul/proc.base.hpp" // extern char **environ; #include <iostream> namespace kul{ namespace this_proc{ inline int32_t id(){ return GetCurrentProcessId(); } inline void kill(const int32_t& e){ TerminateProcess(OpenProcess(PROCESS_TERMINATE, 0, kul::this_proc::id()), 128+e); } } class Process : public kul::AProcess{ private: static ULONG PIPE_ID(){ static ULONG p = 999; p++; return p; } HANDLE g_hChildStd_OUT_Rd = NULL; HANDLE g_hChildStd_OUT_Wr = NULL; HANDLE g_hChildStd_ERR_Rd = NULL; HANDLE g_hChildStd_ERR_Wr = NULL; HANDLE revent = CreateEvent(0, 1, 0, 0); public: Process(const std::string& cmd, const bool& wfe = true) : kul::AProcess(cmd, wfe) {} Process(const std::string& cmd, const std::string& path, const bool& wfe = true): kul::AProcess(cmd, path, wfe){} ~Process(){ tearDown(); } bool kill(int16_t k = 6){ if(!started()) return 0; DWORD dwDesiredAccess = PROCESS_TERMINATE; bool bInheritHandle = 0; HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, pid()); if (hProcess == NULL) return 0; bool r = TerminateProcess(hProcess, 128+k); CloseHandle(hProcess); setFinished(); return r; } protected: void tearDown(){ CloseHandle(g_hChildStd_OUT_Rd); CloseHandle(g_hChildStd_ERR_Rd); } void run() throw (kul::Exception){ SECURITY_ATTRIBUTES sa; ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES)); // Set the bInheritHandle flag so pipe handles are inherited. sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; std::stringstream ss; ss << this; const ULONG& pipeID = PIPE_ID(); std::string pipeOut = "\\\\.\\Pipe\\kul_proc_out."+std::to_string(this_proc::id())+"."+ss.str()+"."+std::to_string(pipeID); std::string pipeErr = "\\\\.\\Pipe\\kul_proc_err."+std::to_string(this_proc::id())+"."+ss.str()+"."+std::to_string(pipeID); std::string pipeIn = "\\\\.\\Pipe\\kul_proc_in." +std::to_string(this_proc::id())+"."+ss.str()+"."+std::to_string(pipeID); LPSTR lPipeOut = _strdup(pipeOut.c_str()); g_hChildStd_OUT_Wr = ::CreateNamedPipeA(lPipeOut, PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, __KUL_PROCESS_BUFFER__, __KUL_PROCESS_BUFFER__, 0, &sa); if(!g_hChildStd_OUT_Wr) error(__LINE__, "CreatePipe failed"); g_hChildStd_OUT_Rd = ::CreateFileA(lPipeOut, GENERIC_READ, 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0); if(!g_hChildStd_OUT_Rd) error(__LINE__, "CreatePipe failed"); if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) error(__LINE__, "SetHandleInformation failed"); LPSTR lPipeErr = _strdup(pipeErr.c_str()); g_hChildStd_ERR_Wr = ::CreateNamedPipeA(lPipeErr, PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, __KUL_PROCESS_BUFFER__, __KUL_PROCESS_BUFFER__, 0, &sa); if(!g_hChildStd_ERR_Wr) error(__LINE__, "CreatePipe failed"); g_hChildStd_ERR_Rd = ::CreateFileA(lPipeErr, GENERIC_READ, 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0); if(!g_hChildStd_ERR_Rd) error(__LINE__, "CreatePipe failed"); if (!SetHandleInformation(g_hChildStd_ERR_Rd, HANDLE_FLAG_INHERIT, 0)) error(__LINE__, "SetHandleInformation failed"); bool bSuccess = FALSE; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.dwFlags = STARTF_USESTDHANDLES; siStartInfo.hStdError = g_hChildStd_ERR_Wr; siStartInfo.hStdOutput = g_hChildStd_OUT_Wr; siStartInfo.wShowWindow = SW_HIDE; siStartInfo.lpDesktop = NULL; siStartInfo.lpReserved = NULL; siStartInfo.lpTitle = NULL; siStartInfo.cbReserved2 = 0; siStartInfo.lpReserved2 = NULL; unsigned flags = CREATE_UNICODE_ENVIRONMENT; HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (cons == INVALID_HANDLE_VALUE) { flags |= DETACHED_PROCESS; } else { CloseHandle(cons); } preStart(); LPTSTR lpszVariable; LPCH lpvEnv; lpvEnv = GetEnvironmentStrings(); if (lpvEnv == NULL) error(__LINE__, "GetEnvironmentStrings() failed."); kul::hash::map::S2S env; for (lpszVariable = (LPTSTR) lpvEnv; *lpszVariable; lpszVariable++){ std::stringstream ss; while (*lpszVariable) ss << *lpszVariable++; std::string var = ss.str(); if(var.find(":") != std::string::npos) env.insert(var.substr(0, var.find(":")), var.substr(var.find(":") + 1)); else env.insert(var, ""); } if(FreeEnvironmentStrings(lpvEnv) == 0) error(__LINE__, "FreeEnvironmentStrings() failed"); const char* dir = directory().empty() ? 0 : directory().c_str(); LPSTR szCmdline = _strdup(toString().c_str()); if(vars().size()){ WCHAR chNewEnv[__KUL_PROCESS_ENV_BUFFER__]; LPWSTR lpszCurrentVariable; lpszCurrentVariable = (LPWSTR) chNewEnv; for(auto& evs : vars()){ std::string var(evs.first + "=" + evs.second); if(FAILED(StringCchCopyW(lpszCurrentVariable, __KUL_PROCESS_ENV_BUFFER__, (std::wstring(var.begin(), var.end()).c_str())))) error(__LINE__, "String copy failed"); lpszCurrentVariable += wcslen(lpszCurrentVariable) + 1; } for(auto& evs : env){ if(vars().count(evs.first)) continue; std::string var(evs.first + "=" + evs.second); if(FAILED(StringCchCopyW(lpszCurrentVariable, __KUL_PROCESS_ENV_BUFFER__, (std::wstring(var.begin(), var.end()).c_str())))) error(__LINE__, "String copy failed"); lpszCurrentVariable += wcslen(lpszCurrentVariable) + 1; } *lpszCurrentVariable = (TCHAR)0; bSuccess = CreateProcess(NULL, szCmdline, NULL, NULL, TRUE, flags, chNewEnv, dir, &siStartInfo, &piProcInfo); }else bSuccess = CreateProcess(NULL, szCmdline, NULL, NULL, TRUE, flags, NULL, dir, &siStartInfo, &piProcInfo); if(!bSuccess) error(__LINE__, "CreateProcess failed with last error: " + GetLastError()); pid(piProcInfo.dwProcessId); CloseHandle(g_hChildStd_OUT_Wr); CloseHandle(g_hChildStd_ERR_Wr); if(this->waitForExit()){ OVERLAPPED il = { 0 }; memset(&il, 0, sizeof(il)); il.hEvent = revent; OVERLAPPED ol = { 0 }; memset(&ol, 0, sizeof(ol)); ol.hEvent = revent; OVERLAPPED el = { 0 }; memset(&el, 0, sizeof(el)); el.hEvent = revent; DWORD dwRead; CHAR chBuf[__KUL_PROCESS_BUFFER__ + 1]; bSuccess = FALSE; bool alive = true; do{ alive = WaitForSingleObject(piProcInfo.hProcess, 11) == WAIT_TIMEOUT; for (;;) { dwRead = 0; bSuccess = ::ReadFile( g_hChildStd_OUT_Rd, chBuf, __KUL_PROCESS_BUFFER__, &dwRead, &ol); while(!bSuccess && (GetLastError() == ERROR_IO_PENDING || GetLastError() == ERROR_IO_INCOMPLETE)){ WaitForSingleObject(ol.hEvent, 11); bSuccess = GetOverlappedResult(g_hChildStd_OUT_Rd, &ol, &dwRead, 0); } if(!bSuccess || dwRead == 0) break; chBuf[dwRead] = '\0'; out(std::string(chBuf, dwRead)); } for (;;) { dwRead = 0; bSuccess = ::ReadFile( g_hChildStd_ERR_Rd, chBuf, __KUL_PROCESS_BUFFER__, &dwRead, &el); if (GetLastError() == ERROR_IO_PENDING) { WaitForSingleObject(el.hEvent, 11); bSuccess = GetOverlappedResult(g_hChildStd_OUT_Rd, &el, &dwRead, 0); } if(!bSuccess || dwRead == 0) break; chBuf[dwRead] = '\0'; err(std::string(chBuf, dwRead)); } }while(alive); } tearDown(); if(this->waitForExit()){ DWORD ec = 0; if (FALSE == GetExitCodeProcess(piProcInfo.hProcess, &ec)) KEXCEPT(kul::proc::Exception, "GetExitCodeProcess failure"); exitCode(ec); finish(); setFinished(); } CloseHandle(piProcInfo.hThread); CloseHandle(piProcInfo.hProcess); } }; } #endif /* _KUL_PROC_HPP_ */ <|endoftext|>
<commit_before>/* * File: PIDController.cpp * Author: User * * Created on April 22, 2014, 6:28 PM */ #include "PIDController.h" using namespace boost::chrono; PIDController::PIDController(double kp, double ki, double kd) { this->setGains(kp, ki, kd); this->setConstraints(-1, -1); this->init(); } PIDController::PIDController(double kp, double ki, double kd, double lowerConstraint, double upperConstraint) { this->setGains(kp, ki, kd); this->setConstraints(lowerConstraint, upperConstraint); this->init(); } PIDController::PIDController() { this->setGains(0, 0, 0); this->setConstraints(-100,100); this->init(); } PIDController::PIDController(const PIDController& orig) { this->setGains(orig.kp, orig.ki, orig.kd); this->setConstraints(orig.lowerConstraint, orig.upperConstraint); integrator = orig.integrator; lastError = orig.lastError; } PIDController::~PIDController() { } void PIDController::targetSetpoint(double setpoint) { this->setpoint = setpoint; peakTime = -1; settlingTime = -1; percentOvershoot = 0; sample_timer.start(); performance_timer.start(); } void PIDController::setGains(double kp, double ki, double kd) { this->kp = kp; this->ki = ki; this->kd = kd; } void PIDController::setConstraints(double lowerConstraint, double upperConstraint) { this->lowerConstraint = lowerConstraint; this->upperConstraint = upperConstraint; } double PIDController::getSetpoint() { return setpoint; } double PIDController::getKp() { return kp; } double PIDController::getKi() { return ki; } double PIDController::getKd() { return kd; } void PIDController::init() { setpoint = 0; integrator = 0; lastError = 0; peakTime = -1; settlingTime = -1; percentOvershoot = 0; sample_timer.stop(); performance_timer.stop(); } bool PIDController::hasSettled() { if(settlingTime != -1) { return true; } else { return false; } } double PIDController::calc(double processVariable) { sample_timer.stop(); double percent = (processVariable/setpoint) - 1; if(percent > percentOvershoot && percent > 0) { percentOvershoot = processVariable/setpoint; peakTime = (performance_timer.elapsed().wall)/1e9; } if(abs(percent) < 0.05 && settlingTime == -1) { performance_timer.stop(); settlingTime = (performance_timer.elapsed().wall)/1e9; std::cout << "Peak Time Tp: " << peakTime << std::endl; std::cout << "Percent Overshoot %OS: " << percentOvershoot << std::endl; std::cout << "Settling Time Ts" << settlingTime << std::endl; } double error = setpoint - processVariable; double samplingTime = (sample_timer.elapsed().wall)/1e9; double differentiator = (error - lastError)/samplingTime; integrator += (error * samplingTime); double controlVariable = kp * error + ki * integrator + kd * differentiator; if(controlVariable < lowerConstraint) { controlVariable = lowerConstraint; } else if(controlVariable > upperConstraint) { controlVariable = upperConstraint; } lastError = error; sample_timer.start(); return controlVariable; } <commit_msg>Attempt to fix tabs<commit_after>/* * File: PIDController.cpp * Author: User * * Created on April 22, 2014, 6:28 PM */ #include "PIDController.h" using namespace boost::chrono; PIDController::PIDController(double kp, double ki, double kd) { this->setGains(kp, ki, kd); this->setConstraints(-1, -1); this->init(); } PIDController::PIDController(double kp, double ki, double kd, double lowerConstraint, double upperConstraint) { this->setGains(kp, ki, kd); this->setConstraints(lowerConstraint, upperConstraint); this->init(); } PIDController::PIDController() { this->setGains(0, 0, 0); this->setConstraints(-100,100); this->init(); } PIDController::PIDController(const PIDController& orig) { this->setGains(orig.kp, orig.ki, orig.kd); this->setConstraints(orig.lowerConstraint, orig.upperConstraint); integrator = orig.integrator; lastError = orig.lastError; } PIDController::~PIDController() { } void PIDController::targetSetpoint(double setpoint) { this->setpoint = setpoint; peakTime = -1; settlingTime = -1; percentOvershoot = 0; sample_timer.start(); performance_timer.start(); } void PIDController::setGains(double kp, double ki, double kd) { this->kp = kp; this->ki = ki; this->kd = kd; } void PIDController::setConstraints(double lowerConstraint, double upperConstraint) { this->lowerConstraint = lowerConstraint; this->upperConstraint = upperConstraint; } double PIDController::getSetpoint() { return setpoint; } double PIDController::getKp() { return kp; } double PIDController::getKi() { return ki; } double PIDController::getKd() { return kd; } void PIDController::init() { setpoint = 0; integrator = 0; lastError = 0; peakTime = -1; settlingTime = -1; percentOvershoot = 0; sample_timer.stop(); performance_timer.stop(); } bool PIDController::hasSettled() { if(settlingTime != -1) { return true; } else { return false; } } double PIDController::calc(double processVariable) { sample_timer.stop(); double percent = (processVariable/setpoint) - 1; if(percent > percentOvershoot && percent > 0) { percentOvershoot = processVariable/setpoint; peakTime = (performance_timer.elapsed().wall)/1e9; } if(abs(percent) < 0.05 && settlingTime == -1) { performance_timer.stop(); settlingTime = (performance_timer.elapsed().wall)/1e9; std::cout << "Peak Time Tp: " << peakTime << std::endl; std::cout << "Percent Overshoot %OS: " << percentOvershoot << std::endl; std::cout << "Settling Time Ts" << settlingTime << std::endl; } double error = setpoint - processVariable; double samplingTime = (sample_timer.elapsed().wall)/1e9; double differentiator = (error - lastError)/samplingTime; integrator += (error * samplingTime); double controlVariable = kp * error + ki * integrator + kd * differentiator; if(controlVariable < lowerConstraint) { controlVariable = lowerConstraint; } else if(controlVariable > upperConstraint) { controlVariable = upperConstraint; } lastError = error; sample_timer.start(); return controlVariable; } <|endoftext|>
<commit_before>/*************************************************************************/ /* random_pcg.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "random_pcg.h" #include "core/os/os.h" RandomPCG::RandomPCG(uint64_t p_seed, uint64_t p_inc) : pcg(), current_inc(p_inc) { seed(p_seed); } void RandomPCG::randomize() { seed((OS::get_singleton()->get_unix_time() + OS::get_singleton()->get_ticks_usec()) * pcg.state + PCG_DEFAULT_INC_64); } double RandomPCG::random(double p_from, double p_to) { return randd() * (p_to - p_from) + p_from; } float RandomPCG::random(float p_from, float p_to) { return randf() * (p_to - p_from) + p_from; } int RandomPCG::random(int p_from, int p_to) { if (p_from == p_to) { return p_from; } return rand(abs(p_from - p_to) + 1) + MIN(p_from, p_to); } <commit_msg>Cast Unix time to uint in the randomize function<commit_after>/*************************************************************************/ /* random_pcg.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "random_pcg.h" #include "core/os/os.h" RandomPCG::RandomPCG(uint64_t p_seed, uint64_t p_inc) : pcg(), current_inc(p_inc) { seed(p_seed); } void RandomPCG::randomize() { seed(((uint64_t)OS::get_singleton()->get_unix_time() + OS::get_singleton()->get_ticks_usec()) * pcg.state + PCG_DEFAULT_INC_64); } double RandomPCG::random(double p_from, double p_to) { return randd() * (p_to - p_from) + p_from; } float RandomPCG::random(float p_from, float p_to) { return randf() * (p_to - p_from) + p_from; } int RandomPCG::random(int p_from, int p_to) { if (p_from == p_to) { return p_from; } return rand(abs(p_from - p_to) + 1) + MIN(p_from, p_to); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: auditsh.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2007-02-27 13:19:56 $ * * 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 SC_AUDITSH_HXX #define SC_AUDITSH_HXX #ifndef _SFX_SHELL_HXX //autogen #include <sfx2/shell.hxx> #endif #ifndef _SFXMODULE_HXX //autogen #include <sfx2/module.hxx> #endif #include "shellids.hxx" class ScViewData; class ScAuditingShell : public SfxShell { private: ScViewData* pViewData; USHORT nFunction; public: TYPEINFO(); SFX_DECL_INTERFACE(SCID_AUDITING_SHELL) ScAuditingShell(ScViewData* pData); ~ScAuditingShell(); void Execute(SfxRequest& rReq); void GetState(SfxItemSet& rSet); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.330); FILE MERGED 2008/04/01 15:30:49 thb 1.3.330.2: #i85898# Stripping all external header guards 2008/03/31 17:15:39 rt 1.3.330.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: auditsh.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_AUDITSH_HXX #define SC_AUDITSH_HXX #include <sfx2/shell.hxx> #include <sfx2/module.hxx> #include "shellids.hxx" class ScViewData; class ScAuditingShell : public SfxShell { private: ScViewData* pViewData; USHORT nFunction; public: TYPEINFO(); SFX_DECL_INTERFACE(SCID_AUDITING_SHELL) ScAuditingShell(ScViewData* pData); ~ScAuditingShell(); void Execute(SfxRequest& rReq); void GetState(SfxItemSet& rSet); }; #endif <|endoftext|>
<commit_before>// Time: O(n) // Space: O(1) /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ // Morris Traversal. class Solution { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */ public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; TreeNode *prev = nullptr; TreeNode *curr = root; while (curr) { if (!curr->left) { res.emplace_back(curr->val); prev = curr; curr = curr->right; } else { TreeNode *node = curr->left; while (node->right && node->right != curr) { node = node->right; } if (!node->right) { node->right = curr; curr = curr->left; } else { res.emplace_back(curr->val); prev = curr; node->right = nullptr; curr = curr->right; } } } return res; } }; // Time: O(n) // Space: O(h) // Stack solution. class Solution2 { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */ public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; stack<pair<TreeNode *, bool>> s; s.emplace(root, false); bool visited; while (!s.empty()) { tie(root, visited) = s.top(); s.pop(); if (root == nullptr) { continue; } if (visited) { res.emplace_back(root->val); } else { s.emplace(root->right, false); s.emplace(root, true); s.emplace(root->left, false); } } return res; } }; <commit_msg>Update binary-tree-inorder-traversal.cpp<commit_after>// Time: O(n) // Space: O(1) /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ // Morris Traversal. class Solution { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */ public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; TreeNode *prev = nullptr; TreeNode *curr = root; while (curr) { if (!curr->left) { res.emplace_back(curr->val); prev = curr; curr = curr->right; } else { TreeNode *node = curr->left; while (node->right && node->right != curr) { node = node->right; } if (!node->right) { node->right = curr; curr = curr->left; } else { res.emplace_back(curr->val); prev = curr; node->right = nullptr; curr = curr->right; } } } return res; } }; // Time: O(n) // Space: O(h) // Stack solution. class Solution2 { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */ public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; stack<pair<TreeNode *, bool>> s; s.emplace(root, false); while (!s.empty()) { bool visited; tie(root, visited) = s.top(); s.pop(); if (root == nullptr) { continue; } if (visited) { res.emplace_back(root->val); } else { s.emplace(root->right, false); s.emplace(root, true); s.emplace(root->left, false); } } return res; } }; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: hdrcont.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-02-03 12:38:55 $ * * 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 SC_HDRCONT_HXX #define SC_HDRCONT_HXX #ifndef _WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #ifndef _SELENG_HXX //autogen #include <vcl/seleng.hxx> #endif // --------------------------------------------------------------------------- #define HDR_HORIZONTAL 0 #define HDR_VERTICAL 1 #define HDR_SIZE_OPTIMUM 0xFFFF // Groesse des Sliders #define HDR_SLIDERSIZE 2 class ScHeaderControl : public Window { private: SelectionEngine* pSelEngine; Font aNormFont; Font aBoldFont; BOOL bBoldSet; USHORT nFlags; BOOL bVertical; // Vertikal = Zeilenheader long nWidth; long nSmallWidth; long nBigWidth; USHORT nSize; USHORT nMarkStart; USHORT nMarkEnd; BOOL bMarkRange; BOOL bDragging; // Groessen aendern USHORT nDragNo; long nDragStart; long nDragPos; BOOL bDragMoved; BOOL bIgnoreMove; long GetScrPos( USHORT nEntryNo ); USHORT GetMousePos( const MouseEvent& rMEvt, BOOL& rBorder ); void ShowDragHelp(); void DoPaint( USHORT nStart, USHORT nEnd ); protected: // von Window ueberladen virtual void Paint( const Rectangle& rRect ); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void Tracking( const TrackingEvent& rTEvt ); virtual void RequestHelp( const HelpEvent& rHEvt ); // neue Methoden virtual USHORT GetPos() = 0; // aktuelle Position (Scrolling) virtual USHORT GetEntrySize( USHORT nEntryNo ) = 0; // Breite / Hoehe (Pixel) virtual String GetEntryText( USHORT nEntryNo ) = 0; virtual USHORT GetHiddenCount( USHORT nEntryNo ); virtual BOOL IsLayoutRTL(); virtual BOOL IsMirrored(); virtual void SetEntrySize( USHORT nPos, USHORT nNewWidth ) = 0; virtual void HideEntries( USHORT nStart, USHORT nEnd ) = 0; virtual void SetMarking( BOOL bSet ); virtual void SelectWindow(); virtual BOOL IsDisabled(); virtual BOOL ResizeAllowed(); virtual String GetDragHelp( long nVal ); virtual void DrawInvert( long nDragPos ); virtual void Command( const CommandEvent& rCEvt ); public: ScHeaderControl( Window* pParent, SelectionEngine* pSelectionEngine, USHORT nNewSize, USHORT nNewFlags ); ~ScHeaderControl(); void SetIgnoreMove(BOOL bSet) { bIgnoreMove = bSet; } void StopMarking(); void SetMark( BOOL bNewSet, USHORT nNewStart, USHORT nNewEnd ); long GetWidth() const { return nWidth; } long GetSmallWidth() const { return nSmallWidth; } long GetBigWidth() const { return nBigWidth; } void SetWidth( long nNew ); }; #endif <commit_msg>INTEGRATION: CWS rowlimit (1.2.12); FILE MERGED 2004/02/26 19:18:37 jmarmion 1.2.12.1: #i1967# setp 5 changes.<commit_after>/************************************************************************* * * $RCSfile: hdrcont.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:34:09 $ * * 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 SC_HDRCONT_HXX #define SC_HDRCONT_HXX #ifndef _WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #ifndef _SELENG_HXX //autogen #include <vcl/seleng.hxx> #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif // --------------------------------------------------------------------------- #define HDR_HORIZONTAL 0 #define HDR_VERTICAL 1 #define HDR_SIZE_OPTIMUM 0xFFFF // Groesse des Sliders #define HDR_SLIDERSIZE 2 class ScHeaderControl : public Window { private: SelectionEngine* pSelEngine; Font aNormFont; Font aBoldFont; BOOL bBoldSet; USHORT nFlags; BOOL bVertical; // Vertikal = Zeilenheader long nWidth; long nSmallWidth; long nBigWidth; SCCOLROW nSize; SCCOLROW nMarkStart; SCCOLROW nMarkEnd; BOOL bMarkRange; BOOL bDragging; // Groessen aendern SCCOLROW nDragNo; long nDragStart; long nDragPos; BOOL bDragMoved; BOOL bIgnoreMove; long GetScrPos( SCCOLROW nEntryNo ); SCCOLROW GetMousePos( const MouseEvent& rMEvt, BOOL& rBorder ); void ShowDragHelp(); void DoPaint( SCCOLROW nStart, SCCOLROW nEnd ); protected: // von Window ueberladen virtual void Paint( const Rectangle& rRect ); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void Tracking( const TrackingEvent& rTEvt ); virtual void RequestHelp( const HelpEvent& rHEvt ); // neue Methoden virtual SCCOLROW GetPos() = 0; // aktuelle Position (Scrolling) virtual USHORT GetEntrySize( SCCOLROW nEntryNo ) = 0; // Breite / Hoehe (Pixel) virtual String GetEntryText( SCCOLROW nEntryNo ) = 0; virtual SCCOLROW GetHiddenCount( SCCOLROW nEntryNo ); virtual BOOL IsLayoutRTL(); virtual BOOL IsMirrored(); virtual void SetEntrySize( SCCOLROW nPos, USHORT nNewWidth ) = 0; virtual void HideEntries( SCCOLROW nStart, SCCOLROW nEnd ) = 0; virtual void SetMarking( BOOL bSet ); virtual void SelectWindow(); virtual BOOL IsDisabled(); virtual BOOL ResizeAllowed(); virtual String GetDragHelp( long nVal ); virtual void DrawInvert( long nDragPos ); virtual void Command( const CommandEvent& rCEvt ); public: ScHeaderControl( Window* pParent, SelectionEngine* pSelectionEngine, SCCOLROW nNewSize, USHORT nNewFlags ); ~ScHeaderControl(); void SetIgnoreMove(BOOL bSet) { bIgnoreMove = bSet; } void StopMarking(); void SetMark( BOOL bNewSet, SCCOLROW nNewStart, SCCOLROW nNewEnd ); long GetWidth() const { return nWidth; } long GetSmallWidth() const { return nSmallWidth; } long GetBigWidth() const { return nBigWidth; } void SetWidth( long nNew ); }; #endif <|endoftext|>
<commit_before>#include "kclinput.h" #include "kclinputevent.h" #include "kclthread.h" #include <KDebug> #include <QApplication> #include <QFile> #include <QMessageBox> #include <QMouseEvent> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #define BITS_PER_LONG (sizeof(long) * 8) #define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1) #define OFF(x) ((x)%BITS_PER_LONG) #define BIT(x) (1UL<<OFF(x)) #define LONG(x) ((x)/BITS_PER_LONG) #define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1) KCLInput::KCLInput(const QString& devicePath, QObject * parent) : QObject(parent) { m_error = false; m_enable = true; m_absMove = false; m_relMove = false; m_lastAbsAxis = 0; m_lastRelAxis = 0; m_msgError = QString(); m_devicePath = devicePath; m_deviceName = "no name"; readInformation(); inputListener = new KCLThread(m_devicePath, this); } KCLInput::~KCLInput() { setDisable(); delete inputListener; kDebug() << "Closed device :" << deviceName(); } bool KCLInput::event(QEvent * evt) { KCLInputEvent * event = (KCLInputEvent*)evt; emit eventSent(event); switch (event->type()) { case KCL::Key: if (event->value() == 1) { // if click m_buttons.append(event->code()); emit buttonPressed(event->code()); emit pressed(); } if (event->value() == 0) { //if release m_buttons.removeOne(event->code()); emit buttonReleased(event->code()); } return true; break; case KCL::RelativeAxis: emit moved(); m_relMove = true; m_lastRelAxis = event->code(); m_relAxis[event->code()] = event->value(); emit relAxisChanged(event->code(), event->value()); return true; break; case KCL::AbsoluAxis: emit moved(); m_absMove = true; m_lastAbsAxis = event->code(); m_absAxis[event->code()] = event->value(); emit absAxisChanged(event->code(), event->value()); return true; break; default:break; } return QObject::event(evt); } void KCLInput::readInformation() { if (!QFile::exists(m_devicePath)) { kDebug() << "m_devicePath does not exist"; m_error = true; m_msgError += "device url does not exist \n"; return; } int m_fd = -1; if ((m_fd = open(m_devicePath.toUtf8(), O_RDONLY)) < 0) { kDebug() << "Could not open device" << m_devicePath; m_error = true; m_msgError += "could not open the device \n"; return; } if (ioctl(m_fd, EVIOCGID, &m_device_info)) { kDebug() << "Could not retrieve information of device" << m_devicePath; m_msgError += "could not retrieve information of device\n"; m_error = true; return; } char name[256] = "Unknown"; if (ioctl(m_fd, EVIOCGNAME(sizeof(name)), name) < 0) { kDebug() << "could not retrieve name of device" << m_devicePath; // m_msgError += "cannot retrieve name of device\n"; // m_error = true; } m_deviceName = QString(name); unsigned long bit[EV_MAX][NBITS(KEY_MAX)]; int abs[5]; memset(bit, 0, sizeof(bit)); ioctl(m_fd, EVIOCGBIT(0, EV_MAX), bit[0]); m_buttonCapabilities.clear(); m_absAxisInfos.clear(); for (int i = 0; i < EV_MAX; i++) { if (test_bit(i, bit[0])) { if (!i) { continue; } ioctl(m_fd, EVIOCGBIT(i, KEY_MAX), bit[i]); for (int j = 0; j < KEY_MAX; j++) { if (test_bit(j, bit[i])) { if (i == EV_KEY) { m_buttonCapabilities.append(j); } if (i == EV_REL) { m_relAxisCapabilities.append(j); } if (i == EV_ABS) { ioctl(m_fd, EVIOCGABS(j), abs); AbsVal cabs(0, 0, 0, 0); for (int k = 0; k < 5; k++) { if ((k < 3) || abs[k]) { switch (k) { case 0: cabs.value = abs[k]; break; case 1: cabs.min = abs[k]; break; case 2: cabs.max = abs[k]; break; case 3: cabs.fuzz = abs[k]; break; case 4: cabs.flat = abs[k]; break; } } } m_absAxisCapabilities.append(j); m_absAxisInfos[j] = cabs; } } } } } //===============Find Force feedback ?? =============== close(m_fd); m_deviceType = KCL::Unknown; if (m_buttonCapabilities.contains(BTN_STYLUS)) { m_deviceType = KCL::Tablet; } if (m_buttonCapabilities.contains(BTN_STYLUS) || m_buttonCapabilities.contains(ABS_PRESSURE)) { m_deviceType = KCL::Mouse; } if (m_buttonCapabilities.contains(BTN_TRIGGER)) { m_deviceType = KCL::Joystick; } if (m_buttonCapabilities.contains(BTN_MOUSE)) { m_deviceType = KCL::Mouse; } if (m_buttonCapabilities.contains(KEY_ESC)) { m_deviceType = KCL::KeyBoard; } } void KCLInput::setEnable() { m_enable = true; if (!error()) { inputListener = new KCLThread(m_devicePath, this); inputListener->start(); } } void KCLInput::setDisable() { m_enable = false; m_buttons.clear(); m_relAxis.clear(); m_absAxis.clear(); m_relMove = false; m_absMove = false; inputListener->terminate(); } <commit_msg>fix a leak regarding kclthread handling<commit_after>#include "kclinput.h" #include "kclinputevent.h" #include "kclthread.h" #include <KDebug> #include <QApplication> #include <QFile> #include <QMessageBox> #include <QMouseEvent> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #define BITS_PER_LONG (sizeof(long) * 8) #define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1) #define OFF(x) ((x)%BITS_PER_LONG) #define BIT(x) (1UL<<OFF(x)) #define LONG(x) ((x)/BITS_PER_LONG) #define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1) KCLInput::KCLInput(const QString& devicePath, QObject * parent) : QObject(parent) { m_error = false; m_enable = true; m_absMove = false; m_relMove = false; m_lastAbsAxis = 0; m_lastRelAxis = 0; m_msgError = QString(); m_devicePath = devicePath; m_deviceName = "no name"; readInformation(); inputListener = NULL; } KCLInput::~KCLInput() { setDisable(); kDebug() << "Closed device :" << deviceName(); } bool KCLInput::event(QEvent * evt) { KCLInputEvent * event = (KCLInputEvent*)evt; emit eventSent(event); switch (event->type()) { case KCL::Key: if (event->value() == 1) { // if click m_buttons.append(event->code()); emit buttonPressed(event->code()); emit pressed(); } if (event->value() == 0) { //if release m_buttons.removeOne(event->code()); emit buttonReleased(event->code()); } return true; break; case KCL::RelativeAxis: emit moved(); m_relMove = true; m_lastRelAxis = event->code(); m_relAxis[event->code()] = event->value(); emit relAxisChanged(event->code(), event->value()); return true; break; case KCL::AbsoluAxis: emit moved(); m_absMove = true; m_lastAbsAxis = event->code(); m_absAxis[event->code()] = event->value(); emit absAxisChanged(event->code(), event->value()); return true; break; default:break; } return QObject::event(evt); } void KCLInput::readInformation() { if (!QFile::exists(m_devicePath)) { kDebug() << "m_devicePath does not exist"; m_error = true; m_msgError += "device url does not exist \n"; return; } int m_fd = -1; if ((m_fd = open(m_devicePath.toUtf8(), O_RDONLY)) < 0) { kDebug() << "Could not open device" << m_devicePath; m_error = true; m_msgError += "could not open the device \n"; return; } if (ioctl(m_fd, EVIOCGID, &m_device_info)) { kDebug() << "Could not retrieve information of device" << m_devicePath; m_msgError += "could not retrieve information of device\n"; m_error = true; return; } char name[256] = "Unknown"; if (ioctl(m_fd, EVIOCGNAME(sizeof(name)), name) < 0) { kDebug() << "could not retrieve name of device" << m_devicePath; // m_msgError += "cannot retrieve name of device\n"; // m_error = true; } m_deviceName = QString(name); unsigned long bit[EV_MAX][NBITS(KEY_MAX)]; int abs[5]; memset(bit, 0, sizeof(bit)); ioctl(m_fd, EVIOCGBIT(0, EV_MAX), bit[0]); m_buttonCapabilities.clear(); m_absAxisInfos.clear(); for (int i = 0; i < EV_MAX; i++) { if (test_bit(i, bit[0])) { if (!i) { continue; } ioctl(m_fd, EVIOCGBIT(i, KEY_MAX), bit[i]); for (int j = 0; j < KEY_MAX; j++) { if (test_bit(j, bit[i])) { if (i == EV_KEY) { m_buttonCapabilities.append(j); } if (i == EV_REL) { m_relAxisCapabilities.append(j); } if (i == EV_ABS) { ioctl(m_fd, EVIOCGABS(j), abs); AbsVal cabs(0, 0, 0, 0); for (int k = 0; k < 5; k++) { if ((k < 3) || abs[k]) { switch (k) { case 0: cabs.value = abs[k]; break; case 1: cabs.min = abs[k]; break; case 2: cabs.max = abs[k]; break; case 3: cabs.fuzz = abs[k]; break; case 4: cabs.flat = abs[k]; break; } } } m_absAxisCapabilities.append(j); m_absAxisInfos[j] = cabs; } } } } } //===============Find Force feedback ?? =============== close(m_fd); m_deviceType = KCL::Unknown; if (m_buttonCapabilities.contains(BTN_STYLUS)) { m_deviceType = KCL::Tablet; } if (m_buttonCapabilities.contains(BTN_STYLUS) || m_buttonCapabilities.contains(ABS_PRESSURE)) { m_deviceType = KCL::Mouse; } if (m_buttonCapabilities.contains(BTN_TRIGGER)) { m_deviceType = KCL::Joystick; } if (m_buttonCapabilities.contains(BTN_MOUSE)) { m_deviceType = KCL::Mouse; } if (m_buttonCapabilities.contains(KEY_ESC)) { m_deviceType = KCL::KeyBoard; } } void KCLInput::setEnable() { setDisable(); m_enable = true; if (!error()) { inputListener = new KCLThread(m_devicePath, this); inputListener->start(); } } void KCLInput::setDisable() { m_enable = false; m_buttons.clear(); m_relAxis.clear(); m_absAxis.clear(); m_relMove = false; m_absMove = false; if (inputListener) { inputListener->terminate(); delete inputListener; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: olkact.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2003-03-26 18:06:47 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #define _BIGINT_HXX #define _CACHESTR_HXX #define _CONFIG_HXX #define _CURSOR_HXX #define _CTRLTOOL_HXX #define _DLGCFG_HXX #define _DYNARR_HXX #define _EXTATTR_HXX #define _FILDLG_HXX #define _FONTDLG_HXX #define _FRM3D_HXX #define _INTRO_HXX #define _ISETBWR_HXX #define _NO_SVRTF_PARSER_HXX #define _MACRODLG_HXX #define _MODALDLG_HXX #define _MOREBUTTON_HXX #define _OUTLINER_HXX #define _PASSWD_HXX #define _PRNDLG_HXX //#define _POLY_HXX #define _PVRWIN_HXX #define _QUEUE_HXX #define _RULER_HXX #define _SCRWIN_HXX #define _SETBRW_HXX #define _STACK_HXX //#define _STATUS_HXX *** #define _STDMENU_HXX #define _TABBAR_HXX //#define _VCBRW_HXX #define _VCTRLS_HXX //#define _VCSBX_HXX #define _VCONT_HXX #define _VDRWOBJ_HXX //sfx #define _SFXAPPWIN_HXX #define _SFXCTRLITEM #define _SFXDISPATCH_HXX #define _SFXFILEDLG_HXX #define _SFXIMGMGR_HXX #define _SFXIPFRM_HXX #define _SFX_MACRO_HXX #define _SFXMULTISEL_HXX #define _SFX_MINFITEM_HXX //sfxcore.hxx //#define _SFXINIMGR_HXX *** //#define _SFXCFGITEM_HXX //#define _SFX_PRINTER_HXX #define _SFXGENLINK_HXX #define _SFXHINTPOST_HXX #define _SFXDOCINF_HXX #define _SFXLINKHDL_HXX //#define _SFX_PROGRESS_HXX //sfxsh.hxx //#define _SFX_SHELL_HXX //#define _SFXAPP_HXX //#define _SFXDISPATCH_HXX //#define _SFXMSG_HXX *** //#define _SFXOBJFACE_HXX *** //#define _SFXREQUEST_HXX #define _SFXMACRO_HXX // SFX //#define _SFXAPPWIN_HXX *** #define _SFX_SAVEOPT_HXX //#define _SFX_CHILDWIN_HXX //#define _SFXCTRLITEM_HXX #define _SFXPRNMON_HXX #define _INTRO_HXX #define _SFXMSGDESCR_HXX #define _SFXMSGPOOL_HXX #define _SFXFILEDLG_HXX #define _PASSWD_HXX #define _SFXTBXCTRL_HXX #define _SFXSTBITEM_HXX #define _SFXMNUITEM_HXX #define _SFXIMGMGR_HXX #define _SFXTBXMGR_HXX #define _SFXSTBMGR_HXX #define _SFX_MINFITEM_HXX #define _SFXEVENT_HXX //sfxdoc.hxx //#define _SFX_OBJSH_HXX //#define _SFX_CLIENTSH_HXX //#define _SFXDOCINF_HXX //#define _SFX_OBJFAC_HXX #define _SFX_DOCFILT_HXX //#define _SFXDOCFILE_HXX *** //define _VIEWFAC_HXX //#define _SFXVIEWFRM_HXX //#define _SFXVIEWSH_HXX //#define _MDIFRM_HXX *** #define _SFX_IPFRM_HXX //#define _SFX_INTERNO_HXX //sfxdlg.hxx //#define _SFXTABDLG_HXX //#define _BASEDLGS_HXX *** #define _SFX_DINFDLG_HXX #define _SFXDINFEDT_HXX #define _SFX_MGETEMPL_HXX #define _SFX_TPLPITEM_HXX //#define _SFX_STYLEDLG_HXX #define _NEWSTYLE_HXX //#define _SFXDOCTEMPL_HXX *** //#define _SFXDOCTDLG_HXX *** //#define _SFX_TEMPLDLG_HXX *** //#define _SFXNEW_HXX *** #define _SFXDOCMAN_HXX //#define _SFXDOCKWIN_HXX //sfxitems.hxx #define _SFX_WHMAP_HXX #define _ARGS_HXX //#define _SFXPOOLITEM_HXX //#define _SFXINTITEM_HXX //#define _SFXENUMITEM_HXX #define _SFXFLAGITEM_HXX //#define _SFXSTRITEM_HXX #define _SFXPTITEM_HXX #define _SFXRECTITEM_HXX //#define _SFXITEMPOOL_HXX //#define _SFXITEMSET_HXX #define _SFXITEMITER_HXX #define _SFX_WHITER_HXX #define _SFXPOOLCACH_HXX //#define _AEITEM_HXX #define _SFXRNGITEM_HXX //#define _SFXSLSTITM_HXX //#define _SFXSTYLE_HXX //xout.hxx //#define _XENUM_HXX //#define _XPOLY_HXX //#define _XATTR_HXX //#define _XOUTX_HXX //#define _XPOOL_HXX //#define _XTABLE_HXX //svdraw.hxx #define _SDR_NOITEMS #define _SDR_NOTOUCH #define _SDR_NOTRANSFORM //#define _SDR_NOOBJECTS //#define _SDR_NOVIEWS #define _SFXBASIC_HXX #define _SFX_DOCFILE_HXX #define _SFX_DOCFILT_HXX #define _SFX_DOCINF_HXX #define _SFX_DOCSH_HXX #define _SFX_TEMPLDLG_HXX #define _SFXSTBMGR_HXX #define _SFXTBXMGR_HXX #define _SFXIMGMGR_HXX #define _SFXMNUITEM_HXX #define _SFXMNUMGR_HXX #define _SFXSTBITEM_HXX #define _SFXTBXCTRL_HXX #define _SFXFILEDLG_HXX #define _SFXREQUEST_HXX #define _SFXOBJFACE_HXX #define _SFXMSGPOOL_HXX #define _SFXMSGDESCR_HXX #define _SFXMSG_HXX #define _SFX_PRNMON_HXX //si #define _SI_NOSBXCONTROLS #define _SI_NOCONTROL //#define SI_NOITEMS //#define SI_NODRW //#define SI_NOOTHERFORMS #define _SIDLL_HXX //#define _VCSBX_HXX //#define _VCBRW_HXX //#define _SVDATTR_HXX <--- der wars #define _SVDXOUT_HXX #define _SVDEC_HXX //#define _SVDIO_HXX //#define _SVDLAYER_HXX //#define _SVDRAG_HXX #define _SVINCVW_HXX #define _SV_MULTISEL_HXX #define _SVRTV_HXX #define _SVTABBX_HXX #define _SVX_DAILDLL_HXX #define _SVX_HYPHEN_HXX #define _SVX_IMPGRF_HXX #define _SVX_OPTITEMS_HXX #define _SVX_OPTGERL_HXX #define _SVX_OPTSAVE_HXX #define _SVX_OPTSPELL_HXX #define _SVX_OPTPATH_HXX #define _SVX_OPTLINGU_HXX #define _SVX_RULER_HXX #define _SVX_RULRITEM_HXX #define _SVX_SPLWRAP_HXX #define _SVX_SPLDLG_HXX #define _SVX_THESDLG_HXX // INCLUDE --------------------------------------------------------------- #include <sfx2/childwin.hxx> #include <sfx2/objsh.hxx> #include "document.hxx" #include "viewdata.hxx" #include "drawview.hxx" #include "drawpage.hxx" #include "drwlayer.hxx" // STATIC DATA ----------------------------------------------------------- // ----------------------------------------------------------------------- void ActivateOlk( ScViewData* pViewData ) { // Browser fuer Virtual Controls fuellen // VC's und den Browser dazu gibts nicht mehr... // GetSbxForm gibt's nicht mehr, muss auch nichts mehr angemeldet werden } void DeActivateOlk( ScViewData* pViewData ) { // Browser fuer Virtual Controls fuellen // VC's und den Browser dazu gibts nicht mehr... // GetSbxForm gibt's nicht mehr, muss auch nichts mehr angemeldet werden } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.798); FILE MERGED 2005/09/05 15:09:34 rt 1.4.798.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: olkact.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 23:01:20 $ * * 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 * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #define _BIGINT_HXX #define _CACHESTR_HXX #define _CONFIG_HXX #define _CURSOR_HXX #define _CTRLTOOL_HXX #define _DLGCFG_HXX #define _DYNARR_HXX #define _EXTATTR_HXX #define _FILDLG_HXX #define _FONTDLG_HXX #define _FRM3D_HXX #define _INTRO_HXX #define _ISETBWR_HXX #define _NO_SVRTF_PARSER_HXX #define _MACRODLG_HXX #define _MODALDLG_HXX #define _MOREBUTTON_HXX #define _OUTLINER_HXX #define _PASSWD_HXX #define _PRNDLG_HXX //#define _POLY_HXX #define _PVRWIN_HXX #define _QUEUE_HXX #define _RULER_HXX #define _SCRWIN_HXX #define _SETBRW_HXX #define _STACK_HXX //#define _STATUS_HXX *** #define _STDMENU_HXX #define _TABBAR_HXX //#define _VCBRW_HXX #define _VCTRLS_HXX //#define _VCSBX_HXX #define _VCONT_HXX #define _VDRWOBJ_HXX //sfx #define _SFXAPPWIN_HXX #define _SFXCTRLITEM #define _SFXDISPATCH_HXX #define _SFXFILEDLG_HXX #define _SFXIMGMGR_HXX #define _SFXIPFRM_HXX #define _SFX_MACRO_HXX #define _SFXMULTISEL_HXX #define _SFX_MINFITEM_HXX //sfxcore.hxx //#define _SFXINIMGR_HXX *** //#define _SFXCFGITEM_HXX //#define _SFX_PRINTER_HXX #define _SFXGENLINK_HXX #define _SFXHINTPOST_HXX #define _SFXDOCINF_HXX #define _SFXLINKHDL_HXX //#define _SFX_PROGRESS_HXX //sfxsh.hxx //#define _SFX_SHELL_HXX //#define _SFXAPP_HXX //#define _SFXDISPATCH_HXX //#define _SFXMSG_HXX *** //#define _SFXOBJFACE_HXX *** //#define _SFXREQUEST_HXX #define _SFXMACRO_HXX // SFX //#define _SFXAPPWIN_HXX *** #define _SFX_SAVEOPT_HXX //#define _SFX_CHILDWIN_HXX //#define _SFXCTRLITEM_HXX #define _SFXPRNMON_HXX #define _INTRO_HXX #define _SFXMSGDESCR_HXX #define _SFXMSGPOOL_HXX #define _SFXFILEDLG_HXX #define _PASSWD_HXX #define _SFXTBXCTRL_HXX #define _SFXSTBITEM_HXX #define _SFXMNUITEM_HXX #define _SFXIMGMGR_HXX #define _SFXTBXMGR_HXX #define _SFXSTBMGR_HXX #define _SFX_MINFITEM_HXX #define _SFXEVENT_HXX //sfxdoc.hxx //#define _SFX_OBJSH_HXX //#define _SFX_CLIENTSH_HXX //#define _SFXDOCINF_HXX //#define _SFX_OBJFAC_HXX #define _SFX_DOCFILT_HXX //#define _SFXDOCFILE_HXX *** //define _VIEWFAC_HXX //#define _SFXVIEWFRM_HXX //#define _SFXVIEWSH_HXX //#define _MDIFRM_HXX *** #define _SFX_IPFRM_HXX //#define _SFX_INTERNO_HXX //sfxdlg.hxx //#define _SFXTABDLG_HXX //#define _BASEDLGS_HXX *** #define _SFX_DINFDLG_HXX #define _SFXDINFEDT_HXX #define _SFX_MGETEMPL_HXX #define _SFX_TPLPITEM_HXX //#define _SFX_STYLEDLG_HXX #define _NEWSTYLE_HXX //#define _SFXDOCTEMPL_HXX *** //#define _SFXDOCTDLG_HXX *** //#define _SFX_TEMPLDLG_HXX *** //#define _SFXNEW_HXX *** #define _SFXDOCMAN_HXX //#define _SFXDOCKWIN_HXX //sfxitems.hxx #define _SFX_WHMAP_HXX #define _ARGS_HXX //#define _SFXPOOLITEM_HXX //#define _SFXINTITEM_HXX //#define _SFXENUMITEM_HXX #define _SFXFLAGITEM_HXX //#define _SFXSTRITEM_HXX #define _SFXPTITEM_HXX #define _SFXRECTITEM_HXX //#define _SFXITEMPOOL_HXX //#define _SFXITEMSET_HXX #define _SFXITEMITER_HXX #define _SFX_WHITER_HXX #define _SFXPOOLCACH_HXX //#define _AEITEM_HXX #define _SFXRNGITEM_HXX //#define _SFXSLSTITM_HXX //#define _SFXSTYLE_HXX //xout.hxx //#define _XENUM_HXX //#define _XPOLY_HXX //#define _XATTR_HXX //#define _XOUTX_HXX //#define _XPOOL_HXX //#define _XTABLE_HXX //svdraw.hxx #define _SDR_NOITEMS #define _SDR_NOTOUCH #define _SDR_NOTRANSFORM //#define _SDR_NOOBJECTS //#define _SDR_NOVIEWS #define _SFXBASIC_HXX #define _SFX_DOCFILE_HXX #define _SFX_DOCFILT_HXX #define _SFX_DOCINF_HXX #define _SFX_DOCSH_HXX #define _SFX_TEMPLDLG_HXX #define _SFXSTBMGR_HXX #define _SFXTBXMGR_HXX #define _SFXIMGMGR_HXX #define _SFXMNUITEM_HXX #define _SFXMNUMGR_HXX #define _SFXSTBITEM_HXX #define _SFXTBXCTRL_HXX #define _SFXFILEDLG_HXX #define _SFXREQUEST_HXX #define _SFXOBJFACE_HXX #define _SFXMSGPOOL_HXX #define _SFXMSGDESCR_HXX #define _SFXMSG_HXX #define _SFX_PRNMON_HXX //si #define _SI_NOSBXCONTROLS #define _SI_NOCONTROL //#define SI_NOITEMS //#define SI_NODRW //#define SI_NOOTHERFORMS #define _SIDLL_HXX //#define _VCSBX_HXX //#define _VCBRW_HXX //#define _SVDATTR_HXX <--- der wars #define _SVDXOUT_HXX #define _SVDEC_HXX //#define _SVDIO_HXX //#define _SVDLAYER_HXX //#define _SVDRAG_HXX #define _SVINCVW_HXX #define _SV_MULTISEL_HXX #define _SVRTV_HXX #define _SVTABBX_HXX #define _SVX_DAILDLL_HXX #define _SVX_HYPHEN_HXX #define _SVX_IMPGRF_HXX #define _SVX_OPTITEMS_HXX #define _SVX_OPTGERL_HXX #define _SVX_OPTSAVE_HXX #define _SVX_OPTSPELL_HXX #define _SVX_OPTPATH_HXX #define _SVX_OPTLINGU_HXX #define _SVX_RULER_HXX #define _SVX_RULRITEM_HXX #define _SVX_SPLWRAP_HXX #define _SVX_SPLDLG_HXX #define _SVX_THESDLG_HXX // INCLUDE --------------------------------------------------------------- #include <sfx2/childwin.hxx> #include <sfx2/objsh.hxx> #include "document.hxx" #include "viewdata.hxx" #include "drawview.hxx" #include "drawpage.hxx" #include "drwlayer.hxx" // STATIC DATA ----------------------------------------------------------- // ----------------------------------------------------------------------- void ActivateOlk( ScViewData* pViewData ) { // Browser fuer Virtual Controls fuellen // VC's und den Browser dazu gibts nicht mehr... // GetSbxForm gibt's nicht mehr, muss auch nichts mehr angemeldet werden } void DeActivateOlk( ScViewData* pViewData ) { // Browser fuer Virtual Controls fuellen // VC's und den Browser dazu gibts nicht mehr... // GetSbxForm gibt's nicht mehr, muss auch nichts mehr angemeldet werden } <|endoftext|>
<commit_before>#include "application.h" #include <QtQml> #include <QScreen> #include <QKeyEvent> #include <QQuickView> #include <QStandardPaths> #include <QDebug> #include <QDir> #include <QFontDatabase> #include <QFile> #include <QWeakPointer> #include "imageprovider.h" #include "quick/enums.h" #include "quick/models.h" #include "quick/quicktrackinfo.h" #include "quick/quickmosaicgenerator.h" #include "quick/quickfactory.h" #include "quick/quickartistsynopsis.h" #include "quick/quickglobalstatemachine.h" #include "../../appkey.c" namespace sp = Spotinetta; namespace { // This global is unfortunately necessary for the Qt Quick models // to retrieve the current session QWeakPointer<Spotinetta::Session> g_session; } namespace Sonetta { Application::Application(QObject * parent) : QObject(parent), m_view(new QQuickView), m_ui(new UIStateCoordinator), m_output(new AudioOutput), m_settings(new Settings), m_exiting(false) { createSession(); m_player.reset(new Player(m_session, m_output)); m_search.reset(new SearchEngine(m_session.constCast<const sp::Session>(), m_settings)); m_collection.reset(new LibraryCollection(m_session.constCast<const sp::Session>(), this)); connect(m_session.data(), &sp::Session::loggedOut, this, &Application::onLogout); connect(m_session.data(), &sp::Session::log, [] (const QString &msg) { qDebug() << msg; }); connect(m_settings.data(), &Settings::mouseEnabledChanged, this, &Application::updateCursor); m_view->installEventFilter(this); } Application::~Application() { // Manually reset view here to make sure it's deleted // before any of the others (Player, SearchEngine etc.) m_view.reset(); } bool Application::initialize() { registerQmlTypes(); // Enable mouse m_settings->setMouseEnabled(true); if (m_session->error() == sp::Error::Ok) { m_navigation.initialize(m_settings->lircDelay()); setupQuickEnvironment(); showUi(); return true; } else { const QByteArray error = sp::errorMessage(m_session->error()).toUtf8(); qFatal("Session creation failed. Error: %s", error.constData()); return false; } } void Application::onExit() { if (!m_exiting) { m_exiting = true; if (m_session->connectionState() == sp::Session::ConnectionState::LoggedIn || m_session->connectionState() == sp::Session::ConnectionState::Offline) { m_session->logout(); } else { // Skip session logout onLogout(); } } } void Application::onLogout() { if (m_exiting) { QCoreApplication::quit(); } } void Application::updateCursor() { if (m_view.isNull()) return; if (m_settings->mouseEnabled()) { m_view->unsetCursor(); } else { m_view->setCursor(QCursor(Qt::BlankCursor)); } } ObjectSharedPointer<sp::Session> Application::session() { return ObjectSharedPointer<sp::Session>(g_session.toStrongRef()); } bool Application::eventFilter(QObject * obj, QEvent * e) { Q_UNUSED(obj); Q_ASSERT(obj == m_view.data()); switch (e->type()) { case QEvent::Close: onExit(); return true; case QEvent::MouseButtonDblClick: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: case QEvent::MouseTrackingChange: if (!m_settings->mouseEnabled()) return true; default: return false; } } void Application::registerQmlTypes() { Navigation::registerTypes(); qmlRegisterType<QuickPlaylistContainerModel>("Sonetta", 0, 1, "PlaylistContainerModel"); qmlRegisterType<QuickPlaylistModel>("Sonetta", 0, 1, "PlaylistModel"); qmlRegisterType<QuickAlbumModel>("Sonetta", 0, 1, "AlbumModel"); qmlRegisterType<QuickTrackInfo>("Sonetta", 0, 1, "TrackInfo"); qmlRegisterType<QuickMosaicGenerator>("Sonetta", 0, 1, "MosaicGenerator"); qmlRegisterType<QuickArtistSynopsis>("Sonetta", 0, 1, "ArtistSynopsis"); qmlRegisterUncreatableType<Spotinetta::Session>("Sonetta", 0, 1, "Session", "Cannot instantiate Session."); qmlRegisterSingletonType<QuickFactory>("Sonetta", 0, 1, "Factory", &quickFactorySingletonProvider); // Enums qmlRegisterUncreatableType<AlbumEnums>("Sonetta", 0, 1, "Album", "Cannot instantiate Album."); qmlRegisterUncreatableType<TrackEnums>("Sonetta", 0, 1, "Track", "Cannot instantiate Track."); // State machine qmlRegisterType<QuickGlobalStateTransition>("Sonetta.Utilities", 0, 1, "GlobalStateTransition"); qmlRegisterSingletonType<QuickGlobalStateMachine>("Sonetta.Utilities", 0, 1, "GlobalStateMachine", [] (QQmlEngine *, QJSEngine *) -> QObject * { return new QuickGlobalStateMachine; }); } void Application::setupQuickEnvironment() { connect(m_view->engine(), &QQmlEngine::quit, this, &Application::onExit); const QString applicationDir = QCoreApplication::applicationDirPath(); ImageProvider * provider = new ImageProvider(m_session.constCast<const sp::Session>(), m_view.data()); m_view->engine()->addImageProvider(QLatin1String("sp"), provider); m_view->engine()->addImportPath(applicationDir + QStringLiteral("/quick")); m_view->engine()->addPluginPath(applicationDir + QStringLiteral("/quick")); m_view->engine()->addPluginPath(applicationDir + QStringLiteral("/plugins")); m_view->engine()->rootContext()->setContextProperty("player", m_player.data()); m_view->engine()->rootContext()->setContextProperty("ui", m_ui.data()); m_view->engine()->rootContext()->setContextProperty("session", m_session.data()); m_view->engine()->rootContext()->setContextProperty("search", m_search.data()); m_view->engine()->rootContext()->setContextProperty("library", m_collection.data()); m_view->engine()->addImportPath(applicationDir + QStringLiteral("/modules/")); m_view->setSource(QUrl::fromLocalFile(applicationDir + QStringLiteral("/interfaces/default/main.qml"))); m_view->setResizeMode(QQuickView::SizeRootObjectToView); } void Application::showUi() { updateCursor(); // Center view QScreen * screen = m_view->screen(); QPoint screenCenter = screen->availableGeometry().center(); QPoint windowCenter = m_view->geometry().center(); m_view->setPosition(screenCenter - windowCenter); m_view->showFullScreen(); //m_view->showNormal(); } void Application::loadFonts() { qDebug() << "Loading supplied applications fonts..."; QDir fontDir (QCoreApplication::applicationDirPath() + "/fonts"); if (fontDir.exists()) { QStringList paths = fontDir.entryList(QDir::Files | QDir::NoDotAndDotDot); for (const QString & path : paths) { QFile file(fontDir.absoluteFilePath(path)); if (file.open(QIODevice::ReadOnly)) { QByteArray data = file.readAll(); int id = QFontDatabase::addApplicationFontFromData(data); qDebug() << "Loaded font families:" << QFontDatabase::applicationFontFamilies(id); } else { qDebug() << "Failed to open font file " << path; } } } qDebug() << "Font loading complete."; } void Application::createSession() { sp::SessionConfig config; config.applicationKey = sp::ApplicationKey(g_appkey, g_appkey_size); config.userAgent = "sonetta"; config.audioOutput = m_output; config.settingsLocation = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/libspotify"; config.cacheLocation = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/libspotify"; // Create directories if they don't exist QDir dir; dir.mkpath(config.settingsLocation); dir.mkpath(config.cacheLocation); m_session.reset(new sp::Session(config)); // See comment above declaration for rationale g_session = m_session; } } <commit_msg>Possible minor fix for crash at shutdown<commit_after>#include "application.h" #include <QtQml> #include <QScreen> #include <QKeyEvent> #include <QQuickView> #include <QStandardPaths> #include <QDebug> #include <QDir> #include <QFontDatabase> #include <QFile> #include <QWeakPointer> #include "imageprovider.h" #include "quick/enums.h" #include "quick/models.h" #include "quick/quicktrackinfo.h" #include "quick/quickmosaicgenerator.h" #include "quick/quickfactory.h" #include "quick/quickartistsynopsis.h" #include "quick/quickglobalstatemachine.h" #include "../../appkey.c" namespace sp = Spotinetta; namespace { // This global is unfortunately necessary for the Qt Quick models // to retrieve the current session QWeakPointer<Spotinetta::Session> g_session; } namespace Sonetta { Application::Application(QObject * parent) : QObject(parent), m_view(new QQuickView), m_ui(new UIStateCoordinator), m_output(new AudioOutput), m_settings(new Settings), m_exiting(false) { createSession(); m_player.reset(new Player(m_session, m_output)); m_search.reset(new SearchEngine(m_session.constCast<const sp::Session>(), m_settings)); m_collection.reset(new LibraryCollection(m_session.constCast<const sp::Session>())); connect(m_session.data(), &sp::Session::loggedOut, this, &Application::onLogout); connect(m_session.data(), &sp::Session::log, [] (const QString &msg) { qDebug() << msg; }); connect(m_settings.data(), &Settings::mouseEnabledChanged, this, &Application::updateCursor); m_view->installEventFilter(this); } Application::~Application() { // Manually reset view here to make sure it's deleted // before any of the others (Player, SearchEngine etc.) m_view.reset(); } bool Application::initialize() { registerQmlTypes(); // Enable mouse m_settings->setMouseEnabled(true); if (m_session->error() == sp::Error::Ok) { m_navigation.initialize(m_settings->lircDelay()); setupQuickEnvironment(); showUi(); return true; } else { const QByteArray error = sp::errorMessage(m_session->error()).toUtf8(); qFatal("Session creation failed. Error: %s", error.constData()); return false; } } void Application::onExit() { if (!m_exiting) { m_exiting = true; if (m_session->connectionState() == sp::Session::ConnectionState::LoggedIn || m_session->connectionState() == sp::Session::ConnectionState::Offline) { m_session->logout(); } else { // Skip session logout onLogout(); } } } void Application::onLogout() { if (m_exiting) { QCoreApplication::quit(); } } void Application::updateCursor() { if (m_view.isNull()) return; if (m_settings->mouseEnabled()) { m_view->unsetCursor(); } else { m_view->setCursor(QCursor(Qt::BlankCursor)); } } ObjectSharedPointer<sp::Session> Application::session() { return ObjectSharedPointer<sp::Session>(g_session.toStrongRef()); } bool Application::eventFilter(QObject * obj, QEvent * e) { Q_UNUSED(obj); Q_ASSERT(obj == m_view.data()); switch (e->type()) { case QEvent::Close: onExit(); return true; case QEvent::MouseButtonDblClick: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: case QEvent::MouseTrackingChange: if (!m_settings->mouseEnabled()) return true; default: return false; } } void Application::registerQmlTypes() { Navigation::registerTypes(); qmlRegisterType<QuickPlaylistContainerModel>("Sonetta", 0, 1, "PlaylistContainerModel"); qmlRegisterType<QuickPlaylistModel>("Sonetta", 0, 1, "PlaylistModel"); qmlRegisterType<QuickAlbumModel>("Sonetta", 0, 1, "AlbumModel"); qmlRegisterType<QuickTrackInfo>("Sonetta", 0, 1, "TrackInfo"); qmlRegisterType<QuickMosaicGenerator>("Sonetta", 0, 1, "MosaicGenerator"); qmlRegisterType<QuickArtistSynopsis>("Sonetta", 0, 1, "ArtistSynopsis"); qmlRegisterUncreatableType<Spotinetta::Session>("Sonetta", 0, 1, "Session", "Cannot instantiate Session."); qmlRegisterSingletonType<QuickFactory>("Sonetta", 0, 1, "Factory", &quickFactorySingletonProvider); // Enums qmlRegisterUncreatableType<AlbumEnums>("Sonetta", 0, 1, "Album", "Cannot instantiate Album."); qmlRegisterUncreatableType<TrackEnums>("Sonetta", 0, 1, "Track", "Cannot instantiate Track."); // State machine qmlRegisterType<QuickGlobalStateTransition>("Sonetta.Utilities", 0, 1, "GlobalStateTransition"); qmlRegisterSingletonType<QuickGlobalStateMachine>("Sonetta.Utilities", 0, 1, "GlobalStateMachine", [] (QQmlEngine *, QJSEngine *) -> QObject * { return new QuickGlobalStateMachine; }); } void Application::setupQuickEnvironment() { connect(m_view->engine(), &QQmlEngine::quit, this, &Application::onExit); const QString applicationDir = QCoreApplication::applicationDirPath(); ImageProvider * provider = new ImageProvider(m_session.constCast<const sp::Session>(), m_view.data()); m_view->engine()->addImageProvider(QLatin1String("sp"), provider); m_view->engine()->addImportPath(applicationDir + QStringLiteral("/quick")); m_view->engine()->addPluginPath(applicationDir + QStringLiteral("/quick")); m_view->engine()->addPluginPath(applicationDir + QStringLiteral("/plugins")); m_view->engine()->rootContext()->setContextProperty("player", m_player.data()); m_view->engine()->rootContext()->setContextProperty("ui", m_ui.data()); m_view->engine()->rootContext()->setContextProperty("session", m_session.data()); m_view->engine()->rootContext()->setContextProperty("search", m_search.data()); m_view->engine()->rootContext()->setContextProperty("library", m_collection.data()); m_view->engine()->addImportPath(applicationDir + QStringLiteral("/modules/")); m_view->setSource(QUrl::fromLocalFile(applicationDir + QStringLiteral("/interfaces/default/main.qml"))); m_view->setResizeMode(QQuickView::SizeRootObjectToView); } void Application::showUi() { updateCursor(); // Center view QScreen * screen = m_view->screen(); QPoint screenCenter = screen->availableGeometry().center(); QPoint windowCenter = m_view->geometry().center(); m_view->setPosition(screenCenter - windowCenter); m_view->showFullScreen(); //m_view->showNormal(); } void Application::loadFonts() { qDebug() << "Loading supplied applications fonts..."; QDir fontDir (QCoreApplication::applicationDirPath() + "/fonts"); if (fontDir.exists()) { QStringList paths = fontDir.entryList(QDir::Files | QDir::NoDotAndDotDot); for (const QString & path : paths) { QFile file(fontDir.absoluteFilePath(path)); if (file.open(QIODevice::ReadOnly)) { QByteArray data = file.readAll(); int id = QFontDatabase::addApplicationFontFromData(data); qDebug() << "Loaded font families:" << QFontDatabase::applicationFontFamilies(id); } else { qDebug() << "Failed to open font file " << path; } } } qDebug() << "Font loading complete."; } void Application::createSession() { sp::SessionConfig config; config.applicationKey = sp::ApplicationKey(g_appkey, g_appkey_size); config.userAgent = "sonetta"; config.audioOutput = m_output; config.settingsLocation = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/libspotify"; config.cacheLocation = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/libspotify"; // Create directories if they don't exist QDir dir; dir.mkpath(config.settingsLocation); dir.mkpath(config.cacheLocation); m_session.reset(new sp::Session(config)); // See comment above declaration for rationale g_session = m_session; } } <|endoftext|>
<commit_before>#include <Eigen/Dense> #include <iostream> // must go before other things because R defines a "length" macro #include <nimble/RcppUtils.h> #include "nimble/RcppNimbleUtils.h" //#include <nimble/ModelClassUtils.h> //#include <nimble/accessorClasses.h> #include <nimble/nimbleGraph.h> #include <nimble/EigenTypedefs.h> #include <nimble/dists.h> #include <R_ext/Rdynload.h> #define FUN(name, numArgs) \ {#name, (DL_FUNC) &name, numArgs} #define CFUN(name, numArgs) \ {"R_"#name, (DL_FUNC) &name, numArgs} R_CallMethodDef CallEntries[] = { // {"getModelValuesPtrFromModel", (DL_FUNC) &getModelValuesPtrFromModel, 1}, // FUN(setNodeModelPtr, 3), // FUN(getAvailableNames, 1), // FUN(getMVElement, 2), // FUN(setMVElement, 3), // FUN(resizeManyModelVarAccessor, 2), // FUN(resizeManyModelValuesAccessor, 2), // FUN(getModelObjectPtr, 2), // FUN(getModelValuesMemberElement, 2), // FUN(getNRow, 1), //FUN(addBlankModelValueRows, 2), //FUN(copyModelValuesElements, 4), FUN(C_dwish_chol, 5), FUN(C_rwish_chol, 3), FUN(C_ddirch, 3), FUN(C_rdirch, 1), FUN(C_dmulti, 4), FUN(C_rmulti, 2), FUN(C_dcat, 3), FUN(C_rcat, 2), FUN(C_dt_nonstandard, 5), FUN(C_rt_nonstandard, 4), FUN(C_dmnorm_chol, 5), FUN(C_rmnorm_chol, 3), FUN(C_dinterval, 4), FUN(C_rinterval, 3), // FUN(makeNumericList, 3), // The following 4 conflict with names of R functions. So we prefix them with a R_ //CFUN(setPtrVectorOfPtrs, 3), //CFUN(setOnePtrVectorOfPtrs, 3), //CFUN(setDoublePtrFromSinglePtr, 2), // CFUN(setSinglePtrFromSinglePtr, 2), // FUN(newModelValues, 1), //These don't register well since they are overloaded // FUN(SEXP_2_double, 3), // FUN(double_2_SEXP, 2), // FUN(SEXP_2_bool, 3), // FUN(bool_2_SEXP, 2), // FUN(SEXP_2_int, 3), // FUN(int_2_SEXP, 2), // FUN(SEXP_2_string, 2), // FUN(SEXP_2_stringVector, 2), // FUN(string_2_SEXP, 1), // FUN(stringVector_2_SEXP, 1) FUN(fastMatrixInsert, 4), FUN(matrix2ListDouble, 5), FUN(matrix2ListInt, 5), // FUN(rankSample, 4), FUN(parseVar, 1), FUN(setGraph, 6), FUN(anyStochDependencies, 1), FUN(anyStochParents, 1), FUN(getDependencies, 4), {NULL, NULL, 0} }; /* Arrange to register the routines so that they can be checked and also accessed by their equivalent name as an R symbol, e.g. .Call(setNodeModelPtr, ....) */ extern "C" void R_init_nimble(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); } <commit_msg>add R_useDynamicSymbols<commit_after>#include <Eigen/Dense> #include <iostream> // must go before other things because R defines a "length" macro #include <nimble/RcppUtils.h> #include "nimble/RcppNimbleUtils.h" //#include <nimble/ModelClassUtils.h> //#include <nimble/accessorClasses.h> #include <nimble/nimbleGraph.h> #include <nimble/EigenTypedefs.h> #include <nimble/dists.h> #include <R_ext/Rdynload.h> #define FUN(name, numArgs) \ {#name, (DL_FUNC) &name, numArgs} #define CFUN(name, numArgs) \ {"R_"#name, (DL_FUNC) &name, numArgs} R_CallMethodDef CallEntries[] = { // {"getModelValuesPtrFromModel", (DL_FUNC) &getModelValuesPtrFromModel, 1}, // FUN(setNodeModelPtr, 3), // FUN(getAvailableNames, 1), // FUN(getMVElement, 2), // FUN(setMVElement, 3), // FUN(resizeManyModelVarAccessor, 2), // FUN(resizeManyModelValuesAccessor, 2), // FUN(getModelObjectPtr, 2), // FUN(getModelValuesMemberElement, 2), // FUN(getNRow, 1), //FUN(addBlankModelValueRows, 2), //FUN(copyModelValuesElements, 4), FUN(C_dwish_chol, 5), FUN(C_rwish_chol, 3), FUN(C_ddirch, 3), FUN(C_rdirch, 1), FUN(C_dmulti, 4), FUN(C_rmulti, 2), FUN(C_dcat, 3), FUN(C_rcat, 2), FUN(C_dt_nonstandard, 5), FUN(C_rt_nonstandard, 4), FUN(C_dmnorm_chol, 5), FUN(C_rmnorm_chol, 3), FUN(C_dinterval, 4), FUN(C_rinterval, 3), // FUN(makeNumericList, 3), // The following 4 conflict with names of R functions. So we prefix them with a R_ //CFUN(setPtrVectorOfPtrs, 3), //CFUN(setOnePtrVectorOfPtrs, 3), //CFUN(setDoublePtrFromSinglePtr, 2), // CFUN(setSinglePtrFromSinglePtr, 2), // FUN(newModelValues, 1), //These don't register well since they are overloaded // FUN(SEXP_2_double, 3), // FUN(double_2_SEXP, 2), // FUN(SEXP_2_bool, 3), // FUN(bool_2_SEXP, 2), // FUN(SEXP_2_int, 3), // FUN(int_2_SEXP, 2), // FUN(SEXP_2_string, 2), // FUN(SEXP_2_stringVector, 2), // FUN(string_2_SEXP, 1), // FUN(stringVector_2_SEXP, 1) FUN(fastMatrixInsert, 4), FUN(matrix2ListDouble, 5), FUN(matrix2ListInt, 5), // FUN(rankSample, 4), FUN(parseVar, 1), FUN(setGraph, 6), FUN(anyStochDependencies, 1), FUN(anyStochParents, 1), FUN(getDependencies, 4), {NULL, NULL, 0} }; /* Arrange to register the routines so that they can be checked and also accessed by their equivalent name as an R symbol, e.g. .Call(setNodeModelPtr, ....) */ extern "C" void R_init_nimble(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dbmetadata.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2006-07-10 14:20:08 $ * * 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 CONNECTIVITY_INC_CONNECTIVITY_DBMETADATA_HXX #include <connectivity/dbmetadata.hxx> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif /** === end UNO includes === **/ #ifndef TOOLS_DIAGNOSE_EX_H #include <tools/diagnose_ex.h> #endif //........................................................................ namespace dbtools { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::sdbc::XConnection; using ::com::sun::star::sdbc::XConnection; using ::com::sun::star::sdbc::XDatabaseMetaData; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::uno::Exception; /** === end UNO using === **/ //==================================================================== //= DatabaseMetaData_Impl //==================================================================== struct DatabaseMetaData_Impl { Reference< XConnection > xConnection; Reference< XDatabaseMetaData > xConnectionMetaData; }; //-------------------------------------------------------------------- namespace { static void lcl_construct( DatabaseMetaData_Impl& _metaDataImpl, const Reference< XConnection >& _connection ) { _metaDataImpl.xConnection = _connection; if ( !_metaDataImpl.xConnection.is() ) return; _metaDataImpl.xConnectionMetaData = _connection->getMetaData(); if ( !_metaDataImpl.xConnectionMetaData.is() ) throw IllegalArgumentException(); } static void lcl_checkConnected( DatabaseMetaData_Impl& _metaDataImpl ) { if ( !_metaDataImpl.xConnection.is() ) throwSQLException( "not connected", SQL_CONNECTION_DOES_NOT_EXIST, NULL ); } } //==================================================================== //= DatabaseMetaData //==================================================================== //-------------------------------------------------------------------- DatabaseMetaData::DatabaseMetaData() :m_pImpl( new DatabaseMetaData_Impl ) { } //-------------------------------------------------------------------- DatabaseMetaData::DatabaseMetaData( const Reference< XConnection >& _connection ) :m_pImpl( new DatabaseMetaData_Impl ) { lcl_construct( *m_pImpl, _connection ); } //-------------------------------------------------------------------- DatabaseMetaData::DatabaseMetaData( const DatabaseMetaData& _copyFrom ) :m_pImpl( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) ) { } //-------------------------------------------------------------------- DatabaseMetaData& DatabaseMetaData::operator=( const DatabaseMetaData& _copyFrom ) { if ( this == &_copyFrom ) return *this; m_pImpl.reset( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) ); return *this; } //-------------------------------------------------------------------- DatabaseMetaData::~DatabaseMetaData() { } //-------------------------------------------------------------------- bool DatabaseMetaData::isConnected() const { return m_pImpl->xConnection.is(); } //-------------------------------------------------------------------- bool SAL_CALL DatabaseMetaData::supportsSubqueriesInFrom() const { lcl_checkConnected( *m_pImpl ); bool supportsSubQueries = false; try { sal_Int32 maxTablesInselect = m_pImpl->xConnectionMetaData->getMaxTablesInSelect(); supportsSubQueries = ( maxTablesInselect > 1 ) || ( maxTablesInselect == 0 ); // TODO: is there a better way to determine this? The above is not really true. More precise, // it's a *very* generous heuristics ... } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } return supportsSubQueries; } //........................................................................ } // namespace dbtools //........................................................................ <commit_msg>INTEGRATION: CWS dba204b (1.2.2); FILE MERGED 2006/07/17 08:06:34 fs 1.2.2.1: #i67260# +restrictIdentifiersToSQL92<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dbmetadata.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2006-07-26 07:21: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 * ************************************************************************/ #ifndef CONNECTIVITY_INC_CONNECTIVITY_DBMETADATA_HXX #include <connectivity/dbmetadata.hxx> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif /** === end UNO includes === **/ #ifndef TOOLS_DIAGNOSE_EX_H #include <tools/diagnose_ex.h> #endif //........................................................................ namespace dbtools { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::sdbc::XConnection; using ::com::sun::star::sdbc::XConnection; using ::com::sun::star::sdbc::XDatabaseMetaData; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::Any; using ::com::sun::star::container::XChild; using ::com::sun::star::uno::UNO_QUERY_THROW; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::uno::Sequence; using ::com::sun::star::beans::PropertyValue; /** === end UNO using === **/ //==================================================================== //= DatabaseMetaData_Impl //==================================================================== struct DatabaseMetaData_Impl { Reference< XConnection > xConnection; Reference< XDatabaseMetaData > xConnectionMetaData; }; //-------------------------------------------------------------------- namespace { static void lcl_construct( DatabaseMetaData_Impl& _metaDataImpl, const Reference< XConnection >& _connection ) { _metaDataImpl.xConnection = _connection; if ( !_metaDataImpl.xConnection.is() ) return; _metaDataImpl.xConnectionMetaData = _connection->getMetaData(); if ( !_metaDataImpl.xConnectionMetaData.is() ) throw IllegalArgumentException(); } static void lcl_checkConnected( DatabaseMetaData_Impl& _metaDataImpl ) { if ( !_metaDataImpl.xConnection.is() ) throwSQLException( "not connected", SQL_CONNECTION_DOES_NOT_EXIST, NULL ); } static bool lcl_getDataSourceSetting( const sal_Char* _asciiName, const DatabaseMetaData_Impl& _metaData, Any& _out_setting ) { try { Reference< XChild > connectionAsChild( _metaData.xConnection, UNO_QUERY_THROW ); Reference< XPropertySet > dataSource( connectionAsChild->getParent(), UNO_QUERY_THROW ); Sequence< PropertyValue > dataSourceSettings; OSL_VERIFY( dataSource->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Info" ) ) ) >>= dataSourceSettings ); const PropertyValue* setting( dataSourceSettings.getConstArray() ); const PropertyValue* settingEnd( setting + dataSourceSettings.getLength() ); for ( ; setting != settingEnd; ++setting ) { if ( setting->Name.equalsAscii( _asciiName ) ) { _out_setting = setting->Value; return true; } } } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } return false; } } //==================================================================== //= DatabaseMetaData //==================================================================== //-------------------------------------------------------------------- DatabaseMetaData::DatabaseMetaData() :m_pImpl( new DatabaseMetaData_Impl ) { } //-------------------------------------------------------------------- DatabaseMetaData::DatabaseMetaData( const Reference< XConnection >& _connection ) :m_pImpl( new DatabaseMetaData_Impl ) { lcl_construct( *m_pImpl, _connection ); } //-------------------------------------------------------------------- DatabaseMetaData::DatabaseMetaData( const DatabaseMetaData& _copyFrom ) :m_pImpl( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) ) { } //-------------------------------------------------------------------- DatabaseMetaData& DatabaseMetaData::operator=( const DatabaseMetaData& _copyFrom ) { if ( this == &_copyFrom ) return *this; m_pImpl.reset( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) ); return *this; } //-------------------------------------------------------------------- DatabaseMetaData::~DatabaseMetaData() { } //-------------------------------------------------------------------- bool DatabaseMetaData::isConnected() const { return m_pImpl->xConnection.is(); } //-------------------------------------------------------------------- bool SAL_CALL DatabaseMetaData::supportsSubqueriesInFrom() const { lcl_checkConnected( *m_pImpl ); bool supportsSubQueries = false; try { sal_Int32 maxTablesInselect = m_pImpl->xConnectionMetaData->getMaxTablesInSelect(); supportsSubQueries = ( maxTablesInselect > 1 ) || ( maxTablesInselect == 0 ); // TODO: is there a better way to determine this? The above is not really true. More precise, // it's a *very* generous heuristics ... } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } return supportsSubQueries; } //-------------------------------------------------------------------- bool SAL_CALL DatabaseMetaData::restrictIdentifiersToSQL92() const { bool restrict( false ); Any setting; if ( lcl_getDataSourceSetting( "EnableSQL92Check", *m_pImpl, setting ) ) OSL_VERIFY( setting >>= restrict ); return restrict; } //........................................................................ } // namespace dbtools //........................................................................ <|endoftext|>
<commit_before>/* * File: Sphere.cpp * Author: Benedikt Vogler * * Created on 4. Juli 2014, 19:25 */ #include "Sphere.hpp" std::pair<bool, Ray> Sphere::intersect(Ray const& ray) const { glm::vec3 l = ray.origin - center; float a = glm::dot(ray.direction, ray.direction); float b = 2.0f*(glm::dot(l,ray.direction)); float c = glm::dot(l,l) - radius*radius; float det = b*b-4.0f*a*c; if (det>=0.0f) {//wenn es min. eine Lösung gibt float t1 = (-b-sqrt(det))/(2.0f*a); float t2 = (-b+sqrt(det))/(2.0f*a); if (t1 < t2){//nimm Punkt, welcher näher dran ist if (t1<0) return std::make_pair(false, Ray());//keine Lösung else return std::make_pair(true, Ray(l-(ray.origin+ray.direction*t1)));//use t1 } else{ if (t2<0) return std::make_pair(false, Ray());//keine Lösung else return std::make_pair(true, Ray(l-(ray.origin+ray.direction*t2)));//use t2 } } else return std::make_pair(false, Ray());//keine Lösung }<commit_msg>returns hopefully the normal #9<commit_after>/* * File: Sphere.cpp * Author: Benedikt Vogler * * Created on 4. Juli 2014, 19:25 */ #include "Sphere.hpp" #include <glm/glm.hpp> std::pair<bool, Ray> Sphere::intersect(Ray const& ray) const { glm::vec3 l = ray.origin - center; float a = glm::dot(ray.direction, ray.direction); float b = 2.0f*(glm::dot(l,ray.direction)); float c = glm::dot(l,l) - radius*radius; float det = b*b-4.0f*a*c; if (det>=0.0f) {//wenn es min. eine Lösung gibt float t1 = (-b-sqrt(det))/(2.0f*a); float t2 = (-b+sqrt(det))/(2.0f*a); if (t1 < t2){//nimm Punkt, welcher näher dran ist if (t1<0) return std::make_pair(false, Ray());//keine Lösung else{ auto p =l-(ray.origin+ray.direction*t1); return std::make_pair(true, Ray(p,glm::normalize(center-p)));//use t1 } } else{ if (t2<0) return std::make_pair(false, Ray());//keine Lösung else{ auto p =l-(ray.origin+ray.direction*t2); return std::make_pair(true, Ray(p,glm::normalize(center-p)));//use t2 } } } else return std::make_pair(false, Ray());//keine Lösung }<|endoftext|>
<commit_before>#include "types.h" #include "kernel.hh" #include "spinlock.h" #include "amd64.h" #include "cpu.hh" #include "kalloc.hh" #include "wq.hh" static wq *wq_; static wq *wqcrit_; void* xallocwork(unsigned long nbytes) { return kmalloc(nbytes, "xallocwork"); } void xfreework(void* ptr, unsigned long nbytes) { kmfree(ptr, nbytes); } size_t wq_size(void) { return sizeof(wq); } int wq_push(work *w) { return wq_->push(w, mycpuid()); } void wqcrit_trywork(void) { while (wqcrit_->trywork(false)) ; } int wqcrit_push(work *w, int c) { return wqcrit_->push(w, c); } int wq_trywork(void) { return wqcrit_->trywork(false) || wq_->trywork(true); } void wq_dump(void) { return wq_->dump(); } void initwq(void) { wq_ = new wq(); wqcrit_ = new wq(); if (wq_ == nullptr || wqcrit_ == nullptr) panic("initwq"); } <commit_msg>Assert if work queues are used too early<commit_after>#include "types.h" #include "kernel.hh" #include "spinlock.h" #include "amd64.h" #include "cpu.hh" #include "kalloc.hh" #include "wq.hh" static wq *wq_; static wq *wqcrit_; void* xallocwork(unsigned long nbytes) { return kmalloc(nbytes, "xallocwork"); } void xfreework(void* ptr, unsigned long nbytes) { kmfree(ptr, nbytes); } size_t wq_size(void) { return sizeof(wq); } int wq_push(work *w) { assert(wq_); return wq_->push(w, mycpuid()); } void wqcrit_trywork(void) { assert(wqcrit_); while (wqcrit_->trywork(false)) ; } int wqcrit_push(work *w, int c) { assert(wqcrit_); return wqcrit_->push(w, c); } int wq_trywork(void) { assert(wq_ && wqcrit_); return wqcrit_->trywork(false) || wq_->trywork(true); } void wq_dump(void) { if (wq_) return wq_->dump(); } void initwq(void) { wq_ = new wq(); wqcrit_ = new wq(); if (wq_ == nullptr || wqcrit_ == nullptr) panic("initwq"); } <|endoftext|>
<commit_before>/* * ==================================================================== * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library (in the file LGPL.txt); if not, * write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://rapidsvn.tigris.org/. * ==================================================================== */ // subversion api #include "svn_path.h" // apr api #include "apr_file_io.h" // svncpp #include "svnqt/path.hpp" #include "svnqt/pool.hpp" #include "svnqt/url.hpp" #include "svnqt/svnqt_defines.hpp" namespace svn { Path::Path (const char * path) { init(QString::FROMUTF8(path)); } Path::Path (const QString & path) { init (path); } Path::Path (const Path & path) : m_path(path.m_path) { } void Path::init (const QString& path) { Pool pool; if (path.isEmpty()) { m_path = ""; } else { const char * int_path = svn_path_internal_style (path.TOUTF8(), pool.pool () ); if (Url::isValid(path) ) { if (!svn_path_is_uri_safe(int_path)) { int_path = svn_path_uri_encode(int_path,pool); } } m_path = QString::FROMUTF8(int_path); } } const QString & Path::path () const { return m_path; } Path::operator const QString&()const { return m_path; } QString Path::prettyPath()const { if (!Url::isValid(m_path)) { return m_path; } Pool pool; const char * int_path = svn_path_uri_decode(m_path.TOUTF8(), pool.pool () ); return QString::FROMUTF8(int_path); } const QByteArray Path::cstr() const { return m_path.TOUTF8(); } Path& Path::operator=(const Path & path) { if (this == &path) return *this; m_path = path.path(); return *this; } bool Path::isset () const { return m_path.length () > 0; } void Path::addComponent (const QString& component) { Pool pool; if (Url::isValid (m_path)) { const char * newPath = svn_path_url_add_component (m_path.TOUTF8(), component.TOUTF8(), pool); m_path = QString::FROMUTF8(newPath); } else { svn_stringbuf_t * pathStringbuf = svn_stringbuf_create (m_path.TOUTF8(), pool); svn_path_add_component (pathStringbuf, component.TOUTF8()); m_path = QString::FROMUTF8(pathStringbuf->data); } } void Path::addComponent (const char* component) { addComponent (QString::FROMUTF8(component)); } void Path::split (QString & dirpath, QString & basename) const { Pool pool; const char * cdirpath; const char * cbasename; svn_path_split (m_path.TOUTF8(), &cdirpath, &cbasename, pool); dirpath = QString::FROMUTF8(cdirpath); basename = QString::FROMUTF8(cbasename); } void Path::split (QString & dir, QString & filename, QString & ext) const { QString basename; // first split path into dir and filename+ext split (dir, basename); // next search for last . #if QT_VERSION < 0x040000 int pos = basename.findRev(QChar('.')); #else int pos = basename.lastIndexOf(QChar('.')); #endif if (pos == -1) { filename = basename; ext = QString::fromLatin1(""); } else { filename = basename.left(pos); ext = basename.mid(pos+1); } } Path Path::getTempDir () { const char * tempdir = 0; Pool pool; if (apr_temp_dir_get (&tempdir, pool) != APR_SUCCESS) { tempdir = 0; } return tempdir; } unsigned int Path::length () const { return m_path.length (); } QString Path::native () const { Pool pool; return QString::FROMUTF8(svn_path_local_style (m_path.TOUTF8(), pool)); } } /* ----------------------------------------------------------------- * local variables: * eval: (load-file "../../rapidsvn-dev.el") * end: */ <commit_msg>fixed a problem with @ in path/file name (Bug #0000132 and another not reported bug)<commit_after>/* * ==================================================================== * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library (in the file LGPL.txt); if not, * write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://rapidsvn.tigris.org/. * ==================================================================== */ // subversion api #include "svn_path.h" // apr api #include "apr_file_io.h" // svncpp #include "svnqt/path.hpp" #include "svnqt/pool.hpp" #include "svnqt/url.hpp" #include "svnqt/svnqt_defines.hpp" namespace svn { Path::Path (const char * path) { init(QString::FROMUTF8(path)); } Path::Path (const QString & path) { init (path); } Path::Path (const Path & path) : m_path(path.m_path) { } void Path::init (const QString& path) { Pool pool; if (path.isEmpty()) { m_path = ""; } else { const char * int_path = svn_path_internal_style (path.TOUTF8(), pool.pool () ); if (Url::isValid(path) ) { if (!svn_path_is_uri_safe(int_path)) { int_path = svn_path_uri_encode(int_path,pool); } } m_path = QString::FROMUTF8(int_path); if (Url::isValid(path) ) { /// @todo make sure that "@" is never used as revision paramter m_path.replace("@","%40"); } } } const QString & Path::path () const { return m_path; } Path::operator const QString&()const { return m_path; } QString Path::prettyPath()const { if (!Url::isValid(m_path)) { return m_path; } Pool pool; const char * int_path = svn_path_uri_decode(m_path.TOUTF8(), pool.pool () ); QString _p = QString::FROMUTF8(int_path); _p.replace("%40","@"); return _p; } const QByteArray Path::cstr() const { return m_path.TOUTF8(); } Path& Path::operator=(const Path & path) { if (this == &path) return *this; m_path = path.path(); return *this; } bool Path::isset () const { return m_path.length () > 0; } void Path::addComponent (const QString& component) { Pool pool; if (Url::isValid (m_path)) { const char * newPath = svn_path_url_add_component (m_path.TOUTF8(), component.TOUTF8(), pool); m_path = QString::FROMUTF8(newPath); } else { svn_stringbuf_t * pathStringbuf = svn_stringbuf_create (m_path.TOUTF8(), pool); svn_path_add_component (pathStringbuf, component.TOUTF8()); m_path = QString::FROMUTF8(pathStringbuf->data); } } void Path::addComponent (const char* component) { addComponent (QString::FROMUTF8(component)); } void Path::split (QString & dirpath, QString & basename) const { Pool pool; const char * cdirpath; const char * cbasename; svn_path_split (m_path.TOUTF8(), &cdirpath, &cbasename, pool); dirpath = QString::FROMUTF8(cdirpath); basename = QString::FROMUTF8(cbasename); } void Path::split (QString & dir, QString & filename, QString & ext) const { QString basename; // first split path into dir and filename+ext split (dir, basename); // next search for last . #if QT_VERSION < 0x040000 int pos = basename.findRev(QChar('.')); #else int pos = basename.lastIndexOf(QChar('.')); #endif if (pos == -1) { filename = basename; ext = QString::fromLatin1(""); } else { filename = basename.left(pos); ext = basename.mid(pos+1); } } Path Path::getTempDir () { const char * tempdir = 0; Pool pool; if (apr_temp_dir_get (&tempdir, pool) != APR_SUCCESS) { tempdir = 0; } return tempdir; } unsigned int Path::length () const { return m_path.length (); } QString Path::native () const { Pool pool; return QString::FROMUTF8(svn_path_local_style (m_path.TOUTF8(), pool)); } } /* ----------------------------------------------------------------- * local variables: * eval: (load-file "../../rapidsvn-dev.el") * end: */ <|endoftext|>
<commit_before>#if ! defined (__CINT__) || defined (__MAKECINT__) #include "AliLog.h" #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "PWG1/TRD/AliTRDinfoGen.h" #include "PWG1/TRD/AliTRDpwg1Helper.h" #include "PWG1/TRD/info/AliTRDeventInfo.h" #endif void AddTRDinfoGen(AliAnalysisManager *mgr, Int_t /*map*/, AliAnalysisDataContainer **/*ci*/, AliAnalysisDataContainer **co) { Bool_t mc=mgr->GetMCtruthEventHandler(); //AliLog::SetClassDebugLevel("AliTRDinfoGen", 2); AliTRDinfoGen *info(NULL); mgr->AddTask(info = new AliTRDinfoGen((char*)"TRDinfoGen")); info->SetDebugLevel(0); info->SetMCdata(mc); info->SetLocalTrkSelection(); info->SetOCDB("alien://folder=/alice/data/2010/OCDB"); // settings for collisions info->SetCollision(/*kFALSE*/); if(info->IsCollision()){ if(!mc) info->SetTrigger( "CINT1B-ABCE-NOPF-ALL" " CINT1WU-B-NOPF-ALL" " CSCO1-ABCE-NOPF-CENT" // cosmic SPD trigger ); info->SetLocalEvSelection(); } // Connect IO slots mgr->ConnectInput (info, 0, mgr->GetCommonInputContainer()); co[AliTRDpwg1Helper::kEventInfo] = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer); co[AliTRDpwg1Helper::kTracksBarrel] = mgr->CreateContainer("tracksBarrel", TObjArray::Class(), AliAnalysisManager::kExchangeContainer); co[AliTRDpwg1Helper::kTracksSA] = mgr->CreateContainer("tracksSA", TObjArray::Class(), AliAnalysisManager::kExchangeContainer); co[AliTRDpwg1Helper::kTracksKink] = mgr->CreateContainer("tracksKink", TObjArray::Class(), AliAnalysisManager::kExchangeContainer); co[AliTRDpwg1Helper::kV0List] = mgr->CreateContainer("v0List", TObjArray::Class(), AliAnalysisManager::kExchangeContainer); for(Int_t ios(1);ios<AliTRDpwg1Helper::kNOutSlots-1;ios++) mgr->ConnectOutput(info, ios, co[ios]); // add last monitor container AliAnalysisDataContainer *mon=mgr->CreateContainer(info->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName())); mgr->ConnectOutput(info, AliTRDpwg1Helper::kNOutSlots-1, mon); } <commit_msg>trigger names changed (Markus)<commit_after>#if ! defined (__CINT__) || defined (__MAKECINT__) #include "AliLog.h" #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "PWG1/TRD/AliTRDinfoGen.h" #include "PWG1/TRD/AliTRDpwg1Helper.h" #include "PWG1/TRD/info/AliTRDeventInfo.h" #endif void AddTRDinfoGen(AliAnalysisManager *mgr, Int_t /*map*/, AliAnalysisDataContainer **/*ci*/, AliAnalysisDataContainer **co) { Bool_t mc=mgr->GetMCtruthEventHandler(); //AliLog::SetClassDebugLevel("AliTRDinfoGen", 2); AliTRDinfoGen *info(NULL); mgr->AddTask(info = new AliTRDinfoGen((char*)"TRDinfoGen")); info->SetDebugLevel(0); info->SetMCdata(mc); info->SetLocalTrkSelection(); info->SetOCDB("alien://folder=/alice/data/2010/OCDB"); // settings for collisions info->SetCollision(/*kFALSE*/); if(info->IsCollision()){ if(!mc) info->SetTrigger( "CINT1B-ABCE-NOPF-ALL" " CINT5-B-NOPF-ALL" " CINT1WU-B-NOPF-ALL" " CINT5WU-B-NOPF-ALL" " CSCO1-ABCE-NOPF-CENT" // cosmic SPD trigger ); info->SetLocalEvSelection(); } // Connect IO slots mgr->ConnectInput (info, 0, mgr->GetCommonInputContainer()); co[AliTRDpwg1Helper::kEventInfo] = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer); co[AliTRDpwg1Helper::kTracksBarrel] = mgr->CreateContainer("tracksBarrel", TObjArray::Class(), AliAnalysisManager::kExchangeContainer); co[AliTRDpwg1Helper::kTracksSA] = mgr->CreateContainer("tracksSA", TObjArray::Class(), AliAnalysisManager::kExchangeContainer); co[AliTRDpwg1Helper::kTracksKink] = mgr->CreateContainer("tracksKink", TObjArray::Class(), AliAnalysisManager::kExchangeContainer); co[AliTRDpwg1Helper::kV0List] = mgr->CreateContainer("v0List", TObjArray::Class(), AliAnalysisManager::kExchangeContainer); for(Int_t ios(1);ios<AliTRDpwg1Helper::kNOutSlots-1;ios++) mgr->ConnectOutput(info, ios, co[ios]); // add last monitor container AliAnalysisDataContainer *mon=mgr->CreateContainer(info->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName())); mgr->ConnectOutput(info, AliTRDpwg1Helper::kNOutSlots-1, mon); } <|endoftext|>
<commit_before>/* * ==================================================================== * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library (in the file LGPL.txt); if not, * write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://rapidsvn.tigris.org/. * ==================================================================== */ // subversion api #include "svn_path.h" // apr api #include "apr_file_io.h" // svncpp #include "svnqt/path.hpp" #include "svnqt/pool.hpp" #include "svnqt/url.hpp" #include "svnqt/svnqt_defines.hpp" #include <qurl.h> namespace svn { Path::Path (const char * path) { init(QString::FROMUTF8(path)); } Path::Path (const QString & path) { init (path); } Path::Path (const Path & path) : m_path(path.m_path) { } void Path::init (const QString& path) { Pool pool; if (path.isEmpty()) { m_path = ""; } else { const char * int_path = svn_path_internal_style (path.TOUTF8(), pool.pool () ); if (Url::isValid(path) ) { if (!svn_path_is_uri_safe(int_path)) { int_path = svn_path_uri_encode(int_path,pool); } } m_path = QString::FROMUTF8(int_path); if (Url::isValid(path) ) { /// @todo make sure that "@" is never used as revision paramter QUrl uri = m_path; m_path = uri.path(); m_path.replace("@","%40"); m_path = uri.protocol()+"://"+(uri.hasUser()?uri.user()+(uri.hasPassword()?":"+uri.hasPassword():"")+"@":"") +uri.host()+m_path; if (m_path.endsWith("/")) { int_path = svn_path_internal_style (path.TOUTF8(), pool.pool () ); m_path = QString::FROMUTF8(int_path); } } } } const QString & Path::path () const { return m_path; } Path::operator const QString&()const { return m_path; } QString Path::prettyPath()const { if (!Url::isValid(m_path)) { return m_path; } Pool pool; const char * int_path = svn_path_uri_decode(m_path.TOUTF8(), pool.pool () ); QString _p = QString::FROMUTF8(int_path); _p.replace("%40","@"); return _p; } const QByteArray Path::cstr() const { return m_path.TOUTF8(); } Path& Path::operator=(const Path & path) { if (this == &path) return *this; m_path = path.path(); return *this; } bool Path::isset () const { return m_path.length () > 0; } void Path::addComponent (const QString& component) { Pool pool; if (Url::isValid (m_path)) { const char * newPath = svn_path_url_add_component (m_path.TOUTF8(), component.TOUTF8(), pool); m_path = QString::FROMUTF8(newPath); } else { svn_stringbuf_t * pathStringbuf = svn_stringbuf_create (m_path.TOUTF8(), pool); svn_path_add_component (pathStringbuf, component.TOUTF8()); m_path = QString::FROMUTF8(pathStringbuf->data); } } void Path::addComponent (const char* component) { addComponent (QString::FROMUTF8(component)); } void Path::split (QString & dirpath, QString & basename) const { Pool pool; const char * cdirpath; const char * cbasename; svn_path_split (m_path.TOUTF8(), &cdirpath, &cbasename, pool); dirpath = QString::FROMUTF8(cdirpath); basename = QString::FROMUTF8(cbasename); } void Path::split (QString & dir, QString & filename, QString & ext) const { QString basename; // first split path into dir and filename+ext split (dir, basename); // next search for last . #if QT_VERSION < 0x040000 int pos = basename.findRev(QChar('.')); #else int pos = basename.lastIndexOf(QChar('.')); #endif if (pos == -1) { filename = basename; ext = QString::fromLatin1(""); } else { filename = basename.left(pos); ext = basename.mid(pos+1); } } Path Path::getTempDir () { const char * tempdir = 0; Pool pool; if (apr_temp_dir_get (&tempdir, pool) != APR_SUCCESS) { tempdir = 0; } return tempdir; } unsigned int Path::length () const { return m_path.length (); } QString Path::native () const { Pool pool; return QString::FROMUTF8(svn_path_local_style (m_path.TOUTF8(), pool)); } } /* ----------------------------------------------------------------- * local variables: * eval: (load-file "../../rapidsvn-dev.el") * end: */ <commit_msg>ChangeLog updated Version increased check for @ in svn::Path before replace-stuff<commit_after>/* * ==================================================================== * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library (in the file LGPL.txt); if not, * write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://rapidsvn.tigris.org/. * ==================================================================== */ // subversion api #include "svn_path.h" // apr api #include "apr_file_io.h" // svncpp #include "svnqt/path.hpp" #include "svnqt/pool.hpp" #include "svnqt/url.hpp" #include "svnqt/svnqt_defines.hpp" #include <qurl.h> namespace svn { Path::Path (const char * path) { init(QString::FROMUTF8(path)); } Path::Path (const QString & path) { init (path); } Path::Path (const Path & path) : m_path(path.m_path) { } void Path::init (const QString& path) { Pool pool; if (path.isEmpty()) { m_path = ""; } else { const char * int_path = svn_path_internal_style (path.TOUTF8(), pool.pool () ); if (Url::isValid(path) ) { if (!svn_path_is_uri_safe(int_path)) { int_path = svn_path_uri_encode(int_path,pool); } } m_path = QString::FROMUTF8(int_path); if (Url::isValid(path) && m_path.find("@")!=-1 ) { /// @todo make sure that "@" is never used as revision paramter QUrl uri = m_path; m_path = uri.path(); m_path.replace("@","%40"); m_path = uri.protocol()+"://"+(uri.hasUser()?uri.user()+(uri.hasPassword()?":"+uri.hasPassword():"")+"@":"") +uri.host()+m_path; if (m_path.endsWith("/")) { int_path = svn_path_internal_style (path.TOUTF8(), pool.pool () ); m_path = QString::FROMUTF8(int_path); } } } } const QString & Path::path () const { return m_path; } Path::operator const QString&()const { return m_path; } QString Path::prettyPath()const { if (!Url::isValid(m_path)) { return m_path; } Pool pool; const char * int_path = svn_path_uri_decode(m_path.TOUTF8(), pool.pool () ); QString _p = QString::FROMUTF8(int_path); _p.replace("%40","@"); return _p; } const QByteArray Path::cstr() const { return m_path.TOUTF8(); } Path& Path::operator=(const Path & path) { if (this == &path) return *this; m_path = path.path(); return *this; } bool Path::isset () const { return m_path.length () > 0; } void Path::addComponent (const QString& component) { Pool pool; if (Url::isValid (m_path)) { const char * newPath = svn_path_url_add_component (m_path.TOUTF8(), component.TOUTF8(), pool); m_path = QString::FROMUTF8(newPath); } else { svn_stringbuf_t * pathStringbuf = svn_stringbuf_create (m_path.TOUTF8(), pool); svn_path_add_component (pathStringbuf, component.TOUTF8()); m_path = QString::FROMUTF8(pathStringbuf->data); } } void Path::addComponent (const char* component) { addComponent (QString::FROMUTF8(component)); } void Path::split (QString & dirpath, QString & basename) const { Pool pool; const char * cdirpath; const char * cbasename; svn_path_split (m_path.TOUTF8(), &cdirpath, &cbasename, pool); dirpath = QString::FROMUTF8(cdirpath); basename = QString::FROMUTF8(cbasename); } void Path::split (QString & dir, QString & filename, QString & ext) const { QString basename; // first split path into dir and filename+ext split (dir, basename); // next search for last . #if QT_VERSION < 0x040000 int pos = basename.findRev(QChar('.')); #else int pos = basename.lastIndexOf(QChar('.')); #endif if (pos == -1) { filename = basename; ext = QString::fromLatin1(""); } else { filename = basename.left(pos); ext = basename.mid(pos+1); } } Path Path::getTempDir () { const char * tempdir = 0; Pool pool; if (apr_temp_dir_get (&tempdir, pool) != APR_SUCCESS) { tempdir = 0; } return tempdir; } unsigned int Path::length () const { return m_path.length (); } QString Path::native () const { Pool pool; return QString::FROMUTF8(svn_path_local_style (m_path.TOUTF8(), pool)); } } /* ----------------------------------------------------------------- * local variables: * eval: (load-file "../../rapidsvn-dev.el") * end: */ <|endoftext|>