text
stringlengths
54
60.6k
<commit_before>/* Copyright (C) 2002 by Norman Kraemer This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "winthread.h" #include <windows.h> #include <process.h> #include "cssys/win32/wintools.h" #ifdef CS_DEBUG #define CS_SHOW_ERROR if (lasterr) printf ("%s\n",lasterr) #else #define CS_SHOW_ERROR #endif #define CS_GET_SYSERROR() \ if (lasterr){delete[] lasterr; lasterr = 0;}\ lasterr = cswinGetErrorMessage (::GetLastError ()) #define CS_TEST(x) if(!(x)) {CS_GET_SYSERROR(); CS_SHOW_ERROR;} // ignore recursive switch... windows mutexes are always recursive. csRef<csMutex> csMutex::Create (bool ) { return csPtr<csMutex>(new csWinMutex ()); } csWinMutex::csWinMutex () { lasterr = 0; mutex = CreateMutex (0, false, 0); CS_TEST (mutex != 0); } csWinMutex::~csWinMutex () { #ifdef CS_DEBUG // CS_ASSERT (Destroy ()); Destroy (); #else Destroy (); #endif if (lasterr) {LocalFree (lasterr); lasterr = 0;} } bool csWinMutex::Destroy () { bool rc = CloseHandle (mutex); CS_TEST (rc); return rc; } bool csWinMutex::LockWait() { bool rc = (WaitForSingleObject (mutex, INFINITE) != WAIT_FAILED); CS_TEST (rc); return rc; } bool csWinMutex::LockTry () { bool rc = (WaitForSingleObject (mutex, 0) != WAIT_FAILED); CS_TEST (rc); return rc; } bool csWinMutex::Release () { bool rc = ReleaseMutex (mutex); CS_TEST (rc); return rc; } char const* csWinMutex::GetLastError () { return (char const*)lasterr; } csRef<csSemaphore> csSemaphore::Create (uint32 value) { return csPtr<csSemaphore>(new csWinSemaphore (value)); } csWinSemaphore::csWinSemaphore (uint32 v) { lasterr = 0; value = v; sem = CreateSemaphore (0, (LONG)value, (LONG)value, 0); if (sem == 0) value = 0; CS_TEST (sem != 0); } csWinSemaphore::~csWinSemaphore () { Destroy (); } bool csWinSemaphore::LockWait () { bool rc = (WaitForSingleObject (sem, INFINITE) != WAIT_FAILED); if (rc) value--; CS_TEST (rc); return rc; } bool csWinSemaphore::LockTry () { bool rc = (WaitForSingleObject (sem, 0) != WAIT_FAILED); if (rc) value--; CS_TEST (rc); return rc; } bool csWinSemaphore::Release () { bool rc = ReleaseSemaphore (sem, 1, &value); if (rc) value++; CS_TEST (rc); return rc; } uint32 csWinSemaphore::Value () { return (uint32)value; } bool csWinSemaphore::Destroy () { bool rc = CloseHandle (sem); CS_TEST (rc); return rc; } char const* csWinSemaphore::GetLastError () { return (char const*)lasterr; } csRef<csCondition> csCondition::Create (uint32 conditionAttributes) { return csPtr<csCondition>(new csWinCondition (conditionAttributes)); } csWinCondition::csWinCondition (uint32 /*conditionAttributes*/) { lasterr = 0; cond = CreateEvent (0, false, false, 0); // auto-reset CS_TEST (cond != 0); } csWinCondition::~csWinCondition () { Destroy (); } void csWinCondition::Signal (bool /*WakeAll*/) { // only releases one waiting thread, coz its auto-reset bool rc = PulseEvent (cond); CS_TEST (rc); } bool csWinCondition::Wait (csMutex* mutex, csTicks timeout) { // SignalObjectAndWait() is only available in WinNT 4.0 and above // so we use the potentially dangerous version below if (mutex->Release () && LockWait ((DWORD)timeout)) return mutex->LockWait (); return false; } bool csWinCondition::LockWait (DWORD nMilliSec) { bool rc = (WaitForSingleObject (cond, nMilliSec) != WAIT_FAILED); CS_TEST (rc); return rc; } bool csWinCondition::Destroy () { bool rc = CloseHandle (cond); CS_TEST (rc); return rc; } char const* csWinCondition::GetLastError () { return (char const*)lasterr; } csRef<csThread> csThread::Create (csRunnable* r, uint32 options) { return csPtr<csThread>(new csWinThread (r, options)); } csWinThread::csWinThread (csRunnable* r, uint32 /*options*/) { runnable = r; running = false; lasterr = 0; } csWinThread::~csWinThread () { if (running) Stop (); CloseHandle (thread); } bool csWinThread::Start () { #if defined (__CYGWIN__) thread = CreateThread (0, 0, (LPTHREAD_START_ROUTINE) ThreadRun, (void*)this, CREATE_SUSPENDED, 0); #else uint dummyThreadId; thread = (HANDLE)_beginthreadex (0, 0, ThreadRun, (void*)this, CREATE_SUSPENDED, &dummyThreadId); #endif bool created = (thread != 0); CS_TEST (created); running = (ResumeThread (thread) != (DWORD)-1); CS_TEST (running); return running; } bool csWinThread::Wait () { if (running) { bool rc = (WaitForSingleObject (thread, INFINITE) != WAIT_FAILED); CS_TEST (rc); return rc; } return true; } void csWinThread::Yield () { if (running) Sleep(0); } bool csWinThread::Stop () { if (running) { running = !TerminateThread (thread, ~0); CS_TEST (!running); } return !running; } char const* csWinThread::GetLastError () { return (char const*)lasterr; } uint csWinThread::ThreadRun (void* param) { csWinThread *thread = (csWinThread*)param; thread->runnable->Run (); thread->running = false; #if defined (__CYGWIN__) ExitThread (0); #else _endthreadex (0); #endif return 0; } #undef CS_TEST #undef CS_SHOW_ERROR <commit_msg>Wrapped to 79 characters.<commit_after>/* Copyright (C) 2002 by Norman Kraemer This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "winthread.h" #include <windows.h> #include <process.h> #include "cssys/win32/wintools.h" #ifdef CS_DEBUG #define CS_SHOW_ERROR if (lasterr) printf ("%s\n",lasterr) #else #define CS_SHOW_ERROR #endif #define CS_GET_SYSERROR() \ if (lasterr){delete[] lasterr; lasterr = 0;}\ lasterr = cswinGetErrorMessage (::GetLastError ()) #define CS_TEST(x) if(!(x)) {CS_GET_SYSERROR(); CS_SHOW_ERROR;} // ignore recursive switch... windows mutexes are always recursive. csRef<csMutex> csMutex::Create (bool ) { return csPtr<csMutex>(new csWinMutex ()); } csWinMutex::csWinMutex () { lasterr = 0; mutex = CreateMutex (0, false, 0); CS_TEST (mutex != 0); } csWinMutex::~csWinMutex () { #ifdef CS_DEBUG // CS_ASSERT (Destroy ()); Destroy (); #else Destroy (); #endif if (lasterr) {LocalFree (lasterr); lasterr = 0;} } bool csWinMutex::Destroy () { bool rc = CloseHandle (mutex); CS_TEST (rc); return rc; } bool csWinMutex::LockWait() { bool rc = (WaitForSingleObject (mutex, INFINITE) != WAIT_FAILED); CS_TEST (rc); return rc; } bool csWinMutex::LockTry () { bool rc = (WaitForSingleObject (mutex, 0) != WAIT_FAILED); CS_TEST (rc); return rc; } bool csWinMutex::Release () { bool rc = ReleaseMutex (mutex); CS_TEST (rc); return rc; } char const* csWinMutex::GetLastError () { return (char const*)lasterr; } csRef<csSemaphore> csSemaphore::Create (uint32 value) { return csPtr<csSemaphore>(new csWinSemaphore (value)); } csWinSemaphore::csWinSemaphore (uint32 v) { lasterr = 0; value = v; sem = CreateSemaphore (0, (LONG)value, (LONG)value, 0); if (sem == 0) value = 0; CS_TEST (sem != 0); } csWinSemaphore::~csWinSemaphore () { Destroy (); } bool csWinSemaphore::LockWait () { bool rc = (WaitForSingleObject (sem, INFINITE) != WAIT_FAILED); if (rc) value--; CS_TEST (rc); return rc; } bool csWinSemaphore::LockTry () { bool rc = (WaitForSingleObject (sem, 0) != WAIT_FAILED); if (rc) value--; CS_TEST (rc); return rc; } bool csWinSemaphore::Release () { bool rc = ReleaseSemaphore (sem, 1, &value); if (rc) value++; CS_TEST (rc); return rc; } uint32 csWinSemaphore::Value () { return (uint32)value; } bool csWinSemaphore::Destroy () { bool rc = CloseHandle (sem); CS_TEST (rc); return rc; } char const* csWinSemaphore::GetLastError () { return (char const*)lasterr; } csRef<csCondition> csCondition::Create (uint32 conditionAttributes) { return csPtr<csCondition>(new csWinCondition (conditionAttributes)); } csWinCondition::csWinCondition (uint32 /*conditionAttributes*/) { lasterr = 0; cond = CreateEvent (0, false, false, 0); // auto-reset CS_TEST (cond != 0); } csWinCondition::~csWinCondition () { Destroy (); } void csWinCondition::Signal (bool /*WakeAll*/) { // only releases one waiting thread, coz its auto-reset bool rc = PulseEvent (cond); CS_TEST (rc); } bool csWinCondition::Wait (csMutex* mutex, csTicks timeout) { // SignalObjectAndWait() is only available in WinNT 4.0 and above // so we use the potentially dangerous version below if (mutex->Release () && LockWait ((DWORD)timeout)) return mutex->LockWait (); return false; } bool csWinCondition::LockWait (DWORD nMilliSec) { bool rc = (WaitForSingleObject (cond, nMilliSec) != WAIT_FAILED); CS_TEST (rc); return rc; } bool csWinCondition::Destroy () { bool rc = CloseHandle (cond); CS_TEST (rc); return rc; } char const* csWinCondition::GetLastError () { return (char const*)lasterr; } csRef<csThread> csThread::Create (csRunnable* r, uint32 options) { return csPtr<csThread>(new csWinThread (r, options)); } csWinThread::csWinThread (csRunnable* r, uint32 /*options*/) { runnable = r; running = false; lasterr = 0; } csWinThread::~csWinThread () { if (running) Stop (); CloseHandle (thread); } bool csWinThread::Start () { #if defined (__CYGWIN__) thread = CreateThread (0, 0, (LPTHREAD_START_ROUTINE) ThreadRun, (void*)this, CREATE_SUSPENDED, 0); #else uint dummyThreadId; thread = (HANDLE)_beginthreadex (0, 0, ThreadRun, (void*)this, CREATE_SUSPENDED, &dummyThreadId); #endif bool created = (thread != 0); CS_TEST (created); running = (ResumeThread (thread) != (DWORD)-1); CS_TEST (running); return running; } bool csWinThread::Wait () { if (running) { bool rc = (WaitForSingleObject (thread, INFINITE) != WAIT_FAILED); CS_TEST (rc); return rc; } return true; } void csWinThread::Yield () { if (running) Sleep(0); } bool csWinThread::Stop () { if (running) { running = !TerminateThread (thread, ~0); CS_TEST (!running); } return !running; } char const* csWinThread::GetLastError () { return (char const*)lasterr; } uint csWinThread::ThreadRun (void* param) { csWinThread *thread = (csWinThread*)param; thread->runnable->Run (); thread->running = false; #if defined (__CYGWIN__) ExitThread (0); #else _endthreadex (0); #endif return 0; } #undef CS_TEST #undef CS_SHOW_ERROR <|endoftext|>
<commit_before>#include "RFProtocolVhome.h" // static range_type g_timing_pause[7] = { { 12000, 18000 }, // { 250, 550 }, // { 1200, 1500 }, // { 0,0 } }; static range_type g_timing_pulse[8] = { { 3500, 3500 }, { 250, 550 }, // { 1200, 1500 }, // { 0,0 } }; CRFProtocolVhome::CRFProtocolVhome() :CRFProtocol(g_timing_pause, g_timing_pulse, 25, 1, "a") { m_Debug = true; } CRFProtocolVhome::~CRFProtocolVhome() { } string CRFProtocolVhome::DecodePacket(const string &pkt) { string packet = pkt, res; if (packet.length() == 48) { if (packet[0] == 'c') packet = "B" + packet; if (packet[0] == 'b') packet = "C" + packet; } if (packet.length() == 49) { if (packet[48] == 'B') packet += "c"; if (packet[48] == 'C') packet += "b"; } else return ""; for (unsigned int i = 0; i < packet.length() - 1; i += 2) { string part = packet.substr(i, 2); if (part == "Bc") res += "0"; else if (part == "Cb") res += "1"; else return ""; } return res; } string CRFProtocolVhome::DecodeData(const string& bits) { if (bits.length() != 25 || bits2long(bits, 0, 4) != 7 || bits[24] != '0') return ""; int addr = bits2long(bits, 4, 16); int cmd = bits2long(bits, 20, 4); char buffer[100]; snprintf(buffer, sizeof(buffer), "addr=%04x cmd=%d", addr, cmd); return buffer; } <commit_msg>vhome improved but not tested<commit_after>#include "RFProtocolVhome.h" // static range_type g_timing_pause[7] = { { 1, 800 }, // lengths of signals are scattered very well { 801, 1400 }, { 20000, 2000 }, { 0,0 } }; static range_type g_timing_pulse[8] = { { 1, 700 }, { 1000, 1400 }, // { 0, 0 }, // { 0,0 } }; CRFProtocolVhome::CRFProtocolVhome() :CRFProtocol(g_timing_pause, g_timing_pulse, 24, 1, "a") { m_Debug = true; } CRFProtocolVhome::~CRFProtocolVhome() { } string CRFProtocolVhome::DecodePacket(const string &pkt) { if (pkt.length() < 50) return ""; string packet; for (int i = 0; i + 1 < (int)pkt.length(); i++) { if (pkt[i] == 'A' && pkt[i + 1] == 'b') { packet.push_back('0'); i++; continue; } if (pkt[i] == 'B' && pkt[i + 1] == 'a') { packet.push_back('1'); i++; continue; } if (pkt[i] == 'A' && pkt[i + 1] == 'c' && packet.length() == 24) { return packet; } return ""; } return ""; } string CRFProtocolVhome::DecodeData(const string& bits) { if (bits.length() != 24) return ""; int cmd = bits2long(bits, 20, 4); if (cmd > 4) return ""; static const int map_1[] = {-1, -1, 1, -1, -1}; static const int map_2[] = {-1, 2, -1, -1, 1}; static const int map_3[] = {-1, 1, 2, -1, 3}; bool is3btn = true; for (int i = 0; i < 9; i++) is3btn &= bits[i] == 1; if (is3btn) { int addr = bits2long(bits, 9, 7); int btn = map_3[cmd]; if (btn == -1) return ""; return String::ComposeFormat("addr=%d type=3 btn=%d", addr, btn); } else { int addr = bits2long(bits, 0, 16); int btn = map_1[cmd]; if (btn != -1) { btn = map_2[cmd]; if (btn == -1) return ""; return String::ComposeFormat("addr=%d type=2 btn=%d", addr, btn); } else { return String::ComposeFormat("addr=%d type=1 btn=1", addr); } } } <|endoftext|>
<commit_before>/*************************************************************************** class.cpp - class Class ------------------- begin : mar avr 15 2003 copyright : (C) 2003 by Michael CATANZARITI email : mcatan@free.fr ***************************************************************************/ /*************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * * * This software is published under the terms of the Apache Software * * License version 1.1, a copy of which has been included with this * * distribution in the LICENSE.txt file. * ***************************************************************************/ #include <log4cxx/helpers/object.h> #include <log4cxx/helpers/class.h> #include <map> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; typedef std::map<String, const Class *> classMap; classMap * registry = 0; class RegistryDestructor { public: ~RegistryDestructor() { if (registry != 0) delete registry; } }; ClassNotFoundException::ClassNotFoundException(const String& className) { message = _T("Class '") + className + _T("' not found"); } String ClassNotFoundException::getMessage() { return message; } Class::Class(const String& name) : name(name) { registerClass(this); } const String& Class::toString() const { return name; } const String& Class::getName() const { return name; } ObjectPtr Class::newInstance() const { throw InstantiationException(); return 0; } const Class& Class::forName(const String& className) { String strippedClassName; String::size_type pos = className.find_last_of(_T('.')); if (pos != String::npos) { strippedClassName = className.substr(pos + 1); } else { strippedClassName = className; } const Class * clazz = (*registry)[StringHelper::toLowerCase(strippedClassName)]; if (clazz == 0) { throw ClassNotFoundException(className); } return *clazz; } void Class::registerClass(const Class * newClass) { if (newClass == 0) { return; } if (registry == 0) { registry = new classMap(); } (*registry)[StringHelper::toLowerCase(newClass->toString())] = newClass; } <commit_msg>fixed memory leak<commit_after>/*************************************************************************** class.cpp - class Class ------------------- begin : mar avr 15 2003 copyright : (C) 2003 by Michael CATANZARITI email : mcatan@free.fr ***************************************************************************/ /*************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * * * This software is published under the terms of the Apache Software * * License version 1.1, a copy of which has been included with this * * distribution in the LICENSE.txt file. * ***************************************************************************/ #include <log4cxx/helpers/object.h> #include <log4cxx/helpers/class.h> #include <map> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; typedef std::map<String, const Class *> classMap; classMap * registry = 0; class RegistryDestructor { public: ~RegistryDestructor() { if (registry != 0) { delete registry; } } } registryDestructor; ClassNotFoundException::ClassNotFoundException(const String& className) { message = _T("Class '") + className + _T("' not found"); } String ClassNotFoundException::getMessage() { return message; } Class::Class(const String& name) : name(name) { registerClass(this); } const String& Class::toString() const { return name; } const String& Class::getName() const { return name; } ObjectPtr Class::newInstance() const { throw InstantiationException(); return 0; } const Class& Class::forName(const String& className) { String strippedClassName; String::size_type pos = className.find_last_of(_T('.')); if (pos != String::npos) { strippedClassName = className.substr(pos + 1); } else { strippedClassName = className; } const Class * clazz = (*registry)[StringHelper::toLowerCase(strippedClassName)]; if (clazz == 0) { throw ClassNotFoundException(className); } return *clazz; } void Class::registerClass(const Class * newClass) { if (newClass == 0) { return; } if (registry == 0) { registry = new classMap(); } (*registry)[StringHelper::toLowerCase(newClass->toString())] = newClass; } <|endoftext|>
<commit_before>#include <node.h> #include <node_buffer.h> #include <mysql/mysql.h> using namespace node; using namespace v8; static Persistent<FunctionTemplate> Client_constructor; static Persistent<String> emit_symbol; const int STATE_CLOSE = -3, STATE_CLOSING = -2, STATE_CLOSED = -1, STATE_CONNECT = 0, STATE_CONNECTING = 1, STATE_CONNECTED = 2, STATE_QUERY = 3, STATE_QUERYING = 4, STATE_QUERIED = 5, STATE_ROWSTREAM = 6, STATE_ROWSTREAMING = 7, STATE_ROWSTREAMED = 8; struct sql_config { char* user; char* password; char* ip; char* db; unsigned int port; bool compress; }; #include <stdio.h> #define DEBUG(s) fprintf(stderr, "BINDING: " s "\n") class Client : public ObjectWrap { public: uv_poll_t poll_handle; MYSQL mysql, *mysql_ret; MYSQL_RES *mysql_res; MYSQL_ROW mysql_row; int mysql_qerr; char* cur_query; sql_config config; bool hadError; int state; Client() { state = STATE_CLOSED; } ~Client() { close(); } void init() { config.user = NULL; config.password = NULL; config.ip = NULL; config.db = NULL; cur_query = NULL; hadError = false; poll_handle.type = UV_UNKNOWN_HANDLE; mysql_init(&mysql); mysql_options(&mysql, MYSQL_OPT_NONBLOCK, 0); } void connect() { if (state == STATE_CLOSED) { state = STATE_CONNECT; doWork(); } } void close() { if (state != STATE_CLOSED) { if (config.user) free(config.user); if (config.password) free(config.password); if (config.ip) free(config.ip); if (config.db) free(config.db); if (cur_query) free(cur_query); state = STATE_CLOSE; doWork(); } } char* escape(const char* str) { unsigned int str_len = strlen(str); char* dest = (char*) malloc(str_len * 2 + 1); mysql_real_escape_string(&mysql, dest, str, str_len); return dest; } void query(const char* qry) { if (state == STATE_CONNECTED) { cur_query = strdup(qry); state = STATE_QUERY; doWork(); } } void doWork(int event = 0) { int status = 0, new_events = 0; bool done = false; while (!done) { switch (state) { case STATE_CONNECT: //DEBUG("STATE_CONNECT"); status = mysql_real_connect_start(&mysql_ret, &mysql, config.ip, config.user, config.password, config.db, config.port, NULL, 0); uv_poll_init_socket(uv_default_loop(), &poll_handle, mysql_get_socket(&mysql)); poll_handle.data = this; if (status) { state = STATE_CONNECTING; done = true; } else { state = STATE_CONNECTED; emit("connect"); } break; case STATE_CONNECTING: //DEBUG("STATE_CONNECTING"); status = mysql_real_connect_cont(&mysql_ret, &mysql, event); if (status) done = true; else { if (!mysql_ret) return emitError("conn"); state = STATE_CONNECTED; emit("connect"); } break; case STATE_CONNECTED: //DEBUG("STATE_CONNECTED"); done = true; break; case STATE_QUERY: //DEBUG("STATE_QUERY"); status = mysql_real_query_start(&mysql_qerr, &mysql, cur_query, strlen(cur_query)); if (status) { state = STATE_QUERYING; done = true; } else state = STATE_QUERIED; break; case STATE_QUERYING: //DEBUG("STATE_QUERYING"); status = mysql_real_query_cont(&mysql_qerr, &mysql, mysql_status(event)); if (status) done = true; else { free(cur_query); if (mysql_qerr) return emitError("query"); state = STATE_QUERIED; } break; case STATE_QUERIED: //DEBUG("STATE_QUERIED"); mysql_res = mysql_use_result(&mysql); if (!mysql_res) return emitError("query"); state = STATE_ROWSTREAM; break; case STATE_ROWSTREAM: //DEBUG("STATE_ROWSTREAM"); status = mysql_fetch_row_start(&mysql_row, mysql_res); if (status) { done = true; state = STATE_ROWSTREAMING; } else state = STATE_ROWSTREAMED; break; case STATE_ROWSTREAMING: //DEBUG("STATE_ROWSTREAMING"); status = mysql_fetch_row_cont(&mysql_row, mysql_res, mysql_status(event)); if (status) done = true; else state = STATE_ROWSTREAMED; break; case STATE_ROWSTREAMED: //DEBUG("STATE_ROWSTREAMED"); if (mysql_row) { state = STATE_ROWSTREAM; emitRow(); } else { if (mysql_errno(&mysql)) { mysql_free_result(mysql_res); return emitError("result"); } else { // no more rows mysql_free_result(mysql_res); state = STATE_CONNECTED; emit("done"); } } break; case STATE_CLOSE: //DEBUG("STATE_CLOSE"); mysql_close(&mysql); state = STATE_CLOSED; uv_close((uv_handle_t*) &poll_handle, cbClose); return; case STATE_CLOSED: return; } } if (status & MYSQL_WAIT_READ) new_events |= UV_READABLE; if (status & MYSQL_WAIT_WRITE) new_events |= UV_WRITABLE; uv_poll_start(&poll_handle, new_events, cbPoll); } void emitError(const char* when) { HandleScope scope; hadError = true; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Value> err = Exception::Error(String::New(mysql_error(&mysql))); Local<Object> err_obj = err->ToObject(); err_obj->Set(String::New("code"), Integer::NewFromUnsigned(mysql_errno(&mysql))); err_obj->Set(String::New("when"), String::New(when)); Local<Value> emit_argv[2] = { String::New("error"), err }; TryCatch try_catch; Emit->Call(handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); close(); } void emit(const char* eventName) { HandleScope scope; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Value> emit_argv[1] = { String::New(eventName) }; TryCatch try_catch; Emit->Call(handle_, 1, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } void emitRow() { HandleScope scope; unsigned int i = 0, len = mysql_num_fields(mysql_res); char* field; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Object> row = Object::New(); for (; i<len; ++i) { field = mysql_fetch_field_direct(mysql_res, i)->name; row->Set(String::New(field), (mysql_row[i] ? String::New(mysql_row[i]) : Null())); } Local<Value> emit_argv[2] = { String::New("result"), row }; TryCatch try_catch; Emit->Call(handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } static void cbPoll(uv_poll_t* handle, int status, int events) { HandleScope scope; Client* obj = (Client*) handle->data; assert(status == 0); int mysql_status = 0; if (events & UV_READABLE) mysql_status |= MYSQL_WAIT_READ; if (events & UV_WRITABLE) mysql_status |= MYSQL_WAIT_WRITE; /*if (events & UV_TIMEOUT) mysql_status |= MYSQL_WAIT_TIMEOUT;*/ obj->doWork(mysql_status); } static void cbClose(uv_handle_t* handle) { HandleScope scope; Client* obj = (Client*) handle->data; Local<Function> Emit = Local<Function>::Cast(obj->handle_->Get(emit_symbol)); TryCatch try_catch; Local<Value> emit_argv[2] = { String::New("close"), Local<Boolean>::New(Boolean::New(obj->hadError)) }; Emit->Call(obj->handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } static Handle<Value> New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use `new` to create instances of this object.")) ); } Client* obj = new Client(); obj->Wrap(args.This()); return args.This(); } static Handle<Value> Escape(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state < STATE_CONNECTED) { return ThrowException(Exception::Error( String::New("Not connected")) ); } else if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("You must supply a string")) ); } String::Utf8Value arg_s(args[0]); char* newstr = obj->escape(*arg_s); Local<String> escaped_s = String::New(newstr); free(newstr); return scope.Close(escaped_s); } static Handle<Value> Connect(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state != STATE_CLOSED) { return ThrowException(Exception::Error( String::New("Not ready to connect")) ); } obj->init(); Local<Object> cfg = args[0]->ToObject(); Local<Value> user_v = cfg->Get(String::New("user")); Local<Value> password_v = cfg->Get(String::New("password")); Local<Value> ip_v = cfg->Get(String::New("host")); Local<Value> port_v = cfg->Get(String::New("port")); Local<Value> db_v = cfg->Get(String::New("db")); Local<Value> compress_v = cfg->Get(String::New("compress")); Local<Value> ssl_v = cfg->Get(String::New("secure")); if (!user_v->IsString() || user_v->ToString()->Length() == 0) { obj->close(); return ThrowException(Exception::Error( String::New("`user` must be a non-empty string")) ); } else { String::Utf8Value user_s(user_v); obj->config.user = strdup(*user_s); } if (!password_v->IsString() || password_v->ToString()->Length() == 0) obj->config.password = NULL; else { String::Utf8Value password_s(password_v); obj->config.password = strdup(*password_s); } if (!ip_v->IsString() || ip_v->ToString()->Length() == 0) obj->config.ip = NULL; else { String::Utf8Value ip_s(ip_v); obj->config.ip = strdup(*ip_s); } if (!port_v->IsUint32() || port_v->Uint32Value() == 0) obj->config.port = 3306; else obj->config.port = port_v->Uint32Value(); if (db_v->IsString() && db_v->ToString()->Length() > 0) { String::Utf8Value db_s(db_v); obj->config.db = strdup(*db_s); } obj->connect(); return Undefined(); } static Handle<Value> Query(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state != STATE_CONNECTED) { return ThrowException(Exception::Error( String::New("Not ready to query")) ); } if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("Query expected")) ); } String::Utf8Value query(args[0]->ToString()); obj->query(*query); return Undefined(); } static Handle<Value> Close(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state == STATE_CLOSED) { return ThrowException(Exception::Error( String::New("Already closed")) ); } obj->close(); return Undefined(); } static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Client"); Client_constructor = Persistent<FunctionTemplate>::New(tpl); Client_constructor->InstanceTemplate()->SetInternalFieldCount(1); Client_constructor->SetClassName(name); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "connect", Connect); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "query", Query); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "escape", Escape); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "end", Close); emit_symbol = NODE_PSYMBOL("emit"); target->Set(name, Client_constructor->GetFunction()); } }; static Handle<Value> Version(const Arguments& args) { HandleScope scope; unsigned long client_ver = mysql_get_client_version(); char major = (client_ver >> 16) & 0xFF, release = (client_ver >> 8) & 0xFF, rel_ver = client_ver & 0xFF; int slen = (major < 10 ? 1 : 2) + (release < 10 ? 1 : 2) + (rel_ver < 10 ? 1 : 2); char* ver = (char*) malloc(slen + 3); sprintf(ver, "%u.%u.%u", major, release, rel_ver); Local<String> ver_str = String::New(ver); free(ver); return scope.Close(ver_str); } extern "C" { void init(Handle<Object> target) { HandleScope scope; Client::Initialize(target); target->Set(String::NewSymbol("version"), FunctionTemplate::New(Version)->GetFunction()); } NODE_MODULE(sqlclient, init); }<commit_msg>Remove last remnants of mysql_close_*() usage<commit_after>#include <node.h> #include <node_buffer.h> #include <mysql/mysql.h> using namespace node; using namespace v8; static Persistent<FunctionTemplate> Client_constructor; static Persistent<String> emit_symbol; const int STATE_CLOSE = -2, STATE_CLOSED = -1, STATE_CONNECT = 0, STATE_CONNECTING = 1, STATE_CONNECTED = 2, STATE_QUERY = 3, STATE_QUERYING = 4, STATE_QUERIED = 5, STATE_ROWSTREAM = 6, STATE_ROWSTREAMING = 7, STATE_ROWSTREAMED = 8; struct sql_config { char* user; char* password; char* ip; char* db; unsigned int port; bool compress; }; #include <stdio.h> #define DEBUG(s) fprintf(stderr, "BINDING: " s "\n") class Client : public ObjectWrap { public: uv_poll_t poll_handle; MYSQL mysql, *mysql_ret; MYSQL_RES *mysql_res; MYSQL_ROW mysql_row; int mysql_qerr; char* cur_query; sql_config config; bool hadError; int state; Client() { state = STATE_CLOSED; } ~Client() { close(); } void init() { config.user = NULL; config.password = NULL; config.ip = NULL; config.db = NULL; cur_query = NULL; hadError = false; poll_handle.type = UV_UNKNOWN_HANDLE; mysql_init(&mysql); mysql_options(&mysql, MYSQL_OPT_NONBLOCK, 0); } void connect() { if (state == STATE_CLOSED) { state = STATE_CONNECT; doWork(); } } void close() { if (state != STATE_CLOSED) { if (config.user) free(config.user); if (config.password) free(config.password); if (config.ip) free(config.ip); if (config.db) free(config.db); if (cur_query) free(cur_query); state = STATE_CLOSE; doWork(); } } char* escape(const char* str) { unsigned int str_len = strlen(str); char* dest = (char*) malloc(str_len * 2 + 1); mysql_real_escape_string(&mysql, dest, str, str_len); return dest; } void query(const char* qry) { if (state == STATE_CONNECTED) { cur_query = strdup(qry); state = STATE_QUERY; doWork(); } } void doWork(int event = 0) { int status = 0, new_events = 0; bool done = false; while (!done) { switch (state) { case STATE_CONNECT: //DEBUG("STATE_CONNECT"); status = mysql_real_connect_start(&mysql_ret, &mysql, config.ip, config.user, config.password, config.db, config.port, NULL, 0); uv_poll_init_socket(uv_default_loop(), &poll_handle, mysql_get_socket(&mysql)); poll_handle.data = this; if (status) { state = STATE_CONNECTING; done = true; } else { state = STATE_CONNECTED; emit("connect"); } break; case STATE_CONNECTING: //DEBUG("STATE_CONNECTING"); status = mysql_real_connect_cont(&mysql_ret, &mysql, event); if (status) done = true; else { if (!mysql_ret) return emitError("conn"); state = STATE_CONNECTED; emit("connect"); } break; case STATE_CONNECTED: //DEBUG("STATE_CONNECTED"); done = true; break; case STATE_QUERY: //DEBUG("STATE_QUERY"); status = mysql_real_query_start(&mysql_qerr, &mysql, cur_query, strlen(cur_query)); if (status) { state = STATE_QUERYING; done = true; } else state = STATE_QUERIED; break; case STATE_QUERYING: //DEBUG("STATE_QUERYING"); status = mysql_real_query_cont(&mysql_qerr, &mysql, mysql_status(event)); if (status) done = true; else { free(cur_query); if (mysql_qerr) return emitError("query"); state = STATE_QUERIED; } break; case STATE_QUERIED: //DEBUG("STATE_QUERIED"); mysql_res = mysql_use_result(&mysql); if (!mysql_res) return emitError("query"); state = STATE_ROWSTREAM; break; case STATE_ROWSTREAM: //DEBUG("STATE_ROWSTREAM"); status = mysql_fetch_row_start(&mysql_row, mysql_res); if (status) { done = true; state = STATE_ROWSTREAMING; } else state = STATE_ROWSTREAMED; break; case STATE_ROWSTREAMING: //DEBUG("STATE_ROWSTREAMING"); status = mysql_fetch_row_cont(&mysql_row, mysql_res, mysql_status(event)); if (status) done = true; else state = STATE_ROWSTREAMED; break; case STATE_ROWSTREAMED: //DEBUG("STATE_ROWSTREAMED"); if (mysql_row) { state = STATE_ROWSTREAM; emitRow(); } else { if (mysql_errno(&mysql)) { mysql_free_result(mysql_res); return emitError("result"); } else { // no more rows mysql_free_result(mysql_res); state = STATE_CONNECTED; emit("done"); } } break; case STATE_CLOSE: //DEBUG("STATE_CLOSE"); mysql_close(&mysql); state = STATE_CLOSED; uv_close((uv_handle_t*) &poll_handle, cbClose); return; case STATE_CLOSED: return; } } if (status & MYSQL_WAIT_READ) new_events |= UV_READABLE; if (status & MYSQL_WAIT_WRITE) new_events |= UV_WRITABLE; uv_poll_start(&poll_handle, new_events, cbPoll); } void emitError(const char* when) { HandleScope scope; hadError = true; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Value> err = Exception::Error(String::New(mysql_error(&mysql))); Local<Object> err_obj = err->ToObject(); err_obj->Set(String::New("code"), Integer::NewFromUnsigned(mysql_errno(&mysql))); err_obj->Set(String::New("when"), String::New(when)); Local<Value> emit_argv[2] = { String::New("error"), err }; TryCatch try_catch; Emit->Call(handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); close(); } void emit(const char* eventName) { HandleScope scope; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Value> emit_argv[1] = { String::New(eventName) }; TryCatch try_catch; Emit->Call(handle_, 1, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } void emitRow() { HandleScope scope; unsigned int i = 0, len = mysql_num_fields(mysql_res); char* field; Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol)); Local<Object> row = Object::New(); for (; i<len; ++i) { field = mysql_fetch_field_direct(mysql_res, i)->name; row->Set(String::New(field), (mysql_row[i] ? String::New(mysql_row[i]) : Null())); } Local<Value> emit_argv[2] = { String::New("result"), row }; TryCatch try_catch; Emit->Call(handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } static void cbPoll(uv_poll_t* handle, int status, int events) { HandleScope scope; Client* obj = (Client*) handle->data; assert(status == 0); int mysql_status = 0; if (events & UV_READABLE) mysql_status |= MYSQL_WAIT_READ; if (events & UV_WRITABLE) mysql_status |= MYSQL_WAIT_WRITE; /*if (events & UV_TIMEOUT) mysql_status |= MYSQL_WAIT_TIMEOUT;*/ obj->doWork(mysql_status); } static void cbClose(uv_handle_t* handle) { HandleScope scope; Client* obj = (Client*) handle->data; Local<Function> Emit = Local<Function>::Cast(obj->handle_->Get(emit_symbol)); TryCatch try_catch; Local<Value> emit_argv[2] = { String::New("close"), Local<Boolean>::New(Boolean::New(obj->hadError)) }; Emit->Call(obj->handle_, 2, emit_argv); if (try_catch.HasCaught()) FatalException(try_catch); } static Handle<Value> New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use `new` to create instances of this object.")) ); } Client* obj = new Client(); obj->Wrap(args.This()); return args.This(); } static Handle<Value> Escape(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state < STATE_CONNECTED) { return ThrowException(Exception::Error( String::New("Not connected")) ); } else if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("You must supply a string")) ); } String::Utf8Value arg_s(args[0]); char* newstr = obj->escape(*arg_s); Local<String> escaped_s = String::New(newstr); free(newstr); return scope.Close(escaped_s); } static Handle<Value> Connect(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state != STATE_CLOSED) { return ThrowException(Exception::Error( String::New("Not ready to connect")) ); } obj->init(); Local<Object> cfg = args[0]->ToObject(); Local<Value> user_v = cfg->Get(String::New("user")); Local<Value> password_v = cfg->Get(String::New("password")); Local<Value> ip_v = cfg->Get(String::New("host")); Local<Value> port_v = cfg->Get(String::New("port")); Local<Value> db_v = cfg->Get(String::New("db")); Local<Value> compress_v = cfg->Get(String::New("compress")); Local<Value> ssl_v = cfg->Get(String::New("secure")); if (!user_v->IsString() || user_v->ToString()->Length() == 0) { obj->close(); return ThrowException(Exception::Error( String::New("`user` must be a non-empty string")) ); } else { String::Utf8Value user_s(user_v); obj->config.user = strdup(*user_s); } if (!password_v->IsString() || password_v->ToString()->Length() == 0) obj->config.password = NULL; else { String::Utf8Value password_s(password_v); obj->config.password = strdup(*password_s); } if (!ip_v->IsString() || ip_v->ToString()->Length() == 0) obj->config.ip = NULL; else { String::Utf8Value ip_s(ip_v); obj->config.ip = strdup(*ip_s); } if (!port_v->IsUint32() || port_v->Uint32Value() == 0) obj->config.port = 3306; else obj->config.port = port_v->Uint32Value(); if (db_v->IsString() && db_v->ToString()->Length() > 0) { String::Utf8Value db_s(db_v); obj->config.db = strdup(*db_s); } obj->connect(); return Undefined(); } static Handle<Value> Query(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state != STATE_CONNECTED) { return ThrowException(Exception::Error( String::New("Not ready to query")) ); } if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(Exception::Error( String::New("Query expected")) ); } String::Utf8Value query(args[0]->ToString()); obj->query(*query); return Undefined(); } static Handle<Value> Close(const Arguments& args) { HandleScope scope; Client* obj = ObjectWrap::Unwrap<Client>(args.This()); if (obj->state == STATE_CLOSED) { return ThrowException(Exception::Error( String::New("Already closed")) ); } obj->close(); return Undefined(); } static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Client"); Client_constructor = Persistent<FunctionTemplate>::New(tpl); Client_constructor->InstanceTemplate()->SetInternalFieldCount(1); Client_constructor->SetClassName(name); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "connect", Connect); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "query", Query); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "escape", Escape); NODE_SET_PROTOTYPE_METHOD(Client_constructor, "end", Close); emit_symbol = NODE_PSYMBOL("emit"); target->Set(name, Client_constructor->GetFunction()); } }; static Handle<Value> Version(const Arguments& args) { HandleScope scope; unsigned long client_ver = mysql_get_client_version(); char major = (client_ver >> 16) & 0xFF, release = (client_ver >> 8) & 0xFF, rel_ver = client_ver & 0xFF; int slen = (major < 10 ? 1 : 2) + (release < 10 ? 1 : 2) + (rel_ver < 10 ? 1 : 2); char* ver = (char*) malloc(slen + 3); sprintf(ver, "%u.%u.%u", major, release, rel_ver); Local<String> ver_str = String::New(ver); free(ver); return scope.Close(ver_str); } extern "C" { void init(Handle<Object> target) { HandleScope scope; Client::Initialize(target); target->Set(String::NewSymbol("version"), FunctionTemplate::New(Version)->GetFunction()); } NODE_MODULE(sqlclient, init); }<|endoftext|>
<commit_before>/* * VectorT.cpp * * Created on: Nov 19, 2015 * Author: ebke */ #ifndef BMPOSTFIX #error "Do not compile directly." #endif #include <type_traits> #define ASSEMBLE_(POSTFIX, PREFIX) PREFIX ## POSTFIX #define ASSEMBLE(POSTFIX, PREFIX) ASSEMBLE_(POSTFIX, PREFIX) #define MYBENCHMARK(NAME) BENCHMARK(NAME) #define MYBENCHMARK_TEMPLATE(NAME, TYPE) BENCHMARK_TEMPLATE(NAME, TYPE) template<class Vec> static inline typename std::enable_if<Vec::size_ == 3, Vec>::type testVec() { return Vec(1.1, 1.2, 1.3); } template<class Vec> static inline typename std::enable_if<Vec::size_ == 4, Vec>::type testVec() { return Vec(1.1, 1.2, 1.3, 1.4); } template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_add_compare)(benchmark::State& state) { Vec v1(0.0); Vec v2(1000.0); while (state.KeepRunning()) { v1 += testVec<Vec>(); v2 -= testVec<Vec>(); if (v1 == v2) { v1 -= v2; v2 += v1; } } // Just so nothing gets optimized away. static double dummy; dummy = v1.norm() + v2.norm(); } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_add_compare), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_add_compare), OpenMesh::Vec3f); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_add_compare), OpenMesh::Vec4d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_add_compare), OpenMesh::Vec4f); template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_cross_product)(benchmark::State& state) { Vec v1(0.0); Vec v2(1000.0); while (state.KeepRunning()) { v1 += testVec<Vec>(); v2 -= testVec<Vec>(); v1 = (v1 % v2); } // Just so nothing gets optimized away. static double dummy; dummy = v1.norm() + v2.norm(); } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_cross_product), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_cross_product), OpenMesh::Vec3f); template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_scalar_product)(benchmark::State& state) { Vec v1(0.0); Vec v2(1000.0); double acc = 0; while (state.KeepRunning()) { v1 += testVec<Vec>(); v2 -= testVec<Vec>(); acc += (v1 | v2); } // Otherwise GCC will optimize everything away. static double dummy; dummy = acc; } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_scalar_product), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_scalar_product), OpenMesh::Vec3f); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_scalar_product), OpenMesh::Vec4d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_scalar_product), OpenMesh::Vec4f); template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_norm)(benchmark::State& state) { Vec v1(0.0); double acc = 0; while (state.KeepRunning()) { v1 += testVec<Vec>(); acc += v1.norm(); } // Otherwise GCC will optimize everything away. static double dummy; dummy = acc; } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_norm), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_norm), OpenMesh::Vec3f); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_norm), OpenMesh::Vec4d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_norm), OpenMesh::Vec4f); template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_times_scalar)(benchmark::State& state) { Vec v1(0.0); while (state.KeepRunning()) { v1 += testVec<Vec>(); v1 *= static_cast<decltype(v1.norm())>(1.0)/v1[0]; v1 *= v1[1]; } // Otherwise GCC will optimize everything away. static double dummy; dummy = v1.norm(); } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_times_scalar), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_times_scalar), OpenMesh::Vec3f); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_times_scalar), OpenMesh::Vec4d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_times_scalar), OpenMesh::Vec4f); <commit_msg>suppress 'unused variable' warnings for benchmark dummy variables<commit_after>/* * VectorT.cpp * * Created on: Nov 19, 2015 * Author: ebke */ #ifndef BMPOSTFIX #error "Do not compile directly." #endif #include <type_traits> #define ASSEMBLE_(POSTFIX, PREFIX) PREFIX ## POSTFIX #define ASSEMBLE(POSTFIX, PREFIX) ASSEMBLE_(POSTFIX, PREFIX) #define MYBENCHMARK(NAME) BENCHMARK(NAME) #define MYBENCHMARK_TEMPLATE(NAME, TYPE) BENCHMARK_TEMPLATE(NAME, TYPE) template<class Vec> static inline typename std::enable_if<Vec::size_ == 3, Vec>::type testVec() { return Vec(1.1, 1.2, 1.3); } template<class Vec> static inline typename std::enable_if<Vec::size_ == 4, Vec>::type testVec() { return Vec(1.1, 1.2, 1.3, 1.4); } template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_add_compare)(benchmark::State& state) { Vec v1(0.0); Vec v2(1000.0); while (state.KeepRunning()) { v1 += testVec<Vec>(); v2 -= testVec<Vec>(); if (v1 == v2) { v1 -= v2; v2 += v1; } } // Just so nothing gets optimized away. static double dummy; dummy = v1.norm() + v2.norm(); static_cast<void>(dummy); } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_add_compare), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_add_compare), OpenMesh::Vec3f); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_add_compare), OpenMesh::Vec4d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_add_compare), OpenMesh::Vec4f); template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_cross_product)(benchmark::State& state) { Vec v1(0.0); Vec v2(1000.0); while (state.KeepRunning()) { v1 += testVec<Vec>(); v2 -= testVec<Vec>(); v1 = (v1 % v2); } // Just so nothing gets optimized away. static double dummy; dummy = v1.norm() + v2.norm(); static_cast<void>(dummy); } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_cross_product), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_cross_product), OpenMesh::Vec3f); template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_scalar_product)(benchmark::State& state) { Vec v1(0.0); Vec v2(1000.0); double acc = 0; while (state.KeepRunning()) { v1 += testVec<Vec>(); v2 -= testVec<Vec>(); acc += (v1 | v2); } // Otherwise GCC will optimize everything away. static double dummy; dummy = acc; static_cast<void>(dummy); } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_scalar_product), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_scalar_product), OpenMesh::Vec3f); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_scalar_product), OpenMesh::Vec4d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_scalar_product), OpenMesh::Vec4f); template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_norm)(benchmark::State& state) { Vec v1(0.0); double acc = 0; while (state.KeepRunning()) { v1 += testVec<Vec>(); acc += v1.norm(); } // Otherwise GCC will optimize everything away. static double dummy; dummy = acc; static_cast<void>(dummy); } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_norm), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_norm), OpenMesh::Vec3f); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_norm), OpenMesh::Vec4d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_norm), OpenMesh::Vec4f); template<class Vec> static void ASSEMBLE(BMPOSTFIX, Vec_times_scalar)(benchmark::State& state) { Vec v1(0.0); while (state.KeepRunning()) { v1 += testVec<Vec>(); v1 *= static_cast<decltype(v1.norm())>(1.0)/v1[0]; v1 *= v1[1]; } // Otherwise GCC will optimize everything away. static double dummy; dummy = v1.norm(); static_cast<void>(dummy); } MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_times_scalar), OpenMesh::Vec3d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_times_scalar), OpenMesh::Vec3f); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_times_scalar), OpenMesh::Vec4d); MYBENCHMARK_TEMPLATE (ASSEMBLE(BMPOSTFIX, Vec_times_scalar), OpenMesh::Vec4f); <|endoftext|>
<commit_before>#include <iostream> #include <iterator> #include <algorithm> #include <signal.h> #include "headings.h" #include "libaps2.h" #include "constants.h" #include "concol.h" #include "helpers.h" #include "optionparser.h" enum optionIndex { UNKNOWN, HELP, WFA_FILE, WFB_FILE, TRIG_MODE, TRIG_INTERVAL, LOG_LEVEL}; const option::Descriptor usage[] = { {UNKNOWN, 0,"" , "" , option::Arg::None, "USAGE: play_waveform [options]\n\n" "Options:" }, {HELP, 0,"" , "help", option::Arg::None, " --help \tPrint usage and exit." }, {WFA_FILE, 0,"", "wfA", option::Arg::Required, " --wfA \tChannel A waveform file (ASCII signed 16 bit integer)" }, {WFB_FILE, 0,"", "wfB", option::Arg::Required, " --wfB \tChannel B waveform file (ASCII signed 16 bit integer)" }, {TRIG_MODE, 0,"", "trigMode", option::Arg::Required, " --trigMode \tTrigger mode (0: external; 1: internal; 2: software" }, {TRIG_INTERVAL, 0,"", "trigInterval", option::Arg::Numeric, " --trigRep \tInternal trigger interval" }, {LOG_LEVEL, 0,"", "logLevel", option::Arg::Numeric, " --logLevel \tLogging level level to print" }, {UNKNOWN, 0,"" , "" , option::Arg::None, "\nExamples:\n" " play_waveform --wfA=../examples/wfA.dat --wfB=../examples/wfB.dat\n" " play_waveform --wfA=../examples/wfB.dat --trigMode=2\n" }, {0,0,0,0,0,0} }; static string deviceSerial; #ifdef _WIN32 BOOL WINAPI ConsoleHandler(DWORD dwType) { switch(dwType) { case CTRL_C_EVENT: printf("ctrl-c\n"); std::cout << std::endl; stop(deviceSerial.c_str()); disconnect_APS(deviceSerial.c_str()); exit(1); default: printf("Some other event\n"); } return TRUE; } #else void clean_up(int sigValue){ std::cout << std::endl; stop(deviceSerial.c_str()); disconnect_APS(deviceSerial.c_str()); exit(1); } #endif int main(int argc, char* argv[]) { argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present option::Stats stats(usage, argc, argv); option::Option options[stats.options_max], buffer[stats.buffer_max]; option::Parser parse(usage, argc, argv, options, buffer); if (parse.error()) return -1; if (options[HELP] || argc == 0) { option::printUsage(std::cout, usage); return 0; } for (option::Option* opt = options[UNKNOWN]; opt; opt = opt->next()) std::cout << "Unknown option: " << opt->name << "\n"; for (int i = 0; i < parse.nonOptionsCount(); ++i) std::cout << "Non-option #" << i << ": " << parse.nonOption(i) << "\n"; //Debug level int debugLevel = 4; if (options[LOG_LEVEL]) { debugLevel = atoi(options[LOG_LEVEL].arg); } //Trigger source -- default of internal int triggerSource = 1; if (options[TRIG_MODE]) { triggerSource = atoi(options[TRIG_MODE].arg); } //Trigger interval -- default of 10ms double trigInterval = 10e-3; if (options[TRIG_INTERVAL]) { trigInterval = atof(options[TRIG_INTERVAL].arg); } //Load the waveform files vector<int16_t> wfA, wfB; std::ifstream ifs; if (options[WFA_FILE]) { ifs.open(std::string(options[WFA_FILE].arg)); std::copy(std::istream_iterator<int16_t>(ifs), std::istream_iterator<int16_t>(), std::back_inserter(wfA) ); ifs.close(); } if (options[WFB_FILE]) { ifs.open(std::string(options[WFB_FILE].arg)); std::copy(std::istream_iterator<int16_t>(ifs), std::istream_iterator<int16_t>(), std::back_inserter(wfB) ); } //Pad the waveforms so they are the same size size_t longestLength = std::max(wfA.size(), wfB.size()); wfA.resize(longestLength, 0); wfB.resize(longestLength, 0); deviceSerial = get_device_id(); set_logging_level(debugLevel); set_log("stdout"); connect_APS(deviceSerial.c_str()); double uptime = get_uptime(deviceSerial.c_str()); cout << concol::RED << "Uptime for device " << deviceSerial << " is " << uptime << " seconds" << concol::RESET << endl; // force initialize device initAPS(deviceSerial.c_str(), 1); //load the waveforms set_waveform_int(deviceSerial.c_str(), 0, wfA.data(), wfA.size()); set_waveform_int(deviceSerial.c_str(), 1, wfB.data(), wfB.size()); //Set the trigger mode set_trigger_source(deviceSerial.c_str(), triggerSource); //Trigger interval set_trigger_interval(deviceSerial.c_str(), trigInterval); //Set to triggered waveform mode set_run_mode(deviceSerial.c_str(), 1); run(deviceSerial.c_str()); //Catch ctrl-c to clean_up the APS -- see http://zguide.zeromq.org/cpp:interrupt //Unfortunately we have some platform nonsense here #ifdef _WIN32 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE)) { std::cerr << "Unable to install handler!" << std::endl; return EXIT_FAILURE; } #else struct sigaction action; action.sa_handler = clean_up; action.sa_flags = 0; sigemptyset(&action.sa_mask); sigaction(SIGINT, &action, NULL); #endif //For software trigger, trigger on key stroke if (triggerSource == 2) { cout << "Return to trigger or ctrl-c to exit"; while(true) { cin.get(); trigger(deviceSerial.c_str()); } cout << endl; } else { cout << "Ctrl-c to quit"; while(true) { cin.get(); } } return 0; }<commit_msg>C++11-compliance on variable-length arrays.<commit_after>#include <iostream> #include <iterator> #include <algorithm> #include <signal.h> #include "headings.h" #include "libaps2.h" #include "constants.h" #include "concol.h" #include "helpers.h" #include "optionparser.h" enum optionIndex { UNKNOWN, HELP, WFA_FILE, WFB_FILE, TRIG_MODE, TRIG_INTERVAL, LOG_LEVEL}; const option::Descriptor usage[] = { {UNKNOWN, 0,"" , "" , option::Arg::None, "USAGE: play_waveform [options]\n\n" "Options:" }, {HELP, 0,"" , "help", option::Arg::None, " --help \tPrint usage and exit." }, {WFA_FILE, 0,"", "wfA", option::Arg::Required, " --wfA \tChannel A waveform file (ASCII signed 16 bit integer)" }, {WFB_FILE, 0,"", "wfB", option::Arg::Required, " --wfB \tChannel B waveform file (ASCII signed 16 bit integer)" }, {TRIG_MODE, 0,"", "trigMode", option::Arg::Required, " --trigMode \tTrigger mode (0: external; 1: internal; 2: software" }, {TRIG_INTERVAL, 0,"", "trigInterval", option::Arg::Numeric, " --trigRep \tInternal trigger interval" }, {LOG_LEVEL, 0,"", "logLevel", option::Arg::Numeric, " --logLevel \tLogging level level to print" }, {UNKNOWN, 0,"" , "" , option::Arg::None, "\nExamples:\n" " play_waveform --wfA=../examples/wfA.dat --wfB=../examples/wfB.dat\n" " play_waveform --wfA=../examples/wfB.dat --trigMode=2\n" }, {0,0,0,0,0,0} }; static string deviceSerial; #ifdef _WIN32 BOOL WINAPI ConsoleHandler(DWORD dwType) { switch(dwType) { case CTRL_C_EVENT: printf("ctrl-c\n"); std::cout << std::endl; stop(deviceSerial.c_str()); disconnect_APS(deviceSerial.c_str()); exit(1); default: printf("Some other event\n"); } return TRUE; } #else void clean_up(int sigValue){ std::cout << std::endl; stop(deviceSerial.c_str()); disconnect_APS(deviceSerial.c_str()); exit(1); } #endif int main(int argc, char* argv[]) { argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present option::Stats stats(usage, argc, argv); option::Option *options = new option::Option[stats.options_max]; option::Option *buffer = new option::Option[stats.buffer_max]; option::Parser parse(usage, argc, argv, options, buffer); if (parse.error()) return -1; if (options[HELP] || argc == 0) { option::printUsage(std::cout, usage); return 0; } for (option::Option* opt = options[UNKNOWN]; opt; opt = opt->next()) std::cout << "Unknown option: " << opt->name << "\n"; for (int i = 0; i < parse.nonOptionsCount(); ++i) std::cout << "Non-option #" << i << ": " << parse.nonOption(i) << "\n"; //Debug level int debugLevel = 4; if (options[LOG_LEVEL]) { debugLevel = atoi(options[LOG_LEVEL].arg); } //Trigger source -- default of internal int triggerSource = 1; if (options[TRIG_MODE]) { triggerSource = atoi(options[TRIG_MODE].arg); } //Trigger interval -- default of 10ms double trigInterval = 10e-3; if (options[TRIG_INTERVAL]) { trigInterval = atof(options[TRIG_INTERVAL].arg); } //Load the waveform files vector<int16_t> wfA, wfB; std::ifstream ifs; if (options[WFA_FILE]) { ifs.open(std::string(options[WFA_FILE].arg)); std::copy(std::istream_iterator<int16_t>(ifs), std::istream_iterator<int16_t>(), std::back_inserter(wfA) ); ifs.close(); } if (options[WFB_FILE]) { ifs.open(std::string(options[WFB_FILE].arg)); std::copy(std::istream_iterator<int16_t>(ifs), std::istream_iterator<int16_t>(), std::back_inserter(wfB) ); } //Pad the waveforms so they are the same size size_t longestLength = std::max(wfA.size(), wfB.size()); wfA.resize(longestLength, 0); wfB.resize(longestLength, 0); deviceSerial = get_device_id(); set_logging_level(debugLevel); set_log("stdout"); connect_APS(deviceSerial.c_str()); double uptime = get_uptime(deviceSerial.c_str()); cout << concol::RED << "Uptime for device " << deviceSerial << " is " << uptime << " seconds" << concol::RESET << endl; // force initialize device initAPS(deviceSerial.c_str(), 1); //load the waveforms set_waveform_int(deviceSerial.c_str(), 0, wfA.data(), wfA.size()); set_waveform_int(deviceSerial.c_str(), 1, wfB.data(), wfB.size()); //Set the trigger mode set_trigger_source(deviceSerial.c_str(), triggerSource); //Trigger interval set_trigger_interval(deviceSerial.c_str(), trigInterval); //Set to triggered waveform mode set_run_mode(deviceSerial.c_str(), 1); run(deviceSerial.c_str()); //Catch ctrl-c to clean_up the APS -- see http://zguide.zeromq.org/cpp:interrupt //Unfortunately we have some platform nonsense here #ifdef _WIN32 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE)) { std::cerr << "Unable to install handler!" << std::endl; return EXIT_FAILURE; } #else struct sigaction action; action.sa_handler = clean_up; action.sa_flags = 0; sigemptyset(&action.sa_mask); sigaction(SIGINT, &action, NULL); #endif //For software trigger, trigger on key stroke if (triggerSource == 2) { cout << "Return to trigger or ctrl-c to exit"; while(true) { cin.get(); trigger(deviceSerial.c_str()); } cout << endl; } else { cout << "Ctrl-c to quit"; while(true) { cin.get(); } } delete[] options; delete[] buffer; return 0; }<|endoftext|>
<commit_before>// C++ General Utility Library (mailto:cgul@zethes.com) // Copyright (C) 2012-2014, Joshua Brookover and Amber Thrall // All rights reserved. /** @file Vector3.hpp */ #pragma once #include <CGUL/Config.hpp> #include "../External/Defines.hpp" // Without this here you would need a human sacrifice each time you wanted to use operator<< namespace CGUL { template< typename Type > struct Vector3T; template< typename Type > _CGUL_INLINE_DEFINE std::ostream& operator<<(std::ostream&, const CGUL::Vector3T< Type >&); } namespace CGUL { template< typename Type > struct Vector2T; template< typename Type > struct Vector4T; template< typename Type > struct MatrixT; /** @brief A three dimensional 32 bit floating point vector. * @todo Template this to allow 64 bit floating point or integer as well? */ template< typename Type > struct Vector3T { union { struct { Type x, y, z; }; Type m[3]; }; //! @brief Zero vector, defined as (0, 0, 0). static const Vector3T zero; //! @brief One vector, defined as (1, 1, 1). static const Vector3T one; //! @brief Unit X vector, defined as (1, 0, 0). static const Vector3T unitX; //! @brief Unit Y vector, defined as (0, 1, 0). static const Vector3T unitY; //! @brief Unit Y vector, defined as (0, 0, 1). static const Vector3T unitZ; _CGUL_INLINE_DEFINE static Type DotProduct(const Vector3T& valueA, const Vector3T& valueB); _CGUL_INLINE_DEFINE static Vector3T CrossProduct(const Vector3T& valueA, const Vector3T& valueB); _CGUL_INLINE_DEFINE static Vector3T Normalized(const Vector3T& value); _CGUL_INLINE_DEFINE static Type Distance(const Vector3T& vectorA, const Vector3T& vectorB); _CGUL_INLINE_DEFINE static Type DistanceSquared(const Vector3T& valueA, const Vector3T& vectorB); _CGUL_INLINE_DEFINE static Type DistanceManhattan(const Vector3T& valueA, const Vector3T& vectorB); //! @brief Initializes to (0, 0, 0). _CGUL_INLINE_DEFINE Vector3T(); //! @brief Copies a vector into this vector. _CGUL_INLINE_DEFINE Vector3T(const Vector3T& copy); //! @brief Copies a vector2 into this vector3's //! first two components and Initializes z to 0. _CGUL_INLINE_DEFINE Vector3T(const Vector2T< Type >& copy); //! @brief Copies a vector2 into this vector3's first two components //! and Initializes z with the individual component value. _CGUL_INLINE_DEFINE Vector3T(const Vector2T< Type >& copy, Type z); //! @brief Initializes all components to a given value. _CGUL_INLINE_DEFINE Vector3T(Type value); //! @brief Initializes the vector with individual component values. _CGUL_INLINE_DEFINE Vector3T(Type x, Type y, Type z); //! @brief Assigns another vector into this vector. _CGUL_INLINE_DEFINE Vector3T& operator=(const Vector3T& operand); //! @brief Accesses an individual component in this vector. _CGUL_INLINE_DEFINE Type& operator[](UInt32 index); //! @brief Accesses an individual (constant) component in this vector. _CGUL_INLINE_DEFINE Type operator[](UInt32 index) const; //! @brief Gets the inverse of the vector. _CGUL_INLINE_DEFINE Vector3T operator-() const; //! @brief Checks if two vectors are @em exactly equal. _CGUL_INLINE_DEFINE bool operator==(const Vector3T& operand) const; //! @brief Checks if two vectors are not @em exactly equal. _CGUL_INLINE_DEFINE bool operator!=(const Vector3T& operand) const; //! @brief Performs component-based addition on two vectors. _CGUL_INLINE_DEFINE Vector3T operator+(const Vector3T& operand) const; //! @brief Adds the individual components of another vector to this vector's components. _CGUL_INLINE_DEFINE Vector3T& operator+=(const Vector3T& operand); //! @brief Adds the individual components of a vector2 to this vector3's first two components. _CGUL_INLINE_DEFINE Vector3T& operator+=(const Vector2T< Type >& operand); //! @brief Performs component-based subtraction on two vectors. _CGUL_INLINE_DEFINE Vector3T operator-(const Vector3T& operand) const; //! @brief Subtracts the individual components of another vector from this vector's //! components. _CGUL_INLINE_DEFINE Vector3T& operator-=(const Vector3T& operand); //! @brief Subtracts the individual components of a vector2 to this vector3's //! first two components. _CGUL_INLINE_DEFINE Vector3T& operator-=(const Vector2T< Type >& operand); //! @brief Performs component-based multiplication on two vectors. _CGUL_INLINE_DEFINE Vector3T operator*(Type operand) const; _CGUL_INLINE_DEFINE Vector3T operator*(const MatrixT< Type >& operand) const; //! @brief Multiplies the individual components of another vector onto this vector's //! components. _CGUL_INLINE_DEFINE Vector3T& operator*=(Type operand); _CGUL_INLINE_DEFINE Vector3T& operator*=(const MatrixT< Type >& operand); //! @brief Performs component-based division on two vectors. _CGUL_INLINE_DEFINE Vector3T operator/(Type operand) const; //! @brief Divides the individual components of another vector onto this vector's //! components. _CGUL_INLINE_DEFINE Vector3T& operator/=(Type operand); //! @brief An operator to output this vector on an output stream. friend std::ostream& operator<< <>(std::ostream& stream, const Vector3T< Type >& vector); template< typename OtherType > _CGUL_INLINE_DEFINE operator Vector3T< OtherType >(); //! @brief Accesses an individual component in this vector. _CGUL_INLINE_DEFINE Type& At(UInt32 index); //! @brief Accesses an individual (constant) component in this vector. _CGUL_INLINE_DEFINE Type At(UInt32 index) const; //! @brief Sets all components to a given value. _CGUL_INLINE_DEFINE void Set(Type value); //! @brief Sets all components to the given values. _CGUL_INLINE_DEFINE void Set(Type x, Type y, Type z); //! @brief Clears the vector to (0, 0, 0). _CGUL_INLINE_DEFINE void Clear(); //! @brief Performs a two dimensional swizzle. _CGUL_INLINE_DEFINE Vector2T< Type > Swizzle(UInt32 x, UInt32 y) const; //! @brief Performs a three dimensional swizzle. _CGUL_INLINE_DEFINE Vector3T< Type > Swizzle(UInt32 x, UInt32 y, UInt32 z) const; //! @brief Performs a four dimensional swizzle. _CGUL_INLINE_DEFINE Vector4T< Type > Swizzle(UInt32 x, UInt32 y, UInt32 z, UInt32 w) const; //! @brief Normalizes the vector resulting in a length of 1. _CGUL_INLINE_DEFINE void Normalize(); //! @brief Checks if the vector is normalizes within a given epsilon. _CGUL_INLINE_DEFINE Boolean IsNormalized(Type epsilon = 0.00001f) const; //! @brief Gets the magnitude of the vector. _CGUL_INLINE_DEFINE Type GetMagnitude() const; //! @brief Gets the squared magnitude of the vector. _CGUL_INLINE_DEFINE Type GetSquaredMagnitude() const; //! @brief Gets the manhattan magnitude of the vector. _CGUL_INLINE_DEFINE Type GetManhattanMagnitude() const; //! @brief Gets the distance between two vectors. _CGUL_INLINE_DEFINE Type GetDistance(const Vector3T& other) const; //! @brief Gets the squared distance between two vectors. _CGUL_INLINE_DEFINE Type GetSquaredDistance(const Vector3T& other) const; //! @brief Gets the manhattan distance between two vectors. _CGUL_INLINE_DEFINE Type GetManhattanDistance(const Vector3T& other) const; //! @brief Rounds down each component to the nearest whole number. _CGUL_INLINE_DEFINE void Floor(); //! @brief Rounds each component to the nearest whole number. _CGUL_INLINE_DEFINE void Round(); //! @brief Rounds up each component to the nearest whole number. _CGUL_INLINE_DEFINE void Ceil(); //! @brief Returns a vector with each component rounded down. _CGUL_INLINE_DEFINE Vector3T Floored() const; //! @brief Returns a vector with each component rounded. _CGUL_INLINE_DEFINE Vector3T Rounded() const; //! @brief Returns a vector with each component rounded up. _CGUL_INLINE_DEFINE Vector3T Ceiled() const; //! @brief Gets the sum of the elements. _CGUL_INLINE_DEFINE Type SumComponents() const; //! @brief Gets the product of the elements. _CGUL_INLINE_DEFINE Type MultiplyComponents() const; _CGUL_INLINE_DEFINE void MakeOrthonormalBasis(Vector3T< Type >* vectorB, Vector3T< Type >* vectorC); }; typedef Vector3T< Float32 > Vector3; typedef Vector3T< Float64 > Vector3D; } #include "../External/Undefines.hpp" #include "Vector3_Implement.hpp" <commit_msg>Fix: - Replace tabs with 4 spaces.<commit_after>// C++ General Utility Library (mailto:cgul@zethes.com) // Copyright (C) 2012-2014, Joshua Brookover and Amber Thrall // All rights reserved. /** @file Vector3.hpp */ #pragma once #include <CGUL/Config.hpp> #include "../External/Defines.hpp" // Without this here you would need a human sacrifice each time you wanted to use operator<< namespace CGUL { template< typename Type > struct Vector3T; template< typename Type > _CGUL_INLINE_DEFINE std::ostream& operator<<(std::ostream&, const CGUL::Vector3T< Type >&); } namespace CGUL { template< typename Type > struct Vector2T; template< typename Type > struct Vector4T; template< typename Type > struct MatrixT; /** @brief A three dimensional 32 bit floating point vector. * @todo Template this to allow 64 bit floating point or integer as well? */ template< typename Type > struct Vector3T { union { struct { Type x, y, z; }; Type m[3]; }; //! @brief Zero vector, defined as (0, 0, 0). static const Vector3T zero; //! @brief One vector, defined as (1, 1, 1). static const Vector3T one; //! @brief Unit X vector, defined as (1, 0, 0). static const Vector3T unitX; //! @brief Unit Y vector, defined as (0, 1, 0). static const Vector3T unitY; //! @brief Unit Y vector, defined as (0, 0, 1). static const Vector3T unitZ; _CGUL_INLINE_DEFINE static Type DotProduct(const Vector3T& valueA, const Vector3T& valueB); _CGUL_INLINE_DEFINE static Vector3T CrossProduct(const Vector3T& valueA, const Vector3T& valueB); _CGUL_INLINE_DEFINE static Vector3T Normalized(const Vector3T& value); _CGUL_INLINE_DEFINE static Type Distance(const Vector3T& vectorA, const Vector3T& vectorB); _CGUL_INLINE_DEFINE static Type DistanceSquared(const Vector3T& valueA, const Vector3T& vectorB); _CGUL_INLINE_DEFINE static Type DistanceManhattan(const Vector3T& valueA, const Vector3T& vectorB); //! @brief Initializes to (0, 0, 0). _CGUL_INLINE_DEFINE Vector3T(); //! @brief Copies a vector into this vector. _CGUL_INLINE_DEFINE Vector3T(const Vector3T& copy); //! @brief Copies a vector2 into this vector3's //! first two components and Initializes z to 0. _CGUL_INLINE_DEFINE Vector3T(const Vector2T< Type >& copy); //! @brief Copies a vector2 into this vector3's first two components //! and Initializes z with the individual component value. _CGUL_INLINE_DEFINE Vector3T(const Vector2T< Type >& copy, Type z); //! @brief Initializes all components to a given value. _CGUL_INLINE_DEFINE Vector3T(Type value); //! @brief Initializes the vector with individual component values. _CGUL_INLINE_DEFINE Vector3T(Type x, Type y, Type z); //! @brief Assigns another vector into this vector. _CGUL_INLINE_DEFINE Vector3T& operator=(const Vector3T& operand); //! @brief Accesses an individual component in this vector. _CGUL_INLINE_DEFINE Type& operator[](UInt32 index); //! @brief Accesses an individual (constant) component in this vector. _CGUL_INLINE_DEFINE Type operator[](UInt32 index) const; //! @brief Gets the inverse of the vector. _CGUL_INLINE_DEFINE Vector3T operator-() const; //! @brief Checks if two vectors are @em exactly equal. _CGUL_INLINE_DEFINE bool operator==(const Vector3T& operand) const; //! @brief Checks if two vectors are not @em exactly equal. _CGUL_INLINE_DEFINE bool operator!=(const Vector3T& operand) const; //! @brief Performs component-based addition on two vectors. _CGUL_INLINE_DEFINE Vector3T operator+(const Vector3T& operand) const; //! @brief Adds the individual components of another vector to this vector's components. _CGUL_INLINE_DEFINE Vector3T& operator+=(const Vector3T& operand); //! @brief Adds the individual components of a vector2 to this vector3's first two components. _CGUL_INLINE_DEFINE Vector3T& operator+=(const Vector2T< Type >& operand); //! @brief Performs component-based subtraction on two vectors. _CGUL_INLINE_DEFINE Vector3T operator-(const Vector3T& operand) const; //! @brief Subtracts the individual components of another vector from this vector's //! components. _CGUL_INLINE_DEFINE Vector3T& operator-=(const Vector3T& operand); //! @brief Subtracts the individual components of a vector2 to this vector3's //! first two components. _CGUL_INLINE_DEFINE Vector3T& operator-=(const Vector2T< Type >& operand); //! @brief Performs component-based multiplication on two vectors. _CGUL_INLINE_DEFINE Vector3T operator*(Type operand) const; _CGUL_INLINE_DEFINE Vector3T operator*(const MatrixT< Type >& operand) const; //! @brief Multiplies the individual components of another vector onto this vector's //! components. _CGUL_INLINE_DEFINE Vector3T& operator*=(Type operand); _CGUL_INLINE_DEFINE Vector3T& operator*=(const MatrixT< Type >& operand); //! @brief Performs component-based division on two vectors. _CGUL_INLINE_DEFINE Vector3T operator/(Type operand) const; //! @brief Divides the individual components of another vector onto this vector's //! components. _CGUL_INLINE_DEFINE Vector3T& operator/=(Type operand); //! @brief An operator to output this vector on an output stream. friend std::ostream& operator<< <>(std::ostream& stream, const Vector3T< Type >& vector); template< typename OtherType > _CGUL_INLINE_DEFINE operator Vector3T< OtherType >(); //! @brief Accesses an individual component in this vector. _CGUL_INLINE_DEFINE Type& At(UInt32 index); //! @brief Accesses an individual (constant) component in this vector. _CGUL_INLINE_DEFINE Type At(UInt32 index) const; //! @brief Sets all components to a given value. _CGUL_INLINE_DEFINE void Set(Type value); //! @brief Sets all components to the given values. _CGUL_INLINE_DEFINE void Set(Type x, Type y, Type z); //! @brief Clears the vector to (0, 0, 0). _CGUL_INLINE_DEFINE void Clear(); //! @brief Performs a two dimensional swizzle. _CGUL_INLINE_DEFINE Vector2T< Type > Swizzle(UInt32 x, UInt32 y) const; //! @brief Performs a three dimensional swizzle. _CGUL_INLINE_DEFINE Vector3T< Type > Swizzle(UInt32 x, UInt32 y, UInt32 z) const; //! @brief Performs a four dimensional swizzle. _CGUL_INLINE_DEFINE Vector4T< Type > Swizzle(UInt32 x, UInt32 y, UInt32 z, UInt32 w) const; //! @brief Normalizes the vector resulting in a length of 1. _CGUL_INLINE_DEFINE void Normalize(); //! @brief Checks if the vector is normalizes within a given epsilon. _CGUL_INLINE_DEFINE Boolean IsNormalized(Type epsilon = 0.00001f) const; //! @brief Gets the magnitude of the vector. _CGUL_INLINE_DEFINE Type GetMagnitude() const; //! @brief Gets the squared magnitude of the vector. _CGUL_INLINE_DEFINE Type GetSquaredMagnitude() const; //! @brief Gets the manhattan magnitude of the vector. _CGUL_INLINE_DEFINE Type GetManhattanMagnitude() const; //! @brief Gets the distance between two vectors. _CGUL_INLINE_DEFINE Type GetDistance(const Vector3T& other) const; //! @brief Gets the squared distance between two vectors. _CGUL_INLINE_DEFINE Type GetSquaredDistance(const Vector3T& other) const; //! @brief Gets the manhattan distance between two vectors. _CGUL_INLINE_DEFINE Type GetManhattanDistance(const Vector3T& other) const; //! @brief Rounds down each component to the nearest whole number. _CGUL_INLINE_DEFINE void Floor(); //! @brief Rounds each component to the nearest whole number. _CGUL_INLINE_DEFINE void Round(); //! @brief Rounds up each component to the nearest whole number. _CGUL_INLINE_DEFINE void Ceil(); //! @brief Returns a vector with each component rounded down. _CGUL_INLINE_DEFINE Vector3T Floored() const; //! @brief Returns a vector with each component rounded. _CGUL_INLINE_DEFINE Vector3T Rounded() const; //! @brief Returns a vector with each component rounded up. _CGUL_INLINE_DEFINE Vector3T Ceiled() const; //! @brief Gets the sum of the elements. _CGUL_INLINE_DEFINE Type SumComponents() const; //! @brief Gets the product of the elements. _CGUL_INLINE_DEFINE Type MultiplyComponents() const; _CGUL_INLINE_DEFINE void MakeOrthonormalBasis(Vector3T< Type >* vectorB, Vector3T< Type >* vectorC); }; typedef Vector3T< Float32 > Vector3; typedef Vector3T< Float64 > Vector3D; } #include "../External/Undefines.hpp" #include "Vector3_Implement.hpp" <|endoftext|>
<commit_before>/** * @file FTAddMyTask.C * @author Freja Thoresen <freja.thoresen@cern.ch> * * @brief Add Q-cummulant forward task to train * * * @ingroup pwglf_forward_scripts_tasks */ /** * @defgroup pwglf_forward_flow Flow * * Code to deal with flow * * @ingroup pwglf_forward_topical */ /** * Add Flow task to train * * @ingroup pwglf_forward_flow */ AliAnalysisTaskSE* AddTaskForwardFlowRun2( bool doNUA, bool makeFakeHoles, TString nua_file, UShort_t nua_mode, bool doetagap, Double_t gap, bool mc, bool esd,bool prim_cen,bool prim_fwd , UInt_t tracktype, TString centrality,Double_t minpt,Double_t maxpt,TString sec_file_cen,TString sec_file_fwd,TString suffix) { std::cout << "______________________________________________________________________________" << std::endl; std::cout << "AddTaskForwardFlowRun2" << std::endl; // --- Get analysis manager ---------------------------------------- AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) Fatal("","No analysis manager to connect to."); TString name = suffix; AliForwardFlowRun2Task* task = new AliForwardFlowRun2Task(name); TString resName = "ForwardFlow"; if (doetagap){ // if etagap otherwise comment out, and it will be standard task->fSettings.fFlowFlags = task->fSettings.kEtaGap; task->fSettings.fNRefEtaBins = 1; task->fSettings.gap = gap; resName += "_etagap"; resName += std::to_string((int)(10*gap)); //resName += std::to_string(gap); } else { task->fSettings.fNRefEtaBins = 1; // eller skal det være et andet antal? task->fSettings.gap = 0.0; } if (makeFakeHoles){ task->fSettings.makeFakeHoles = kTRUE; resName += "_fakeholes"; } task->fSettings.use_primaries_cen = prim_cen; if (mc) resName += (prim_cen ? "_primcen" : "_trcen"); task->fSettings.use_primaries_fwd = prim_fwd; if (mc) resName += (prim_fwd ? "_primfwd" : "_trfwd"); task->fSettings.mc = mc; task->fSettings.esd = esd; std::cout << "Using tracktype = " << tracktype << std::endl; if (tracktype == 0){ task->fSettings.fFlowFlags = task->fSettings.kSPD; task->fSettings.useSPD = kTRUE; resName += "_SPD"; } else{ task->fSettings.fFlowFlags = task->fSettings.kTPC; if (tracktype == 768){ task->fSettings.tracktype = AliForwardSettings::kHybrid; resName += "_hybrid"; } else if (tracktype == 128){ task->fSettings.tracktype = AliForwardSettings::kTPCOnly; resName += "_TPConly"; } else if (tracktype == 32){ task->fSettings.tracktype = AliForwardSettings::kGlobal; resName += "_global"; } else if (tracktype == 64){ task->fSettings.tracktype = AliForwardSettings::kGlobalLoose; resName += "_globalLoose"; } else if (tracktype == 96){ task->fSettings.tracktype = AliForwardSettings::kGlobalComb; resName += "_globalComb"; } else{ std::cout << "INVALID TRACK TYPE FOR TPC" << std::endl; } } task->fSettings.minpt = minpt; resName += "_minpt"; resName += std::to_string((int)(minpt*10)); task->fSettings.maxpt = maxpt; resName += "_maxpt"; resName += std::to_string((int)(maxpt*10)); task->fSettings.doNUA = doNUA; if (task->fSettings.doNUA){ //TString nua_filepath = std::getenv("NUA_FILE"); //if (!nua_filepath) { TString nua_filepath = "/home/thoresen/Documents/PhD/Analysis/nua.root"; // std::cerr << "Environment variable 'NUA_FILE' not found (this should be a path to nua.root).\n"; // std::cerr << " Using default value: '" << nua_filepath << "'\n"; //} TFile *file; file = new TFile(nua_file); if (nua_mode == AliForwardSettings::kInterpolate) resName += "_NUA_interpolate"; if (nua_mode == AliForwardSettings::kFill) resName += "_NUA_fill"; if (nua_mode == AliForwardSettings::kNormal) resName += "_NUA_normal"; task->fSettings.nua_mode = nua_mode; // "V0M";// RefMult08; // "V0M" // "SPDTracklets"; file->GetObject("nuacentral", task->fSettings.nuacentral); task->fSettings.nuacentral->SetDirectory(0); file->GetObject("nuaforward", task->fSettings.nuaforward); task->fSettings.nuaforward->SetDirectory(0); file->Close(); } if (sec_file_fwd != ""){ TFile *file1 = new TFile(sec_file_fwd); file1->GetObject("correction", task->fSettings.seccorr_fwd); task->fSettings.seccorr_fwd->SetDirectory(0); file1->Close(); } if (sec_file_cen != ""){ TFile *file2 = new TFile(sec_file_cen); file2->GetObject("correction", task->fSettings.seccorr_cen); task->fSettings.seccorr_cen->SetDirectory(0); file2->Close(); } resName += "_" + centrality; if (mc) resName += "_mc"; task->fSettings.centrality_estimator = centrality; // "V0M";// RefMult08; // "V0M" // "SPDTracklets"; TString combName = suffix; std::cout << "Container name: " << combName << std::endl; //resName = "hej"; std::cout << "______________________________________________________________________________" << std::endl; AliAnalysisDataContainer *coutput_recon = mgr->CreateContainer(suffix,//combName, TList::Class(), AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName()); AliAnalysisDataContainer* valid = (AliAnalysisDataContainer*)mgr->GetContainers()->FindObject("event_selection_xchange"); task->ConnectInput(1,valid); mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, coutput_recon); return task; } /* * EOF * */ <commit_msg>removed std::tostring.<commit_after>/** * @file FTAddMyTask.C * @author Freja Thoresen <freja.thoresen@cern.ch> * * @brief Add Q-cummulant forward task to train * * * @ingroup pwglf_forward_scripts_tasks */ /** * @defgroup pwglf_forward_flow Flow * * Code to deal with flow * * @ingroup pwglf_forward_topical */ /** * Add Flow task to train * * @ingroup pwglf_forward_flow */ AliAnalysisTaskSE* AddTaskForwardFlowRun2( bool doNUA, bool makeFakeHoles, TString nua_file, UShort_t nua_mode, bool doetagap, Double_t gap, bool mc, bool esd,bool prim_cen,bool prim_fwd , UInt_t tracktype, TString centrality,Double_t minpt,Double_t maxpt,TString sec_file_cen,TString sec_file_fwd,TString suffix) { std::cout << "______________________________________________________________________________" << std::endl; std::cout << "AddTaskForwardFlowRun2" << std::endl; // --- Get analysis manager ---------------------------------------- AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) Fatal("","No analysis manager to connect to."); TString name = suffix; AliForwardFlowRun2Task* task = new AliForwardFlowRun2Task(name); TString resName = "ForwardFlow"; if (doetagap){ // if etagap otherwise comment out, and it will be standard task->fSettings.fFlowFlags = task->fSettings.kEtaGap; task->fSettings.fNRefEtaBins = 1; task->fSettings.gap = gap; resName += "_etagap"; // resName += std::to_string((int)(10*gap)); //resName += std::to_string(gap); } else { task->fSettings.fNRefEtaBins = 1; // eller skal det være et andet antal? task->fSettings.gap = 0.0; } if (makeFakeHoles){ task->fSettings.makeFakeHoles = kTRUE; resName += "_fakeholes"; } task->fSettings.use_primaries_cen = prim_cen; if (mc) resName += (prim_cen ? "_primcen" : "_trcen"); task->fSettings.use_primaries_fwd = prim_fwd; if (mc) resName += (prim_fwd ? "_primfwd" : "_trfwd"); task->fSettings.mc = mc; task->fSettings.esd = esd; std::cout << "Using tracktype = " << tracktype << std::endl; if (tracktype == 0){ task->fSettings.fFlowFlags = task->fSettings.kSPD; task->fSettings.useSPD = kTRUE; resName += "_SPD"; } else{ task->fSettings.fFlowFlags = task->fSettings.kTPC; if (tracktype == 768){ task->fSettings.tracktype = AliForwardSettings::kHybrid; resName += "_hybrid"; } else if (tracktype == 128){ task->fSettings.tracktype = AliForwardSettings::kTPCOnly; resName += "_TPConly"; } else if (tracktype == 32){ task->fSettings.tracktype = AliForwardSettings::kGlobal; resName += "_global"; } else if (tracktype == 64){ task->fSettings.tracktype = AliForwardSettings::kGlobalLoose; resName += "_globalLoose"; } else if (tracktype == 96){ task->fSettings.tracktype = AliForwardSettings::kGlobalComb; resName += "_globalComb"; } else{ std::cout << "INVALID TRACK TYPE FOR TPC" << std::endl; } } task->fSettings.minpt = minpt; resName += "_minpt"; //resName += std::to_string((int)(minpt*10)); task->fSettings.maxpt = maxpt; resName += "_maxpt"; //resName += std::to_string((int)(maxpt*10)); task->fSettings.doNUA = doNUA; if (task->fSettings.doNUA){ //TString nua_filepath = std::getenv("NUA_FILE"); //if (!nua_filepath) { TString nua_filepath = "/home/thoresen/Documents/PhD/Analysis/nua.root"; // std::cerr << "Environment variable 'NUA_FILE' not found (this should be a path to nua.root).\n"; // std::cerr << " Using default value: '" << nua_filepath << "'\n"; //} TFile *file; file = new TFile(nua_file); if (nua_mode == AliForwardSettings::kInterpolate) resName += "_NUA_interpolate"; if (nua_mode == AliForwardSettings::kFill) resName += "_NUA_fill"; if (nua_mode == AliForwardSettings::kNormal) resName += "_NUA_normal"; task->fSettings.nua_mode = nua_mode; // "V0M";// RefMult08; // "V0M" // "SPDTracklets"; file->GetObject("nuacentral", task->fSettings.nuacentral); task->fSettings.nuacentral->SetDirectory(0); file->GetObject("nuaforward", task->fSettings.nuaforward); task->fSettings.nuaforward->SetDirectory(0); file->Close(); } if (sec_file_fwd != ""){ TFile *file1 = new TFile(sec_file_fwd); file1->GetObject("correction", task->fSettings.seccorr_fwd); task->fSettings.seccorr_fwd->SetDirectory(0); file1->Close(); } if (sec_file_cen != ""){ TFile *file2 = new TFile(sec_file_cen); file2->GetObject("correction", task->fSettings.seccorr_cen); task->fSettings.seccorr_cen->SetDirectory(0); file2->Close(); } resName += "_" + centrality; if (mc) resName += "_mc"; task->fSettings.centrality_estimator = centrality; // "V0M";// RefMult08; // "V0M" // "SPDTracklets"; TString combName = suffix; std::cout << "Container name: " << combName << std::endl; //resName = "hej"; std::cout << "______________________________________________________________________________" << std::endl; AliAnalysisDataContainer *coutput_recon = mgr->CreateContainer(suffix,//combName, TList::Class(), AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName()); AliAnalysisDataContainer* valid = (AliAnalysisDataContainer*)mgr->GetContainers()->FindObject("event_selection_xchange"); task->ConnectInput(1,valid); mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, coutput_recon); return task; } /* * EOF * */ <|endoftext|>
<commit_before>// HeeksCNCInterface.cpp #include "stdafx.h" #include "HeeksCNCInterface.h" #include "Program.h" #include "Operations.h" #include "CTool.h" #include "Tools.h" #include "interface/HDialogs.h" #include <wx/aui/aui.h> CProgram* CHeeksCNCInterface::GetProgram() { return theApp.m_program; } CTools* CHeeksCNCInterface::GetTools() { if(theApp.m_program == NULL)return NULL; return theApp.m_program->Tools(); } std::vector< std::pair< int, wxString > > CHeeksCNCInterface::FindAllTools() { std::vector< std::pair< int, wxString > > tools; HTypeObjectDropDown::GetObjectArrayString(ToolType, theApp.m_program->Tools(), tools); return tools; } int CHeeksCNCInterface::FindFirstToolByType( unsigned int type ) { return CTool::FindFirstByType((CToolParams::eToolType)type); } COperations* CHeeksCNCInterface::GetOperations() { if(theApp.m_program == NULL)return NULL; return theApp.m_program->Operations(); } void CHeeksCNCInterface::RegisterOnRewritePython( void(*callbackfunc)() ) { theApp.m_OnRewritePython_list.push_back(callbackfunc); } void CHeeksCNCInterface::RegisterOperationType( int type ) { theApp.m_external_op_types.insert(type); } bool CHeeksCNCInterface::IsAnOperation( int type ) { return COperations::IsAnOperation(type); } wxString CHeeksCNCInterface::GetDllFolder() { return theApp.GetDllFolder(); } void CHeeksCNCInterface::SetMachinesFile( const wxString& filepath ) { CProgram::alternative_machines_file = filepath; } void CHeeksCNCInterface::HideMachiningMenu() { wxAuiManager* aui_manager = heeksCAD->GetAuiManager(); aui_manager->GetPane(theApp.m_machiningBar).Show(false); aui_manager->Update(); aui_manager->DetachPane(theApp.m_machiningBar); heeksCAD->RemoveHideableWindow(theApp.m_machiningBar); wxMenu* window_menu = heeksCAD->GetWindowMenu(); window_menu->Remove(window_menu->FindItem(_T("Machining"))); theApp.m_machining_hidden = true; heeksCAD->RemoveToolBar(theApp.m_machiningBar); wxFrame* frame = heeksCAD->GetMainFrame(); wxMenuBar* menu_bar = frame->GetMenuBar(); int pos = menu_bar->FindMenu(_("Machining")); if(pos != wxNOT_FOUND) menu_bar->Remove(pos); } void CHeeksCNCInterface::SetProcessRedirect(bool redirect) { CPyProcess::redirect = redirect; } void CHeeksCNCInterface::PostProcess() { // write the python program theApp.m_program->RewritePythonProgram(); // run it theApp.RunPythonScript(); } <commit_msg>Fix minor typo<commit_after>// HeeksCNCInterface.cpp #include "stdafx.h" #include "HeeksCNCInterface.h" #include "Program.h" #include "Operations.h" #include "CTool.h" #include "Tools.h" #include "interface/HDialogs.h" #include <wx/aui/aui.h> CProgram* CHeeksCNCInterface::GetProgram() { return theApp.m_program; } CTools* CHeeksCNCInterface::GetTools() { if(theApp.m_program == NULL)return NULL; return theApp.m_program->Tools(); } std::vector< std::pair< int, wxString > > CHeeksCNCInterface::FindAllTools() { std::vector< std::pair< int, wxString > > tools; HTypeObjectDropDown::GetObjectArrayString(ToolType, theApp.m_program->Tools(), tools); return tools; } int CHeeksCNCInterface::FindFirstToolByType( unsigned int type ) { return CTool::FindFirstByType((CToolParams::eToolType)type); } COperations* CHeeksCNCInterface::GetOperations() { if(theApp.m_program == NULL)return NULL; return theApp.m_program->Operations(); } void CHeeksCNCInterface::RegisterOnRewritePython( void(*callbackfunc)() ) { theApp.m_OnRewritePython_list.push_back(callbackfunc); } void CHeeksCNCInterface::RegisterOperationType( int type ) { theApp.m_external_op_types.insert(type); } bool CHeeksCNCInterface::IsAnOperation( int type ) { return COperations::IsAnOperation(type); } wxString CHeeksCNCInterface::GetDllFolder() { return theApp.GetDllFolder(); } void CHeeksCNCInterface::SetMachinesFile( const wxString& filepath ) { CProgram::alternative_machines_file = filepath; } void CHeeksCNCInterface::HideMachiningMenu() { wxAuiManager* aui_manager = heeksCAD->GetAuiManager(); aui_manager->GetPane(theApp.m_machiningBar).Show(false); aui_manager->Update(); aui_manager->DetachPane(theApp.m_machiningBar); heeksCAD->RemoveHideableWindow(theApp.m_machiningBar); wxMenu* window_menu = heeksCAD->GetWindowMenu(); window_menu->Remove(window_menu->FindItem(_T("Machining"))); theApp.m_machining_hidden = true; heeksCAD->RemoveToolBar(theApp.m_machiningBar); wxFrame* frame = heeksCAD->GetMainFrame(); wxMenuBar* menu_bar = frame->GetMenuBar(); int pos = menu_bar->FindMenu(_("&Machining")); if(pos != wxNOT_FOUND) menu_bar->Remove(pos); } void CHeeksCNCInterface::SetProcessRedirect(bool redirect) { CPyProcess::redirect = redirect; } void CHeeksCNCInterface::PostProcess() { // write the python program theApp.m_program->RewritePythonProgram(); // run it theApp.RunPythonScript(); } <|endoftext|>
<commit_before> #include <Hord/IO/Datastore.hpp> #include <utility> #include <Hord/detail/gr_core.hpp> namespace Hord { namespace IO { // class Datastore implementation #define HORD_SCOPE_CLASS IO::Datastore Datastore::Datastore( String root_path ) noexcept : m_root_path(std::move(root_path)) {} Datastore::~Datastore() = default; #define HORD_CLOSED_CHECK_ \ if (!is_open()) { \ HORD_THROW_FQN( \ ErrorCode::datastore_closed, \ "cannot perform this operation while" \ " datastore is closed" \ ); \ } #define HORD_LOCKED_CHECK_ \ if (is_locked()) { \ HORD_THROW_FQN( \ ErrorCode::datastore_locked, \ "cannot perform this operation while" \ " datastore is locked" \ ); \ } #define HORD_SCOPE_FUNC set_root_path void Datastore::set_root_path( String root_path ) { if (is_open()) { HORD_THROW_FQN( ErrorCode::datastore_property_immutable, "cannot change root path while datastore is open" ); } m_root_path.assign(std::move(root_path)); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC open void Datastore::open() { if (is_open()) { HORD_THROW_FQN( ErrorCode::datastore_open_already, "datastore is already open" ); } open_impl(); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC close void Datastore::close() { HORD_LOCKED_CHECK_; if (is_open()) { close_impl(); } } #undef HORD_SCOPE_FUNC // acquire #define HORD_SCOPE_FUNC acquire_input_stream std::istream& Datastore::acquire_input_stream( IO::PropInfo const& prop_info ) { HORD_CLOSED_CHECK_; HORD_LOCKED_CHECK_; return acquire_input_stream_impl(prop_info); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC acquire_output_stream std::ostream& Datastore::acquire_output_stream( IO::PropInfo const& prop_info ) { HORD_CLOSED_CHECK_; HORD_LOCKED_CHECK_; return acquire_output_stream_impl(prop_info); } #undef HORD_SCOPE_FUNC // release #define HORD_RELEASE_CHECK_ \ if (!is_locked()) { \ HORD_THROW_FQN( \ ErrorCode::datastore_prop_not_locked, \ "prop is not locked" \ ); \ } #define HORD_SCOPE_FUNC release_input_stream void Datastore::release_input_stream( IO::PropInfo const& prop_info ) { HORD_CLOSED_CHECK_; HORD_RELEASE_CHECK_; release_input_stream_impl(prop_info); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC release_output_stream void Datastore::release_output_stream( IO::PropInfo const& prop_info ) { HORD_CLOSED_CHECK_; HORD_RELEASE_CHECK_; release_output_stream_impl(prop_info); } #undef HORD_SCOPE_FUNC #undef HORD_RELEASE_CHECK_ // objects #define HORD_SCOPE_FUNC generate_id Object::ID Datastore::generate_id( System::IDGenerator& generator ) const { HORD_CLOSED_CHECK_; return generate_id_impl(generator); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC create_object void Datastore::create_object( Object::ID const object_id, Object::Type const object_type ) { if (Object::Type::Node != object_type) { HORD_THROW_FQN( ErrorCode::datastore_object_type_prohibited, "cannot create object other than Node" ); } HORD_CLOSED_CHECK_; HORD_LOCKED_CHECK_; create_object_impl(object_id, object_type); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC destroy_object void Datastore::destroy_object( Object::ID const object_id ) { HORD_CLOSED_CHECK_; HORD_LOCKED_CHECK_; destroy_object_impl(object_id); } #undef HORD_SCOPE_FUNC #undef HORD_CLOSED_CHECK_ #undef HORD_LOCKED_CHECK_ #undef HORD_SCOPE_CLASS } // namespace IO } // namespace Hord <commit_msg>IO::Datastore::create_object(): throw datastore_object_already_exists with null ID.<commit_after> #include <Hord/IO/Datastore.hpp> #include <utility> #include <Hord/detail/gr_core.hpp> namespace Hord { namespace IO { // class Datastore implementation #define HORD_SCOPE_CLASS IO::Datastore Datastore::Datastore( String root_path ) noexcept : m_root_path(std::move(root_path)) {} Datastore::~Datastore() = default; #define HORD_CLOSED_CHECK_ \ if (!is_open()) { \ HORD_THROW_FQN( \ ErrorCode::datastore_closed, \ "cannot perform this operation while" \ " datastore is closed" \ ); \ } #define HORD_LOCKED_CHECK_ \ if (is_locked()) { \ HORD_THROW_FQN( \ ErrorCode::datastore_locked, \ "cannot perform this operation while" \ " datastore is locked" \ ); \ } #define HORD_SCOPE_FUNC set_root_path void Datastore::set_root_path( String root_path ) { if (is_open()) { HORD_THROW_FQN( ErrorCode::datastore_property_immutable, "cannot change root path while datastore is open" ); } m_root_path.assign(std::move(root_path)); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC open void Datastore::open() { if (is_open()) { HORD_THROW_FQN( ErrorCode::datastore_open_already, "datastore is already open" ); } open_impl(); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC close void Datastore::close() { HORD_LOCKED_CHECK_; if (is_open()) { close_impl(); } } #undef HORD_SCOPE_FUNC // acquire #define HORD_SCOPE_FUNC acquire_input_stream std::istream& Datastore::acquire_input_stream( IO::PropInfo const& prop_info ) { HORD_CLOSED_CHECK_; HORD_LOCKED_CHECK_; return acquire_input_stream_impl(prop_info); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC acquire_output_stream std::ostream& Datastore::acquire_output_stream( IO::PropInfo const& prop_info ) { HORD_CLOSED_CHECK_; HORD_LOCKED_CHECK_; return acquire_output_stream_impl(prop_info); } #undef HORD_SCOPE_FUNC // release #define HORD_RELEASE_CHECK_ \ if (!is_locked()) { \ HORD_THROW_FQN( \ ErrorCode::datastore_prop_not_locked, \ "prop is not locked" \ ); \ } #define HORD_SCOPE_FUNC release_input_stream void Datastore::release_input_stream( IO::PropInfo const& prop_info ) { HORD_CLOSED_CHECK_; HORD_RELEASE_CHECK_; release_input_stream_impl(prop_info); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC release_output_stream void Datastore::release_output_stream( IO::PropInfo const& prop_info ) { HORD_CLOSED_CHECK_; HORD_RELEASE_CHECK_; release_output_stream_impl(prop_info); } #undef HORD_SCOPE_FUNC #undef HORD_RELEASE_CHECK_ // objects #define HORD_SCOPE_FUNC generate_id Object::ID Datastore::generate_id( System::IDGenerator& generator ) const { HORD_CLOSED_CHECK_; return generate_id_impl(generator); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC create_object void Datastore::create_object( Object::ID const object_id, Object::Type const object_type ) { if (Object::Type::Node != object_type) { HORD_THROW_FQN( ErrorCode::datastore_object_type_prohibited, "cannot create object other than Node" ); } else if (Object::NULL_ID == object_id) { HORD_THROW_FQN( ErrorCode::datastore_object_already_exists, "null object already exists (alias to Hive)" ); } HORD_CLOSED_CHECK_; HORD_LOCKED_CHECK_; create_object_impl(object_id, object_type); } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC destroy_object void Datastore::destroy_object( Object::ID const object_id ) { HORD_CLOSED_CHECK_; HORD_LOCKED_CHECK_; destroy_object_impl(object_id); } #undef HORD_SCOPE_FUNC #undef HORD_CLOSED_CHECK_ #undef HORD_LOCKED_CHECK_ #undef HORD_SCOPE_CLASS } // namespace IO } // namespace Hord <|endoftext|>
<commit_before>#include "lodmaker.h" struct QVertex { aten::vertex v; uint32_t idx; uint32_t grid[3]; uint64_t hash; QVertex() {} QVertex( aten::vertex _v, uint32_t i, uint64_t h, uint32_t gx, uint32_t gy, uint32_t gz) : v(_v), idx(i), hash(h) { grid[0] = gx; grid[1] = gy; grid[2] = gz; } const QVertex& operator=(const QVertex& rhs) { v = rhs.v; idx = rhs.idx; grid[0] = rhs.grid[0]; grid[1] = rhs.grid[1]; grid[2] = rhs.grid[2]; hash = rhs.hash; return *this; } }; // NOTE // gridX * gridY * gridZ uint64_t 𒴂Ȃ悤ɂ using qit = std::vector<QVertex>::iterator; static void computeAverage(qit start, qit end) { aten::vec4 pos(start->v.pos); aten::vec3 nml(start->v.nml); aten::vec3 uv(start->v.uv); uint32_t cnt = 1; for (auto q = start + 1; q != end; q++) { pos += q->v.pos; nml += q->v.nml; uv += q->v.uv; cnt++; } real div = real(1) / cnt; pos *= div; nml *= div; uv *= div; pos.w = real(1); nml = normalize(nml); // NOTE // z is used for checking to compute plane normal in real-time. uv.z = uv.z >= 0 ? 1 : 0; // vZʂ߂... for (auto q = start; q != end; q++) { q->v.pos = pos; q->v.nml = nml; q->v.uv = uv; } } void LodMaker::make( std::vector<aten::vertex>& dstVertices, std::vector<std::vector<int>>& dstIndices, const aten::aabb& bound, const std::vector<aten::vertex>& vertices, const std::vector<std::vector<aten::face*>>& triGroups, int gridX, int gridY, int gridZ) { auto bmin = bound.minPos(); auto range = bound.size(); aten::vec3 scale( (gridX - 1) / range.x, (gridY - 1) / range.y, (gridZ - 1) / range.z); std::vector<std::vector<QVertex>> qvtxs(triGroups.size()); std::vector<std::vector<uint32_t>> sortedIndices(triGroups.size()); for (uint32_t i = 0; i < triGroups.size(); i++) { const auto tris = triGroups[i]; qvtxs[i].reserve(tris.size()); for (uint32_t n = 0; n < tris.size(); n++) { const auto tri = tris[n]; for (int t = 0; t < 3; t++) { uint32_t idx = tri->param.idx[t]; const auto& v = vertices[idx]; auto grid = ((aten::vec3)v.pos - bmin) * scale + real(0.5); uint32_t gx = (uint32_t)grid.x; uint32_t gy = (uint32_t)grid.y; uint32_t gz = (uint32_t)grid.z; uint64_t hash = gz * (gridX * gridY) + gy * gridX + gx; qvtxs[i].push_back(QVertex(v, idx, hash, gx, gy, gz)); } } } // ObhɓĂ钸_̏ɂȂ悤Ƀ\[g. for (uint32_t i = 0; i < qvtxs.size(); i++) { std::sort( qvtxs[i].begin(), qvtxs[i].end(), [](const QVertex& q0, const QVertex& q1) { return q0.hash > q1.hash; }); uint32_t num = (uint32_t)qvtxs[i].size(); sortedIndices[i].resize(num); // CfbNX_ɂ킹ĕבւ. for (uint32_t n = 0; n < num; n++) { const auto& q = qvtxs[i][n]; // X̃CfbNẌʒuɐVCfbNXl. sortedIndices[i][q.idx] = n; } } // ObhɓĂ钸_̕ϒlvZāAP‚̒_ɂĂ܂. // UV͕邪AFZJ_oEXɎĝŁA͋CɂȂ. for (uint32_t i = 0; i < qvtxs.size(); i++) { auto start = qvtxs[i].begin(); while (start != qvtxs[i].end()) { auto end = start; // ObhقȂ钸_ɂȂ܂ŒT. while (end != qvtxs[i].end() && start->hash == end->hash) { end++; } // TODO // όvZ. computeAverage(start, end); for (auto q = start; q != end; q++) { if (q == start) { dstVertices.push_back(q->v); } else { // قȂʒu̓_̏ꍇ. // O̓_Ɣr. auto prev = q - 1; auto v0 = q->v.pos; auto v1 = prev->v.pos; bool isEqual = (memcmp(&v0, &v1, sizeof(v0)) == 0); if (!isEqual) { dstVertices.push_back(q->v); } } // CfbNXXV. q->idx = (uint32_t)dstVertices.size() - 1; } // ̊JnʒuXV start = end; } } // LODꂽʂ̃CfbNXi[. dstIndices.resize(triGroups.size()); for (uint32_t i = 0; i < triGroups.size(); i++) { const auto tris = triGroups[i]; dstIndices[i].reserve(tris.size() * 3); for (uint32_t n = 0; n < tris.size(); n++) { const auto tri = tris[n]; for (int t = 0; t < 3; t++) { uint32_t idx = tri->param.idx[t]; auto sortedIdx = sortedIndices[i][idx]; auto newIdx = qvtxs[i][sortedIdx].idx; dstIndices[i].push_back(newIdx); } } } } void LodMaker::removeCollapsedTriangles( std::vector<std::vector<int>>& dstIndices, const std::vector<aten::vertex>& vertices, const std::vector<std::vector<int>>& indices) { dstIndices.resize(indices.size()); for (int i = 0; i < indices.size(); i++) { const auto& idxs = indices[i]; for (int n = 0; n < idxs.size(); n += 3) { auto id0 = idxs[n + 0]; auto id1 = idxs[n + 1]; auto id2 = idxs[n + 2]; const auto& v0 = vertices[id0]; const auto& v1 = vertices[id1]; const auto& v2 = vertices[id2]; // Op`̖ʐ = Qӂ̊Oς̒ / 2; auto e0 = v1.pos - v0.pos; auto e1 = v2.pos - v0.pos; auto area = real(0.5) * cross(e0, e1).length(); if (area > real(0)) { dstIndices[i].push_back(id0); dstIndices[i].push_back(id1); dstIndices[i].push_back(id2); } } } }<commit_msg>Modify to compute lod vertex.<commit_after>#include "lodmaker.h" struct QVertex { aten::vertex v; uint32_t idx; uint32_t grid[3]; uint64_t hash; QVertex() {} QVertex( aten::vertex _v, uint32_t i, uint64_t h, uint32_t gx, uint32_t gy, uint32_t gz) : v(_v), idx(i), hash(h) { grid[0] = gx; grid[1] = gy; grid[2] = gz; } const QVertex& operator=(const QVertex& rhs) { v = rhs.v; idx = rhs.idx; grid[0] = rhs.grid[0]; grid[1] = rhs.grid[1]; grid[2] = rhs.grid[2]; hash = rhs.hash; return *this; } }; // NOTE // gridX * gridY * gridZ uint64_t 𒴂Ȃ悤ɂ using qit = std::vector<QVertex>::iterator; static void computeAverage(qit start, qit end) { aten::vec4 pos(start->v.pos); aten::vec3 nml(start->v.nml); aten::vec3 uv(start->v.uv); uint32_t cnt = 1; for (auto q = start + 1; q != end; q++) { pos += q->v.pos; nml += q->v.nml; uv += q->v.uv; cnt++; } real div = real(1) / cnt; pos *= div; nml *= div; uv *= div; pos.w = real(1); nml = normalize(nml); // NOTE // z is used for checking to compute plane normal in real-time. uv.z = uv.z >= 0 ? 1 : 0; // vZʂ߂... for (auto q = start; q != end; q++) { q->v.pos = pos; q->v.nml = nml; q->v.uv = uv; } } static void computeClosestFromAvg(qit start, qit end) { aten::vec4 pos(start->v.pos); uint32_t cnt = 1; for (auto q = start + 1; q != end; q++) { pos += q->v.pos; cnt++; } real div = real(1) / cnt; pos *= div; real distMin = AT_MATH_INF; qit closest = start; for (auto q = start; q != end; q++) { auto d = (pos - q->v.pos).length(); if (d < distMin) { distMin = d; closest = q; } } // vZʂ߂... for (auto q = start; q != end; q++) { q->v = closest->v; } } void LodMaker::make( std::vector<aten::vertex>& dstVertices, std::vector<std::vector<int>>& dstIndices, const aten::aabb& bound, const std::vector<aten::vertex>& vertices, const std::vector<std::vector<aten::face*>>& triGroups, int gridX, int gridY, int gridZ) { auto bmin = bound.minPos(); auto range = bound.size(); aten::vec3 scale( (gridX - 1) / range.x, (gridY - 1) / range.y, (gridZ - 1) / range.z); std::vector<std::vector<QVertex>> qvtxs(triGroups.size()); std::vector<std::vector<uint32_t>> sortedIndices(triGroups.size()); for (uint32_t i = 0; i < triGroups.size(); i++) { const auto tris = triGroups[i]; qvtxs[i].reserve(tris.size()); for (uint32_t n = 0; n < tris.size(); n++) { const auto tri = tris[n]; for (int t = 0; t < 3; t++) { uint32_t idx = tri->param.idx[t]; const auto& v = vertices[idx]; auto grid = ((aten::vec3)v.pos - bmin) * scale + real(0.5); uint32_t gx = (uint32_t)grid.x; uint32_t gy = (uint32_t)grid.y; uint32_t gz = (uint32_t)grid.z; uint64_t hash = gz * (gridX * gridY) + gy * gridX + gx; qvtxs[i].push_back(QVertex(v, idx, hash, gx, gy, gz)); } } } // ObhɓĂ钸_̏ɂȂ悤Ƀ\[g. for (uint32_t i = 0; i < qvtxs.size(); i++) { std::sort( qvtxs[i].begin(), qvtxs[i].end(), [](const QVertex& q0, const QVertex& q1) { return q0.hash > q1.hash; }); uint32_t num = (uint32_t)qvtxs[i].size(); sortedIndices[i].resize(num); // CfbNX_ɂ킹ĕבւ. for (uint32_t n = 0; n < num; n++) { const auto& q = qvtxs[i][n]; // X̃CfbNẌʒuɐVCfbNXl. sortedIndices[i][q.idx] = n; } } // ObhɓĂ钸_̕ϒlvZāAP‚̒_ɂĂ܂. // UV͕邪AFZJ_oEXɎĝŁA͋CɂȂ. for (uint32_t i = 0; i < qvtxs.size(); i++) { auto start = qvtxs[i].begin(); while (start != qvtxs[i].end()) { auto end = start; // ObhقȂ钸_ɂȂ܂ŒT. while (end != qvtxs[i].end() && start->hash == end->hash) { end++; } // TODO // όvZ. //computeAverage(start, end); computeClosestFromAvg(start, end); for (auto q = start; q != end; q++) { if (q == start) { dstVertices.push_back(q->v); } else { // قȂʒu̓_̏ꍇ. // O̓_Ɣr. auto prev = q - 1; auto v0 = q->v.pos; auto v1 = prev->v.pos; bool isEqual = (memcmp(&v0, &v1, sizeof(v0)) == 0); if (!isEqual) { dstVertices.push_back(q->v); } } // CfbNXXV. q->idx = (uint32_t)dstVertices.size() - 1; } // ̊JnʒuXV start = end; } } // LODꂽʂ̃CfbNXi[. dstIndices.resize(triGroups.size()); for (uint32_t i = 0; i < triGroups.size(); i++) { const auto tris = triGroups[i]; dstIndices[i].reserve(tris.size() * 3); for (uint32_t n = 0; n < tris.size(); n++) { const auto tri = tris[n]; for (int t = 0; t < 3; t++) { uint32_t idx = tri->param.idx[t]; auto sortedIdx = sortedIndices[i][idx]; auto newIdx = qvtxs[i][sortedIdx].idx; dstIndices[i].push_back(newIdx); } } } } void LodMaker::removeCollapsedTriangles( std::vector<std::vector<int>>& dstIndices, const std::vector<aten::vertex>& vertices, const std::vector<std::vector<int>>& indices) { dstIndices.resize(indices.size()); for (int i = 0; i < indices.size(); i++) { const auto& idxs = indices[i]; for (int n = 0; n < idxs.size(); n += 3) { auto id0 = idxs[n + 0]; auto id1 = idxs[n + 1]; auto id2 = idxs[n + 2]; const auto& v0 = vertices[id0]; const auto& v1 = vertices[id1]; const auto& v2 = vertices[id2]; // Op`̖ʐ = Qӂ̊Oς̒ / 2; auto e0 = v1.pos - v0.pos; auto e1 = v2.pos - v0.pos; auto area = real(0.5) * cross(e0, e1).length(); if (area > real(0)) { dstIndices[i].push_back(id0); dstIndices[i].push_back(id1); dstIndices[i].push_back(id2); } } } }<|endoftext|>
<commit_before>/* Copyright (c) 2010-2012 Stanford University * * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 "TestUtil.h" #include "LogCabinHelper.h" #include "MockCluster.h" namespace RAMCloud { class LogCabinHelperTest : public ::testing::Test { public: Context context; MockCluster cluster; LogCabinHelper* logCabinHelper; LogCabin::Client::Log* logCabinLog; LogCabinHelperTest() : context() , cluster(&context) , logCabinHelper() , logCabinLog() { Logger::get().setLogLevels(RAMCloud::SILENT_LOG_LEVEL); logCabinHelper = cluster.coordinator.get()->logCabinHelper.get(); logCabinLog = cluster.coordinator.get()->logCabinLog.get(); } ~LogCabinHelperTest() { } DISALLOW_COPY_AND_ASSIGN(LogCabinHelperTest); }; TEST_F(LogCabinHelperTest, appendProtoBuf_and_parseProtoBufFromEntry) { ProtoBuf::EntryType entry0; entry0.set_entry_type("DummyEntry0"); EntryId entryId0 = logCabinHelper->appendProtoBuf(entry0); EXPECT_EQ(0U, entryId0); ProtoBuf::EntryType entry1; entry1.set_entry_type("DummyEntry1"); EntryId entryId1 = logCabinHelper->appendProtoBuf(entry1, vector<EntryId>({entryId0})); EXPECT_EQ(1U, entryId1); vector<Entry> allEntries = logCabinLog->read(0); ProtoBuf::EntryType entry0ProtoBuf; logCabinHelper->parseProtoBufFromEntry(allEntries[0], entry0ProtoBuf); EXPECT_EQ("entry_type: \"DummyEntry0\"\n", entry0ProtoBuf.DebugString()); ProtoBuf::EntryType entry1ProtoBuf; logCabinHelper->parseProtoBufFromEntry(allEntries[1], entry1ProtoBuf); EXPECT_EQ("entry_type: \"DummyEntry1\"\n", entry1ProtoBuf.DebugString()); vector<EntryId> invalidates1 = allEntries[1].getInvalidates(); EXPECT_FALSE(invalidates1.empty()); } TEST_F(LogCabinHelperTest, getEntryType) { ProtoBuf::EntryType entry0; entry0.set_entry_type("DummyEntry0"); logCabinHelper->appendProtoBuf(entry0); vector<Entry> allEntries = logCabinLog->read(0); string entryType = logCabinHelper->getEntryType(allEntries[0]); EXPECT_EQ("DummyEntry0", entryType); } TEST_F(LogCabinHelperTest, readValidEntries) { ProtoBuf::EntryType entry0; entry0.set_entry_type("DummyEntry0"); EntryId entryId0 = logCabinHelper->appendProtoBuf(entry0); ProtoBuf::EntryType entry1; entry1.set_entry_type("DummyEntry1"); logCabinHelper->appendProtoBuf(entry1); ProtoBuf::EntryType entry2; entry2.set_entry_type("DummyEntry2"); logCabinHelper->appendProtoBuf(entry2, vector<EntryId>({entryId0})); vector<Entry> validEntries = logCabinHelper->readValidEntries(); string check = ""; for (vector<Entry>::iterator it = validEntries.begin(); it < validEntries.end(); it++) { string entryType = logCabinHelper->getEntryType(*it); check = format("%sEntryType: %s | ", check.c_str(), entryType.c_str()); } EXPECT_EQ("EntryType: DummyEntry1 | EntryType: DummyEntry2 | ", check); } } // namespace RAMCloud <commit_msg>Added more test cases to LogCabinHelper unit tests.<commit_after>/* Copyright (c) 2010-2012 Stanford University * * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 "TestUtil.h" #include "LogCabinHelper.h" #include "MockCluster.h" namespace RAMCloud { class LogCabinHelperTest : public ::testing::Test { public: Context context; MockCluster cluster; LogCabinHelper* logCabinHelper; LogCabin::Client::Log* logCabinLog; LogCabinHelperTest() : context() , cluster(&context) , logCabinHelper() , logCabinLog() { Logger::get().setLogLevels(RAMCloud::SILENT_LOG_LEVEL); logCabinHelper = cluster.coordinator.get()->logCabinHelper.get(); logCabinLog = cluster.coordinator.get()->logCabinLog.get(); } ~LogCabinHelperTest() { } DISALLOW_COPY_AND_ASSIGN(LogCabinHelperTest); }; TEST_F(LogCabinHelperTest, appendProtoBuf_and_parseProtoBufFromEntry) { ProtoBuf::EntryType entry0; entry0.set_entry_type("DummyEntry0"); EntryId entryId0 = logCabinHelper->appendProtoBuf(entry0); EXPECT_EQ(0U, entryId0); ProtoBuf::EntryType entry1; entry1.set_entry_type("DummyEntry1"); EntryId entryId1 = logCabinHelper->appendProtoBuf(entry1, vector<EntryId>({entryId0})); EXPECT_EQ(1U, entryId1); vector<Entry> allEntries = logCabinLog->read(0); ProtoBuf::EntryType entry0ProtoBuf; logCabinHelper->parseProtoBufFromEntry(allEntries[0], entry0ProtoBuf); EXPECT_EQ("entry_type: \"DummyEntry0\"\n", entry0ProtoBuf.DebugString()); ProtoBuf::EntryType entry1ProtoBuf; logCabinHelper->parseProtoBufFromEntry(allEntries[1], entry1ProtoBuf); EXPECT_EQ("entry_type: \"DummyEntry1\"\n", entry1ProtoBuf.DebugString()); vector<EntryId> invalidates1 = allEntries[1].getInvalidates(); EXPECT_FALSE(invalidates1.empty()); } TEST_F(LogCabinHelperTest, getEntryType) { ProtoBuf::EntryType entry0; entry0.set_entry_type("DummyEntry0"); logCabinHelper->appendProtoBuf(entry0); vector<Entry> allEntries = logCabinLog->read(0); string entryType = logCabinHelper->getEntryType(allEntries[0]); EXPECT_EQ("DummyEntry0", entryType); } TEST_F(LogCabinHelperTest, readValidEntries) { ProtoBuf::EntryType entry0, entry1, entry2, entry3, entry4, entry5; entry0.set_entry_type("DummyEntry0"); EntryId entryId0 = logCabinHelper->appendProtoBuf(entry0); entry1.set_entry_type("DummyEntry1"); logCabinHelper->appendProtoBuf(entry1); entry2.set_entry_type("DummyEntry2"); vector<EntryId> invalidates2 = {entryId0}; EntryId entryId2 = logCabinHelper->appendProtoBuf(entry2, invalidates2); entry3.set_entry_type("DummyEntry3"); logCabinHelper->appendProtoBuf(entry3); entry4.set_entry_type("DummyEntry4"); EntryId entryId4 = logCabinHelper->appendProtoBuf(entry4); entry5.set_entry_type("DummyEntry5"); vector<EntryId> invalidates5 {entryId2, entryId4}; logCabinHelper->appendProtoBuf(entry5, invalidates5); vector<Entry> validEntries = logCabinHelper->readValidEntries(); string check = ""; for (vector<Entry>::iterator it = validEntries.begin(); it < validEntries.end(); it++) { string entryType = logCabinHelper->getEntryType(*it); check = format("%sEntryType: %s | ", check.c_str(), entryType.c_str()); } EXPECT_EQ("EntryType: DummyEntry1 | " "EntryType: DummyEntry3 | " "EntryType: DummyEntry5 | ", check); } } // namespace RAMCloud <|endoftext|>
<commit_before>#include "crc32.h" /* Crc - 32 BIT ANSI X3.66 CRC checksum files */ #include <stdio.h> /**********************************************************************\ |* Demonstration program to compute the 32-bit CRC used as the frame *| |* check sequence in ADCCP (ANSI X3.66, also known as FIPS PUB 71 *| |* and FED-STD-1003, the U.S. versions of CCITT's X.25 link-level *| |* protocol). The 32-bit FCS was added via the Federal Register, *| |* 1 June 1982, p.23798. I presume but don't know for certain that *| |* this polynomial is or will be included in CCITT V.41, which *| |* defines the 16-bit CRC (often called CRC-CCITT) polynomial. FIPS *| |* PUB 78 says that the 32-bit FCS reduces otherwise undetected *| |* errors by a factor of 10^-5 over 16-bit FCS. *| \**********************************************************************/ /* Need an unsigned type capable of holding 32 bits; */ /* Copyright (C) 1986 Gary S. Brown. You may use this program, or code or tables extracted from it, as desired without restriction.*/ /* First, the polynomial itself and its table of feedback terms. The */ /* polynomial is */ /* X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 */ /* Note that we take it "backwards" and put the highest-order term in */ /* the lowest-order bit. The X^32 term is "implied"; the LSB is the */ /* X^31 term, etc. The X^0 term (usually shown as "+1") results in */ /* the MSB being 1. */ /* Note that the usual hardware shift register implementation, which */ /* is what we're using (we're merely optimizing it by doing eight-bit */ /* chunks at a time) shifts bits into the lowest-order term. In our */ /* implementation, that means shifting towards the right. Why do we */ /* do it this way? Because the calculated CRC must be transmitted in */ /* order from highest-order term to lowest-order term. UARTs transmit */ /* characters in order from LSB to MSB. By storing the CRC this way, */ /* we hand it to the UART in the order low-byte to high-byte; the UART */ /* sends each low-bit to hight-bit; and the result is transmission bit */ /* by bit from highest- to lowest-order term without requiring any bit */ /* shuffling on our part. Reception works similarly. */ /* The feedback terms table consists of 256, 32-bit entries. Notes: */ /* */ /* 1. The table can be generated at runtime if desired; code to do so */ /* is shown later. It might not be obvious, but the feedback */ /* terms simply represent the results of eight shift/xor opera- */ /* tions for all combinations of data and CRC register values. */ /* */ /* 2. The CRC accumulation logic is the same for all CRC polynomials, */ /* be they sixteen or thirty-two bits wide. You simply choose the */ /* appropriate table. Alternatively, because the table can be */ /* generated at runtime, you can start by generating the table for */ /* the polynomial in question and use exactly the same "updcrc", */ /* if your application needn't simultaneously handle two CRC */ /* polynomials. (Note, however, that XMODEM is strange.) */ /* */ /* 3. For 16-bit CRCs, the table entries need be only 16 bits wide; */ /* of course, 32-bit entries work OK if the high 16 bits are zero. */ /* */ /* 4. The values must be right-shifted by eight bits by the "updcrc" */ /* logic; the shift must be unsigned (bring in zeroes). On some */ /* hardware you could probably optimize the shift in assembler by */ /* using byte-swap instructions. */ static quint32 crc_32_tab[] = { /* CRC polynomial 0xedb88320 */ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; quint32 updateCRC32(char ch, quint32 crc) { //return UPDC32(ch, crc); return (crc_32_tab[((crc) ^ ((unsigned char)ch)) & 0xff] ^ ((crc) >> 8)); } quint32 crc32buf(const char *buf, size_t len) { register quint32 oldcrc32; oldcrc32 = 0xFFFFFFFF; for ( ; len; --len, ++buf) { oldcrc32 = UPDC32(*buf, oldcrc32); } return ~oldcrc32; } <commit_msg>Macro replaced with function<commit_after>#include "crc32.h" /* Crc - 32 BIT ANSI X3.66 CRC checksum files */ #include <stdio.h> /**********************************************************************\ |* Demonstration program to compute the 32-bit CRC used as the frame *| |* check sequence in ADCCP (ANSI X3.66, also known as FIPS PUB 71 *| |* and FED-STD-1003, the U.S. versions of CCITT's X.25 link-level *| |* protocol). The 32-bit FCS was added via the Federal Register, *| |* 1 June 1982, p.23798. I presume but don't know for certain that *| |* this polynomial is or will be included in CCITT V.41, which *| |* defines the 16-bit CRC (often called CRC-CCITT) polynomial. FIPS *| |* PUB 78 says that the 32-bit FCS reduces otherwise undetected *| |* errors by a factor of 10^-5 over 16-bit FCS. *| \**********************************************************************/ /* Need an unsigned type capable of holding 32 bits; */ /* Copyright (C) 1986 Gary S. Brown. You may use this program, or code or tables extracted from it, as desired without restriction.*/ /* First, the polynomial itself and its table of feedback terms. The */ /* polynomial is */ /* X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 */ /* Note that we take it "backwards" and put the highest-order term in */ /* the lowest-order bit. The X^32 term is "implied"; the LSB is the */ /* X^31 term, etc. The X^0 term (usually shown as "+1") results in */ /* the MSB being 1. */ /* Note that the usual hardware shift register implementation, which */ /* is what we're using (we're merely optimizing it by doing eight-bit */ /* chunks at a time) shifts bits into the lowest-order term. In our */ /* implementation, that means shifting towards the right. Why do we */ /* do it this way? Because the calculated CRC must be transmitted in */ /* order from highest-order term to lowest-order term. UARTs transmit */ /* characters in order from LSB to MSB. By storing the CRC this way, */ /* we hand it to the UART in the order low-byte to high-byte; the UART */ /* sends each low-bit to hight-bit; and the result is transmission bit */ /* by bit from highest- to lowest-order term without requiring any bit */ /* shuffling on our part. Reception works similarly. */ /* The feedback terms table consists of 256, 32-bit entries. Notes: */ /* */ /* 1. The table can be generated at runtime if desired; code to do so */ /* is shown later. It might not be obvious, but the feedback */ /* terms simply represent the results of eight shift/xor opera- */ /* tions for all combinations of data and CRC register values. */ /* */ /* 2. The CRC accumulation logic is the same for all CRC polynomials, */ /* be they sixteen or thirty-two bits wide. You simply choose the */ /* appropriate table. Alternatively, because the table can be */ /* generated at runtime, you can start by generating the table for */ /* the polynomial in question and use exactly the same "updcrc", */ /* if your application needn't simultaneously handle two CRC */ /* polynomials. (Note, however, that XMODEM is strange.) */ /* */ /* 3. For 16-bit CRCs, the table entries need be only 16 bits wide; */ /* of course, 32-bit entries work OK if the high 16 bits are zero. */ /* */ /* 4. The values must be right-shifted by eight bits by the "updcrc" */ /* logic; the shift must be unsigned (bring in zeroes). On some */ /* hardware you could probably optimize the shift in assembler by */ /* using byte-swap instructions. */ static quint32 crc_32_tab[] = { /* CRC polynomial 0xedb88320 */ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; quint32 updateCRC32(char ch, quint32 crc) { //return UPDC32(ch, crc); return (crc_32_tab[((crc) ^ ((unsigned char)ch)) & 0xff] ^ ((crc) >> 8)); } quint32 crc32buf(const char *buf, size_t len) { register quint32 oldcrc32; oldcrc32 = 0xFFFFFFFF; for ( ; len; --len, ++buf) { oldcrc32 = updateCRC32(*buf, oldcrc32); } return ~oldcrc32; } <|endoftext|>
<commit_before>// // Copyright (c) 2016 CNRS // Author: NMansard // // // This file is part of hpp-pinocchio // hpp-pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio If not, see // <http://www.gnu.org/licenses/>. #include <Eigen/Core> #include <hpp/pinocchio/fwd.hh> //#include <hpp/pinocchio/distance-result.hh> #include <hpp/pinocchio/extra-config-space.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/device.hh> #include <pinocchio/algorithm/center-of-mass.hpp> #include <pinocchio/algorithm/jacobian.hpp> #include <pinocchio/algorithm/kinematics.hpp> #include <pinocchio/algorithm/collisions.hpp> #include <boost/foreach.hpp> namespace hpp { namespace pinocchio { Device:: Device(const std::string& name) : model_() , data_ () , name_ (name) , jointVector_() , obstacles_() , weakPtr_() {} // static method DevicePtr_t Device:: create (const std::string & name) { DevicePtr_t res = DevicePtr_t(new Device(name)); // init shared ptr res->weakPtr_ = res; res->jointVector_ = JointVector(res); res->obstacles_ = ObjectVector(res,0,CollisionObject::INNER); return res; } // static method DevicePtr_t Device:: createCopy (const DevicePtr_t& device) { DevicePtr_t res = Device::create(device->name()); // init shared ptr res->model(device->model()); // Copy pointer to pinocchio model res->createData(); // Create a new data, dont copy the pointer. return res; } // static method DevicePtr_t Device:: createCopyConst (const DeviceConstPtr_t& device) { DevicePtr_t res = Device::create(device->name()); // init shared ptr /* The copy of Pinocchio::Model is not implemented yet. */ /* We need this feature to finish the implementation of this method. */ assert( false && "TODO: createCopyConst is not implemented yet." ); return res; } void Device:: createData() { data_ = DataPtr_t( new se3::Data(*model_) ); // We assume that model is now complete and state can be resized. resizeState(); } void Device:: createGeomData() { geomData_ = GeomDataPtr_t( new se3::GeometryData(*geomModel_) ); } /* ---------------------------------------------------------------------- */ /* --- JOINT ------------------------------------------------------------ */ /* ---------------------------------------------------------------------- */ JointPtr_t Device:: rootJoint () const { return JointPtr_t( new Joint(weakPtr_.lock(),1) ); } JointPtr_t Device:: getJointAtConfigRank (const size_type& r) const { assert(model_); //BOOST_FOREACH( const se3::JointModel & j, // Skip "universe" joint //std::make_pair(model_->joints.begin()+1,model_->joints.end()) ) BOOST_FOREACH( const se3::JointModel & j, model_->joints ) { if( j.id()==0 ) continue; // Skip "universe" joint if( j.idx_q() == r ) return JointPtr_t( new Joint(weakPtr_.lock(),j.id()) ); } assert(false && "The joint at config rank has not been found"); return JointPtr_t(); } JointPtr_t Device:: getJointAtVelocityRank (const size_type& r) const { assert(model_); BOOST_FOREACH( const se3::JointModel & j,model_->joints ) { if( j.id()==0 ) continue; // Skip "universe" joint if( j.idx_v() == r ) return JointPtr_t( new Joint(weakPtr_.lock(),j.id()) ); } assert(false && "The joint at velocity rank has not been found"); return JointPtr_t(); } JointPtr_t Device:: getJointByName (const std::string& name) const { assert(model_); if(! model_->existJointName(name)) throw std::runtime_error ("Device " + name_ + " does not have any joint named " + name); se3::Index id = model_->getJointId(name); return JointPtr_t( new Joint(weakPtr_.lock(),id) ); } JointPtr_t Device:: getJointByBodyName (const std::string& name) const { assert(model_); assert(model_->existFrame(name)); se3::Model::FrameIndex bodyId = model_->getFrameId(name); assert(model_->frames[bodyId].type == se3::BODY); se3::Model::JointIndex jointId = model_->frames[bodyId].parent; //assert(jointId>=0); assert((int)jointId<model_->njoint); return JointPtr_t( new Joint(weakPtr_.lock(),jointId) ); } size_type Device:: configSize () const { assert(model_); return model_->nq+extraConfigSpace_.dimension(); } size_type Device:: numberDof () const { assert(model_); return model_->nv; } /* ---------------------------------------------------------------------- */ /* --- CONFIG ----------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ /* Previous implementation of resizeState in hpp::model:: was setting the * new part of the configuration to neutral configuration. This is not * working but for empty extra-config. The former behavior is therefore not * propagated here. The configuration is resized without setting the new * memory. */ void Device:: resizeState() { currentConfiguration_.resize(configSize()); currentVelocity_.resize(numberDof()); currentAcceleration_.resize(numberDof()); } bool Device:: currentConfiguration (ConfigurationIn_t configuration) { if (configuration != currentConfiguration_) { upToDate_ = false; currentConfiguration_ = configuration; return true; } return false; } const value_type& Device:: mass () const { assert(data_); return data_->mass[0]; } vector3_t Device:: positionCenterOfMass () const { assert(data_); return data_->com[0]; } const ComJacobian_t& Device:: jacobianCenterOfMass () const { assert(data_); return data_->Jcom; } void Device:: computeForwardKinematics () { if(upToDate_) return; assert(model_); assert(data_); // a IMPLIES b === (b || ~a) // velocity IMPLIES position assert( (computationFlag_|JOINT_POSITION) || (!(computationFlag_|VELOCITY)) ); // acceleration IMPLIES velocity assert( (computationFlag_|VELOCITY) || (!(computationFlag_|ACCELERATION)) ); // com IMPLIES position assert( (computationFlag_|JOINT_POSITION) || (!(computationFlag_|COM)) ); // jacobian IMPLIES position assert( (computationFlag_|JOINT_POSITION) || (!(computationFlag_|JACOBIAN)) ); if (computationFlag_ | ACCELERATION ) se3::forwardKinematics(*model_,*data_,currentConfiguration_, currentVelocity_,currentAcceleration_); else if (computationFlag_ | VELOCITY ) se3::forwardKinematics(*model_,*data_,currentConfiguration_, currentVelocity_); else if (computationFlag_ | JOINT_POSITION ) se3::forwardKinematics(*model_,*data_,currentConfiguration_); if (computationFlag_|COM) { if (computationFlag_|JACOBIAN) // TODO: Jcom should not recompute the kinematics (\sa pinocchio issue #219) se3::jacobianCenterOfMass(*model_,*data_,currentConfiguration_,true); else se3::centerOfMass(*model_,*data_,currentConfiguration_,true,false); } if(computationFlag_|JACOBIAN) se3::computeJacobians(*model_,*data_,currentConfiguration_); } std::ostream& Device:: print (std::ostream& os) const { //NOTYET return os; } /* ---------------------------------------------------------------------- */ /* --- COLLISIONS ------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ bool Device::collisionTest (const bool stopAtFirstCollision) { /* Following hpp::model API, the forward kinematics (joint placement) is * supposed to have already been computed. */ se3::updateGeometryPlacements(*model(),*data(),*geomModel(),*geomData()); return se3::computeCollisions(*geomData(),stopAtFirstCollision); } void Device::computeDistances () { /* Following hpp::model API, the forward kinematics (joint placement) is * supposed to have already been computed. */ se3::updateGeometryPlacements(*model(),*data(),*geomModel(),*geomData()); se3::computeDistances (*geomData()); } const DistanceResults_t& Device::distanceResults () const { return geomData()->distance_results; } } // namespace pinocchio } // namespace hpp <commit_msg>Fix getJointAtConfigRank and getJointAtVelocityRank<commit_after>// // Copyright (c) 2016 CNRS // Author: NMansard // // // This file is part of hpp-pinocchio // hpp-pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio If not, see // <http://www.gnu.org/licenses/>. #include <Eigen/Core> #include <hpp/pinocchio/fwd.hh> //#include <hpp/pinocchio/distance-result.hh> #include <hpp/pinocchio/extra-config-space.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/device.hh> #include <pinocchio/algorithm/center-of-mass.hpp> #include <pinocchio/algorithm/jacobian.hpp> #include <pinocchio/algorithm/kinematics.hpp> #include <pinocchio/algorithm/collisions.hpp> #include <boost/foreach.hpp> namespace hpp { namespace pinocchio { Device:: Device(const std::string& name) : model_() , data_ () , name_ (name) , jointVector_() , obstacles_() , weakPtr_() {} // static method DevicePtr_t Device:: create (const std::string & name) { DevicePtr_t res = DevicePtr_t(new Device(name)); // init shared ptr res->weakPtr_ = res; res->jointVector_ = JointVector(res); res->obstacles_ = ObjectVector(res,0,CollisionObject::INNER); return res; } // static method DevicePtr_t Device:: createCopy (const DevicePtr_t& device) { DevicePtr_t res = Device::create(device->name()); // init shared ptr res->model(device->model()); // Copy pointer to pinocchio model res->createData(); // Create a new data, dont copy the pointer. return res; } // static method DevicePtr_t Device:: createCopyConst (const DeviceConstPtr_t& device) { DevicePtr_t res = Device::create(device->name()); // init shared ptr /* The copy of Pinocchio::Model is not implemented yet. */ /* We need this feature to finish the implementation of this method. */ assert( false && "TODO: createCopyConst is not implemented yet." ); return res; } void Device:: createData() { data_ = DataPtr_t( new se3::Data(*model_) ); // We assume that model is now complete and state can be resized. resizeState(); } void Device:: createGeomData() { geomData_ = GeomDataPtr_t( new se3::GeometryData(*geomModel_) ); } /* ---------------------------------------------------------------------- */ /* --- JOINT ------------------------------------------------------------ */ /* ---------------------------------------------------------------------- */ JointPtr_t Device:: rootJoint () const { return JointPtr_t( new Joint(weakPtr_.lock(),1) ); } JointPtr_t Device:: getJointAtConfigRank (const size_type& r) const { assert(model_); //BOOST_FOREACH( const se3::JointModel & j, // Skip "universe" joint //std::make_pair(model_->joints.begin()+1,model_->joints.end()) ) BOOST_FOREACH( const se3::JointModel & j, model_->joints ) { if( j.id()==0 ) continue; // Skip "universe" joint const size_type iq = j.idx_q() - r; if( 0 <= iq && iq < j.nq() ) return JointPtr_t( new Joint(weakPtr_,j.id()) ); } assert(false && "The joint at config rank has not been found"); return JointPtr_t(); } JointPtr_t Device:: getJointAtVelocityRank (const size_type& r) const { assert(model_); BOOST_FOREACH( const se3::JointModel & j,model_->joints ) { if( j.id()==0 ) continue; // Skip "universe" joint const size_type iv = j.idx_v() - r; if( 0 <= iv && iv < j.nv() ) return JointPtr_t( new Joint(weakPtr_,j.id()) ); } assert(false && "The joint at velocity rank has not been found"); return JointPtr_t(); } JointPtr_t Device:: getJointByName (const std::string& name) const { assert(model_); if(! model_->existJointName(name)) throw std::runtime_error ("Device " + name_ + " does not have any joint named " + name); se3::Index id = model_->getJointId(name); return JointPtr_t( new Joint(weakPtr_.lock(),id) ); } JointPtr_t Device:: getJointByBodyName (const std::string& name) const { assert(model_); assert(model_->existFrame(name)); se3::Model::FrameIndex bodyId = model_->getFrameId(name); assert(model_->frames[bodyId].type == se3::BODY); se3::Model::JointIndex jointId = model_->frames[bodyId].parent; //assert(jointId>=0); assert((int)jointId<model_->njoint); return JointPtr_t( new Joint(weakPtr_.lock(),jointId) ); } size_type Device:: configSize () const { assert(model_); return model_->nq+extraConfigSpace_.dimension(); } size_type Device:: numberDof () const { assert(model_); return model_->nv; } /* ---------------------------------------------------------------------- */ /* --- CONFIG ----------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ /* Previous implementation of resizeState in hpp::model:: was setting the * new part of the configuration to neutral configuration. This is not * working but for empty extra-config. The former behavior is therefore not * propagated here. The configuration is resized without setting the new * memory. */ void Device:: resizeState() { currentConfiguration_.resize(configSize()); currentVelocity_.resize(numberDof()); currentAcceleration_.resize(numberDof()); } bool Device:: currentConfiguration (ConfigurationIn_t configuration) { if (configuration != currentConfiguration_) { upToDate_ = false; currentConfiguration_ = configuration; return true; } return false; } const value_type& Device:: mass () const { assert(data_); return data_->mass[0]; } vector3_t Device:: positionCenterOfMass () const { assert(data_); return data_->com[0]; } const ComJacobian_t& Device:: jacobianCenterOfMass () const { assert(data_); return data_->Jcom; } void Device:: computeForwardKinematics () { if(upToDate_) return; assert(model_); assert(data_); // a IMPLIES b === (b || ~a) // velocity IMPLIES position assert( (computationFlag_|JOINT_POSITION) || (!(computationFlag_|VELOCITY)) ); // acceleration IMPLIES velocity assert( (computationFlag_|VELOCITY) || (!(computationFlag_|ACCELERATION)) ); // com IMPLIES position assert( (computationFlag_|JOINT_POSITION) || (!(computationFlag_|COM)) ); // jacobian IMPLIES position assert( (computationFlag_|JOINT_POSITION) || (!(computationFlag_|JACOBIAN)) ); if (computationFlag_ | ACCELERATION ) se3::forwardKinematics(*model_,*data_,currentConfiguration_, currentVelocity_,currentAcceleration_); else if (computationFlag_ | VELOCITY ) se3::forwardKinematics(*model_,*data_,currentConfiguration_, currentVelocity_); else if (computationFlag_ | JOINT_POSITION ) se3::forwardKinematics(*model_,*data_,currentConfiguration_); if (computationFlag_|COM) { if (computationFlag_|JACOBIAN) // TODO: Jcom should not recompute the kinematics (\sa pinocchio issue #219) se3::jacobianCenterOfMass(*model_,*data_,currentConfiguration_,true); else se3::centerOfMass(*model_,*data_,currentConfiguration_,true,false); } if(computationFlag_|JACOBIAN) se3::computeJacobians(*model_,*data_,currentConfiguration_); } std::ostream& Device:: print (std::ostream& os) const { //NOTYET return os; } /* ---------------------------------------------------------------------- */ /* --- COLLISIONS ------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ bool Device::collisionTest (const bool stopAtFirstCollision) { /* Following hpp::model API, the forward kinematics (joint placement) is * supposed to have already been computed. */ se3::updateGeometryPlacements(*model(),*data(),*geomModel(),*geomData()); return se3::computeCollisions(*geomData(),stopAtFirstCollision); } void Device::computeDistances () { /* Following hpp::model API, the forward kinematics (joint placement) is * supposed to have already been computed. */ se3::updateGeometryPlacements(*model(),*data(),*geomModel(),*geomData()); se3::computeDistances (*geomData()); } const DistanceResults_t& Device::distanceResults () const { return geomData()->distance_results; } } // namespace pinocchio } // namespace hpp <|endoftext|>
<commit_before>#ifndef _SMRH_ #define _SMRH_ #include <list> #include <vector> #include <algorithm> #include <atomic> #include <boost/thread/tss.hpp> namespace DNFC { template <typename T> class HazardPointer { public: void subscribe() { // First try to reuse a retire HP record boost::thread_specific_ptr<HazardPointerRecord> &myhp = get_myhp(); bool expected = false; for (HazardPointerRecord *i = this->head.load(std::memory_order_relaxed); i; i = i->next) { if (i->active.load(std::memory_order_relaxed) || !i->active.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) continue; // Sucessfully locked one record to use myhp.reset(i); return; } // No HP records available for reuse so we add new ones this->nbhp.fetch_add(this->nbpointers, std::memory_order_relaxed); // Allocate and push a new record myhp.reset(new HazardPointerRecord()); myhp->hp = new std::atomic<T *>[this->nbpointers]; myhp->next = this->head.load(std::memory_order_relaxed); myhp->active.store(true, std::memory_order_relaxed); // Add the new record to the list while (!this->head.compare_exchange_weak(myhp->next, myhp.get(), std::memory_order_release, std::memory_order_relaxed)) ; } void unsubscribe() { boost::thread_specific_ptr<HazardPointerRecord> &myhp = get_myhp(); if (!myhp.get()) return; // Clear hp for (int i = 0; i < this->nbpointers; i++) myhp->hp[i].store(nullptr, std::memory_order_relaxed); myhp->active.store(false, std::memory_order_relaxed); myhp.release(); } T *load(const int &index) { boost::thread_specific_ptr<HazardPointerRecord> &myhp = get_myhp(); if (!myhp.get() || index >= this->nbpointers) return NULL; return myhp->hp[index].load(std::memory_order_relaxed); } void store(const int &index, T *value) { boost::thread_specific_ptr<HazardPointerRecord> &myhp = get_myhp(); if (!myhp.get() || index >= this->nbpointers) return; myhp->hp[index].store(value, std::memory_order_relaxed); } void delete_node(T *node) { boost::thread_specific_ptr<HazardPointerRecord> &myhp = get_myhp(); if (!myhp.get()) return; myhp->rlist.push_front(node); if (myhp->rlist.size() >= this->get_batch_size()) { this->scan(); this->help_scan(); } } HazardPointer(int a) : head(nullptr), nbhp(0), nbpointers(a){}; ~HazardPointer(){}; private: struct HazardPointerRecord { std::atomic<T *> *hp; std::list<T *> rlist; std::atomic<bool> active; HazardPointerRecord *next; }; std::atomic<HazardPointerRecord *> head; std::atomic<int> nbhp; int nbpointers; static inline boost::thread_specific_ptr<HazardPointerRecord> &get_myhp() { static boost::thread_specific_ptr<HazardPointerRecord> myhp; return myhp; } unsigned int get_batch_size() { return (this->nbhp.load(std::memory_order_relaxed) * this->nbpointers * 2) + this->nbhp.load(std::memory_order_relaxed); } void scan() { // Stage 1 boost::thread_specific_ptr<HazardPointerRecord> &myhp = get_myhp(); std::vector<T *> plist; for (HazardPointerRecord *i = this->head.load(std::memory_order_relaxed); i; i = i->next) { for (int j = 0; j < this->nbpointers; j++) { T *hp = i->hp[j].load(std::memory_order_relaxed); if (hp) plist.push_back(hp); } } if (plist.size() <= 0) return; // Stage 2 std::sort(plist.begin(), plist.end()); std::list<T *> localRList = myhp->rlist; myhp->rlist.clear(); // Stage 3 for (T *e : localRList) { if (std::binary_search(plist.begin(), plist.end(), e)) myhp->rlist.push_front(e); else delete e; } } void help_scan() { boost::thread_specific_ptr<HazardPointerRecord> &myhp = get_myhp(); bool expected = false; for (HazardPointerRecord *i = this->head.load(std::memory_order_relaxed); i; i = i->next) { // Trying to lock the next non-used hazard pointer record if (i->active.load(std::memory_order_relaxed) || !i->active.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) continue; // Inserting the rlist of the node in myhp for (T *e : i->rlist) { myhp->rlist.push_front(e); // scan if we reached the threshold if (myhp->rlist.size() >= this->get_batch_size()) this->scan(); } // Release the record i->rlist.clear(); i->active.store(false, std::memory_order_relaxed); } } }; } // namespace DNFC #endif <commit_msg>[WIP] hazardpointer: improvement and robustness in progress<commit_after>#ifndef _SMRH_ #define _SMRH_ #include <list> #include <vector> #include <algorithm> #include <atomic> #include <boost/thread/tss.hpp> namespace DNFC { typedef void *data_pointer; template <std::size_t NbPtr> class HazardPointer { public: static constexpr const std::size_t capacity = NbPtr; std::atomic<data_pointer> &operator[](std::size_t index) { boost::thread_specific_ptr<HazardPointerRecord> &myhp = getMyhp(); assert(index >= myhp->hp.size()); return myhp->hp[index]; } template <typename T> void deleteNode(T &&node) { boost::thread_specific_ptr<HazardPointerRecord> &myhp = getMyhp(); if (!myhp.get()) return; myhp->rlist.push_front(std::forward(node)); if (myhp->rlist.size() >= getBatchSize()) { scan(); help_scan(); } } HazardPointer() { getManager()->subscribe(); }; ~HazardPointer() { getManager()->unsubscribe(); }; private: static inline boost::thread_specific_ptr<HazardPointerRecord> &getMyhp() { static boost::thread_specific_ptr<HazardPointerRecord> myhp; return myhp; } static HazardPointerManager &getManager() { static HazardPointerManager m; return m; } class HazardPointerManager { public: // Does not allow to copy or move the manager HazardPointerManager &operator=(HazardPointerManager &&) = delete; HazardPointerManager &operator=(const HazardPointerManager &) = delete; // Does not allow to copy construct or move construct the manager HazardPointerManager(const HazardPointerManager &) = delete; HazardPointerManager(HazardPointerManager &&) = delete; HazardPointerManager() : nbhp(0){}; ~HazardPointerManager(){}; static void subscribe() { // First try to reuse a retire HP record boost::thread_specific_ptr<HazardPointerRecord> &myhp = getMyhp(); bool expected = false; for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i; i = i->next) { if (i->active.load(std::memory_order_relaxed) || !i->active.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) continue; // Sucessfully locked one record to use myhp.reset(i); return; } // No HP records available for reuse so we add new ones nbhp.fetch_add(nbPointers, std::memory_order_relaxed); // Allocate and push a new record myhp.reset(new HazardPointerRecord( head.load(std::memory_order_relaxed), true)); // Add the new record to the list while (!head.compare_exchange_weak(myhp->next, myhp.get(), std::memory_order_release, std::memory_order_relaxed)) ; } static void unsubscribe() { boost::thread_specific_ptr<HazardPointerRecord> &myhp = getMyhp(); if (!myhp.get()) return; // Clear hp for (int i = 0; i < nbPointers; i++) myhp->hp[i].store(nullptr, atomics::memory_order_release); myhp->active.store(false, std::memory_order_relaxed); myhp.release(); } private: std::atomic<HazardPointerRecord *> head; std::atomic<int> nbhp; // Class that actually represent a Hazard Pointer class HazardPointerRecord { std::atomic<data_pointer> *hp; std::list<data_pointer> rlist; std::atomic<bool> active; HazardPointerRecord *next; std::atomic<data_pointer> &operator[](std::size_t index) { assert(index >= NbPointers); return hp[index]; } HazardPointerRecord &operator=(HazardPointerRecord &&other) = delete; HazardPointerRecord &operator=(const HazardPointerRecord &) = delete; HazardPointerRecord(const HazardPointerRecord &head, const bool active) : next(head) { active.store(active, std::memory_order_relaxed); } ~HazardPointerRecord(){}; }; unsigned int getBatchSize() { return (nbhp.load(std::memory_order_relaxed) * nbPointers * 2) + nbhp.load(std::memory_order_relaxed); } void scan() { // Stage 1 boost::thread_specific_ptr<HazardPointerRecord> &myhp = getMyhp(); std::vector<data_pointer> plist; for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i; i = i->next) { for (int j = 0; j < nbPointers; j++) { T hp = i->hp[j].load(std::memory_order_relaxed); if (hp.get()) plist.push_back(hp); } } if (plist.size() <= 0) return; // Stage 2 std::sort(plist.begin(), plist.end()); std::list<data_pointer> localRList = myhp->rlist; myhp->rlist.clear(); // Stage 3 for (auto &&e : localRList) { if (std::binary_search(plist.begin(), plist.end(), e)) myhp->rlist.push_front(e); else delete e; } } void help_scan() { boost::thread_specific_ptr<HazardPointerRecord> &myhp = getMyhp(); bool expected = false; for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i; i = i->next) { // Trying to lock the next non-used hazard pointer record if (i->active.load(std::memory_order_relaxed) || !i->active.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) continue; // Inserting the rlist of the node in myhp for (auto &&e : i->rlist) { myhp->rlist.push_front(e); // scan if we reached the threshold if (myhp->rlist.size() >= getBatchSize()) scan(); } // Release the record i->rlist.clear(); i->active.store(false, std::memory_order_relaxed); } } }; }; } // namespace DNFC #endif <|endoftext|>
<commit_before>/* * Copyright 2017 deepstreamHub GmbH * * 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 <cstdio> #include <algorithm> #include <stdexcept> #include <deepstream/buffer.hpp> #include <deepstream/event.hpp> #include <deepstream/message_builder.hpp> #include <cassert> namespace deepstream { Event::Event(const SendFn& send) : send_(send) { assert( send_ ); } void Event::emit(const Name& name, const Buffer& buffer) { if( name.empty() ) throw std::invalid_argument( "Empty event name" ); MessageBuilder evt(Topic::EVENT, Action::EVENT); evt.add_argument(name); evt.add_argument(buffer); if( !send_(evt) ) return; notify_(evt); } Event::SubscribeFnPtr Event::subscribe(const Name& name, const SubscribeFn& f) { SubscribeFnPtr p_f( new SubscribeFn(f) ); subscribe(name, p_f); return p_f; } void Event::subscribe(const Name& name, const SubscribeFnPtr& p_f) { if( name.empty() ) throw std::invalid_argument( "Empty event subscription pattern" ); if( !p_f ) throw std::invalid_argument( "Subscribe function pointer is NULL" ); auto ret = subscriber_map_.equal_range(name); SubscriberMap::iterator first = ret.first; SubscriberMap::iterator last = ret.second; if( first != last ) { assert( first != subscriber_map_.end() ); assert( first->first == name ); assert( std::distance(first, last) == 1 ); // avoid inserting duplicates SubscriberList& subscribers = first->second; assert( !subscribers.empty() ); SubscriberList::const_iterator it = std::find( subscribers.cbegin(), subscribers.cend(), p_f ); if( it == subscribers.cend() ) subscribers.push_back(p_f); return; } subscriber_map_[name].push_back(p_f); MessageBuilder message(Topic::EVENT, Action::SUBSCRIBE); message.add_argument( name ); send_(message); } void Event::unsubscribe(const Name& name) { SubscriberMap::iterator it = subscriber_map_.find(name); if( it == subscriber_map_.end() ) return; subscriber_map_.erase(it); MessageBuilder message(Topic::EVENT, Action::UNSUBSCRIBE); message.add_argument(name); send_(message); } void Event::unsubscribe(const Name& name, const SubscribeFnPtr& p_f) { SubscriberMap::iterator it = subscriber_map_.find(name); if( it == subscriber_map_.end() ) return; SubscriberList& subscribers = it->second; SubscriberList::iterator ju = std::find( subscribers.begin(), subscribers.end(), p_f ); if( ju == subscribers.end() ) return; subscribers.erase(ju); if( subscribers.empty() ) unsubscribe(name); } Event::ListenFnPtr Event::listen(const Name& pattern, const ListenFn& f) { ListenFnPtr p_f( new ListenFn(f) ); listen(pattern, p_f); return p_f; } void Event::listen(const Name& pattern, const ListenFnPtr& p_f) { if( pattern.empty() ) throw std::invalid_argument( "Cannot listen for empty patterns" ); if( !p_f ) throw std::invalid_argument( "Listen function pointer is NULL" ); ListenerMap::iterator it = listener_map_.find(pattern); if( it != listener_map_.end() ) return; listener_map_[pattern] = p_f; MessageBuilder message(Topic::EVENT, Action::LISTEN); message.add_argument(pattern); send_(message); } void Event::unlisten(const Name& pattern) { ListenerMap::iterator it = listener_map_.find(pattern); if( it == listener_map_.end() ) return; listener_map_.erase(it); MessageBuilder message(Topic::EVENT, Action::UNLISTEN); message.add_argument(pattern); send_(message); } void Event::notify_(const Message& message) { assert( message.topic() == Topic::EVENT ); switch( message.action() ) { case Action::EVENT: notify_subscribers_(message); break; case Action::SUBSCRIPTION_FOR_PATTERN_FOUND: case Action::SUBSCRIPTION_FOR_PATTERN_REMOVED: assert( !message.is_ack() ); notify_listeners_(message); break; case Action::LISTEN: case Action::SUBSCRIBE: assert( message.is_ack() ); break; case Action::UNLISTEN: case Action::UNSUBSCRIBE: assert( message.is_ack() ); break; default: assert(0); } } void Event::notify_subscribers_(const Message& message) { assert( message.action() == Action::EVENT ); assert( message.num_arguments() == (message.is_ack() ? 1 : 2) ); if( message.is_ack() ) return; Name name = message[0]; const Buffer& data = message[1]; SubscriberMap::iterator it = subscriber_map_.find(name); if( it == subscriber_map_.end() ) { name.push_back(0); std::fprintf( stderr, "E|EVT: no subscriber named '%s'\n", name.data() ); return; } assert( it->first == name ); // Copying the list of subscribers is a necessity here because the callbacks // may unsubscribe during their execution and modifications of a subscriber // list may invalidate iterations and ranges. Also, copying the smart // pointer pointer here is a necessity because the referenced function may // decide to unsubscribe and in this case, the std::function object must not // be destructed. Copying ensures a non-zero reference count until `*p_f` // returns. // Finally, the iterator `it` may be invalid after executing a callback // because the list of subscribers for this `name` may have been erased. SubscriberList subscribers = it->second; it = subscriber_map_.end(); for(const SubscribeFnPtr& p_f : subscribers) { auto f = *p_f; f(data); } } void Event::notify_listeners_(const Message& message) { assert( message.action() == Action::SUBSCRIPTION_FOR_PATTERN_FOUND || message.action() == Action::SUBSCRIPTION_FOR_PATTERN_REMOVED ); assert( !message.is_ack() ); assert( message.num_arguments() == 2 ); const Name& pattern = message[0]; const Name& match = message[1]; bool is_subscribed = message.action() == Action::SUBSCRIPTION_FOR_PATTERN_FOUND; ListenerMap::iterator it = listener_map_.find(pattern); if( it == listener_map_.end() ) { Name pattern_str(pattern); pattern_str.push_back(0); std::fprintf( stderr, "%s: no listener for pattern '%s'\n", message.header().to_string(), pattern_str.data() ); return; } assert( it->first == pattern ); // copy the smart pointer (increase the reference count) because the // listener may decide to unlisten. ListenFnPtr p_f = it->second; auto f = *p_f; bool accept = f(pattern, is_subscribed, match); if( message.action() == Action::SUBSCRIPTION_FOR_PATTERN_REMOVED ) return; Action action = accept ? Action::LISTEN_ACCEPT : Action::LISTEN_REJECT; MessageBuilder el(Topic::EVENT, action); el.add_argument(pattern); el.add_argument(match); send_(el); } } <commit_msg>Events: avoid error messages when on `Event::emit`<commit_after>/* * Copyright 2017 deepstreamHub GmbH * * 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 <cstdio> #include <algorithm> #include <stdexcept> #include <deepstream/buffer.hpp> #include <deepstream/event.hpp> #include <deepstream/message_builder.hpp> #include <cassert> namespace deepstream { Event::Event(const SendFn& send) : send_(send) { assert( send_ ); } void Event::emit(const Name& name, const Buffer& buffer) { if( name.empty() ) throw std::invalid_argument( "Empty event name" ); MessageBuilder evt(Topic::EVENT, Action::EVENT); evt.add_argument(name); evt.add_argument(buffer); if( !send_(evt) ) return; if( subscriber_map_.find(name) == subscriber_map_.end() ) return; notify_(evt); } Event::SubscribeFnPtr Event::subscribe(const Name& name, const SubscribeFn& f) { SubscribeFnPtr p_f( new SubscribeFn(f) ); subscribe(name, p_f); return p_f; } void Event::subscribe(const Name& name, const SubscribeFnPtr& p_f) { if( name.empty() ) throw std::invalid_argument( "Empty event subscription pattern" ); if( !p_f ) throw std::invalid_argument( "Subscribe function pointer is NULL" ); auto ret = subscriber_map_.equal_range(name); SubscriberMap::iterator first = ret.first; SubscriberMap::iterator last = ret.second; if( first != last ) { assert( first != subscriber_map_.end() ); assert( first->first == name ); assert( std::distance(first, last) == 1 ); // avoid inserting duplicates SubscriberList& subscribers = first->second; assert( !subscribers.empty() ); SubscriberList::const_iterator it = std::find( subscribers.cbegin(), subscribers.cend(), p_f ); if( it == subscribers.cend() ) subscribers.push_back(p_f); return; } subscriber_map_[name].push_back(p_f); MessageBuilder message(Topic::EVENT, Action::SUBSCRIBE); message.add_argument( name ); send_(message); } void Event::unsubscribe(const Name& name) { SubscriberMap::iterator it = subscriber_map_.find(name); if( it == subscriber_map_.end() ) return; subscriber_map_.erase(it); MessageBuilder message(Topic::EVENT, Action::UNSUBSCRIBE); message.add_argument(name); send_(message); } void Event::unsubscribe(const Name& name, const SubscribeFnPtr& p_f) { SubscriberMap::iterator it = subscriber_map_.find(name); if( it == subscriber_map_.end() ) return; SubscriberList& subscribers = it->second; SubscriberList::iterator ju = std::find( subscribers.begin(), subscribers.end(), p_f ); if( ju == subscribers.end() ) return; subscribers.erase(ju); if( subscribers.empty() ) unsubscribe(name); } Event::ListenFnPtr Event::listen(const Name& pattern, const ListenFn& f) { ListenFnPtr p_f( new ListenFn(f) ); listen(pattern, p_f); return p_f; } void Event::listen(const Name& pattern, const ListenFnPtr& p_f) { if( pattern.empty() ) throw std::invalid_argument( "Cannot listen for empty patterns" ); if( !p_f ) throw std::invalid_argument( "Listen function pointer is NULL" ); ListenerMap::iterator it = listener_map_.find(pattern); if( it != listener_map_.end() ) return; listener_map_[pattern] = p_f; MessageBuilder message(Topic::EVENT, Action::LISTEN); message.add_argument(pattern); send_(message); } void Event::unlisten(const Name& pattern) { ListenerMap::iterator it = listener_map_.find(pattern); if( it == listener_map_.end() ) return; listener_map_.erase(it); MessageBuilder message(Topic::EVENT, Action::UNLISTEN); message.add_argument(pattern); send_(message); } void Event::notify_(const Message& message) { assert( message.topic() == Topic::EVENT ); switch( message.action() ) { case Action::EVENT: notify_subscribers_(message); break; case Action::SUBSCRIPTION_FOR_PATTERN_FOUND: case Action::SUBSCRIPTION_FOR_PATTERN_REMOVED: assert( !message.is_ack() ); notify_listeners_(message); break; case Action::LISTEN: case Action::SUBSCRIBE: assert( message.is_ack() ); break; case Action::UNLISTEN: case Action::UNSUBSCRIBE: assert( message.is_ack() ); break; default: assert(0); } } void Event::notify_subscribers_(const Message& message) { assert( message.action() == Action::EVENT ); assert( message.num_arguments() == (message.is_ack() ? 1 : 2) ); if( message.is_ack() ) return; Name name = message[0]; const Buffer& data = message[1]; SubscriberMap::iterator it = subscriber_map_.find(name); if( it == subscriber_map_.end() ) { name.push_back(0); std::fprintf( stderr, "E|EVT: no subscriber named '%s'\n", name.data() ); return; } assert( it->first == name ); // Copying the list of subscribers is a necessity here because the callbacks // may unsubscribe during their execution and modifications of a subscriber // list may invalidate iterations and ranges. Also, copying the smart // pointer pointer here is a necessity because the referenced function may // decide to unsubscribe and in this case, the std::function object must not // be destructed. Copying ensures a non-zero reference count until `*p_f` // returns. // Finally, the iterator `it` may be invalid after executing a callback // because the list of subscribers for this `name` may have been erased. SubscriberList subscribers = it->second; it = subscriber_map_.end(); for(const SubscribeFnPtr& p_f : subscribers) { auto f = *p_f; f(data); } } void Event::notify_listeners_(const Message& message) { assert( message.action() == Action::SUBSCRIPTION_FOR_PATTERN_FOUND || message.action() == Action::SUBSCRIPTION_FOR_PATTERN_REMOVED ); assert( !message.is_ack() ); assert( message.num_arguments() == 2 ); const Name& pattern = message[0]; const Name& match = message[1]; bool is_subscribed = message.action() == Action::SUBSCRIPTION_FOR_PATTERN_FOUND; ListenerMap::iterator it = listener_map_.find(pattern); if( it == listener_map_.end() ) { Name pattern_str(pattern); pattern_str.push_back(0); std::fprintf( stderr, "%s: no listener for pattern '%s'\n", message.header().to_string(), pattern_str.data() ); return; } assert( it->first == pattern ); // copy the smart pointer (increase the reference count) because the // listener may decide to unlisten. ListenFnPtr p_f = it->second; auto f = *p_f; bool accept = f(pattern, is_subscribed, match); if( message.action() == Action::SUBSCRIPTION_FOR_PATTERN_REMOVED ) return; Action action = accept ? Action::LISTEN_ACCEPT : Action::LISTEN_REJECT; MessageBuilder el(Topic::EVENT, action); el.add_argument(pattern); el.add_argument(match); send_(el); } } <|endoftext|>
<commit_before>#include "UnixSocketHandler.hpp" #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <unistd.h> namespace et { UnixSocketHandler::UnixSocketHandler() {} bool UnixSocketHandler::hasData(int fd) { fd_set input; FD_ZERO(&input); FD_SET(fd, &input); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 1 * 100; int n = select(fd + 1, &input, NULL, NULL, &timeout); if (n == -1) { // Select timed out or failed. return false; } else if (n == 0) return false; if (!FD_ISSET(fd, &input)) { LOG(FATAL) << "FD_ISSET is false but we should have data by now."; } return true; } ssize_t UnixSocketHandler::read(int fd, void *buf, size_t count) { if (fd <= 0) { LOG(FATAL) << "Tried to read from an invalid socket: " << fd; } ssize_t readBytes = ::read(fd, buf, count); if (readBytes == 0) { throw runtime_error("Remote host closed connection"); } if (readBytes < 0) { LOG(ERROR) << "Error reading: " << errno << " " << strerror(errno) << endl; } return readBytes; } ssize_t UnixSocketHandler::write(int fd, const void *buf, size_t count) { if (fd <= 0) { LOG(FATAL) << "Tried to write to an invalid socket: " << fd; } return ::write(fd, buf, count); } int UnixSocketHandler::connect(const std::string &hostname, int port) { int sockfd = -1; addrinfo *results; addrinfo *p; addrinfo hints; memset(&hints, 0, sizeof(addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_CANONNAME; std::string portname = std::to_string(port); int rc = getaddrinfo(hostname.c_str(), portname.c_str(), &hints, &results); if (rc == -1) { freeaddrinfo(results); LOG(ERROR) << "Error getting address info for " << hostname << ":" << portname << ": " << rc << " (" << gai_strerror(rc) << ")"; return -1; } // loop through all the results and connect to the first we can for (p = results; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { LOG(INFO) << "Error creating socket " << p->ai_canonname << ": " << errno << " " << strerror(errno); continue; } initSocket(sockfd); if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno << " " << strerror(errno); ::close(sockfd); sockfd = -1; continue; } LOG(INFO) << "Connected to server: " << p->ai_canonname << " using fd " << sockfd; break; // if we get here, we must have connected successfully } if (sockfd == -1) { LOG(ERROR) << "ERROR, no host found"; } return sockfd; } int UnixSocketHandler::listen(int port) { if (serverSockets.empty()) { addrinfo hints, *servinfo, *p; int rc; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP address std::string portname = std::to_string(port); if ((rc = getaddrinfo(NULL, portname.c_str(), &hints, &servinfo)) != 0) { LOG(ERROR) << "Error getting address info for " << port << ": " << rc << " (" << gai_strerror(rc) << ")"; exit(1); } // loop through all the results and bind to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { int sockfd; if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { LOG(INFO) << "Error creating socket " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno); continue; } initSocket(sockfd); // Also set the accept socket as non-blocking { int opts; opts = fcntl(sockfd, F_GETFL); FATAL_FAIL(opts); opts |= O_NONBLOCK; FATAL_FAIL(fcntl(sockfd, F_SETFL, opts)); } if (p->ai_family == AF_INET6) { // Also ensure that IPV6 sockets only listen on IPV6 // interfaces. We will create another socket object for IPV4 // if it doesn't already exist. int flag = 1; FATAL_FAIL(setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&flag, sizeof(int))); } if (::bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { // This most often happens because the port is in use. LOG(ERROR) << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno); cerr << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno) << flush; exit(1); // close(sockfd); // continue; } // Listen FATAL_FAIL(::listen(sockfd, 32)); LOG(INFO) << "Listening on " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol; // if we get here, we must have connected successfully serverSockets.push_back(sockfd); } if (serverSockets.empty()) { LOG(FATAL) << "Could not bind to any interface!"; } } for (int sockfd : serverSockets) { sockaddr_in client; socklen_t c = sizeof(sockaddr_in); int client_sock = ::accept(sockfd, (sockaddr *)&client, &c); if (client_sock >= 0) { initSocket(client_sock); // Make sure that socket becomes blocking once it's attached to a client. { int opts; opts = fcntl(client_sock, F_GETFL); FATAL_FAIL(opts); opts &= (~O_NONBLOCK); FATAL_FAIL(fcntl(client_sock, F_SETFL, opts)); } return client_sock; } else if (errno != EAGAIN && errno != EWOULDBLOCK) { FATAL_FAIL(-1); // LOG(FATAL) with the error } } return -1; } void UnixSocketHandler::stopListening() { for (int sockfd : serverSockets) { close(sockfd); } } void UnixSocketHandler::close(int fd) { if (fd == -1) { return; } VLOG(1) << "Shutting down connection: " << fd << endl; int rc = ::shutdown(fd, SHUT_RDWR); if (rc == -1) { if (errno == ENOTCONN) { // This is harmless } else { FATAL_FAIL(rc); } } FATAL_FAIL(::close(fd)); } void UnixSocketHandler::initSocket(int fd) { int flag = 1; FATAL_FAIL(setsockopt(fd, /* socket affected */ IPPROTO_TCP, /* set option at TCP level */ TCP_NODELAY, /* name of option */ (char *)&flag, /* the cast is historical cruft */ sizeof(int))); /* length of option value */ timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv))); FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv))); } } <commit_msg>make server sockets reusable<commit_after>#include "UnixSocketHandler.hpp" #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <unistd.h> namespace et { UnixSocketHandler::UnixSocketHandler() {} bool UnixSocketHandler::hasData(int fd) { fd_set input; FD_ZERO(&input); FD_SET(fd, &input); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 1 * 100; int n = select(fd + 1, &input, NULL, NULL, &timeout); if (n == -1) { // Select timed out or failed. return false; } else if (n == 0) return false; if (!FD_ISSET(fd, &input)) { LOG(FATAL) << "FD_ISSET is false but we should have data by now."; } return true; } ssize_t UnixSocketHandler::read(int fd, void *buf, size_t count) { if (fd <= 0) { LOG(FATAL) << "Tried to read from an invalid socket: " << fd; } ssize_t readBytes = ::read(fd, buf, count); if (readBytes == 0) { throw runtime_error("Remote host closed connection"); } if (readBytes < 0) { LOG(ERROR) << "Error reading: " << errno << " " << strerror(errno) << endl; } return readBytes; } ssize_t UnixSocketHandler::write(int fd, const void *buf, size_t count) { if (fd <= 0) { LOG(FATAL) << "Tried to write to an invalid socket: " << fd; } return ::write(fd, buf, count); } int UnixSocketHandler::connect(const std::string &hostname, int port) { int sockfd = -1; addrinfo *results; addrinfo *p; addrinfo hints; memset(&hints, 0, sizeof(addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_CANONNAME; std::string portname = std::to_string(port); int rc = getaddrinfo(hostname.c_str(), portname.c_str(), &hints, &results); if (rc == -1) { freeaddrinfo(results); LOG(ERROR) << "Error getting address info for " << hostname << ":" << portname << ": " << rc << " (" << gai_strerror(rc) << ")"; return -1; } // loop through all the results and connect to the first we can for (p = results; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { LOG(INFO) << "Error creating socket " << p->ai_canonname << ": " << errno << " " << strerror(errno); continue; } initSocket(sockfd); if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno << " " << strerror(errno); ::close(sockfd); sockfd = -1; continue; } LOG(INFO) << "Connected to server: " << p->ai_canonname << " using fd " << sockfd; break; // if we get here, we must have connected successfully } if (sockfd == -1) { LOG(ERROR) << "ERROR, no host found"; } return sockfd; } int UnixSocketHandler::listen(int port) { if (serverSockets.empty()) { addrinfo hints, *servinfo, *p; int rc; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP address std::string portname = std::to_string(port); if ((rc = getaddrinfo(NULL, portname.c_str(), &hints, &servinfo)) != 0) { LOG(ERROR) << "Error getting address info for " << port << ": " << rc << " (" << gai_strerror(rc) << ")"; exit(1); } // loop through all the results and bind to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { int sockfd; if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { LOG(INFO) << "Error creating socket " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno); continue; } initSocket(sockfd); // Also set the accept socket as non-blocking { int opts; opts = fcntl(sockfd, F_GETFL); FATAL_FAIL(opts); opts |= O_NONBLOCK; FATAL_FAIL(fcntl(sockfd, F_SETFL, opts)); } // Also set the accept socket as reusable { int flag = 1; FATAL_FAIL(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int))); } if (p->ai_family == AF_INET6) { // Also ensure that IPV6 sockets only listen on IPV6 // interfaces. We will create another socket object for IPV4 // if it doesn't already exist. int flag = 1; FATAL_FAIL(setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&flag, sizeof(int))); } if (::bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { // This most often happens because the port is in use. LOG(ERROR) << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno); cerr << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno) << flush; exit(1); // close(sockfd); // continue; } // Listen FATAL_FAIL(::listen(sockfd, 32)); LOG(INFO) << "Listening on " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol; // if we get here, we must have connected successfully serverSockets.push_back(sockfd); } if (serverSockets.empty()) { LOG(FATAL) << "Could not bind to any interface!"; } } for (int sockfd : serverSockets) { sockaddr_in client; socklen_t c = sizeof(sockaddr_in); int client_sock = ::accept(sockfd, (sockaddr *)&client, &c); if (client_sock >= 0) { initSocket(client_sock); // Make sure that socket becomes blocking once it's attached to a client. { int opts; opts = fcntl(client_sock, F_GETFL); FATAL_FAIL(opts); opts &= (~O_NONBLOCK); FATAL_FAIL(fcntl(client_sock, F_SETFL, opts)); } return client_sock; } else if (errno != EAGAIN && errno != EWOULDBLOCK) { FATAL_FAIL(-1); // LOG(FATAL) with the error } } return -1; } void UnixSocketHandler::stopListening() { for (int sockfd : serverSockets) { close(sockfd); } } void UnixSocketHandler::close(int fd) { if (fd == -1) { return; } VLOG(1) << "Shutting down connection: " << fd << endl; int rc = ::shutdown(fd, SHUT_RDWR); if (rc == -1) { if (errno == ENOTCONN) { // This is harmless } else { FATAL_FAIL(rc); } } FATAL_FAIL(::close(fd)); } void UnixSocketHandler::initSocket(int fd) { int flag = 1; FATAL_FAIL(setsockopt(fd, /* socket affected */ IPPROTO_TCP, /* set option at TCP level */ TCP_NODELAY, /* name of option */ (char *)&flag, /* the cast is historical cruft */ sizeof(int))); /* length of option value */ timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv))); FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv))); } } <|endoftext|>
<commit_before>// MassTable class #define DB_SELECT 1 // 0 for sqlite, 1 for hdf5 #include "MassTable.h" #include "CycException.h" #include <iostream> #include <stdlib.h> #include "Env.h" using namespace std; MassTable* MassTable::instance_ = 0; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MassTable* MassTable::Instance() { // If we haven't created a MassTable yet, create it, and then and return it // either way. if (0 == instance_) { instance_ = new MassTable(); } return instance_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MassTable::MassTable() { // figure out what's in the file if (DB_SELECT == 0) initializeSQL(); else if (DB_SELECT == 1) initializeHDF(); else throw CycIOException("Unknown mass database type"); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MassTable::~MassTable() { //Should close the 'mass.h5' file }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MassTable::getMassInGrams(int tope) { double toRet = nuclide_vec_[isoIndex_[tope]].mass; return toRet; }; // =========================================================================== // Only include files and function if we know sqlite3 is installed and chosen #if DB_SELECT == 0 #include "Database.h" //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MassTable::initializeSQL() { string file_path = ENV->getCyclusPath() + "/Data/mass.sqlite"; Database *db = new Database( file_path ); query_result result = db->query("SELECT * FROM IsotopeMasses"); int nResults = result.size(); for (int i = 0; i < nResults; i++){ // // obtain the database row and declare the appropriate members query_row row = result.at(i); std::string Zstr = row.at(0), Astr = row.at(1), Mstr = row.at(2); int Znum = atoi( Zstr.c_str() ); int Anum = atoi( Astr.c_str() ); double mass = atof( Mstr.c_str() ); // create a nuclide member and add it to the nuclide vector nuclide_t n = {Znum,Anum,mass}; nuclide_vec_.push_back(n); // create an index and log it accordingly int tope = Znum*1000 + Anum; isoIndex_.insert(make_pair(tope,i)); } // set the total number of nuclides nuclide_len_ = nuclide_vec_.size(); }; #endif // =========================================================================== // =========================================================================== // Only include files and function if we know HDF5 is installed and chosen #if DB_SELECT == 1 #include "hdf5.h" #include "H5Cpp.h" #include "H5CompType.h" #include "H5Exception.h" using namespace H5; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MassTable::initializeHDF() { string file_path = ENV->getCyclusPath() + "/Data/mass.h5"; const H5std_string filename = file_path; const H5std_string groupname = "ame03"; const H5std_string datasetname = "nuclide"; const H5std_string A_memb = "A"; const H5std_string Z_memb = "Z"; const H5std_string mass_memb = "mass"; const H5std_string name_memb = "name"; //check if the file is an hdf5 file first. if (! H5File::isHdf5(file_path)) { throw CycIOException("The MASS_FILE is not an hdf5 file."); } try { /* * Turn off the auto-printing when failure occurs so that we can * handle the errors appropriately */ Exception::dontPrint(); /* * Open the file and the dataset. */ H5File* file; file = new H5File( filename, H5F_ACC_RDONLY ); Group* group; group = new Group (file->openGroup( groupname )); DataSet* dataset; dataset = new DataSet (group->openDataSet( datasetname )); DataSpace* dataspace; dataspace = new DataSpace (dataset->getSpace( )); hsize_t dims_out[2]; int ndims = dataspace->getSimpleExtentDims(dims_out, NULL); nuclide_len_ = dims_out[0]; /* * Create a datatype for nuclide */ CompType mtype( sizeof(nuclide_t) ); mtype.insertMember( A_memb, HOFFSET(nuclide_t, A), PredType::NATIVE_INT); mtype.insertMember( Z_memb, HOFFSET(nuclide_t, Z), PredType::NATIVE_INT); mtype.insertMember( mass_memb, HOFFSET(nuclide_t, mass), PredType::IEEE_F64LE); /* * Read two fields c and a from s1 dataset. Fields in the file * are found by their names "c_name" and "a_name". */ nuclide_t nuclide[nuclide_len_]; dataset->read( nuclide, mtype ); nuclide_vec_.resize(nuclide_len_); copy(nuclide, nuclide + nuclide_len_, nuclide_vec_.begin() ); // create a map whose indices are the Iso identifier. int Anum; int Znum; int tope; for(int i = 0; i < nuclide_len_; i++) { Znum = nuclide[i].Z*1000; Anum = nuclide[i].A; tope = Anum+Znum; isoIndex_.insert(make_pair(tope, i)); }; delete dataspace; delete group; delete dataset; delete file; // catch failure caused by the H5File operations } catch( Exception error ) { error.printError(); } }; #endif // =========================================================================== <commit_msg>Added sqlite and ability to copy mass.sqlite to the make file.<commit_after>// MassTable class #define DB_SELECT 0 // 0 for sqlite, 1 for hdf5 #include "MassTable.h" #include "CycException.h" #include <iostream> #include <stdlib.h> #include "Env.h" using namespace std; MassTable* MassTable::instance_ = 0; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MassTable* MassTable::Instance() { // If we haven't created a MassTable yet, create it, and then and return it // either way. if (0 == instance_) { instance_ = new MassTable(); } return instance_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MassTable::MassTable() { // figure out what's in the file if (DB_SELECT == 0) initializeSQL(); else if (DB_SELECT == 1) initializeHDF(); else throw CycIOException("Unknown mass database type"); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MassTable::~MassTable() { //Should close the 'mass.h5' file }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double MassTable::getMassInGrams(int tope) { double toRet = nuclide_vec_[isoIndex_[tope]].mass; return toRet; }; // =========================================================================== // Only include files and function if we know sqlite3 is installed and chosen #if DB_SELECT == 0 #include "Database.h" //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MassTable::initializeSQL() { string file_path = ENV->getCyclusPath() + "/Data/mass.sqlite"; Database *db = new Database( file_path ); query_result result = db->query("SELECT * FROM IsotopeMasses"); int nResults = result.size(); for (int i = 0; i < nResults; i++){ // // obtain the database row and declare the appropriate members query_row row = result.at(i); std::string Zstr = row.at(0), Astr = row.at(1), Mstr = row.at(2); int Znum = atoi( Zstr.c_str() ); int Anum = atoi( Astr.c_str() ); double mass = atof( Mstr.c_str() ); // create a nuclide member and add it to the nuclide vector nuclide_t n = {Znum,Anum,mass}; nuclide_vec_.push_back(n); // create an index and log it accordingly int tope = Znum*1000 + Anum; isoIndex_.insert(make_pair(tope,i)); } // set the total number of nuclides nuclide_len_ = nuclide_vec_.size(); }; #endif // =========================================================================== // =========================================================================== // Only include files and function if we know HDF5 is installed and chosen #if DB_SELECT == 1 #include "hdf5.h" #include "H5Cpp.h" #include "H5CompType.h" #include "H5Exception.h" using namespace H5; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void MassTable::initializeHDF() { string file_path = ENV->getCyclusPath() + "/Data/mass.h5"; const H5std_string filename = file_path; const H5std_string groupname = "ame03"; const H5std_string datasetname = "nuclide"; const H5std_string A_memb = "A"; const H5std_string Z_memb = "Z"; const H5std_string mass_memb = "mass"; const H5std_string name_memb = "name"; //check if the file is an hdf5 file first. if (! H5File::isHdf5(file_path)) { throw CycIOException("The MASS_FILE is not an hdf5 file."); } try { /* * Turn off the auto-printing when failure occurs so that we can * handle the errors appropriately */ Exception::dontPrint(); /* * Open the file and the dataset. */ H5File* file; file = new H5File( filename, H5F_ACC_RDONLY ); Group* group; group = new Group (file->openGroup( groupname )); DataSet* dataset; dataset = new DataSet (group->openDataSet( datasetname )); DataSpace* dataspace; dataspace = new DataSpace (dataset->getSpace( )); hsize_t dims_out[2]; int ndims = dataspace->getSimpleExtentDims(dims_out, NULL); nuclide_len_ = dims_out[0]; /* * Create a datatype for nuclide */ CompType mtype( sizeof(nuclide_t) ); mtype.insertMember( A_memb, HOFFSET(nuclide_t, A), PredType::NATIVE_INT); mtype.insertMember( Z_memb, HOFFSET(nuclide_t, Z), PredType::NATIVE_INT); mtype.insertMember( mass_memb, HOFFSET(nuclide_t, mass), PredType::IEEE_F64LE); /* * Read two fields c and a from s1 dataset. Fields in the file * are found by their names "c_name" and "a_name". */ nuclide_t nuclide[nuclide_len_]; dataset->read( nuclide, mtype ); nuclide_vec_.resize(nuclide_len_); copy(nuclide, nuclide + nuclide_len_, nuclide_vec_.begin() ); // create a map whose indices are the Iso identifier. int Anum; int Znum; int tope; for(int i = 0; i < nuclide_len_; i++) { Znum = nuclide[i].Z*1000; Anum = nuclide[i].A; tope = Anum+Znum; isoIndex_.insert(make_pair(tope, i)); }; delete dataspace; delete group; delete dataset; delete file; // catch failure caused by the H5File operations } catch( Exception error ) { error.printError(); } }; #endif // =========================================================================== <|endoftext|>
<commit_before>#include "input.h" InputHandler::InputHandler(sf::Window* Window, Player* Player) : app(Window), player(Player) { app->ShowMouseCursor(false); } void InputHandler::handleEvent(sf::Event Event) { // Close window : exit if (Event.Type == sf::Event::Closed) app->Close(); // Escape key : exit if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape)) app->Close(); // Resize event : adjust viewport if (Event.Type == sf::Event::Resized) glViewport(0, 0, Event.Size.Width, Event.Size.Height); } float ElapsedTime; float mouseDeltaX, mouseDeltaY; void InputHandler::handleEvents() { const sf::Input& Input = app->GetInput(); ElapsedTime = Clock.GetElapsedTime(); Clock.Reset(); // Handle held keys if ((Input.IsKeyDown(sf::Key::S))) player->Forward(-ElapsedTime); if ((Input.IsKeyDown(sf::Key::W))) player->Forward( ElapsedTime); if ((Input.IsKeyDown(sf::Key::D))) player->Strafe(-ElapsedTime); if ((Input.IsKeyDown(sf::Key::A))) player->Strafe( ElapsedTime); if ((Input.IsKeyDown(sf::Key::Z))) player->Speed++; if ((Input.IsKeyDown(sf::Key::X))) player->Speed--; // Rotate view based on mouse movement mouseDeltaX = Input.GetMouseX() - 100; mouseDeltaY = Input.GetMouseY() - 100; app->SetCursorPosition(100, 100); if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0)) player->ChangeRotation((mouseDeltaY/10), (mouseDeltaX/10)); // Handle other events sf::Event Event; while (app->GetEvent(Event)) { handleEvent(Event); } } <commit_msg>Fixed mouselook while moving. Again.<commit_after>#include "input.h" InputHandler::InputHandler(sf::Window* Window, Player* Player) : app(Window), player(Player) { app->ShowMouseCursor(false); } void InputHandler::handleEvent(sf::Event Event) { // Close window : exit if (Event.Type == sf::Event::Closed) app->Close(); // Escape key : exit if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape)) app->Close(); // Resize event : adjust viewport if (Event.Type == sf::Event::Resized) glViewport(0, 0, Event.Size.Width, Event.Size.Height); } float ElapsedTime; float mouseDeltaX, mouseDeltaY; void InputHandler::handleEvents() { const sf::Input& Input = app->GetInput(); // Constant movement speed ElapsedTime = Clock.GetElapsedTime(); Clock.Reset(); // Handle held keys if ((Input.IsKeyDown(sf::Key::S))) player->Forward(-ElapsedTime); if ((Input.IsKeyDown(sf::Key::W))) player->Forward( ElapsedTime); if ((Input.IsKeyDown(sf::Key::D))) player->Strafe(-ElapsedTime); if ((Input.IsKeyDown(sf::Key::A))) player->Strafe( ElapsedTime); if ((Input.IsKeyDown(sf::Key::Z))) player->Speed++; if ((Input.IsKeyDown(sf::Key::X))) player->Speed--; // Handle other events sf::Event Event; while (app->GetEvent(Event)) { handleEvent(Event); } // Rotate view based on mouse movement mouseDeltaX = Input.GetMouseX() - 100; mouseDeltaY = Input.GetMouseY() - 100; app->SetCursorPosition(100, 100); if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0)) player->ChangeRotation((mouseDeltaY/10), (mouseDeltaX/10)); } <|endoftext|>
<commit_before>/* Copyright 2015-2020 Igor Petrovic 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 "board/Board.h" #include "board/Internal.h" #include "board/common/io/Helpers.h" #include "Pins.h" #include "core/src/general/Timing.h" #include "common/OpenDeckMIDIformat/OpenDeckMIDIformat.h" namespace Board { namespace detail { namespace setup { void bootloader() { if (Board::detail::bootloader::btldrTrigger() == Board::detail::bootloader::btldrTrigger_t::none) { if (Board::detail::isAppCRCvalid()) Board::detail::runApplication(); } else { #if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED) Board::UART::init(UART_USB_LINK_CHANNEL, UART_BAUDRATE_MIDI_OD); #ifndef USB_MIDI_SUPPORTED // make sure USB link goes to bootloader mode as well MIDI::USBMIDIpacket_t packet; packet.Event = static_cast<uint8_t>(OpenDeckMIDIformat::command_t::btldrReboot); packet.Data1 = 0x00; packet.Data2 = 0x00; packet.Data3 = 0x00; //add some delay - it case of hardware btldr entry both MCUs will boot up in the same time //so it's possible USB link MCU will miss this packet core::timing::waitMs(1000); OpenDeckMIDIformat::write(UART_USB_LINK_CHANNEL, packet, OpenDeckMIDIformat::packetType_t::internalCommand); #endif #endif Board::detail::bootloader::indicate(); #ifdef USB_MIDI_SUPPORTED Board::detail::setup::usb(); #endif } } } // namespace setup namespace bootloader { btldrTrigger_t btldrTrigger() { //add some delay before reading the pins to avoid incorrect state detection core::timing::waitMs(100); bool hardwareTrigger = Board::detail::bootloader::isHWtriggerActive(); //check if user wants to enter bootloader bool softwareTrigger = Board::detail::bootloader::isSWtriggerActive(); detail::bootloader::clearSWtrigger(); if (softwareTrigger && hardwareTrigger) return btldrTrigger_t::all; else if (!softwareTrigger && hardwareTrigger) return btldrTrigger_t::hardware; else if (softwareTrigger && !hardwareTrigger) return btldrTrigger_t::software; else return btldrTrigger_t::none; } void indicate() { #if defined(LED_INDICATORS) INT_LED_ON(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN); INT_LED_ON(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN); #elif defined(NUMBER_OF_OUT_SR) && !defined(NUMBER_OF_LED_COLUMNS) //turn on all available LEDs CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); for (int i = 0; i < NUMBER_OF_OUT_SR; i++) { for (int j = 0; j < 8; j++) { EXT_LED_ON(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN); CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); _NOP(); _NOP(); CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); } } CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); #elif defined(OD_BOARD_TEENSY2PP) //only one led INT_LED_ON(LED_IN_PORT, LED_IN_PIN); #endif } bool isHWtriggerActive() { #if defined(BTLDR_BUTTON_INDEX) CORE_IO_SET_LOW(SR_DIN_CLK_PORT, SR_DIN_CLK_PIN); CORE_IO_SET_LOW(SR_DIN_LATCH_PORT, SR_DIN_LATCH_PIN); _NOP(); CORE_IO_SET_HIGH(SR_DIN_LATCH_PORT, SR_DIN_LATCH_PIN); for (int j = 0; j < NUMBER_OF_IN_SR; j++) { for (int i = 0; i < NUMBER_OF_IN_SR_INPUTS; i++) { uint8_t index = (7 - i) + j * NUMBER_OF_OUT_SR_INPUTS; if (index == BTLDR_BUTTON_INDEX) { if (!CORE_IO_READ(SR_DIN_DATA_PORT, SR_DIN_DATA_PIN)) return true; } CORE_IO_SET_LOW(SR_DIN_CLK_PORT, SR_DIN_CLK_PIN); _NOP(); CORE_IO_SET_HIGH(SR_DIN_CLK_PORT, SR_DIN_CLK_PIN); } } return false; #elif defined(BTLDR_BUTTON_PORT) return !CORE_IO_READ(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN); #else //no hardware entry possible in this case return false; #endif } } // namespace bootloader } // namespace detail } // namespace Board<commit_msg>make sure to enter bootloader if app crc is invalid<commit_after>/* Copyright 2015-2020 Igor Petrovic 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 "board/Board.h" #include "board/Internal.h" #include "board/common/io/Helpers.h" #include "Pins.h" #include "core/src/general/Timing.h" #include "common/OpenDeckMIDIformat/OpenDeckMIDIformat.h" namespace Board { namespace detail { namespace setup { void bootloader() { if (Board::detail::bootloader::btldrTrigger() == Board::detail::bootloader::btldrTrigger_t::none) { if (Board::detail::isAppCRCvalid()) Board::detail::runApplication(); } #if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED) Board::UART::init(UART_USB_LINK_CHANNEL, UART_BAUDRATE_MIDI_OD); #ifndef USB_MIDI_SUPPORTED // make sure USB link goes to bootloader mode as well MIDI::USBMIDIpacket_t packet; packet.Event = static_cast<uint8_t>(OpenDeckMIDIformat::command_t::btldrReboot); packet.Data1 = 0x00; packet.Data2 = 0x00; packet.Data3 = 0x00; //add some delay - it case of hardware btldr entry both MCUs will boot up in the same time //so it's possible USB link MCU will miss this packet core::timing::waitMs(1000); OpenDeckMIDIformat::write(UART_USB_LINK_CHANNEL, packet, OpenDeckMIDIformat::packetType_t::internalCommand); #endif #endif Board::detail::bootloader::indicate(); #ifdef USB_MIDI_SUPPORTED Board::detail::setup::usb(); #endif } } // namespace setup namespace bootloader { btldrTrigger_t btldrTrigger() { //add some delay before reading the pins to avoid incorrect state detection core::timing::waitMs(100); bool hardwareTrigger = Board::detail::bootloader::isHWtriggerActive(); //check if user wants to enter bootloader bool softwareTrigger = Board::detail::bootloader::isSWtriggerActive(); detail::bootloader::clearSWtrigger(); if (softwareTrigger && hardwareTrigger) return btldrTrigger_t::all; else if (!softwareTrigger && hardwareTrigger) return btldrTrigger_t::hardware; else if (softwareTrigger && !hardwareTrigger) return btldrTrigger_t::software; else return btldrTrigger_t::none; } void indicate() { #if defined(LED_INDICATORS) INT_LED_ON(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN); INT_LED_ON(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN); #elif defined(NUMBER_OF_OUT_SR) && !defined(NUMBER_OF_LED_COLUMNS) //turn on all available LEDs CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); for (int i = 0; i < NUMBER_OF_OUT_SR; i++) { for (int j = 0; j < 8; j++) { EXT_LED_ON(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN); CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); _NOP(); _NOP(); CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); } } CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); #elif defined(OD_BOARD_TEENSY2PP) //only one led INT_LED_ON(LED_IN_PORT, LED_IN_PIN); #endif } bool isHWtriggerActive() { #if defined(BTLDR_BUTTON_INDEX) CORE_IO_SET_LOW(SR_DIN_CLK_PORT, SR_DIN_CLK_PIN); CORE_IO_SET_LOW(SR_DIN_LATCH_PORT, SR_DIN_LATCH_PIN); _NOP(); CORE_IO_SET_HIGH(SR_DIN_LATCH_PORT, SR_DIN_LATCH_PIN); for (int j = 0; j < NUMBER_OF_IN_SR; j++) { for (int i = 0; i < NUMBER_OF_IN_SR_INPUTS; i++) { uint8_t index = (7 - i) + j * NUMBER_OF_OUT_SR_INPUTS; if (index == BTLDR_BUTTON_INDEX) { if (!CORE_IO_READ(SR_DIN_DATA_PORT, SR_DIN_DATA_PIN)) return true; } CORE_IO_SET_LOW(SR_DIN_CLK_PORT, SR_DIN_CLK_PIN); _NOP(); CORE_IO_SET_HIGH(SR_DIN_CLK_PORT, SR_DIN_CLK_PIN); } } return false; #elif defined(BTLDR_BUTTON_PORT) return !CORE_IO_READ(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN); #else //no hardware entry possible in this case return false; #endif } } // namespace bootloader } // namespace detail } // namespace Board<|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <map> #include <unordered_map> #include <vector> #include <string> #include "dict.h" #include "dictglobal.h" using Dict = std::unordered_map<std::string, std::string>; using IdentifierType = unsigned long; namespace { #ifdef NDEBUG const bool debug = false; #else const bool debug = true; #endif IdentifierType dictCounter = 0; std::map<IdentifierType, Dict>& dicts() { static std::map<IdentifierType, Dict> dicts; return dicts; } std::string parse_char_param(const char* param) { if (param != NULL) { std::string paramStr(param); return "\"" + paramStr + "\""; } else return "NULL"; } void function_called_msg(std::string funcName, std::string params) { if (debug) std::cerr << funcName << "(" << params << ")" << std::endl; } void dict_new_msg(IdentifierType id) { if (debug) std::cerr << "dict_new: dict " << id << " has been created" << std::endl; } void dict_delete_success_msg(IdentifierType id) { if (debug) std::cerr << "dict_delete: dict " << id << " has been deleted" << std::endl; } void dict_delete_error_msg() { if (debug) std::cerr << "dict_delete: an attempt to remove the Global Dictionary" << std::endl; } void dict_description_msg(IdentifierType id) { if (debug) { if (id != dict_global()) std::cerr << "dict " << id; else std::cerr << "the Global Dictionary"; } } void dict_size_msg(IdentifierType id, size_t size) { if (debug) { std::cerr << "dict_size: "; dict_description_msg(id); std::cerr << " contains " << size << " element(s)" << std::endl; } } void dict_insert_global_dict_msg() { if (debug) std::cerr << "dict_insert: attempt to overfill the Global Dictionary" << std::endl; } void dict_insert_success_msg(IdentifierType id, std::string key, std::string value) { if (debug) { std::cerr << "dict_insert: "; dict_description_msg(id); std::cerr << ", the pair (" << key << ", " << value << ")" << " has been inserted" << std::endl; } } void dict_insert_error_msg(IdentifierType id, std::string param) { if (debug) std::cerr << "dict_insert: dict " << id << " an attempt to insert NULL " << param << std::endl; } void dict_not_found_msg(std::string funcName, IdentifierType id) { if (debug) std::cerr << funcName << ": dict " << id << " does not exist" << "\n"; } void key_not_found_msg(std::string funcName, IdentifierType id, const char* key) { if (debug) std::cerr << funcName << ": dict " << id << " does not contain the key \"" << key << "\"\n"; } void key_removed_msg(std::string funcName, IdentifierType id, const char* key) { if (debug) std::cerr << funcName << ": dict " << id << ", the key \"" << key << "\" has been removed\n"; } void value_found_msg(std::string funcName, IdentifierType id, const char* key, std::string value) { if (debug) std::cerr << funcName << ": dict " << id << ", the key \"" << key << "\" has the value \"" << value << "\"\n"; } void dict_copied_msg(std::string funcName, IdentifierType src_id, IdentifierType dst_id) { if (debug) std::cerr << funcName << ": dict " << src_id << " has been copied into dict " << dst_id << "\n"; } void search_global_dict_msg(std::string funcName) { if (debug) std::cerr << funcName << ": looking up the Global Dictionary\n"; } void dict_cleared_msg(std::string funcName, IdentifierType id) { if (debug) std::cerr << funcName << ": dict " << id << " has been cleared\n"; } } IdentifierType dict_new() { function_called_msg("dict_new", ""); dicts().insert(std::make_pair(++dictCounter, Dict())); dict_new_msg(dictCounter); return dictCounter; } void dict_delete(unsigned long id) { std::stringstream ss; ss << id; function_called_msg("dict_delete", ss.str()); const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (id == dict_global()) { dict_delete_error_msg(); } else { dicts().erase(id); dict_delete_success_msg(id); } } } size_t dict_size(unsigned long id) { std::stringstream ss; ss << id; function_called_msg("dict_size", ss.str()); const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { size_t dictSize = dictionaryIt->second.size(); dict_size_msg(id, dictSize); return dictSize; } else { dict_not_found_msg("dict_size", id); return 0; } } void dict_insert(unsigned long id, const char* key, const char* value) { std::stringstream ss; const std::string keyDescription = parse_char_param(key); const std::string valueDescription = parse_char_param(value); ss << id << ", " << keyDescription << ", " << valueDescription; function_called_msg("dict_insert", ss.str()); const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (key == NULL) { dict_insert_error_msg(id, "key"); } else if (value == NULL) { dict_insert_error_msg(id, "value"); } else { IdentifierType globalDictId = dict_global(); if ((id == globalDictId) && (dict_size(globalDictId) == MAX_GLOBAL_DICT_SIZE)) { dict_insert_global_dict_msg(); return; } const std::string keyStr(key); const std::string valueStr(value); Dict dict = dictionaryIt->second; auto dictIt = dict.find(keyStr); if (dictIt != dict.end()) dictIt->second = valueStr; else dictionaryIt->second.insert(std::make_pair(keyStr, valueStr)); dict_insert_success_msg(id, keyDescription, valueDescription); } } else dict_not_found_msg("dict_insert", id); } void dict_remove(IdentifierType id, const char* key) { const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (dictionaryIt->second.erase(key) > 0) { key_removed_msg("dict_remove", id, key); } else key_not_found_msg("dict_remove", id, key); } else dict_not_found_msg("dict_remove", id); } const char* dict_find(IdentifierType id, const char* key) { const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { const Dict dict = dictionaryIt->second; const auto stringIt = dict.find(key); if (stringIt != dict.end()) { const std::string value = stringIt->second; value_found_msg("dict_find", id, key, value); return value.c_str(); } else key_not_found_msg("dict_find", id, key); } else dict_not_found_msg("dict_find", id); if (id != dict_global()) { search_global_dict_msg("dict_find"); return dict_find(dict_global(), key); } return NULL; } void dict_clear(IdentifierType id) { const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { dictionaryIt->second.clear(); dict_cleared_msg("dict_clear", id); } else dict_not_found_msg("dict_clear", id); } void dict_copy(IdentifierType src_id, IdentifierType dst_id) { if (src_id == dst_id) return; const auto srcDictionaryIt = dicts().find(src_id); const auto dstDictionaryIt = dicts().find(dst_id); if (srcDictionaryIt != dicts().end() && dstDictionaryIt != dicts().end()) { Dict srcDict = srcDictionaryIt->second; Dict dstDict = dstDictionaryIt->second; const bool isGlobalDict = dst_id == dict_global(); for (auto srcIt = srcDict.begin(); srcIt != srcDict.end(); ++srcIt) { std::string srcKey = srcIt->first; std::string srcValue = srcIt->second; auto dstIt = dstDict.find(srcKey); if (dstIt != dstDict.end()) dstIt->second = srcValue; else { dstDict.insert(make_pair(srcKey, srcValue)); if (isGlobalDict && (dstDict.size() == MAX_GLOBAL_DICT_SIZE)) break; } } dict_copied_msg("dict_copy", src_id, dst_id); } else if (srcDictionaryIt != dicts().end()) dict_not_found_msg("dict_copy", src_id); else dict_not_found_msg("dict_copy", dst_id); } <commit_msg>Dictionaries description<commit_after>#include <iostream> #include <sstream> #include <map> #include <unordered_map> #include <vector> #include <string> #include "dict.h" #include "dictglobal.h" using Dict = std::unordered_map<std::string, std::string>; using IdentifierType = unsigned long; namespace { #ifdef NDEBUG const bool debug = false; #else const bool debug = true; #endif IdentifierType dictCounter = 0; std::map<IdentifierType, Dict>& dicts() { static std::map<IdentifierType, Dict> dicts; return dicts; } std::string parse_char_param(const char* param) { if (param != NULL) { std::string paramStr(param); return "\"" + paramStr + "\""; } else return "NULL"; } void function_called_msg(std::string funcName, std::string params) { if (debug) std::cerr << funcName << "(" << params << ")" << std::endl; } void dict_new_msg(IdentifierType id) { if (debug) std::cerr << "dict_new: dict " << id << " has been created" << std::endl; } void dict_delete_success_msg(IdentifierType id) { if (debug) std::cerr << "dict_delete: dict " << id << " has been deleted" << std::endl; } void dict_delete_error_msg() { if (debug) std::cerr << "dict_delete: an attempt to remove the Global Dictionary" << std::endl; } void dict_description_msg(IdentifierType id) { if (debug) { if (id != dict_global()) std::cerr << "dict " << id; else std::cerr << "the Global Dictionary"; } } void dict_size_msg(IdentifierType id, size_t size) { if (debug) { std::cerr << "dict_size: "; dict_description_msg(id); std::cerr << " contains " << size << " element(s)" << std::endl; } } void dict_insert_global_dict_msg() { if (debug) std::cerr << "dict_insert: attempt to overfill the Global Dictionary" << std::endl; } void dict_insert_success_msg(IdentifierType id, std::string key, std::string value) { if (debug) { std::cerr << "dict_insert: "; dict_description_msg(id); std::cerr << ", the pair (" << key << ", " << value << ")" << " has been inserted" << std::endl; } } void dict_insert_error_msg(IdentifierType id, std::string param) { if (debug) std::cerr << "dict_insert: dict " << id << " an attempt to insert NULL " << param << std::endl; } void dict_not_found_msg(std::string funcName, IdentifierType id) { if (debug) std::cerr << funcName << ": dict " << id << " does not exist" << "\n"; } void key_not_found_msg(std::string funcName, IdentifierType id, const char* key) { if (debug) std::cerr << funcName << ": dict " << id << " does not contain the key \"" << key << "\"\n"; } void key_removed_msg(std::string funcName, IdentifierType id, const char* key) { if (debug) { std::cerr << funcName << ": "; dict_description_msg(id); std::cerr << " , the key \"" << key << "\" has been removed" << std::endl; } } void value_found_msg(std::string funcName, IdentifierType id, const char* key, std::string value) { if (debug) { std::cerr << funcName << ": "; dict_description_msg(id); std::cerr << ", the key \"" << key << "\" has the value \"" << value << "\"" << std::endl; } } void dict_copied_msg(std::string funcName, IdentifierType src_id, IdentifierType dst_id) { if (debug) { std::cerr << funcName << ": "; dict_description_msg(src_id); std::cerr << " has been copied into "; dict_description_msg(dst_id); std::cerr << std::endl; } } void search_global_dict_msg(std::string funcName) { if (debug) std::cerr << funcName << ": looking up the Global Dictionary\n"; } void dict_cleared_msg(std::string funcName, IdentifierType id) { if (debug) { std::cerr << funcName << ": "; dict_description_msg(id); std::cerr << " has been cleared" << std::endl; } } } IdentifierType dict_new() { function_called_msg("dict_new", ""); dicts().insert(std::make_pair(++dictCounter, Dict())); dict_new_msg(dictCounter); return dictCounter; } void dict_delete(unsigned long id) { std::stringstream ss; ss << id; function_called_msg("dict_delete", ss.str()); const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (id == dict_global()) { dict_delete_error_msg(); } else { dicts().erase(id); dict_delete_success_msg(id); } } } size_t dict_size(unsigned long id) { std::stringstream ss; ss << id; function_called_msg("dict_size", ss.str()); const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { size_t dictSize = dictionaryIt->second.size(); dict_size_msg(id, dictSize); return dictSize; } else { dict_not_found_msg("dict_size", id); return 0; } } void dict_insert(unsigned long id, const char* key, const char* value) { std::stringstream ss; const std::string keyDescription = parse_char_param(key); const std::string valueDescription = parse_char_param(value); ss << id << ", " << keyDescription << ", " << valueDescription; function_called_msg("dict_insert", ss.str()); const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (key == NULL) { dict_insert_error_msg(id, "key"); } else if (value == NULL) { dict_insert_error_msg(id, "value"); } else { IdentifierType globalDictId = dict_global(); if ((id == globalDictId) && (dict_size(globalDictId) == MAX_GLOBAL_DICT_SIZE)) { dict_insert_global_dict_msg(); return; } const std::string keyStr(key); const std::string valueStr(value); Dict dict = dictionaryIt->second; auto dictIt = dict.find(keyStr); if (dictIt != dict.end()) dictIt->second = valueStr; else dictionaryIt->second.insert(std::make_pair(keyStr, valueStr)); dict_insert_success_msg(id, keyDescription, valueDescription); } } else dict_not_found_msg("dict_insert", id); } void dict_remove(IdentifierType id, const char* key) { const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (dictionaryIt->second.erase(key) > 0) { key_removed_msg("dict_remove", id, key); } else key_not_found_msg("dict_remove", id, key); } else dict_not_found_msg("dict_remove", id); } const char* dict_find(IdentifierType id, const char* key) { const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { const Dict dict = dictionaryIt->second; const auto stringIt = dict.find(key); if (stringIt != dict.end()) { const std::string value = stringIt->second; value_found_msg("dict_find", id, key, value); return value.c_str(); } else key_not_found_msg("dict_find", id, key); } else dict_not_found_msg("dict_find", id); if (id != dict_global()) { search_global_dict_msg("dict_find"); return dict_find(dict_global(), key); } return NULL; } void dict_clear(IdentifierType id) { const auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { dictionaryIt->second.clear(); dict_cleared_msg("dict_clear", id); } else dict_not_found_msg("dict_clear", id); } void dict_copy(IdentifierType src_id, IdentifierType dst_id) { if (src_id == dst_id) return; const auto srcDictionaryIt = dicts().find(src_id); const auto dstDictionaryIt = dicts().find(dst_id); if (srcDictionaryIt != dicts().end() && dstDictionaryIt != dicts().end()) { Dict srcDict = srcDictionaryIt->second; Dict dstDict = dstDictionaryIt->second; const bool isGlobalDict = dst_id == dict_global(); for (auto srcIt = srcDict.begin(); srcIt != srcDict.end(); ++srcIt) { std::string srcKey = srcIt->first; std::string srcValue = srcIt->second; auto dstIt = dstDict.find(srcKey); if (dstIt != dstDict.end()) dstIt->second = srcValue; else { dstDict.insert(make_pair(srcKey, srcValue)); if (isGlobalDict && (dstDict.size() == MAX_GLOBAL_DICT_SIZE)) break; } } dict_copied_msg("dict_copy", src_id, dst_id); } else if (srcDictionaryIt != dicts().end()) dict_not_found_msg("dict_copy", src_id); else dict_not_found_msg("dict_copy", dst_id); } <|endoftext|>
<commit_before>/* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2015 Filipe Coelho <falktx@falktx.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * For a full copy of the license see the LGPL.txt file */ #include "DistrhoPluginInternal.hpp" #if DISTRHO_PLUGIN_HAS_UI && ! defined(HAVE_DGL) # undef DISTRHO_PLUGIN_HAS_UI # define DISTRHO_PLUGIN_HAS_UI 0 #endif #if DISTRHO_PLUGIN_HAS_UI # include "DistrhoUIInternal.hpp" #else # include "../extra/Sleep.hpp" #endif #include "jack/jack.h" #include "jack/midiport.h" #include "jack/transport.h" #ifndef DISTRHO_OS_WINDOWS # include <signal.h> #endif // ----------------------------------------------------------------------- START_NAMESPACE_DISTRHO #if DISTRHO_PLUGIN_HAS_UI && ! DISTRHO_PLUGIN_WANT_STATE static const setStateFunc setStateCallback = nullptr; #endif // ----------------------------------------------------------------------- static volatile bool gCloseSignalReceived = false; #ifdef DISTRHO_OS_WINDOWS static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept { if (dwCtrlType == CTRL_C_EVENT) { gCloseSignalReceived = true; return TRUE; } return FALSE; } static void initSignalHandler() { SetConsoleCtrlHandler(winSignalHandler, TRUE); } #else static void closeSignalHandler(int) noexcept { gCloseSignalReceived = true; } static void initSignalHandler() { struct sigaction sint; struct sigaction sterm; sint.sa_handler = closeSignalHandler; sint.sa_flags = SA_RESTART; sint.sa_restorer = nullptr; sigemptyset(&sint.sa_mask); sigaction(SIGINT, &sint, nullptr); sterm.sa_handler = closeSignalHandler; sterm.sa_flags = SA_RESTART; sterm.sa_restorer = nullptr; sigemptyset(&sterm.sa_mask); sigaction(SIGTERM, &sterm, nullptr); } #endif // ----------------------------------------------------------------------- #if DISTRHO_PLUGIN_HAS_UI class PluginJack : public IdleCallback #else class PluginJack #endif { public: PluginJack(jack_client_t* const client) : fPlugin(), #if DISTRHO_PLUGIN_HAS_UI fUI(this, 0, nullptr, setParameterValueCallback, setStateCallback, nullptr, setSizeCallback, fPlugin.getInstancePointer()), #endif fClient(client) { char strBuf[0xff+1]; strBuf[0xff] = '\0'; #if DISTRHO_PLUGIN_NUM_INPUTS > 0 for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) { std::snprintf(strBuf, 0xff, "in%i", i+1); fPortAudioIns[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); } #endif #if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) { std::snprintf(strBuf, 0xff, "out%i", i+1); fPortAudioOuts[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); } #endif #if DISTRHO_PLUGIN_IS_SYNTH fPortMidiIn = jack_port_register(fClient, "midi-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0); #endif #if DISTRHO_PLUGIN_WANT_PROGRAMS if (fPlugin.getProgramCount() > 0) { fPlugin.loadProgram(0); # if DISTRHO_PLUGIN_HAS_UI fUI.programLoaded(0); # endif } #endif if (const uint32_t count = fPlugin.getParameterCount()) { fLastOutputValues = new float[count]; for (uint32_t i=0; i < count; ++i) { if (fPlugin.isParameterOutput(i)) { fLastOutputValues[i] = fPlugin.getParameterValue(i); } else { fLastOutputValues[i] = 0.0f; # if DISTRHO_PLUGIN_HAS_UI fUI.parameterChanged(i, fPlugin.getParameterValue(i)); # endif } } } else { fLastOutputValues = nullptr; } jack_set_buffer_size_callback(fClient, jackBufferSizeCallback, this); jack_set_sample_rate_callback(fClient, jackSampleRateCallback, this); jack_set_process_callback(fClient, jackProcessCallback, this); jack_on_shutdown(fClient, jackShutdownCallback, this); jack_activate(fClient); #if DISTRHO_PLUGIN_HAS_UI if (const char* const name = jack_get_client_name(fClient)) fUI.setWindowTitle(name); else fUI.setWindowTitle(fPlugin.getName()); fUI.exec(this); #else while (! gCloseSignalReceived) d_sleep(1); #endif } ~PluginJack() { if (fClient == nullptr) return; jack_deactivate(fClient); #if DISTRHO_PLUGIN_IS_SYNTH jack_port_unregister(fClient, fPortMidiIn); fPortMidiIn = nullptr; #endif #if DISTRHO_PLUGIN_NUM_INPUTS > 0 for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) { jack_port_unregister(fClient, fPortAudioIns[i]); fPortAudioIns[i] = nullptr; } #endif #if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) { jack_port_unregister(fClient, fPortAudioOuts[i]); fPortAudioOuts[i] = nullptr; } #endif jack_client_close(fClient); } // ------------------------------------------------------------------- protected: #if DISTRHO_PLUGIN_HAS_UI void idleCallback() override { if (gCloseSignalReceived) return fUI.quit(); float value; for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) { if (! fPlugin.isParameterOutput(i)) continue; value = fPlugin.getParameterValue(i); if (fLastOutputValues[i] == value) continue; fLastOutputValues[i] = value; fUI.parameterChanged(i, value); } fUI.exec_idle(); } #endif void jackBufferSize(const jack_nframes_t nframes) { fPlugin.setBufferSize(nframes, true); } void jackSampleRate(const jack_nframes_t nframes) { fPlugin.setSampleRate(nframes, true); } void jackProcess(const jack_nframes_t nframes) { #if DISTRHO_PLUGIN_NUM_INPUTS > 0 const float* audioIns[DISTRHO_PLUGIN_NUM_INPUTS]; for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) audioIns[i] = (const float*)jack_port_get_buffer(fPortAudioIns[i], nframes); #else static const float** audioIns = nullptr; #endif #if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 float* audioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS]; for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) audioOuts[i] = (float*)jack_port_get_buffer(fPortAudioOuts[i], nframes); #else static float** audioOuts = nullptr; #endif #if DISTRHO_PLUGIN_WANT_TIMEPOS jack_position_t pos; fTimePosition.playing = (jack_transport_query(fClient, &pos) == JackTransportRolling); if (pos.unique_1 == pos.unique_2) { fTimePosition.frame = pos.frame; if (pos.valid & JackTransportBBT) { fTimePosition.bbt.valid = true; fTimePosition.bbt.bar = pos.bar; fTimePosition.bbt.beat = pos.beat; fTimePosition.bbt.tick = pos.tick; fTimePosition.bbt.barStartTick = pos.bar_start_tick; fTimePosition.bbt.beatsPerBar = pos.beats_per_bar; fTimePosition.bbt.beatType = pos.beat_type; fTimePosition.bbt.ticksPerBeat = pos.ticks_per_beat; fTimePosition.bbt.beatsPerMinute = pos.beats_per_minute; } else fTimePosition.bbt.valid = false; } else { fTimePosition.bbt.valid = false; fTimePosition.frame = 0; } fPlugin.setTimePosition(fTimePosition); #endif #if DISTRHO_PLUGIN_IS_SYNTH void* const midiBuf = jack_port_get_buffer(fPortMidiIn, nframes); if (const uint32_t eventCount = jack_midi_get_event_count(midiBuf)) { uint32_t midiEventCount = 0; MidiEvent midiEvents[eventCount]; jack_midi_event_t jevent; for (uint32_t i=0; i < eventCount; ++i) { if (jack_midi_event_get(&jevent, midiBuf, i) != 0) break; MidiEvent& midiEvent(midiEvents[midiEventCount++]); midiEvent.frame = jevent.time; midiEvent.size = jevent.size; if (midiEvent.size > MidiEvent::kDataSize) midiEvent.dataExt = jevent.buffer; else std::memcpy(midiEvent.data, jevent.buffer, midiEvent.size); } fPlugin.run(audioIns, audioOuts, nframes, midiEvents, midiEventCount); } else { fPlugin.run(audioIns, audioOuts, nframes, nullptr, 0); } #else fPlugin.run(audioIns, audioOuts, nframes); #endif } void jackShutdown() { d_stderr("jack has shutdown, quitting now..."); fClient = nullptr; #if DISTRHO_PLUGIN_HAS_UI fUI.quit(); #endif } // ------------------------------------------------------------------- void setParameterValue(const uint32_t index, const float value) { fPlugin.setParameterValue(index, value); } #if DISTRHO_PLUGIN_WANT_STATE void setState(const char* const key, const char* const value) { fPlugin.setState(key, value); } #endif #if DISTRHO_PLUGIN_HAS_UI void setSize(const uint width, const uint height) { fUI.setWindowSize(width, height); } #endif // ------------------------------------------------------------------- private: PluginExporter fPlugin; #if DISTRHO_PLUGIN_HAS_UI UIExporter fUI; #endif jack_client_t* fClient; #if DISTRHO_PLUGIN_NUM_INPUTS > 0 jack_port_t* fPortAudioIns[DISTRHO_PLUGIN_NUM_INPUTS]; #endif #if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 jack_port_t* fPortAudioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS]; #endif #if DISTRHO_PLUGIN_IS_SYNTH jack_port_t* fPortMidiIn; #endif #if DISTRHO_PLUGIN_WANT_TIMEPOS TimePosition fTimePosition; #endif // Temporary data float* fLastOutputValues; // ------------------------------------------------------------------- // Callbacks #define uiPtr ((PluginJack*)ptr) static int jackBufferSizeCallback(jack_nframes_t nframes, void* ptr) { uiPtr->jackBufferSize(nframes); return 0; } static int jackSampleRateCallback(jack_nframes_t nframes, void* ptr) { uiPtr->jackSampleRate(nframes); return 0; } static int jackProcessCallback(jack_nframes_t nframes, void* ptr) { uiPtr->jackProcess(nframes); return 0; } static void jackShutdownCallback(void* ptr) { uiPtr->jackShutdown(); } static void setParameterValueCallback(void* ptr, uint32_t index, float value) { uiPtr->setParameterValue(index, value); } #if DISTRHO_PLUGIN_WANT_STATE static void setStateCallback(void* ptr, const char* key, const char* value) { uiPtr->setState(key, value); } #endif #if DISTRHO_PLUGIN_HAS_UI static void setSizeCallback(void* ptr, uint width, uint height) { uiPtr->setSize(width, height); } #endif #undef uiPtr }; END_NAMESPACE_DISTRHO // ----------------------------------------------------------------------- int main() { USE_NAMESPACE_DISTRHO; jack_status_t status = jack_status_t(0x0); jack_client_t* client = jack_client_open(DISTRHO_PLUGIN_NAME, JackNoStartServer, &status); if (client == nullptr) { String errorString; if (status & JackFailure) errorString += "Overall operation failed;\n"; if (status & JackInvalidOption) errorString += "The operation contained an invalid or unsupported option;\n"; if (status & JackNameNotUnique) errorString += "The desired client name was not unique;\n"; if (status & JackServerStarted) errorString += "The JACK server was started as a result of this operation;\n"; if (status & JackServerFailed) errorString += "Unable to connect to the JACK server;\n"; if (status & JackServerError) errorString += "Communication error with the JACK server;\n"; if (status & JackNoSuchClient) errorString += "Requested client does not exist;\n"; if (status & JackLoadFailure) errorString += "Unable to load internal client;\n"; if (status & JackInitFailure) errorString += "Unable to initialize client;\n"; if (status & JackShmFailure) errorString += "Unable to access shared memory;\n"; if (status & JackVersionError) errorString += "Client's protocol version does not match;\n"; if (status & JackBackendError) errorString += "Backend Error;\n"; if (status & JackClientZombie) errorString += "Client is being shutdown against its will;\n"; if (errorString.isNotEmpty()) { errorString[errorString.length()-2] = '.'; d_stderr("Failed to create jack client, reason was:\n%s", errorString.buffer()); } else d_stderr("Failed to create jack client, cannot continue!"); return 1; } USE_NAMESPACE_DISTRHO; initSignalHandler(); d_lastBufferSize = jack_get_buffer_size(client); d_lastSampleRate = jack_get_sample_rate(client); #if DISTRHO_PLUGIN_HAS_UI d_lastUiSampleRate = d_lastSampleRate; #endif const PluginJack p(client); return 0; } // ----------------------------------------------------------------------- <commit_msg>Call plugin de/activate in JACK standalone mode<commit_after>/* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2015 Filipe Coelho <falktx@falktx.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * For a full copy of the license see the LGPL.txt file */ #include "DistrhoPluginInternal.hpp" #if DISTRHO_PLUGIN_HAS_UI && ! defined(HAVE_DGL) # undef DISTRHO_PLUGIN_HAS_UI # define DISTRHO_PLUGIN_HAS_UI 0 #endif #if DISTRHO_PLUGIN_HAS_UI # include "DistrhoUIInternal.hpp" #else # include "../extra/Sleep.hpp" #endif #include "jack/jack.h" #include "jack/midiport.h" #include "jack/transport.h" #ifndef DISTRHO_OS_WINDOWS # include <signal.h> #endif // ----------------------------------------------------------------------- START_NAMESPACE_DISTRHO #if DISTRHO_PLUGIN_HAS_UI && ! DISTRHO_PLUGIN_WANT_STATE static const setStateFunc setStateCallback = nullptr; #endif // ----------------------------------------------------------------------- static volatile bool gCloseSignalReceived = false; #ifdef DISTRHO_OS_WINDOWS static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept { if (dwCtrlType == CTRL_C_EVENT) { gCloseSignalReceived = true; return TRUE; } return FALSE; } static void initSignalHandler() { SetConsoleCtrlHandler(winSignalHandler, TRUE); } #else static void closeSignalHandler(int) noexcept { gCloseSignalReceived = true; } static void initSignalHandler() { struct sigaction sint; struct sigaction sterm; sint.sa_handler = closeSignalHandler; sint.sa_flags = SA_RESTART; sint.sa_restorer = nullptr; sigemptyset(&sint.sa_mask); sigaction(SIGINT, &sint, nullptr); sterm.sa_handler = closeSignalHandler; sterm.sa_flags = SA_RESTART; sterm.sa_restorer = nullptr; sigemptyset(&sterm.sa_mask); sigaction(SIGTERM, &sterm, nullptr); } #endif // ----------------------------------------------------------------------- #if DISTRHO_PLUGIN_HAS_UI class PluginJack : public IdleCallback #else class PluginJack #endif { public: PluginJack(jack_client_t* const client) : fPlugin(), #if DISTRHO_PLUGIN_HAS_UI fUI(this, 0, nullptr, setParameterValueCallback, setStateCallback, nullptr, setSizeCallback, fPlugin.getInstancePointer()), #endif fClient(client) { char strBuf[0xff+1]; strBuf[0xff] = '\0'; #if DISTRHO_PLUGIN_NUM_INPUTS > 0 for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) { std::snprintf(strBuf, 0xff, "in%i", i+1); fPortAudioIns[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); } #endif #if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) { std::snprintf(strBuf, 0xff, "out%i", i+1); fPortAudioOuts[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); } #endif #if DISTRHO_PLUGIN_IS_SYNTH fPortMidiIn = jack_port_register(fClient, "midi-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0); #endif #if DISTRHO_PLUGIN_WANT_PROGRAMS if (fPlugin.getProgramCount() > 0) { fPlugin.loadProgram(0); # if DISTRHO_PLUGIN_HAS_UI fUI.programLoaded(0); # endif } #endif if (const uint32_t count = fPlugin.getParameterCount()) { fLastOutputValues = new float[count]; for (uint32_t i=0; i < count; ++i) { if (fPlugin.isParameterOutput(i)) { fLastOutputValues[i] = fPlugin.getParameterValue(i); } else { fLastOutputValues[i] = 0.0f; # if DISTRHO_PLUGIN_HAS_UI fUI.parameterChanged(i, fPlugin.getParameterValue(i)); # endif } } } else { fLastOutputValues = nullptr; } jack_set_buffer_size_callback(fClient, jackBufferSizeCallback, this); jack_set_sample_rate_callback(fClient, jackSampleRateCallback, this); jack_set_process_callback(fClient, jackProcessCallback, this); jack_on_shutdown(fClient, jackShutdownCallback, this); fPlugin.activate(); jack_activate(fClient); #if DISTRHO_PLUGIN_HAS_UI if (const char* const name = jack_get_client_name(fClient)) fUI.setWindowTitle(name); else fUI.setWindowTitle(fPlugin.getName()); fUI.exec(this); #else while (! gCloseSignalReceived) d_sleep(1); #endif } ~PluginJack() { if (fClient == nullptr) return; jack_deactivate(fClient); fPlugin.deactivate(); #if DISTRHO_PLUGIN_IS_SYNTH jack_port_unregister(fClient, fPortMidiIn); fPortMidiIn = nullptr; #endif #if DISTRHO_PLUGIN_NUM_INPUTS > 0 for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) { jack_port_unregister(fClient, fPortAudioIns[i]); fPortAudioIns[i] = nullptr; } #endif #if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) { jack_port_unregister(fClient, fPortAudioOuts[i]); fPortAudioOuts[i] = nullptr; } #endif jack_client_close(fClient); } // ------------------------------------------------------------------- protected: #if DISTRHO_PLUGIN_HAS_UI void idleCallback() override { if (gCloseSignalReceived) return fUI.quit(); float value; for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) { if (! fPlugin.isParameterOutput(i)) continue; value = fPlugin.getParameterValue(i); if (fLastOutputValues[i] == value) continue; fLastOutputValues[i] = value; fUI.parameterChanged(i, value); } fUI.exec_idle(); } #endif void jackBufferSize(const jack_nframes_t nframes) { fPlugin.setBufferSize(nframes, true); } void jackSampleRate(const jack_nframes_t nframes) { fPlugin.setSampleRate(nframes, true); } void jackProcess(const jack_nframes_t nframes) { #if DISTRHO_PLUGIN_NUM_INPUTS > 0 const float* audioIns[DISTRHO_PLUGIN_NUM_INPUTS]; for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) audioIns[i] = (const float*)jack_port_get_buffer(fPortAudioIns[i], nframes); #else static const float** audioIns = nullptr; #endif #if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 float* audioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS]; for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) audioOuts[i] = (float*)jack_port_get_buffer(fPortAudioOuts[i], nframes); #else static float** audioOuts = nullptr; #endif #if DISTRHO_PLUGIN_WANT_TIMEPOS jack_position_t pos; fTimePosition.playing = (jack_transport_query(fClient, &pos) == JackTransportRolling); if (pos.unique_1 == pos.unique_2) { fTimePosition.frame = pos.frame; if (pos.valid & JackTransportBBT) { fTimePosition.bbt.valid = true; fTimePosition.bbt.bar = pos.bar; fTimePosition.bbt.beat = pos.beat; fTimePosition.bbt.tick = pos.tick; fTimePosition.bbt.barStartTick = pos.bar_start_tick; fTimePosition.bbt.beatsPerBar = pos.beats_per_bar; fTimePosition.bbt.beatType = pos.beat_type; fTimePosition.bbt.ticksPerBeat = pos.ticks_per_beat; fTimePosition.bbt.beatsPerMinute = pos.beats_per_minute; } else fTimePosition.bbt.valid = false; } else { fTimePosition.bbt.valid = false; fTimePosition.frame = 0; } fPlugin.setTimePosition(fTimePosition); #endif #if DISTRHO_PLUGIN_IS_SYNTH void* const midiBuf = jack_port_get_buffer(fPortMidiIn, nframes); if (const uint32_t eventCount = jack_midi_get_event_count(midiBuf)) { uint32_t midiEventCount = 0; MidiEvent midiEvents[eventCount]; jack_midi_event_t jevent; for (uint32_t i=0; i < eventCount; ++i) { if (jack_midi_event_get(&jevent, midiBuf, i) != 0) break; MidiEvent& midiEvent(midiEvents[midiEventCount++]); midiEvent.frame = jevent.time; midiEvent.size = jevent.size; if (midiEvent.size > MidiEvent::kDataSize) midiEvent.dataExt = jevent.buffer; else std::memcpy(midiEvent.data, jevent.buffer, midiEvent.size); } fPlugin.run(audioIns, audioOuts, nframes, midiEvents, midiEventCount); } else { fPlugin.run(audioIns, audioOuts, nframes, nullptr, 0); } #else fPlugin.run(audioIns, audioOuts, nframes); #endif } void jackShutdown() { d_stderr("jack has shutdown, quitting now..."); fClient = nullptr; #if DISTRHO_PLUGIN_HAS_UI fUI.quit(); #endif } // ------------------------------------------------------------------- void setParameterValue(const uint32_t index, const float value) { fPlugin.setParameterValue(index, value); } #if DISTRHO_PLUGIN_WANT_STATE void setState(const char* const key, const char* const value) { fPlugin.setState(key, value); } #endif #if DISTRHO_PLUGIN_HAS_UI void setSize(const uint width, const uint height) { fUI.setWindowSize(width, height); } #endif // ------------------------------------------------------------------- private: PluginExporter fPlugin; #if DISTRHO_PLUGIN_HAS_UI UIExporter fUI; #endif jack_client_t* fClient; #if DISTRHO_PLUGIN_NUM_INPUTS > 0 jack_port_t* fPortAudioIns[DISTRHO_PLUGIN_NUM_INPUTS]; #endif #if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 jack_port_t* fPortAudioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS]; #endif #if DISTRHO_PLUGIN_IS_SYNTH jack_port_t* fPortMidiIn; #endif #if DISTRHO_PLUGIN_WANT_TIMEPOS TimePosition fTimePosition; #endif // Temporary data float* fLastOutputValues; // ------------------------------------------------------------------- // Callbacks #define uiPtr ((PluginJack*)ptr) static int jackBufferSizeCallback(jack_nframes_t nframes, void* ptr) { uiPtr->jackBufferSize(nframes); return 0; } static int jackSampleRateCallback(jack_nframes_t nframes, void* ptr) { uiPtr->jackSampleRate(nframes); return 0; } static int jackProcessCallback(jack_nframes_t nframes, void* ptr) { uiPtr->jackProcess(nframes); return 0; } static void jackShutdownCallback(void* ptr) { uiPtr->jackShutdown(); } static void setParameterValueCallback(void* ptr, uint32_t index, float value) { uiPtr->setParameterValue(index, value); } #if DISTRHO_PLUGIN_WANT_STATE static void setStateCallback(void* ptr, const char* key, const char* value) { uiPtr->setState(key, value); } #endif #if DISTRHO_PLUGIN_HAS_UI static void setSizeCallback(void* ptr, uint width, uint height) { uiPtr->setSize(width, height); } #endif #undef uiPtr }; END_NAMESPACE_DISTRHO // ----------------------------------------------------------------------- int main() { USE_NAMESPACE_DISTRHO; jack_status_t status = jack_status_t(0x0); jack_client_t* client = jack_client_open(DISTRHO_PLUGIN_NAME, JackNoStartServer, &status); if (client == nullptr) { String errorString; if (status & JackFailure) errorString += "Overall operation failed;\n"; if (status & JackInvalidOption) errorString += "The operation contained an invalid or unsupported option;\n"; if (status & JackNameNotUnique) errorString += "The desired client name was not unique;\n"; if (status & JackServerStarted) errorString += "The JACK server was started as a result of this operation;\n"; if (status & JackServerFailed) errorString += "Unable to connect to the JACK server;\n"; if (status & JackServerError) errorString += "Communication error with the JACK server;\n"; if (status & JackNoSuchClient) errorString += "Requested client does not exist;\n"; if (status & JackLoadFailure) errorString += "Unable to load internal client;\n"; if (status & JackInitFailure) errorString += "Unable to initialize client;\n"; if (status & JackShmFailure) errorString += "Unable to access shared memory;\n"; if (status & JackVersionError) errorString += "Client's protocol version does not match;\n"; if (status & JackBackendError) errorString += "Backend Error;\n"; if (status & JackClientZombie) errorString += "Client is being shutdown against its will;\n"; if (errorString.isNotEmpty()) { errorString[errorString.length()-2] = '.'; d_stderr("Failed to create jack client, reason was:\n%s", errorString.buffer()); } else d_stderr("Failed to create jack client, cannot continue!"); return 1; } USE_NAMESPACE_DISTRHO; initSignalHandler(); d_lastBufferSize = jack_get_buffer_size(client); d_lastSampleRate = jack_get_sample_rate(client); #if DISTRHO_PLUGIN_HAS_UI d_lastUiSampleRate = d_lastSampleRate; #endif const PluginJack p(client); return 0; } // ----------------------------------------------------------------------- <|endoftext|>
<commit_before>/**helloWorld.cpp*/ //Std #include <iostream> #include <math.h> #include <cstdlib> //eigen #include <eigen3/Eigen/Dense> #include <eigen3/Eigen/Geometry> // import most common Eigen types using namespace std; using namespace Eigen; int main(int argc, char *argv[]) { // Let's print it pretty cout.precision(4); // Given data Vector2f p_O(10.8, -2.7); Vector2f m_B(3.1, 1.2); double theta = 28.0; double beta = 41.0; Vector2f q_S(12.0, 3.0); cout << "The points involved are:" << endl; cout << "p wrt O:" << endl; cout << p_O << endl << endl; cout << "m wrt B:" << endl; cout << m_B << endl << endl; cout << "The rotation matrixes involved are:" << endl; Matrix2f R_B_O; Matrix2f R_S_B; R_B_O << cos(theta), -sin(theta), sin(theta), cos(theta); R_S_B << cos(beta), -sin(beta), sin(beta), cos(beta); cout << "R_B wrt O:" << endl; cout << R_B_O << endl << endl; cout << "R_S wrt B:" << endl; cout << R_S_B << endl << endl; cout << "and the homogeneous matrixes representing the" << endl; cout << "transformations from the origin to the base," << endl; cout << "and from the base to the sensor, are respectively:" << endl; Matrix3f T_B_O; Matrix3f T_S_B; T_B_O << R_B_O(0,0), R_B_O(0,1), p_O[0], R_B_O(1,0), R_B_O(1,1), p_O[1], 0, 0, 1; T_S_B << R_S_B(0,0), R_S_B(0,1), m_B[0], R_S_B(1,0), R_S_B(1,1), m_B[1], 0, 0, 1; cout << "T in B wrt O:" << endl; cout << T_B_O << endl << endl; cout << "T in S wrt B:" << endl; cout << T_S_B << endl << endl; cout << "So the point q with respect to the vehicle base frame" << endl; cout << "and with respect to the origin of the trajectory is:" << endl; Vector3f q_S_tmp(q_S[0], q_S[1], 1); Vector3f q_B_tmp = T_S_B * q_S_tmp; Vector3f q_O_tmp = T_B_O * T_S_B * q_S_tmp; Vector2f q_B(q_B_tmp[0], q_B_tmp[1]); Vector2f q_O(q_O_tmp[0], q_O_tmp[1]); cout << "Coordinates of q wrt B:" << endl; cout << q_B << endl << endl; cout << "Coordinates of q wrt O:" << endl; cout << q_O << endl << endl; return 0; } <commit_msg>Small fix.<commit_after>/**helloWorld.cpp*/ //Std #include <iostream> #include <math.h> #include <cstdlib> //eigen #include <eigen3/Eigen/Dense> #include <eigen3/Eigen/Geometry> // import most common Eigen types using namespace std; using namespace Eigen; int main(int argc, char *argv[]) { // Let's print it pretty cout.precision(4); // Given data Vector2f p_O(10.8, -2.7); Vector2f m_B(3.1, 1.2); double theta = 28.0; double beta = 41.0; Vector2f q_S(12.0, 3.0); cout << "The points involved are:" << endl; cout << "Coordinates of p wrt O:" << endl; cout << p_O << endl << endl; cout << "Coordinates of m wrt B:" << endl; cout << m_B << endl << endl; cout << "Coordinates of q wrt S:" << endl; cout << q_S << endl << endl; cout << "The rotation matrixes involved are:" << endl; Matrix2f R_B_O; Matrix2f R_S_B; R_B_O << cos(theta), -sin(theta), sin(theta), cos(theta); R_S_B << cos(beta), -sin(beta), sin(beta), cos(beta); cout << "R in B wrt O:" << endl; cout << R_B_O << endl << endl; cout << "R in S wrt B:" << endl; cout << R_S_B << endl << endl; cout << "and the homogeneous matrixes representing the" << endl; cout << "transformations from the origin to the base," << endl; cout << "and from the base to the sensor, are respectively:" << endl; Matrix3f T_B_O; Matrix3f T_S_B; T_B_O << R_B_O(0,0), R_B_O(0,1), p_O[0], R_B_O(1,0), R_B_O(1,1), p_O[1], 0, 0, 1; T_S_B << R_S_B(0,0), R_S_B(0,1), m_B[0], R_S_B(1,0), R_S_B(1,1), m_B[1], 0, 0, 1; cout << "T in B wrt O:" << endl; cout << T_B_O << endl << endl; cout << "T in S wrt B:" << endl; cout << T_S_B << endl << endl; cout << "So the point q with respect to the vehicle base frame" << endl; cout << "and with respect to the origin of the trajectory is:" << endl; Vector3f q_S_tmp(q_S[0], q_S[1], 1); Vector3f q_B_tmp = T_S_B * q_S_tmp; Vector3f q_O_tmp = T_B_O * T_S_B * q_S_tmp; Vector2f q_B(q_B_tmp[0], q_B_tmp[1]); Vector2f q_O(q_O_tmp[0], q_O_tmp[1]); cout << "Coordinates of q wrt B:" << endl; cout << q_B << endl << endl; cout << "Coordinates of q wrt O:" << endl; cout << q_O << endl << endl; return 0; } <|endoftext|>
<commit_before>/* * ClusteringAlgoGTest.cpp * * Created on: 10.01.2013 * Author: Christian Staudt (christian.staudt@kit.edu) */ #include "ClusteringAlgoGTest.h" #include "../PLP.h" #include "../PLM.h" #include "../CNM.h" #include "../ParallelAgglomerativeClusterer.h" #include "../../clustering/Modularity.h" #include "../../graph/GraphGenerator.h" #include "../../clustering/ClusteringGenerator.h" #include "../../io/METISGraphReader.h" #include "../EPP.h" #include "../../overlap/HashingOverlapper.h" #include "../EPPFactory.h" #include "../CommunityGraph.h" #include "../PLM2.h" #include "../../clustering/GraphClusteringTools.h" #ifndef NOGTEST namespace NetworKit { TEST_F(ClusteringAlgoGTest, testEnsemblePreprocessing) { count n = 1000; count k = 10; double pin = 1.0; double pout = 0.0; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); EPP ensemble; count b = 4; for (count i = 0; i < b; ++i) { ensemble.addBaseClusterer(*(new PLP())); } ensemble.setFinalClusterer(*(new PLM())); ensemble.setOverlapper(*(new HashingOverlapper)); Partition zeta = ensemble.run(G); INFO("number of clusters:" , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnUniformGraph) { GraphGenerator graphGenerator; int n = 100; Graph G = graphGenerator.makeErdosRenyiGraph(n, 0.2); PLP lp; Partition zeta = lp.run(G); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)) << "the resulting partition should be a proper clustering"; Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); EXPECT_GE(1.0, mod) << "valid modularity values are in [-0.5, 1]"; EXPECT_LE(-0.5, mod) << "valid modularity values are in [-0.5, 1]"; } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnClusteredGraph_ForNumberOfClusters) { GraphGenerator graphGenerator; int64_t n = 100; count k = 3; // number of clusters Graph G = graphGenerator.makeClusteredRandomGraph(n, k, 1.0, 0.001); PLP lp; Partition zeta = lp.run(G); Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)) << "the resulting partition should be a proper clustering"; EXPECT_EQ(k, zeta.numberOfSubsets()) << " " << k << " clusters are easy to detect"; } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnClusteredGraph_ForEquality) { int64_t n = 100; GraphGenerator graphGen; Graph Gtrash = graphGen.makeCompleteGraph(n); count k = 3; // number of clusters ClusteringGenerator clusteringGen; Partition reference = clusteringGen.makeRandomClustering(Gtrash, k); assert (reference.numberOfSubsets() == k); Graph G = graphGen.makeClusteredRandomGraph(reference, 1.0, 0.0); // LabelPropagation is very bad at discerning clusters and needs this large pin/pout difference PLP lp; Partition zeta = lp.run(G); Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); DEBUG("number of clusters produced by LabelPropagation: k=" , zeta.numberOfSubsets()); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)) << "the resulting partition should be a proper clustering"; EXPECT_TRUE(GraphClusteringTools::equalClusterings(zeta, reference, G)) << "LP should detect exactly the reference clustering"; } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnDisconnectedGraph) { GraphGenerator graphGenerator; int n = 100; int k = 2; // number of clusters Graph G = graphGenerator.makeClusteredRandomGraph(n, k, 1.0, 0.0); PLP lp; Partition zeta = lp.run(G); Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)) << "the resulting partition should be a proper clustering"; EXPECT_EQ(k, zeta.numberOfSubsets()) << " " << k << " clusters are easy to detect"; //FIXME } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnSingleNodeWithSelfLoop) { Graph G(1); node v = 0; G.setWeight(v, v, 42.0); PLP lp; Partition zeta = lp.run(G); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)); EXPECT_TRUE(GraphClusteringTools::isSingletonClustering(G, zeta)); EXPECT_TRUE(GraphClusteringTools::isOneClustering(G, zeta)); //FIXME does this make sense? singleton and one partition at the same time. Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnManySmallClusters) { int64_t n = 1000; int k = 100; // number of clusters double pin = 1.0; double pout = 0.0; GraphGenerator graphGen; std::pair<Graph, Partition> G_ref = graphGen.makeClusteredRandomGraphWithReferenceClustering(n, k, pin, pout); PLP lp; Partition zeta = lp.run(G_ref.first); Modularity modularity; double mod = modularity.getQuality(zeta, G_ref.first); DEBUG("modularity produced by LabelPropagation: " , mod); DEBUG("number of clusters produced by LabelPropagation: k=" , zeta.numberOfSubsets()); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G_ref.first, zeta)) << "the resulting partition should be a proper clustering"; EXPECT_TRUE(GraphClusteringTools::equalClusterings(zeta, G_ref.second, G_ref.first)) << "Can LabelPropagation detect the reference clustering?"; } TEST_F(ClusteringAlgoGTest, testLouvain) { count n = 500; count k = 25; double pin = 0.9; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); PLM louvain; Partition zeta = louvain.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } TEST_F(ClusteringAlgoGTest, testLouvainParallelSimple) { count n = 500; count k = 25; double pin = 0.9; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); PLM louvain("simple"); Partition zeta = louvain.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } /* TEST_F(ClusteringAlgoGTest, testLouvainParallel2Naive) { count n = 1000; count k = 100; double pin = 1.0; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); LouvainParallel louvain; Partition zeta = louvain.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } */ TEST_F(ClusteringAlgoGTest, testLouvainParallelBalanced) { count n = 500; count k = 25; double pin = 0.9; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); PLM louvain("balanced"); Partition zeta = louvain.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } TEST_F(ClusteringAlgoGTest, testCNM) { count n = 200; count k = 25; double pin = 0.9; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); Modularity modularity; // CNM with PQ CNM cnm; Partition clustering = cnm.run(G); INFO("CNM number of clusters: " , clustering.numberOfSubsets()); INFO("modularity clustered random graph: " , modularity.getQuality(clustering, G)); // EXPECT_GE(modularity.getQuality(clustering, G), 0.5); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, clustering)); } TEST_F(ClusteringAlgoGTest, testCNMandLouvain) { Modularity modularity; CNM cnm; PLM louvain; METISGraphReader reader; Graph jazz = reader.read("input/jazz.graph"); // this takes much longer than a unit test should // Graph blog = reader.read("input/polblogs.graph"); // *** jazz graph // Louvain Partition clustering = louvain.run(jazz); INFO("Louvain number of jazz clusters: " , clustering.numberOfSubsets()); INFO("Louvain modularity jazz graph: " , modularity.getQuality(clustering, jazz)); // CNM clustering = cnm.run(jazz); INFO("CNM number of jazz clusters: " , clustering.numberOfSubsets()); INFO("CNM modularity jazz graph: " , modularity.getQuality(clustering, jazz)); // // *** blog graph // // CNM // clustering = cnm.run(blog); // INFO("CNM number of blog clusters: " , clustering.numberOfSubsets()); // INFO("CNM modularity blog graph: " , modularity.getQuality(clustering, jazz)); // // // Louvain // clustering = louvain.run(blog); // INFO("Louvain number of blog clusters: " , clustering.numberOfSubsets()); // INFO("Louvain modularity blog graph: " , modularity.getQuality(clustering, jazz)); } TEST_F(ClusteringAlgoGTest, testParallelAgglomerativeAndLouvain) { Modularity modularity; ParallelAgglomerativeClusterer aggl; PLM louvain; METISGraphReader reader; Graph jazz = reader.read("input/jazz.graph"); Graph blog = reader.read("input/polblogs.graph"); // *** jazz graph // aggl Partition clustering = aggl.run(jazz); INFO("Match-AGGL number of jazz clusters: " , clustering.numberOfSubsets()); INFO("Match-AGGL modularity jazz graph: " , modularity.getQuality(clustering, jazz)); // Louvain clustering = louvain.run(jazz); INFO("Louvain number of jazz clusters: " , clustering.numberOfSubsets()); INFO("Louvain modularity jazz graph: " , modularity.getQuality(clustering, jazz)); // *** blog graph // CNM clustering = aggl.run(blog); INFO("Match-AGGL number of blog clusters: " , clustering.numberOfSubsets()); INFO("Match-AGGL modularity blog graph: " , modularity.getQuality(clustering, blog)); // Louvain clustering = louvain.run(blog); INFO("Louvain number of blog clusters: " , clustering.numberOfSubsets()); INFO("Louvain modularity blog graph: " , modularity.getQuality(clustering, blog)); } TEST_F(ClusteringAlgoGTest, testEPPFactory) { EPPFactory factory; EPP epp = factory.make(4, "PLP", "PLM"); METISGraphReader reader; Graph jazz = reader.read("input/jazz.graph"); Partition zeta = epp.run(jazz); INFO("number of clusters: " , zeta.numberOfSubsets()); EXPECT_TRUE(GraphClusteringTools::isProperClustering(jazz, zeta)); } TEST_F(ClusteringAlgoGTest, testPLM2) { METISGraphReader reader; Modularity modularity; Graph G = reader.read("input/PGPgiantcompo.graph"); PLM2 plm(false, 1.0); Partition zeta = plm.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); INFO("modularity: " , modularity.getQuality(zeta, G)); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)); PLM2 plmr(true, 1.0); Partition zeta2 = plmr.run(G); INFO("number of clusters: " , zeta2.numberOfSubsets()); INFO("modularity: " , modularity.getQuality(zeta2, G)); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta2)); } TEST_F(ClusteringAlgoGTest, testCommunityGraph) { CommunityGraph com; METISGraphReader reader; Graph G = reader.read("input/jazz.graph"); ClusteringGenerator clusteringGen; Partition one = clusteringGen.makeOneClustering(G); com.run(G, one); EXPECT_EQ(1, com.getGraph().numberOfNodes()); Partition singleton = clusteringGen.makeSingletonClustering(G); com.run(G, singleton); EXPECT_EQ(G.numberOfNodes(), com.getGraph().numberOfNodes()); Partition zeta = (new PLP())->run(G); com.run(G, zeta); EXPECT_EQ(zeta.numberOfSubsets(), com.getGraph().numberOfNodes()); } } /* namespace NetworKit */ #endif /*NOGTEST */ <commit_msg>test update<commit_after>/* * ClusteringAlgoGTest.cpp * * Created on: 10.01.2013 * Author: Christian Staudt (christian.staudt@kit.edu) */ #include "ClusteringAlgoGTest.h" #include "../PLP.h" #include "../PLM.h" #include "../CNM.h" #include "../ParallelAgglomerativeClusterer.h" #include "../../clustering/Modularity.h" #include "../../graph/GraphGenerator.h" #include "../../clustering/ClusteringGenerator.h" #include "../../io/METISGraphReader.h" #include "../EPP.h" #include "../../overlap/HashingOverlapper.h" #include "../EPPFactory.h" #include "../CommunityGraph.h" #include "../PLM2.h" #include "../../clustering/GraphClusteringTools.h" #ifndef NOGTEST namespace NetworKit { TEST_F(ClusteringAlgoGTest, testEnsemblePreprocessing) { count n = 1000; count k = 10; double pin = 1.0; double pout = 0.0; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); EPP ensemble; count b = 4; for (count i = 0; i < b; ++i) { ensemble.addBaseClusterer(*(new PLP())); } ensemble.setFinalClusterer(*(new PLM())); ensemble.setOverlapper(*(new HashingOverlapper)); Partition zeta = ensemble.run(G); INFO("number of clusters:" , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnUniformGraph) { GraphGenerator graphGenerator; int n = 100; Graph G = graphGenerator.makeErdosRenyiGraph(n, 0.2); PLP lp; Partition zeta = lp.run(G); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)) << "the resulting partition should be a proper clustering"; Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); EXPECT_GE(1.0, mod) << "valid modularity values are in [-0.5, 1]"; EXPECT_LE(-0.5, mod) << "valid modularity values are in [-0.5, 1]"; } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnClusteredGraph_ForNumberOfClusters) { GraphGenerator graphGenerator; int64_t n = 100; count k = 3; // number of clusters Graph G = graphGenerator.makeClusteredRandomGraph(n, k, 1.0, 0.001); PLP lp; Partition zeta = lp.run(G); Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)) << "the resulting partition should be a proper clustering"; EXPECT_EQ(k, zeta.numberOfSubsets()) << " " << k << " clusters are easy to detect"; } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnClusteredGraph_ForEquality) { int64_t n = 100; GraphGenerator graphGen; Graph Gtrash = graphGen.makeCompleteGraph(n); count k = 3; // number of clusters ClusteringGenerator clusteringGen; Partition reference = clusteringGen.makeRandomClustering(Gtrash, k); assert (reference.numberOfSubsets() == k); Graph G = graphGen.makeClusteredRandomGraph(reference, 1.0, 0.0); // LabelPropagation is very bad at discerning clusters and needs this large pin/pout difference PLP lp; Partition zeta = lp.run(G); Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); DEBUG("number of clusters produced by LabelPropagation: k=" , zeta.numberOfSubsets()); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)) << "the resulting partition should be a proper clustering"; EXPECT_TRUE(GraphClusteringTools::equalClusterings(zeta, reference, G)) << "LP should detect exactly the reference clustering"; } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnDisconnectedGraph) { GraphGenerator graphGenerator; int n = 100; int k = 2; // number of clusters Graph G = graphGenerator.makeClusteredRandomGraph(n, k, 1.0, 0.0); PLP lp; Partition zeta = lp.run(G); Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)) << "the resulting partition should be a proper clustering"; EXPECT_EQ(k, zeta.numberOfSubsets()) << " " << k << " clusters are easy to detect"; //FIXME } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnSingleNodeWithSelfLoop) { Graph G(1); node v = 0; G.setWeight(v, v, 42.0); PLP lp; Partition zeta = lp.run(G); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)); EXPECT_TRUE(GraphClusteringTools::isSingletonClustering(G, zeta)); EXPECT_TRUE(GraphClusteringTools::isOneClustering(G, zeta)); //FIXME does this make sense? singleton and one partition at the same time. Modularity modularity; double mod = modularity.getQuality(zeta, G); DEBUG("modularity produced by LabelPropagation: " , mod); } TEST_F(ClusteringAlgoGTest, testLabelPropagationOnManySmallClusters) { int64_t n = 1000; int k = 100; // number of clusters double pin = 1.0; double pout = 0.0; GraphGenerator graphGen; std::pair<Graph, Partition> G_ref = graphGen.makeClusteredRandomGraphWithReferenceClustering(n, k, pin, pout); PLP lp; Partition zeta = lp.run(G_ref.first); Modularity modularity; double mod = modularity.getQuality(zeta, G_ref.first); DEBUG("modularity produced by LabelPropagation: " , mod); DEBUG("number of clusters produced by LabelPropagation: k=" , zeta.numberOfSubsets()); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G_ref.first, zeta)) << "the resulting partition should be a proper clustering"; EXPECT_TRUE(GraphClusteringTools::equalClusterings(zeta, G_ref.second, G_ref.first)) << "Can LabelPropagation detect the reference clustering?"; } TEST_F(ClusteringAlgoGTest, testLouvain) { count n = 500; count k = 25; double pin = 0.9; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); PLM louvain; Partition zeta = louvain.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } TEST_F(ClusteringAlgoGTest, testLouvainParallelSimple) { count n = 500; count k = 25; double pin = 0.9; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); PLM louvain("simple"); Partition zeta = louvain.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } /* TEST_F(ClusteringAlgoGTest, testLouvainParallel2Naive) { count n = 1000; count k = 100; double pin = 1.0; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); LouvainParallel louvain; Partition zeta = louvain.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } */ TEST_F(ClusteringAlgoGTest, testLouvainParallelBalanced) { count n = 500; count k = 25; double pin = 0.9; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); PLM louvain("balanced"); Partition zeta = louvain.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); Modularity modularity; INFO("modularity: " , modularity.getQuality(zeta, G)); } TEST_F(ClusteringAlgoGTest, testCNM) { count n = 200; count k = 25; double pin = 0.9; double pout = 0.005; GraphGenerator graphGen; Graph G = graphGen.makeClusteredRandomGraph(n, k, pin, pout); Modularity modularity; // CNM with PQ CNM cnm; Partition clustering = cnm.run(G); INFO("CNM number of clusters: " , clustering.numberOfSubsets()); INFO("modularity clustered random graph: " , modularity.getQuality(clustering, G)); // EXPECT_GE(modularity.getQuality(clustering, G), 0.5); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, clustering)); } TEST_F(ClusteringAlgoGTest, testCNMandLouvain) { Modularity modularity; CNM cnm; PLM louvain; METISGraphReader reader; Graph jazz = reader.read("input/jazz.graph"); // this takes much longer than a unit test should // Graph blog = reader.read("input/polblogs.graph"); // *** jazz graph // Louvain Partition clustering = louvain.run(jazz); INFO("Louvain number of jazz clusters: " , clustering.numberOfSubsets()); INFO("Louvain modularity jazz graph: " , modularity.getQuality(clustering, jazz)); // CNM clustering = cnm.run(jazz); INFO("CNM number of jazz clusters: " , clustering.numberOfSubsets()); INFO("CNM modularity jazz graph: " , modularity.getQuality(clustering, jazz)); // // *** blog graph // // CNM // clustering = cnm.run(blog); // INFO("CNM number of blog clusters: " , clustering.numberOfSubsets()); // INFO("CNM modularity blog graph: " , modularity.getQuality(clustering, jazz)); // // // Louvain // clustering = louvain.run(blog); // INFO("Louvain number of blog clusters: " , clustering.numberOfSubsets()); // INFO("Louvain modularity blog graph: " , modularity.getQuality(clustering, jazz)); } TEST_F(ClusteringAlgoGTest, testParallelAgglomerativeAndPLM2) { Modularity modularity; ParallelAgglomerativeClusterer aggl; PLM2 louvain; METISGraphReader reader; Graph jazz = reader.read("input/jazz.graph"); Graph blog = reader.read("input/polblogs.graph"); // *** jazz graph // parallel agglomerative Partition clustering = aggl.run(jazz); INFO("Match-AGGL number of jazz clusters: " , clustering.numberOfSubsets()); INFO("Match-AGGL modularity jazz graph: " , modularity.getQuality(clustering, jazz)); // Louvain clustering = louvain.run(jazz); INFO("Louvain number of jazz clusters: " , clustering.numberOfSubsets()); INFO("Louvain modularity jazz graph: " , modularity.getQuality(clustering, jazz)); // *** blog graph // parallel agglomerative clustering = aggl.run(blog); INFO("Match-AGGL number of blog clusters: " , clustering.numberOfSubsets()); INFO("Match-AGGL modularity blog graph: " , modularity.getQuality(clustering, blog)); // Louvain clustering = louvain.run(blog); INFO("Louvain number of blog clusters: " , clustering.numberOfSubsets()); INFO("Louvain modularity blog graph: " , modularity.getQuality(clustering, blog)); } TEST_F(ClusteringAlgoGTest, testEPPFactory) { EPPFactory factory; EPP epp = factory.make(4, "PLP", "PLM"); METISGraphReader reader; Graph jazz = reader.read("input/jazz.graph"); Partition zeta = epp.run(jazz); INFO("number of clusters: " , zeta.numberOfSubsets()); EXPECT_TRUE(GraphClusteringTools::isProperClustering(jazz, zeta)); } TEST_F(ClusteringAlgoGTest, testPLM2) { METISGraphReader reader; Modularity modularity; Graph G = reader.read("input/PGPgiantcompo.graph"); PLM2 plm(false, 1.0); Partition zeta = plm.run(G); INFO("number of clusters: " , zeta.numberOfSubsets()); INFO("modularity: " , modularity.getQuality(zeta, G)); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta)); PLM2 plmr(true, 1.0); Partition zeta2 = plmr.run(G); INFO("number of clusters: " , zeta2.numberOfSubsets()); INFO("modularity: " , modularity.getQuality(zeta2, G)); EXPECT_TRUE(GraphClusteringTools::isProperClustering(G, zeta2)); } TEST_F(ClusteringAlgoGTest, testCommunityGraph) { CommunityGraph com; METISGraphReader reader; Graph G = reader.read("input/jazz.graph"); ClusteringGenerator clusteringGen; Partition one = clusteringGen.makeOneClustering(G); com.run(G, one); EXPECT_EQ(1, com.getGraph().numberOfNodes()); Partition singleton = clusteringGen.makeSingletonClustering(G); com.run(G, singleton); EXPECT_EQ(G.numberOfNodes(), com.getGraph().numberOfNodes()); Partition zeta = (new PLP())->run(G); com.run(G, zeta); EXPECT_EQ(zeta.numberOfSubsets(), com.getGraph().numberOfNodes()); } } /* namespace NetworKit */ #endif /*NOGTEST */ <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreGLES2Texture.h" #include "OgreGLES2PixelFormat.h" #include "OgreGLES2RenderSystem.h" #include "OgreGLES2HardwarePixelBuffer.h" #include "OgreRoot.h" namespace Ogre { static inline void doImageIO(const String &name, const String &group, const String &ext, vector<Image>::type &images, Resource *r) { size_t imgIdx = images.size(); images.push_back(Image()); DataStreamPtr dstream = ResourceGroupManager::getSingleton().openResource( name, group, true, r); images[imgIdx].load(dstream, ext); } GLES2Texture::GLES2Texture(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader, GLES2Support& support) : Texture(creator, name, handle, group, isManual, loader), mTextureID(0), mGLSupport(support) { } GLES2Texture::~GLES2Texture() { // have to call this here rather than in Resource destructor // since calling virtual methods in base destructors causes crash if (isLoaded()) { unload(); } else { freeInternalResources(); } } GLenum GLES2Texture::getGLES2TextureTarget(void) const { switch(mTextureType) { case TEX_TYPE_1D: case TEX_TYPE_2D: return GL_TEXTURE_2D; case TEX_TYPE_CUBE_MAP: return GL_TEXTURE_CUBE_MAP; default: return 0; }; } // Creation / loading methods void GLES2Texture::createInternalResourcesImpl(void) { // Convert to nearest power-of-two size if required mWidth = GLES2PixelUtil::optionalPO2(mWidth); mHeight = GLES2PixelUtil::optionalPO2(mHeight); mDepth = GLES2PixelUtil::optionalPO2(mDepth); // Adjust format if required mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); // Check requested number of mipmaps size_t maxMips = GLES2PixelUtil::getMaxMipmaps(mWidth, mHeight, mDepth, mFormat); if(PixelUtil::isCompressed(mFormat) && (mNumMipmaps == 0)) mNumRequestedMipmaps = 0; mNumMipmaps = mNumRequestedMipmaps; if (mNumMipmaps > maxMips) mNumMipmaps = maxMips; // Generate texture name glGenTextures(1, &mTextureID); GL_CHECK_ERROR; // Set texture type glBindTexture(getGLES2TextureTarget(), mTextureID); GL_CHECK_ERROR; #if GL_APPLE_texture_max_level glTexParameteri( getGLES2TextureTarget(), GL_TEXTURE_MAX_LEVEL_APPLE, mNumMipmaps ); #endif // Set some misc default parameters, these can of course be changed later glTexParameteri(getGLES2TextureTarget(), GL_TEXTURE_MIN_FILTER, GL_NEAREST); GL_CHECK_ERROR; glTexParameteri(getGLES2TextureTarget(), GL_TEXTURE_MAG_FILTER, GL_NEAREST); GL_CHECK_ERROR; glTexParameteri(getGLES2TextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); GL_CHECK_ERROR; glTexParameteri(getGLES2TextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); GL_CHECK_ERROR; // If we can do automip generation and the user desires this, do so mMipmapsHardwareGenerated = Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_AUTOMIPMAP) && !PixelUtil::isCompressed(mFormat); if ((mUsage & TU_AUTOMIPMAP) && mNumRequestedMipmaps && mMipmapsHardwareGenerated) { glGenerateMipmap(getGLES2TextureTarget()); GL_CHECK_ERROR; } // Allocate internal buffer so that glTexSubImageXD can be used // Internal format GLenum format = GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma); GLenum datatype = GLES2PixelUtil::getGLOriginDataType(mFormat); size_t width = mWidth; size_t height = mHeight; size_t depth = mDepth; if (PixelUtil::isCompressed(mFormat)) { // Compressed formats size_t size = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); // Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not // accept a 0 pointer like normal glTexImageXD // Run through this process for every mipmap to pregenerate mipmap pyramid uint8* tmpdata = OGRE_NEW_FIX_FOR_WIN32 uint8[size]; memset(tmpdata, 0, size); for (size_t mip = 0; mip <= mNumMipmaps; mip++) { size = PixelUtil::getMemorySize(width, height, depth, mFormat); switch(mTextureType) { case TEX_TYPE_1D: case TEX_TYPE_2D: glCompressedTexImage2D(GL_TEXTURE_2D, mip, format, width, height, 0, size, tmpdata); GL_CHECK_ERROR; break; case TEX_TYPE_CUBE_MAP: for(int face = 0; face < 6; face++) { glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, width, height, 0, size, tmpdata); GL_CHECK_ERROR; } break; case TEX_TYPE_3D: default: break; }; // LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) + // " Width: " + StringConverter::toString(width) + // " Height: " + StringConverter::toString(height) + // " Internal Format: " + StringConverter::toString(format) // ); if(width > 1) { width = width / 2; } if(height > 1) { height = height / 2; } if(depth > 1) { depth = depth / 2; } } OGRE_DELETE [] tmpdata; } else { // Run through this process to pregenerate mipmap pyramid for(size_t mip = 0; mip <= mNumMipmaps; mip++) { // Normal formats switch(mTextureType) { case TEX_TYPE_1D: case TEX_TYPE_2D: glTexImage2D(GL_TEXTURE_2D, mip, format, width, height, 0, format, datatype, 0); GL_CHECK_ERROR; break; case TEX_TYPE_CUBE_MAP: for(int face = 0; face < 6; face++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, width, height, 0, format, datatype, 0); } break; case TEX_TYPE_3D: default: break; }; // LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) + // " Width: " + StringConverter::toString(width) + // " Height: " + StringConverter::toString(height) + // " Internal Format: " + StringConverter::toString(format) // ); if (width > 1) { width = width / 2; } if (height > 1) { height = height / 2; } } } _createSurfaceList(); // Get final internal format mFormat = getBuffer(0,0)->getFormat(); } void GLES2Texture::createRenderTexture(void) { // Create the GL texture // This already does everything neccessary createInternalResources(); } void GLES2Texture::prepareImpl() { if (mUsage & TU_RENDERTARGET) return; String baseName, ext; size_t pos = mName.find_last_of("."); baseName = mName.substr(0, pos); if (pos != String::npos) { ext = mName.substr(pos+1); } LoadedImages loadedImages = LoadedImages(OGRE_NEW_FIX_FOR_WIN32 vector<Image>::type()); if (mTextureType == TEX_TYPE_1D || mTextureType == TEX_TYPE_2D) { doImageIO(mName, mGroup, ext, *loadedImages, this); // If this is a volumetric texture set the texture type flag accordingly. // If this is a cube map, set the texture type flag accordingly. if ((*loadedImages)[0].hasFlag(IF_CUBEMAP)) mTextureType = TEX_TYPE_CUBE_MAP; // If PVRTC and 0 custom mipmap disable auto mip generation and disable software mipmap creation PixelFormat imageFormat = (*loadedImages)[0].getFormat(); if (imageFormat == PF_PVRTC_RGB2 || imageFormat == PF_PVRTC_RGBA2 || imageFormat == PF_PVRTC_RGB4 || imageFormat == PF_PVRTC_RGBA4) { size_t imageMips = (*loadedImages)[0].getNumMipmaps(); if (imageMips == 0) { mNumMipmaps = mNumRequestedMipmaps = imageMips; // Disable flag for auto mip generation mUsage &= ~TU_AUTOMIPMAP; } } } else if (mTextureType == TEX_TYPE_CUBE_MAP) { if(getSourceFileType() == "dds") { // XX HACK there should be a better way to specify whether // all faces are in the same file or not doImageIO(mName, mGroup, ext, *loadedImages, this); } else { vector<Image>::type images(6); ConstImagePtrList imagePtrs; static const String suffixes[6] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"}; for(size_t i = 0; i < 6; i++) { String fullName = baseName + suffixes[i]; if (!ext.empty()) fullName = fullName + "." + ext; // find & load resource data intro stream to allow resource // group changes if required doImageIO(fullName, mGroup, ext, *loadedImages, this); } } } else { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "**** Unknown texture type ****", "GLES2Texture::prepare"); } mLoadedImages = loadedImages; } void GLES2Texture::unprepareImpl() { mLoadedImages.setNull(); } void GLES2Texture::loadImpl() { if (mUsage & TU_RENDERTARGET) { createRenderTexture(); return; } // Now the only copy is on the stack and will be cleaned in case of // exceptions being thrown from _loadImages LoadedImages loadedImages = mLoadedImages; mLoadedImages.setNull(); // Call internal _loadImages, not loadImage since that's external and // will determine load status etc again ConstImagePtrList imagePtrs; for (size_t i = 0; i < loadedImages->size(); ++i) { imagePtrs.push_back(&(*loadedImages)[i]); } _loadImages(imagePtrs); } void GLES2Texture::freeInternalResourcesImpl() { mSurfaceList.clear(); glDeleteTextures(1, &mTextureID); GL_CHECK_ERROR; } void GLES2Texture::_createSurfaceList() { mSurfaceList.clear(); // For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr bool wantGeneratedMips = (mUsage & TU_AUTOMIPMAP)!=0; // Do mipmapping in software? (uses GLU) For some cards, this is still needed. Of course, // only when mipmap generation is desired. bool doSoftware = wantGeneratedMips && !mMipmapsHardwareGenerated && getNumMipmaps(); for (size_t face = 0; face < getNumFaces(); face++) { size_t width = mWidth; size_t height = mHeight; for (size_t mip = 0; mip <= getNumMipmaps(); mip++) { GLES2HardwarePixelBuffer *buf = OGRE_NEW GLES2TextureBuffer(mName, getGLES2TextureTarget(), mTextureID, width, height, GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma), GLES2PixelUtil::getGLOriginDataType(mFormat), face, mip, static_cast<HardwareBuffer::Usage>(mUsage), doSoftware && mip==0, mHwGamma, mFSAA); mSurfaceList.push_back(HardwarePixelBufferSharedPtr(buf)); // If format is PVRTC then every mipmap is a custom one so to allow the upload of the compressed data // provided by the file we need to adjust the current mip level's dimention if (mFormat == PF_PVRTC_RGB2 || mFormat == PF_PVRTC_RGBA2 || mFormat == PF_PVRTC_RGB4 || mFormat == PF_PVRTC_RGBA4) { if(width > 1) { width = width / 2; } if(height > 1) { height = height / 2; } } /// Check for error if (buf->getWidth() == 0 || buf->getHeight() == 0 || buf->getDepth() == 0) { OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, "Zero sized texture surface on texture "+getName()+ " face "+StringConverter::toString(face)+ " mipmap "+StringConverter::toString(mip)+ ". The GL probably driver refused to create the texture.", "GLES2Texture::_createSurfaceList"); } } } } HardwarePixelBufferSharedPtr GLES2Texture::getBuffer(size_t face, size_t mipmap) { if (face >= getNumFaces()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Face index out of range", "GLES2Texture::getBuffer"); } if (mipmap > mNumMipmaps) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Mipmap index out of range", "GLES2Texture::getBuffer"); } unsigned int idx = face * (mNumMipmaps + 1) + mipmap; assert(idx < mSurfaceList.size()); return mSurfaceList[idx]; } } <commit_msg>GLES2: Fix using PVR textures<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreGLES2Texture.h" #include "OgreGLES2PixelFormat.h" #include "OgreGLES2RenderSystem.h" #include "OgreGLES2HardwarePixelBuffer.h" #include "OgreRoot.h" namespace Ogre { static inline void doImageIO(const String &name, const String &group, const String &ext, vector<Image>::type &images, Resource *r) { size_t imgIdx = images.size(); images.push_back(Image()); DataStreamPtr dstream = ResourceGroupManager::getSingleton().openResource( name, group, true, r); images[imgIdx].load(dstream, ext); } GLES2Texture::GLES2Texture(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader, GLES2Support& support) : Texture(creator, name, handle, group, isManual, loader), mTextureID(0), mGLSupport(support) { } GLES2Texture::~GLES2Texture() { // have to call this here rather than in Resource destructor // since calling virtual methods in base destructors causes crash if (isLoaded()) { unload(); } else { freeInternalResources(); } } GLenum GLES2Texture::getGLES2TextureTarget(void) const { switch(mTextureType) { case TEX_TYPE_1D: case TEX_TYPE_2D: return GL_TEXTURE_2D; case TEX_TYPE_CUBE_MAP: return GL_TEXTURE_CUBE_MAP; default: return 0; }; } // Creation / loading methods void GLES2Texture::createInternalResourcesImpl(void) { // Convert to nearest power-of-two size if required mWidth = GLES2PixelUtil::optionalPO2(mWidth); mHeight = GLES2PixelUtil::optionalPO2(mHeight); mDepth = GLES2PixelUtil::optionalPO2(mDepth); // Adjust format if required mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); // Check requested number of mipmaps size_t maxMips = GLES2PixelUtil::getMaxMipmaps(mWidth, mHeight, mDepth, mFormat); if(PixelUtil::isCompressed(mFormat) && (mNumMipmaps == 0)) mNumRequestedMipmaps = 0; mNumMipmaps = mNumRequestedMipmaps; if (mNumMipmaps > maxMips) mNumMipmaps = maxMips; // Generate texture name glGenTextures(1, &mTextureID); GL_CHECK_ERROR; // Set texture type glBindTexture(getGLES2TextureTarget(), mTextureID); GL_CHECK_ERROR; #if GL_APPLE_texture_max_level glTexParameteri( getGLES2TextureTarget(), GL_TEXTURE_MAX_LEVEL_APPLE, mNumMipmaps ); #endif // Set some misc default parameters, these can of course be changed later glTexParameteri(getGLES2TextureTarget(), GL_TEXTURE_MIN_FILTER, GL_NEAREST); GL_CHECK_ERROR; glTexParameteri(getGLES2TextureTarget(), GL_TEXTURE_MAG_FILTER, GL_NEAREST); GL_CHECK_ERROR; glTexParameteri(getGLES2TextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); GL_CHECK_ERROR; glTexParameteri(getGLES2TextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); GL_CHECK_ERROR; // If we can do automip generation and the user desires this, do so mMipmapsHardwareGenerated = Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_AUTOMIPMAP) && !PixelUtil::isCompressed(mFormat); if ((mUsage & TU_AUTOMIPMAP) && mNumRequestedMipmaps && mMipmapsHardwareGenerated) { glGenerateMipmap(getGLES2TextureTarget()); GL_CHECK_ERROR; } // Allocate internal buffer so that glTexSubImageXD can be used // Internal format GLenum format = GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma); GLenum datatype = GLES2PixelUtil::getGLOriginDataType(mFormat); size_t width = mWidth; size_t height = mHeight; size_t depth = mDepth; if (PixelUtil::isCompressed(mFormat)) { // Compressed formats size_t size = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); // Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not // accept a 0 pointer like normal glTexImageXD // Run through this process for every mipmap to pregenerate mipmap pyramid uint8* tmpdata = OGRE_NEW_FIX_FOR_WIN32 uint8[size]; memset(tmpdata, 0, size); for (size_t mip = 0; mip <= mNumMipmaps; mip++) { size = PixelUtil::getMemorySize(width, height, depth, mFormat); switch(mTextureType) { case TEX_TYPE_1D: case TEX_TYPE_2D: glCompressedTexImage2D(GL_TEXTURE_2D, mip, format, width, height, 0, size, tmpdata); GL_CHECK_ERROR; break; case TEX_TYPE_CUBE_MAP: for(int face = 0; face < 6; face++) { glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, width, height, 0, size, tmpdata); GL_CHECK_ERROR; } break; case TEX_TYPE_3D: default: break; }; // LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) + // " Width: " + StringConverter::toString(width) + // " Height: " + StringConverter::toString(height) + // " Internal Format: " + StringConverter::toString(format) // ); if(width > 1) { width = width / 2; } if(height > 1) { height = height / 2; } if(depth > 1) { depth = depth / 2; } } OGRE_DELETE [] tmpdata; } else { // Run through this process to pregenerate mipmap pyramid for(size_t mip = 0; mip <= mNumMipmaps; mip++) { // Normal formats switch(mTextureType) { case TEX_TYPE_1D: case TEX_TYPE_2D: glTexImage2D(GL_TEXTURE_2D, mip, format, width, height, 0, format, datatype, 0); GL_CHECK_ERROR; break; case TEX_TYPE_CUBE_MAP: for(int face = 0; face < 6; face++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, width, height, 0, format, datatype, 0); } break; case TEX_TYPE_3D: default: break; }; // LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) + // " Width: " + StringConverter::toString(width) + // " Height: " + StringConverter::toString(height) + // " Internal Format: " + StringConverter::toString(format) // ); if (width > 1) { width = width / 2; } if (height > 1) { height = height / 2; } } } _createSurfaceList(); // Get final internal format mFormat = getBuffer(0,0)->getFormat(); } void GLES2Texture::createRenderTexture(void) { // Create the GL texture // This already does everything neccessary createInternalResources(); } void GLES2Texture::prepareImpl() { if (mUsage & TU_RENDERTARGET) return; String baseName, ext; size_t pos = mName.find_last_of("."); baseName = mName.substr(0, pos); if (pos != String::npos) { ext = mName.substr(pos+1); } LoadedImages loadedImages = LoadedImages(OGRE_NEW_FIX_FOR_WIN32 vector<Image>::type()); if (mTextureType == TEX_TYPE_1D || mTextureType == TEX_TYPE_2D) { doImageIO(mName, mGroup, ext, *loadedImages, this); // If this is a volumetric texture set the texture type flag accordingly. // If this is a cube map, set the texture type flag accordingly. if ((*loadedImages)[0].hasFlag(IF_CUBEMAP)) mTextureType = TEX_TYPE_CUBE_MAP; // If PVRTC and 0 custom mipmap disable auto mip generation and disable software mipmap creation PixelFormat imageFormat = (*loadedImages)[0].getFormat(); if (imageFormat == PF_PVRTC_RGB2 || imageFormat == PF_PVRTC_RGBA2 || imageFormat == PF_PVRTC_RGB4 || imageFormat == PF_PVRTC_RGBA4) { size_t imageMips = (*loadedImages)[0].getNumMipmaps(); if (imageMips == 0) { mNumMipmaps = mNumRequestedMipmaps = imageMips; // Disable flag for auto mip generation mUsage &= ~TU_AUTOMIPMAP; } } } else if (mTextureType == TEX_TYPE_CUBE_MAP) { if(getSourceFileType() == "dds") { // XX HACK there should be a better way to specify whether // all faces are in the same file or not doImageIO(mName, mGroup, ext, *loadedImages, this); } else { vector<Image>::type images(6); ConstImagePtrList imagePtrs; static const String suffixes[6] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"}; for(size_t i = 0; i < 6; i++) { String fullName = baseName + suffixes[i]; if (!ext.empty()) fullName = fullName + "." + ext; // find & load resource data intro stream to allow resource // group changes if required doImageIO(fullName, mGroup, ext, *loadedImages, this); } } } else { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "**** Unknown texture type ****", "GLES2Texture::prepare"); } mLoadedImages = loadedImages; } void GLES2Texture::unprepareImpl() { mLoadedImages.setNull(); } void GLES2Texture::loadImpl() { if (mUsage & TU_RENDERTARGET) { createRenderTexture(); return; } // Now the only copy is on the stack and will be cleaned in case of // exceptions being thrown from _loadImages LoadedImages loadedImages = mLoadedImages; mLoadedImages.setNull(); // Call internal _loadImages, not loadImage since that's external and // will determine load status etc again ConstImagePtrList imagePtrs; for (size_t i = 0; i < loadedImages->size(); ++i) { imagePtrs.push_back(&(*loadedImages)[i]); } _loadImages(imagePtrs); } void GLES2Texture::freeInternalResourcesImpl() { mSurfaceList.clear(); glDeleteTextures(1, &mTextureID); GL_CHECK_ERROR; } void GLES2Texture::_createSurfaceList() { mSurfaceList.clear(); // For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr bool wantGeneratedMips = (mUsage & TU_AUTOMIPMAP)!=0; // Do mipmapping in software? (uses GLU) For some cards, this is still needed. Of course, // only when mipmap generation is desired. bool doSoftware = wantGeneratedMips && !mMipmapsHardwareGenerated && getNumMipmaps(); for (size_t face = 0; face < getNumFaces(); face++) { size_t width = mWidth; size_t height = mHeight; for (size_t mip = 0; mip <= getNumMipmaps(); mip++) { GLES2HardwarePixelBuffer *buf = OGRE_NEW GLES2TextureBuffer(mName, getGLES2TextureTarget(), mTextureID, width, height, GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma), GLES2PixelUtil::getGLOriginDataType(mFormat), face, mip, static_cast<HardwareBuffer::Usage>(mUsage), doSoftware && mip==0, mHwGamma, mFSAA); mSurfaceList.push_back(HardwarePixelBufferSharedPtr(buf)); // Check for error if (buf->getWidth() == 0 || buf->getHeight() == 0 || buf->getDepth() == 0) { OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, "Zero sized texture surface on texture "+getName()+ " face "+StringConverter::toString(face)+ " mipmap "+StringConverter::toString(mip)+ ". The GL driver probably refused to create the texture.", "GLES2Texture::_createSurfaceList"); } } } } HardwarePixelBufferSharedPtr GLES2Texture::getBuffer(size_t face, size_t mipmap) { if (face >= getNumFaces()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Face index out of range", "GLES2Texture::getBuffer"); } if (mipmap > mNumMipmaps) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Mipmap index out of range", "GLES2Texture::getBuffer"); } unsigned int idx = face * (mNumMipmaps + 1) + mipmap; assert(idx < mSurfaceList.size()); return mSurfaceList[idx]; } } <|endoftext|>
<commit_before>#include "musiclrcmanager.h" #include <QFile> #include <QFontDatabase> MusicLRCManager::MusicLRCManager(QWidget *parent) : QLabel(parent) { m_intervalCount = 0.0f; m_linearGradient.setStart(0, 10);//The starting point coordinates filled m_linearGradient.setFinalStop(0, 40);//The coordinates of the end filling //A linear gradient mask filling m_maskLinearGradient.setStart(0, 10); m_maskLinearGradient.setFinalStop(0, 40); //Set the font m_font.setFamily("Times New Roman"); m_font.setBold(true); //Set the timer m_timer = new QTimer(this); connect(m_timer, SIGNAL(timeout()), SLOT(setTimeOut())); m_lrcMaskWidth = 0; m_lrcMaskWidthInterval = 0; m_speedLeve = 1; m_transparent = 100; } MusicLRCManager::~MusicLRCManager() { delete m_timer; } void MusicLRCManager::startTimerClock() { m_timer->start(LRC_PER_TIME); } void MusicLRCManager::setLrcFontSize(LrcSizeTable size) { m_font.setPointSize(size); setText( text() ); update(); } void MusicLRCManager::setFontFamily(int index) { if(index < 0) { return; } QStringList family = QFontDatabase().families(QFontDatabase::Any); if(!family.isEmpty()) { if(index >= family.count()) { index = 0; } m_font.setFamily(family[index]); } } void MusicLRCManager::setFontType(int type) { m_font.setBold( (type == 1 || type == 3) ? true : false ); m_font.setItalic( (type == 2 || type == 3) ? true : false ); } void MusicLRCManager::startLrcMask(qint64 intervaltime) { /*Open the mask, need to specify the current lyrics start with the interval between the end of,Here set every 30 msec update a mask width, because if too frequent updates,The CPU occupancy rate will increase, and if the time interval is too large, then the animation is not smooth */ m_intervalCount = 0.0f; m_geometry.setX(QFontMetrics(m_font).width(text())); qreal count = intervaltime / m_speedLeve; m_lrcMaskWidthInterval = m_geometry.x() / count; m_lrcMaskWidth = 0; m_timer->start(LRC_PER_TIME); } void MusicLRCManager::stopLrcMask() { m_timer->stop(); update(); } void MusicLRCManager::setLinearGradientColor(QColor color) { //The first parameter coordinates relative to the US, the area above, //calculated in accordance with the proportion of color.setAlpha(m_transparent*2.55); m_linearGradient.setColorAt(0.1, color); m_linearGradient.setColorAt(0.5, QColor(114, 232, 255, m_transparent*2.55)); m_linearGradient.setColorAt(0.9, color); update(); } void MusicLRCManager::setMaskLinearGradientColor(QColor color) { color.setAlpha(m_transparent*2.55); m_maskLinearGradient.setColorAt(0.1, color); m_maskLinearGradient.setColorAt(0.5, QColor(255, 72, 16,m_transparent*2.55)); m_maskLinearGradient.setColorAt(0.9, color); } void MusicLRCManager::setTimeOut() { //At a fixed period of time covered length increases. m_lrcMaskWidth += m_lrcMaskWidthInterval; update(); } void MusicLRCManager::setText(const QString &str) { m_geometry.setX(QFontMetrics(m_font).width(str)); QLabel::setText(str); } <commit_msg>clean code for musiclrcmanager[831258]<commit_after>#include "musiclrcmanager.h" #include <QFile> #include <QFontDatabase> MusicLRCManager::MusicLRCManager(QWidget *parent) : QLabel(parent) { m_intervalCount = 0.0f; m_linearGradient.setStart(0, 10);//The starting point coordinates filled m_linearGradient.setFinalStop(0, 40);//The coordinates of the end filling //A linear gradient mask filling m_maskLinearGradient.setStart(0, 10); m_maskLinearGradient.setFinalStop(0, 40); //Set the font m_font.setFamily("Times New Roman"); m_font.setBold(true); //Set the timer m_timer = new QTimer(this); connect(m_timer, SIGNAL(timeout()), SLOT(setTimeOut())); m_lrcMaskWidth = 0; m_lrcMaskWidthInterval = 0; m_speedLeve = 1; m_transparent = 100; } MusicLRCManager::~MusicLRCManager() { delete m_timer; } void MusicLRCManager::startTimerClock() { m_timer->start(LRC_PER_TIME); } void MusicLRCManager::setLrcFontSize(LrcSizeTable size) { m_font.setPointSize(size); setText( text() ); update(); } void MusicLRCManager::setFontFamily(int index) { if(index < 0) { return; } QStringList family = QFontDatabase().families(QFontDatabase::Any); if(!family.isEmpty()) { if(index >= family.count()) { index = 0; } m_font.setFamily(family[index]); } } void MusicLRCManager::setFontType(int type) { m_font.setBold( (type == 1 || type == 3) ? true : false ); m_font.setItalic( (type == 2 || type == 3) ? true : false ); } void MusicLRCManager::startLrcMask(qint64 intervaltime) { /*Open the mask, need to specify the current lyrics start with the interval between the end of,Here set every 30 msec update a mask width, because if too frequent updates,The CPU occupancy rate will increase, and if the time interval is too large, then the animation is not smooth */ m_intervalCount = 0.0f; m_geometry.setX(QFontMetrics(m_font).width(text())); qreal count = intervaltime / m_speedLeve; m_lrcMaskWidthInterval = m_geometry.x() / count; m_lrcMaskWidth = 0; m_timer->start(LRC_PER_TIME); } void MusicLRCManager::stopLrcMask() { m_timer->stop(); update(); } void MusicLRCManager::setLinearGradientColor(QColor color) { //The first parameter coordinates relative to the US, the area above, //calculated in accordance with the proportion of color.setAlpha(m_transparent*2.55); m_linearGradient.setColorAt(0.1, color); m_linearGradient.setColorAt(0.5, QColor(114, 232, 255, m_transparent*2.55)); m_linearGradient.setColorAt(0.9, color); update(); } void MusicLRCManager::setMaskLinearGradientColor(QColor color) { color.setAlpha(m_transparent*2.55); m_maskLinearGradient.setColorAt(0.1, color); m_maskLinearGradient.setColorAt(0.5, QColor(255, 72, 16, m_transparent*2.55)); m_maskLinearGradient.setColorAt(0.9, color); } void MusicLRCManager::setTimeOut() { //At a fixed period of time covered length increases. m_lrcMaskWidth += m_lrcMaskWidthInterval; update(); } void MusicLRCManager::setText(const QString &str) { m_geometry.setX(QFontMetrics(m_font).width(str)); QLabel::setText(str); } <|endoftext|>
<commit_before>/********************************************************************* * * Condor ClassAd library * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, WI, and Rajesh Raman. * * This library is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the GNU Lesser General * Public License as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * *********************************************************************/ #include "common.h" #include "classad.h" #include "condor_attributes.h" #include "condor_debug.h" #include "condor_classad.h" // AttrList methods ClassAd:: ClassAd( FILE *file, char *delimitor, int &isEOF, int&error, int &empty ) { char buffer[ATTRLIST_MAX_EXPRESSION]; int delimLen = strlen( delimitor ); buffer[0] = '\0'; while( 1 ) { // get a line from the file if( fgets( buffer, delimLen+1, file ) == NULL ) { error = ( isEOF = feof( file ) ) ? 0 : errno; return; } // did we hit the delimitor? if( strncmp( buffer, delimitor, delimLen ) == 0 ) { // yes ... stop isEOF = feof( file ); error = 0; return; } else { // no ... read the rest of the line (into the same buffer) if( fgets( buffer+delimLen, ATTRLIST_MAX_EXPRESSION-delimLen,file ) == NULL ) { error = ( isEOF = feof( file ) ) ? 0 : errno; return; } } // if the string is empty, try reading again if( strlen( buffer ) == 0 || strcmp( buffer, "\n" ) == 0 ) { continue; } // Insert the string into the classad if( Insert( buffer ) == FALSE ) { // print out where we barfed to the log file dprintf(D_ALWAYS,"failed to create classad; bad expr = %s\n", buffer); // read until delimitor or EOF; whichever comes first while( strncmp( buffer, delimitor, delimLen ) && !feof( file ) ) { fgets( buffer, delimLen+1, file ); } isEOF = feof( file ); error = -1; return; } else { empty = FALSE; } } return; } int ClassAd:: Insert( const char *str ) { ClassAdParser parser; ClassAd *newAd; vector< pair< string, ExprTree *> > vec; vector< pair< string, ExprTree *> >::iterator itr; string newAdStr = "[" + string( str ) + "]"; newAd = parser.ParseClassAd( newAdStr ); newAd->GetComponents( vec ); for( itr = vec.begin( ); itr != vec.end( ); itr++ ) { if( !Insert( itr->first, itr->second ) ) { return FALSE; } itr->first = ""; itr->second = NULL; } return TRUE; } // void ClassAd:: // ResetExpr() { this->ptrExpr = exprList; } // ExprTree* ClassAd:: // NextExpr(){} // void ClassAd:: // ResetName() { this->ptrName = exprList; } // const char* ClassAd:: // NextNameOriginal(){} // ExprTree* ClassAd:: // Lookup(char *) const{} // ExprTree* ClassAd:: // Lookup(const char*) const{} int ClassAd:: LookupString( const char *name, char *value ) { string strVal; if( !EvaluateAttrString( string( name ), strVal ) ) { return 0; } strcpy( value, strVal.c_str( ) ); return 1; } int ClassAd:: LookupInteger( const char *name, int &value ) { bool boolVal; int haveInteger; string sName; sName = string(name); if( EvaluateAttrInt(sName, value ) ) { haveInteger = TRUE; } else if( EvaluateAttrBool(sName, boolVal ) ) { value = boolVal ? 1 : 0; haveInteger = TRUE; } else { haveInteger = FALSE; } return haveInteger; } int ClassAd:: LookupFloat( const char *name, float &value ) { double doubleVal; int intVal; int haveFloat; if(EvaluateAttrReal( string( name ), doubleVal ) ) { haveFloat = TRUE; value = (float) doubleVal; } else if(EvaluateAttrInt( string( name ), intVal ) ) { haveFloat = TRUE; value = (float)intVal; } else { haveFloat = FALSE; } return haveFloat; } int ClassAd:: LookupBool( const char *name, int &value ) { int intVal; bool boolVal; int haveBool; string sName; sName = string(name); if (EvaluateAttrBool(name, boolVal)) { haveBool = true; value = boolVal ? 1 : 0; } else if (EvaluateAttrInt(name, intVal)) { haveBool = true; value = (intVal != 0) ? 1 : 0; } else { haveBool = false; value = 0; } return haveBool; } int ClassAd:: EvalString( const char *name, class ClassAd *target, char *value ) { ExprTree *tree; Value val; string strVal; tree = Lookup( name ); if( !tree ) { if( target ) { tree = target->Lookup( name ); } else { evalFromEnvironment( name, val ); if( val.IsStringValue( strVal ) ) { strcpy( value, strVal.c_str( ) ); return 1; } return 0; } } if( target->EvaluateExpr( tree, val ) && val.IsStringValue( strVal ) ) { strcpy( value, strVal.c_str( ) ); return 1; } return 0; } int ClassAd:: EvalInteger (const char *name, class ClassAd *target, int &value) { ExprTree *tree; Value val; tree = Lookup( name ); if( !tree ) { if( target ) { tree = target->Lookup( name ); } else { evalFromEnvironment( name, val ); if( val.IsIntegerValue( value ) ) { return 1; } return 0; } } if( target->EvaluateExpr( tree, val ) && val.IsIntegerValue( value ) ) { return 1; } return 0; } int ClassAd:: EvalFloat (const char *name, class ClassAd *target, float &value) { ExprTree *tree; Value val; double doubleVal; int intVal; tree = Lookup( name ); if( !tree ) { if( target ) { tree = target->Lookup( name ); } else { evalFromEnvironment( name, val ); if( val.IsRealValue( doubleVal ) ) { value = ( float )doubleVal; return 1; } if( val.IsIntegerValue( intVal ) ) { value = ( float )intVal; return 1; } return 0; } } if( target->EvaluateExpr( tree, val ) ) { if( val.IsRealValue( doubleVal ) ) { value = ( float )doubleVal; return 1; } if( val.IsIntegerValue( intVal ) ) { value = ( float )intVal; return 1; } } return 0; } int ClassAd:: EvalBool (const char *name, class ClassAd *target, int &value) { ExprTree *tree; Value val; double doubleVal; int intVal; bool boolVal; tree = Lookup( name ); if( !tree ) { if( target ) { tree = target->Lookup( name ); } else { evalFromEnvironment( name, val ); if( val.IsBooleanValue( boolVal ) ) { value = boolVal ? 1 : 0; return 1; } if( val.IsIntegerValue( value ) ) { value = intVal ? 1 : 0; return 1; } return 0; } } if( target->EvaluateExpr( tree, val ) ) { if( val.IsBooleanValue( boolVal ) ) { value = boolVal ? 1 : 0; return 1; } if( val.IsIntegerValue( value ) ) { value = intVal ? 1 : 0; return 1; } if( val.IsRealValue( doubleVal ) ) { value = doubleVal ? 1 : 0; return 1; } } return 0; } // shipping functions int ClassAd:: put( Stream &s ) { if( !putOldClassAd( &s, *this ) ) { return FALSE; } return TRUE; } int ClassAd:: initFromStream(Stream& s) { ClassAd *newAd; if( !( newAd = getOldClassAd( &s ) ) ) { return FALSE; } if( ! CopyFrom( *newAd ) ) { return FALSE; } return TRUE; } // output functions int ClassAd:: fPrint( FILE *f ) { ClassAdUnParser unp; unp.SetOldClassAd( true ); string buffer; if( !f ) { return FALSE; } unp.Unparse( buffer, this ); fprintf( f, "%s", buffer.c_str( ) ); return TRUE; } void ClassAd:: dPrint( int level ) { PrettyPrint pp; pp.SetOldClassAd( true ); string buffer; pp.Unparse( buffer, this ); dprintf( level, "%s", buffer.c_str( ) ); return; } // ClassAd methods // Type operations void ClassAd:: SetMyTypeName( const char *myType ) { if( myType ) { InsertAttr( ATTR_MY_TYPE, string( myType ) ); } return; } const char* ClassAd:: GetMyTypeName( ) { string myTypeStr; if( !EvaluateAttrString( ATTR_MY_TYPE, myTypeStr ) ) { return NULL; } return myTypeStr.c_str( ); } void ClassAd:: SetTargetTypeName( const char *targetType ) { if( targetType ) { InsertAttr( ATTR_TARGET_TYPE, string( targetType ) ); } return; } const char* ClassAd:: GetTargetTypeName( ) { string targetTypeStr; if( !EvaluateAttrString( ATTR_TARGET_TYPE, targetTypeStr ) ) { return NULL; } return targetTypeStr.c_str( ); } // private methods void ClassAd:: evalFromEnvironment( const char *name, Value val ) { if (strcmp (name, "CurrentTime") == 0) { time_t now = time (NULL); if (now == (time_t) -1) { val.SetErrorValue( ); return; } val.SetIntegerValue( ( int ) now ); return; } val.SetUndefinedValue( ); return; } <commit_msg>The fPrint and dPrint methods now use ClassAdUnparser instead of PrettyPrint to display ClassAds. With the oldClassAd flag set ClassAdUnparser will unparse a ClassAd in "old ClassAd" style (assuming no list, function calls or nested ClassAds.<commit_after>/********************************************************************* * * Condor ClassAd library * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, WI, and Rajesh Raman. * * This library is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the GNU Lesser General * Public License as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * *********************************************************************/ #include "common.h" #include "classad.h" #include "condor_attributes.h" #include "condor_debug.h" #include "condor_classad.h" // AttrList methods ClassAd:: ClassAd( FILE *file, char *delimitor, int &isEOF, int&error, int &empty ) { nodeKind = CLASSAD_NODE; char buffer[ATTRLIST_MAX_EXPRESSION]; int delimLen = strlen( delimitor ); buffer[0] = '\0'; while( 1 ) { // get a line from the file if( fgets( buffer, delimLen+1, file ) == NULL ) { error = ( isEOF = feof( file ) ) ? 0 : errno; return; } // did we hit the delimitor? if( strncmp( buffer, delimitor, delimLen ) == 0 ) { // yes ... stop isEOF = feof( file ); error = 0; return; } else { // no ... read the rest of the line (into the same buffer) if( fgets( buffer+delimLen, ATTRLIST_MAX_EXPRESSION-delimLen,file ) == NULL ) { error = ( isEOF = feof( file ) ) ? 0 : errno; return; } } // if the string is empty, try reading again if( strlen( buffer ) == 0 || strcmp( buffer, "\n" ) == 0 ) { continue; } // Insert the string into the classad if( Insert( buffer ) == FALSE ) { // print out where we barfed to the log file dprintf(D_ALWAYS,"failed to create classad; bad expr = %s\n", buffer); // read until delimitor or EOF; whichever comes first while( strncmp( buffer, delimitor, delimLen ) && !feof( file ) ) { fgets( buffer, delimLen+1, file ); } isEOF = feof( file ); error = -1; return; } else { empty = FALSE; } } return; } int ClassAd:: Insert( const char *str ) { ClassAdParser parser; ClassAd *newAd; vector< pair< string, ExprTree *> > vec; vector< pair< string, ExprTree *> >::iterator itr; string newAdStr = "[" + string( str ) + "]"; newAd = parser.ParseClassAd( newAdStr ); newAd->GetComponents( vec ); for( itr = vec.begin( ); itr != vec.end( ); itr++ ) { if( !Insert( itr->first, itr->second ) ) { return FALSE; } itr->first = ""; itr->second = NULL; } return TRUE; } // void ClassAd:: // ResetExpr() { this->ptrExpr = exprList; } // ExprTree* ClassAd:: // NextExpr(){} // void ClassAd:: // ResetName() { this->ptrName = exprList; } // const char* ClassAd:: // NextNameOriginal(){} // ExprTree* ClassAd:: // Lookup(char *) const{} // ExprTree* ClassAd:: // Lookup(const char*) const{} int ClassAd:: LookupString( const char *name, char *value ) { string strVal; if( !EvaluateAttrString( string( name ), strVal ) ) { return 0; } strcpy( value, strVal.c_str( ) ); return 1; } int ClassAd:: LookupInteger( const char *name, int &value ) { bool boolVal; int haveInteger; string sName; sName = string(name); if( EvaluateAttrInt(sName, value ) ) { haveInteger = TRUE; } else if( EvaluateAttrBool(sName, boolVal ) ) { value = boolVal ? 1 : 0; haveInteger = TRUE; } else { haveInteger = FALSE; } return haveInteger; } int ClassAd:: LookupFloat( const char *name, float &value ) { double doubleVal; int intVal; int haveFloat; if(EvaluateAttrReal( string( name ), doubleVal ) ) { haveFloat = TRUE; value = (float) doubleVal; } else if(EvaluateAttrInt( string( name ), intVal ) ) { haveFloat = TRUE; value = (float)intVal; } else { haveFloat = FALSE; } return haveFloat; } int ClassAd:: LookupBool( const char *name, int &value ) { int intVal; bool boolVal; int haveBool; string sName; sName = string(name); if (EvaluateAttrBool(name, boolVal)) { haveBool = true; value = boolVal ? 1 : 0; } else if (EvaluateAttrInt(name, intVal)) { haveBool = true; value = (intVal != 0) ? 1 : 0; } else { haveBool = false; value = 0; } return haveBool; } int ClassAd:: EvalString( const char *name, class ClassAd *target, char *value ) { ExprTree *tree; Value val; string strVal; tree = Lookup( name ); if( !tree ) { if( target ) { tree = target->Lookup( name ); } else { evalFromEnvironment( name, val ); if( val.IsStringValue( strVal ) ) { strcpy( value, strVal.c_str( ) ); return 1; } return 0; } } if( target->EvaluateExpr( tree, val ) && val.IsStringValue( strVal ) ) { strcpy( value, strVal.c_str( ) ); return 1; } return 0; } int ClassAd:: EvalInteger (const char *name, class ClassAd *target, int &value) { ExprTree *tree; Value val; tree = Lookup( name ); if( !tree ) { if( target ) { tree = target->Lookup( name ); } else { evalFromEnvironment( name, val ); if( val.IsIntegerValue( value ) ) { return 1; } return 0; } } if( target->EvaluateExpr( tree, val ) && val.IsIntegerValue( value ) ) { return 1; } return 0; } int ClassAd:: EvalFloat (const char *name, class ClassAd *target, float &value) { ExprTree *tree; Value val; double doubleVal; int intVal; tree = Lookup( name ); if( !tree ) { if( target ) { tree = target->Lookup( name ); } else { evalFromEnvironment( name, val ); if( val.IsRealValue( doubleVal ) ) { value = ( float )doubleVal; return 1; } if( val.IsIntegerValue( intVal ) ) { value = ( float )intVal; return 1; } return 0; } } if( target->EvaluateExpr( tree, val ) ) { if( val.IsRealValue( doubleVal ) ) { value = ( float )doubleVal; return 1; } if( val.IsIntegerValue( intVal ) ) { value = ( float )intVal; return 1; } } return 0; } int ClassAd:: EvalBool (const char *name, class ClassAd *target, int &value) { ExprTree *tree; Value val; double doubleVal; int intVal; bool boolVal; tree = Lookup( name ); if( !tree ) { if( target ) { tree = target->Lookup( name ); } else { evalFromEnvironment( name, val ); if( val.IsBooleanValue( boolVal ) ) { value = boolVal ? 1 : 0; return 1; } if( val.IsIntegerValue( value ) ) { value = intVal ? 1 : 0; return 1; } return 0; } } if( target->EvaluateExpr( tree, val ) ) { if( val.IsBooleanValue( boolVal ) ) { value = boolVal ? 1 : 0; return 1; } if( val.IsIntegerValue( value ) ) { value = intVal ? 1 : 0; return 1; } if( val.IsRealValue( doubleVal ) ) { value = doubleVal ? 1 : 0; return 1; } } return 0; } // shipping functions int ClassAd:: put( Stream &s ) { if( !putOldClassAd( &s, *this ) ) { return FALSE; } return TRUE; } int ClassAd:: initFromStream(Stream& s) { ClassAd *newAd; if( !( newAd = getOldClassAd( &s ) ) ) { return FALSE; } if( ! CopyFrom( *newAd ) ) { return FALSE; } return TRUE; } // output functions int ClassAd:: fPrint( FILE *f ) { ClassAdUnParser unp; unp.SetOldClassAd( true ); string buffer; if( !f ) { return FALSE; } unp.Unparse( buffer, this ); fprintf( f, "%s", buffer.c_str( ) ); return TRUE; } void ClassAd:: dPrint( int level ) { ClassAdUnParser unp; unp.SetOldClassAd( true ); string buffer; unp.Unparse( buffer, this ); dprintf( level, "%s", buffer.c_str( ) ); return; } // ClassAd methods // Type operations void ClassAd:: SetMyTypeName( const char *myType ) { if( myType ) { InsertAttr( ATTR_MY_TYPE, string( myType ) ); } return; } const char* ClassAd:: GetMyTypeName( ) { string myTypeStr; if( !EvaluateAttrString( ATTR_MY_TYPE, myTypeStr ) ) { return NULL; } return myTypeStr.c_str( ); } void ClassAd:: SetTargetTypeName( const char *targetType ) { if( targetType ) { InsertAttr( ATTR_TARGET_TYPE, string( targetType ) ); } return; } const char* ClassAd:: GetTargetTypeName( ) { string targetTypeStr; if( !EvaluateAttrString( ATTR_TARGET_TYPE, targetTypeStr ) ) { return NULL; } return targetTypeStr.c_str( ); } // private methods void ClassAd:: evalFromEnvironment( const char *name, Value val ) { if (strcmp (name, "CurrentTime") == 0) { time_t now = time (NULL); if (now == (time_t) -1) { val.SetErrorValue( ); return; } val.SetIntegerValue( ( int ) now ); return; } val.SetUndefinedValue( ); return; } <|endoftext|>
<commit_before>// This file is part of playd. // playd is licenced under the MIT license: see LICENSE.txt. /** * @file * Tests for the Tokeniser class. */ #include "catch.hpp" #include "../io/tokeniser.hpp" SCENARIO("Tokenisers can handle complete, unquoted commands", "[tokeniser]") { GIVEN("A fresh Tokeniser") { Tokeniser t; WHEN("the Tokeniser is fed a nullary command") { auto words = t.Feed("stop\n"); THEN("one line is returned") { REQUIRE(words.size() == 1); } THEN("the line contains one word") { REQUIRE(words[0].size() == 1); } THEN("the word is the nullary command") { REQUIRE(words[0][0] == "stop"); } } WHEN("the Tokeniser is fed a unary command") { auto words = t.Feed("seek 10s\n"); THEN("one line is returned") { REQUIRE(words.size() == 1); } THEN("the line contains two words") { REQUIRE(words[0].size() == 2); } THEN("the first word is the command") { REQUIRE(words[0][0] == "seek"); } THEN("the second word is the argument") { REQUIRE(words[0][1] == "10s"); } } } } <commit_msg>Add tokeniser tests for backslash-escape.<commit_after>// This file is part of playd. // playd is licenced under the MIT license: see LICENSE.txt. /** * @file * Tests for the Tokeniser class. */ #include "catch.hpp" #include "../io/tokeniser.hpp" SCENARIO("Tokenisers can handle complete, unquoted commands", "[tokeniser]") { GIVEN("A fresh Tokeniser") { Tokeniser t; WHEN("the Tokeniser is fed a nullary command") { auto lines = t.Feed("stop\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains one word") { REQUIRE(lines[0].size() == 1); } THEN("the word is the nullary command") { REQUIRE(lines[0][0] == "stop"); } } WHEN("the Tokeniser is fed a unary command") { auto lines = t.Feed("seek 10s\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains two words") { REQUIRE(lines[0].size() == 2); } THEN("the first word is the command") { REQUIRE(lines[0][0] == "seek"); } THEN("the second word is the argument") { REQUIRE(lines[0][1] == "10s"); } } } } SCENARIO("Tokenisers can handle single-quoted strings", "[tokeniser-single]") { GIVEN("A fresh Tokeniser") { Tokeniser t; WHEN("the Tokeniser is fed a single-quoted string with no special characters") { auto lines = t.Feed("'normal_string'\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains only one word") { REQUIRE(lines[0].size() == 1); } THEN("the word contains the bytes enclosed in the single quotes") { REQUIRE(lines[0][0] == "normal_string"); } } WHEN("the Tokeniser is fed a single-quoted string with spaces") { auto lines = t.Feed("'not three words'\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains only one word") { REQUIRE(lines[0].size() == 1); } THEN("the word contains the bytes enclosed in the single quotes") { REQUIRE(lines[0][0] == "not three words"); } } // Backslashes are tested in [tokeniser-escape]. } } SCENARIO("Tokenisers can handle double-quoted strings", "[tokeniser-double]") { GIVEN("A fresh Tokeniser") { Tokeniser t; WHEN("the Tokeniser is fed a double-quoted string with no special characters") { auto lines = t.Feed("\"normal_string\"\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains only one word") { REQUIRE(lines[0].size() == 1); } THEN("the word contains the bytes enclosed in the double quotes") { REQUIRE(lines[0][0] == "normal_string"); } } WHEN("the Tokeniser is fed a double-quoted string with spaces") { auto lines = t.Feed("\"not three words\"\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains only one word") { REQUIRE(lines[0].size() == 1); } THEN("the word contains the bytes enclosed in the double quotes") { REQUIRE(lines[0][0] == "not three words"); } } // Backslashes are tested in [tokeniser-escape]. } } SCENARIO("Tokenisers can handle mixed-quoted strings", "[tokeniser-mixed]") { // This is a slightly strange concept, but is based on what happens in POSIX // shell. GIVEN("A fresh Tokeniser") { Tokeniser t; WHEN("the Tokeniser is fed a word with a mixture of different quote styles") { auto lines = t.Feed("This' is'\\ perfectly\"\\ valid \"syntax!\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains only one word") { REQUIRE(lines[0].size() == 1); } THEN("the word contains the concatenation of each") { REQUIRE(lines[0][0] == "This is perfectly valid syntax!"); } } } } SCENARIO("Tokenisers can backslash-escape bytes", "[tokeniser-escape]") { GIVEN("A fresh Tokeniser") { Tokeniser t; WHEN("the Tokeniser is fed a backslashed space in unquoted mode") { auto lines = t.Feed("backslashed\\ space\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains only one word") { REQUIRE(lines[0].size() == 1); } THEN("the line contains the space, but no backslash") { REQUIRE(lines[0][0] == "backslashed space"); } } WHEN("the Tokeniser is fed a backslashed space in double-quoted mode") { auto lines = t.Feed("\"backslashed\\ space\"\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains only one word") { REQUIRE(lines[0].size() == 1); } THEN("the line contains the space, but no backslash or quotes") { REQUIRE(lines[0][0] == "backslashed space"); } } WHEN("the Tokeniser is fed a backslashed space in single-quoted mode") { auto lines = t.Feed("'backslashed\\ space'\n"); THEN("one line is returned") { REQUIRE(lines.size() == 1); } THEN("the line contains only one word") { REQUIRE(lines[0].size() == 1); } THEN("the line contains the space AND backslash, but no quotes") { REQUIRE(lines[0][0] == "backslashed\\ space"); } } } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ //mapnik #include <mapnik/text_symbolizer.hpp> // boost #include <boost/scoped_ptr.hpp> namespace mapnik { static const char * label_placement_strings[] = { "point", "line", "vertex", "" }; IMPLEMENT_ENUM( label_placement_e, label_placement_strings ); static const char * vertical_alignment_strings[] = { "top", "middle", "bottom", "" }; IMPLEMENT_ENUM( vertical_alignment_e, vertical_alignment_strings ); static const char * horizontal_alignment_strings[] = { "left", "middle", "right", "" }; IMPLEMENT_ENUM( horizontal_alignment_e, horizontal_alignment_strings ); static const char * justify_alignment_strings[] = { "left", "middle", "right", "" }; IMPLEMENT_ENUM( justify_alignment_e, justify_alignment_strings ); static const char * text_transform_strings[] = { "none", "uppercase", "lowercase", "" }; IMPLEMENT_ENUM( text_transform_e, text_transform_strings ); text_symbolizer::text_symbolizer(expression_ptr name, std::string const& face_name, unsigned size, color const& fill) : symbolizer_base(), name_(name), face_name_(face_name), //fontset_(default_fontset), size_(size), text_ratio_(0), wrap_width_(0), wrap_char_(' '), text_transform_(NONE), line_spacing_(0), character_spacing_(0), label_spacing_(0), label_position_tolerance_(0), force_odd_labels_(false), max_char_angle_delta_(0.0), fill_(fill), halo_fill_(color(255,255,255)), halo_radius_(0), label_p_(POINT_PLACEMENT), valign_(MIDDLE), anchor_(0.0,0.5), displacement_(0.0,0.0), avoid_edges_(false), minimum_distance_(0.0), overlap_(false), text_opacity_(1.0), wrap_before_(false), halign_(H_MIDDLE), jalign_(J_MIDDLE) {} text_symbolizer::text_symbolizer(expression_ptr name, unsigned size, color const& fill) : symbolizer_base(), name_(name), //face_name_(""), //fontset_(default_fontset), size_(size), text_ratio_(0), wrap_width_(0), wrap_char_(' '), text_transform_(NONE), line_spacing_(0), character_spacing_(0), label_spacing_(0), label_position_tolerance_(0), force_odd_labels_(false), max_char_angle_delta_(0.0), fill_(fill), halo_fill_(color(255,255,255)), halo_radius_(0), label_p_(POINT_PLACEMENT), valign_(MIDDLE), anchor_(0.0,0.5), displacement_(0.0,0.0), avoid_edges_(false), minimum_distance_(0.0), overlap_(false), text_opacity_(1.0), wrap_before_(false), halign_(H_MIDDLE), jalign_(J_MIDDLE) {} text_symbolizer::text_symbolizer(text_symbolizer const& rhs) : symbolizer_base(rhs), name_(rhs.name_), orientation_(rhs.orientation_), face_name_(rhs.face_name_), fontset_(rhs.fontset_), size_(rhs.size_), text_ratio_(rhs.text_ratio_), wrap_width_(rhs.wrap_width_), wrap_char_(rhs.wrap_char_), text_transform_(rhs.text_transform_), line_spacing_(rhs.line_spacing_), character_spacing_(rhs.character_spacing_), label_spacing_(rhs.label_spacing_), label_position_tolerance_(rhs.label_position_tolerance_), force_odd_labels_(rhs.force_odd_labels_), max_char_angle_delta_(rhs.max_char_angle_delta_), fill_(rhs.fill_), halo_fill_(rhs.halo_fill_), halo_radius_(rhs.halo_radius_), label_p_(rhs.label_p_), valign_(rhs.valign_), anchor_(rhs.anchor_), displacement_(rhs.displacement_), avoid_edges_(rhs.avoid_edges_), minimum_distance_(rhs.minimum_distance_), overlap_(rhs.overlap_), text_opacity_(rhs.text_opacity_), wrap_before_(rhs.wrap_before_), halign_(rhs.halign_), jalign_(rhs.jalign_) {} text_symbolizer& text_symbolizer::operator=(text_symbolizer const& other) { if (this == &other) return *this; name_ = other.name_; orientation_ = other.orientation_; face_name_ = other.face_name_; fontset_ = other.fontset_; size_ = other.size_; text_ratio_ = other.text_ratio_; wrap_width_ = other.wrap_width_; wrap_char_ = other.wrap_char_; text_transform_ = other.text_transform_; line_spacing_ = other.line_spacing_; character_spacing_ = other.character_spacing_; label_spacing_ = other.label_spacing_; label_position_tolerance_ = other.label_position_tolerance_; force_odd_labels_ = other.force_odd_labels_; max_char_angle_delta_ = other.max_char_angle_delta_; fill_ = other.fill_; halo_fill_ = other.halo_fill_; halo_radius_ = other.halo_radius_; label_p_ = other.label_p_; valign_ = other.valign_; anchor_ = other.anchor_; displacement_ = other.displacement_; avoid_edges_ = other.avoid_edges_; minimum_distance_ = other.minimum_distance_; overlap_ = other.overlap_; text_opacity_ = other.text_opacity_; wrap_before_ = other.wrap_before_; halign_ = other.halign_; jalign_ = other.jalign_; std::cout << "TODO: Metawriter (text_symbolizer::operator=)\n"; return *this; } expression_ptr text_symbolizer::get_name() const { return name_; } void text_symbolizer::set_name(expression_ptr name) { name_ = name; } expression_ptr text_symbolizer::get_orientation() const { return orientation_; } void text_symbolizer::set_orientation(expression_ptr orientation) { orientation_ = orientation; } std::string const& text_symbolizer::get_face_name() const { return face_name_; } void text_symbolizer::set_face_name(std::string face_name) { face_name_ = face_name; } void text_symbolizer::set_fontset(font_set const& fontset) { fontset_ = fontset; } font_set const& text_symbolizer::get_fontset() const { return fontset_; } unsigned text_symbolizer::get_text_ratio() const { return text_ratio_; } void text_symbolizer::set_text_ratio(unsigned ratio) { text_ratio_ = ratio; } unsigned text_symbolizer::get_wrap_width() const { return wrap_width_; } void text_symbolizer::set_wrap_width(unsigned width) { wrap_width_ = width; } bool text_symbolizer::get_wrap_before() const { return wrap_before_; } void text_symbolizer::set_wrap_before(bool wrap_before) { wrap_before_ = wrap_before; } unsigned char text_symbolizer::get_wrap_char() const { return wrap_char_; } std::string text_symbolizer::get_wrap_char_string() const { return std::string(1, wrap_char_); } void text_symbolizer::set_wrap_char(unsigned char character) { wrap_char_ = character; } void text_symbolizer::set_wrap_char_from_string(std::string const& character) { wrap_char_ = (character)[0]; } text_transform_e text_symbolizer::get_text_transform() const { return text_transform_; } void text_symbolizer::set_text_transform(text_transform_e convert) { text_transform_ = convert; } unsigned text_symbolizer::get_line_spacing() const { return line_spacing_; } void text_symbolizer::set_line_spacing(unsigned spacing) { line_spacing_ = spacing; } unsigned text_symbolizer::get_character_spacing() const { return character_spacing_; } void text_symbolizer::set_character_spacing(unsigned spacing) { character_spacing_ = spacing; } unsigned text_symbolizer::get_label_spacing() const { return label_spacing_; } void text_symbolizer::set_label_spacing(unsigned spacing) { label_spacing_ = spacing; } unsigned text_symbolizer::get_label_position_tolerance() const { return label_position_tolerance_; } void text_symbolizer::set_label_position_tolerance(unsigned tolerance) { label_position_tolerance_ = tolerance; } bool text_symbolizer::get_force_odd_labels() const { return force_odd_labels_; } void text_symbolizer::set_force_odd_labels(bool force) { force_odd_labels_ = force; } double text_symbolizer::get_max_char_angle_delta() const { return max_char_angle_delta_; } void text_symbolizer::set_max_char_angle_delta(double angle) { max_char_angle_delta_ = angle; } void text_symbolizer::set_text_size(unsigned size) { size_ = size; } unsigned text_symbolizer::get_text_size() const { return size_; } void text_symbolizer::set_fill(color const& fill) { fill_ = fill; } color const& text_symbolizer::get_fill() const { return fill_; } void text_symbolizer::set_halo_fill(color const& fill) { halo_fill_ = fill; } color const& text_symbolizer::get_halo_fill() const { return halo_fill_; } void text_symbolizer::set_halo_radius(double radius) { halo_radius_ = radius; } double text_symbolizer::get_halo_radius() const { return halo_radius_; } void text_symbolizer::set_label_placement(label_placement_e label_p) { label_p_ = label_p; } label_placement_e text_symbolizer::get_label_placement() const { return label_p_; } void text_symbolizer::set_vertical_alignment(vertical_alignment_e valign) { valign_ = valign; } vertical_alignment_e text_symbolizer::get_vertical_alignment() const { return valign_; } void text_symbolizer::set_anchor(double x, double y) { anchor_ = boost::make_tuple(x,y); } position const& text_symbolizer::get_anchor() const { return anchor_; } void text_symbolizer::set_displacement(double x, double y) { displacement_ = boost::make_tuple(x,y); } position const& text_symbolizer::get_displacement() const { return displacement_; } bool text_symbolizer::get_avoid_edges() const { return avoid_edges_; } void text_symbolizer::set_avoid_edges(bool avoid) { avoid_edges_ = avoid; } double text_symbolizer::get_minimum_distance() const { return minimum_distance_; } void text_symbolizer::set_minimum_distance(double distance) { minimum_distance_ = distance; } void text_symbolizer::set_allow_overlap(bool overlap) { overlap_ = overlap; } bool text_symbolizer::get_allow_overlap() const { return overlap_; } void text_symbolizer::set_text_opacity(double text_opacity) { text_opacity_ = text_opacity; } double text_symbolizer::get_text_opacity() const { return text_opacity_; } void text_symbolizer::set_horizontal_alignment(horizontal_alignment_e halign) { halign_ = halign; } horizontal_alignment_e text_symbolizer::get_horizontal_alignment() const { return halign_; } void text_symbolizer::set_justify_alignment(justify_alignment_e jalign) { jalign_ = jalign; } justify_alignment_e text_symbolizer::get_justify_alignment() const { return jalign_; } } <commit_msg>+ max_char_angle default to 25 degrees<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ //mapnik #include <mapnik/text_symbolizer.hpp> // boost #include <boost/scoped_ptr.hpp> namespace mapnik { static const char * label_placement_strings[] = { "point", "line", "vertex", "" }; IMPLEMENT_ENUM( label_placement_e, label_placement_strings ); static const char * vertical_alignment_strings[] = { "top", "middle", "bottom", "" }; IMPLEMENT_ENUM( vertical_alignment_e, vertical_alignment_strings ); static const char * horizontal_alignment_strings[] = { "left", "middle", "right", "" }; IMPLEMENT_ENUM( horizontal_alignment_e, horizontal_alignment_strings ); static const char * justify_alignment_strings[] = { "left", "middle", "right", "" }; IMPLEMENT_ENUM( justify_alignment_e, justify_alignment_strings ); static const char * text_transform_strings[] = { "none", "uppercase", "lowercase", "" }; IMPLEMENT_ENUM( text_transform_e, text_transform_strings ); text_symbolizer::text_symbolizer(expression_ptr name, std::string const& face_name, unsigned size, color const& fill) : symbolizer_base(), name_(name), face_name_(face_name), //fontset_(default_fontset), size_(size), text_ratio_(0), wrap_width_(0), wrap_char_(' '), text_transform_(NONE), line_spacing_(0), character_spacing_(0), label_spacing_(0), label_position_tolerance_(0), force_odd_labels_(false), max_char_angle_delta_(25.0 * M_PI/180.0), fill_(fill), halo_fill_(color(255,255,255)), halo_radius_(0), label_p_(POINT_PLACEMENT), valign_(MIDDLE), anchor_(0.0,0.5), displacement_(0.0,0.0), avoid_edges_(false), minimum_distance_(0.0), overlap_(false), text_opacity_(1.0), wrap_before_(false), halign_(H_MIDDLE), jalign_(J_MIDDLE) {} text_symbolizer::text_symbolizer(expression_ptr name, unsigned size, color const& fill) : symbolizer_base(), name_(name), //face_name_(""), //fontset_(default_fontset), size_(size), text_ratio_(0), wrap_width_(0), wrap_char_(' '), text_transform_(NONE), line_spacing_(0), character_spacing_(0), label_spacing_(0), label_position_tolerance_(0), force_odd_labels_(false), max_char_angle_delta_(25.0 * M_PI/180.0), fill_(fill), halo_fill_(color(255,255,255)), halo_radius_(0), label_p_(POINT_PLACEMENT), valign_(MIDDLE), anchor_(0.0,0.5), displacement_(0.0,0.0), avoid_edges_(false), minimum_distance_(0.0), overlap_(false), text_opacity_(1.0), wrap_before_(false), halign_(H_MIDDLE), jalign_(J_MIDDLE) {} text_symbolizer::text_symbolizer(text_symbolizer const& rhs) : symbolizer_base(rhs), name_(rhs.name_), orientation_(rhs.orientation_), face_name_(rhs.face_name_), fontset_(rhs.fontset_), size_(rhs.size_), text_ratio_(rhs.text_ratio_), wrap_width_(rhs.wrap_width_), wrap_char_(rhs.wrap_char_), text_transform_(rhs.text_transform_), line_spacing_(rhs.line_spacing_), character_spacing_(rhs.character_spacing_), label_spacing_(rhs.label_spacing_), label_position_tolerance_(rhs.label_position_tolerance_), force_odd_labels_(rhs.force_odd_labels_), max_char_angle_delta_(rhs.max_char_angle_delta_), fill_(rhs.fill_), halo_fill_(rhs.halo_fill_), halo_radius_(rhs.halo_radius_), label_p_(rhs.label_p_), valign_(rhs.valign_), anchor_(rhs.anchor_), displacement_(rhs.displacement_), avoid_edges_(rhs.avoid_edges_), minimum_distance_(rhs.minimum_distance_), overlap_(rhs.overlap_), text_opacity_(rhs.text_opacity_), wrap_before_(rhs.wrap_before_), halign_(rhs.halign_), jalign_(rhs.jalign_) {} text_symbolizer& text_symbolizer::operator=(text_symbolizer const& other) { if (this == &other) return *this; name_ = other.name_; orientation_ = other.orientation_; face_name_ = other.face_name_; fontset_ = other.fontset_; size_ = other.size_; text_ratio_ = other.text_ratio_; wrap_width_ = other.wrap_width_; wrap_char_ = other.wrap_char_; text_transform_ = other.text_transform_; line_spacing_ = other.line_spacing_; character_spacing_ = other.character_spacing_; label_spacing_ = other.label_spacing_; label_position_tolerance_ = other.label_position_tolerance_; force_odd_labels_ = other.force_odd_labels_; max_char_angle_delta_ = other.max_char_angle_delta_; fill_ = other.fill_; halo_fill_ = other.halo_fill_; halo_radius_ = other.halo_radius_; label_p_ = other.label_p_; valign_ = other.valign_; anchor_ = other.anchor_; displacement_ = other.displacement_; avoid_edges_ = other.avoid_edges_; minimum_distance_ = other.minimum_distance_; overlap_ = other.overlap_; text_opacity_ = other.text_opacity_; wrap_before_ = other.wrap_before_; halign_ = other.halign_; jalign_ = other.jalign_; std::cout << "TODO: Metawriter (text_symbolizer::operator=)\n"; return *this; } expression_ptr text_symbolizer::get_name() const { return name_; } void text_symbolizer::set_name(expression_ptr name) { name_ = name; } expression_ptr text_symbolizer::get_orientation() const { return orientation_; } void text_symbolizer::set_orientation(expression_ptr orientation) { orientation_ = orientation; } std::string const& text_symbolizer::get_face_name() const { return face_name_; } void text_symbolizer::set_face_name(std::string face_name) { face_name_ = face_name; } void text_symbolizer::set_fontset(font_set const& fontset) { fontset_ = fontset; } font_set const& text_symbolizer::get_fontset() const { return fontset_; } unsigned text_symbolizer::get_text_ratio() const { return text_ratio_; } void text_symbolizer::set_text_ratio(unsigned ratio) { text_ratio_ = ratio; } unsigned text_symbolizer::get_wrap_width() const { return wrap_width_; } void text_symbolizer::set_wrap_width(unsigned width) { wrap_width_ = width; } bool text_symbolizer::get_wrap_before() const { return wrap_before_; } void text_symbolizer::set_wrap_before(bool wrap_before) { wrap_before_ = wrap_before; } unsigned char text_symbolizer::get_wrap_char() const { return wrap_char_; } std::string text_symbolizer::get_wrap_char_string() const { return std::string(1, wrap_char_); } void text_symbolizer::set_wrap_char(unsigned char character) { wrap_char_ = character; } void text_symbolizer::set_wrap_char_from_string(std::string const& character) { wrap_char_ = (character)[0]; } text_transform_e text_symbolizer::get_text_transform() const { return text_transform_; } void text_symbolizer::set_text_transform(text_transform_e convert) { text_transform_ = convert; } unsigned text_symbolizer::get_line_spacing() const { return line_spacing_; } void text_symbolizer::set_line_spacing(unsigned spacing) { line_spacing_ = spacing; } unsigned text_symbolizer::get_character_spacing() const { return character_spacing_; } void text_symbolizer::set_character_spacing(unsigned spacing) { character_spacing_ = spacing; } unsigned text_symbolizer::get_label_spacing() const { return label_spacing_; } void text_symbolizer::set_label_spacing(unsigned spacing) { label_spacing_ = spacing; } unsigned text_symbolizer::get_label_position_tolerance() const { return label_position_tolerance_; } void text_symbolizer::set_label_position_tolerance(unsigned tolerance) { label_position_tolerance_ = tolerance; } bool text_symbolizer::get_force_odd_labels() const { return force_odd_labels_; } void text_symbolizer::set_force_odd_labels(bool force) { force_odd_labels_ = force; } double text_symbolizer::get_max_char_angle_delta() const { return max_char_angle_delta_; } void text_symbolizer::set_max_char_angle_delta(double angle) { max_char_angle_delta_ = angle; } void text_symbolizer::set_text_size(unsigned size) { size_ = size; } unsigned text_symbolizer::get_text_size() const { return size_; } void text_symbolizer::set_fill(color const& fill) { fill_ = fill; } color const& text_symbolizer::get_fill() const { return fill_; } void text_symbolizer::set_halo_fill(color const& fill) { halo_fill_ = fill; } color const& text_symbolizer::get_halo_fill() const { return halo_fill_; } void text_symbolizer::set_halo_radius(double radius) { halo_radius_ = radius; } double text_symbolizer::get_halo_radius() const { return halo_radius_; } void text_symbolizer::set_label_placement(label_placement_e label_p) { label_p_ = label_p; } label_placement_e text_symbolizer::get_label_placement() const { return label_p_; } void text_symbolizer::set_vertical_alignment(vertical_alignment_e valign) { valign_ = valign; } vertical_alignment_e text_symbolizer::get_vertical_alignment() const { return valign_; } void text_symbolizer::set_anchor(double x, double y) { anchor_ = boost::make_tuple(x,y); } position const& text_symbolizer::get_anchor() const { return anchor_; } void text_symbolizer::set_displacement(double x, double y) { displacement_ = boost::make_tuple(x,y); } position const& text_symbolizer::get_displacement() const { return displacement_; } bool text_symbolizer::get_avoid_edges() const { return avoid_edges_; } void text_symbolizer::set_avoid_edges(bool avoid) { avoid_edges_ = avoid; } double text_symbolizer::get_minimum_distance() const { return minimum_distance_; } void text_symbolizer::set_minimum_distance(double distance) { minimum_distance_ = distance; } void text_symbolizer::set_allow_overlap(bool overlap) { overlap_ = overlap; } bool text_symbolizer::get_allow_overlap() const { return overlap_; } void text_symbolizer::set_text_opacity(double text_opacity) { text_opacity_ = text_opacity; } double text_symbolizer::get_text_opacity() const { return text_opacity_; } void text_symbolizer::set_horizontal_alignment(horizontal_alignment_e halign) { halign_ = halign; } horizontal_alignment_e text_symbolizer::get_horizontal_alignment() const { return halign_; } void text_symbolizer::set_justify_alignment(justify_alignment_e jalign) { jalign_ = jalign; } justify_alignment_e text_symbolizer::get_justify_alignment() const { return jalign_; } } <|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011, 2012 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #include <map> #include <cwchar> #include <limits> #include <vector> #include <typeinfo> #include <stdexcept> #include <algorithm> #include "cppa/atom.hpp" #include "cppa/actor.hpp" #include "cppa/group.hpp" #include "cppa/channel.hpp" #include "cppa/any_tuple.hpp" #include "cppa/any_tuple.hpp" #include "cppa/util/void_type.hpp" #include "cppa/detail/demangle.hpp" #include "cppa/detail/to_uniform_name.hpp" #include "cppa/detail/addressed_message.hpp" namespace { using namespace std; using namespace cppa; using namespace detail; constexpr const char* mapped_int_names[][2] = { { nullptr, nullptr }, // sizeof 0-> invalid { "@i8", "@u8" }, // sizeof 1 -> signed / unsigned int8 { "@i16", "@u16" }, // sizeof 2 -> signed / unsigned int16 { nullptr, nullptr }, // sizeof 3-> invalid { "@i32", "@u32" }, // sizeof 4 -> signed / unsigned int32 { nullptr, nullptr }, // sizeof 5-> invalid { nullptr, nullptr }, // sizeof 6-> invalid { nullptr, nullptr }, // sizeof 7-> invalid { "@i64", "@u64" } // sizeof 8 -> signed / unsigned int64 }; template<typename T> constexpr size_t sign_index() { static_assert(numeric_limits<T>::is_integer, "T is not an integer"); return numeric_limits<T>::is_signed ? 0 : 1; } template<typename T> inline string demangled() { return demangle(typeid(T)); } template<typename T> constexpr const char* mapped_int_name() { return mapped_int_names[sizeof(T)][sign_index<T>()]; } template<typename Iterator> string to_uniform_name_impl(Iterator begin, Iterator end, bool first_run = false) { // all integer type names as uniform representation static map<string, string> mapped_demangled_names = { // integer types { demangled<char>(), mapped_int_name<char>() }, { demangled<signed char>(), mapped_int_name<signed char>() }, { demangled<unsigned char>(), mapped_int_name<unsigned char>() }, { demangled<short>(), mapped_int_name<short>() }, { demangled<signed short>(), mapped_int_name<signed short>() }, { demangled<unsigned short>(), mapped_int_name<unsigned short>() }, { demangled<short int>(), mapped_int_name<short int>() }, { demangled<signed short int>(), mapped_int_name<signed short int>() }, { demangled<unsigned short int>(), mapped_int_name<unsigned short int>()}, { demangled<int>(), mapped_int_name<int>() }, { demangled<signed int>(), mapped_int_name<signed int>() }, { demangled<unsigned int>(), mapped_int_name<unsigned int>() }, { demangled<long int>(), mapped_int_name<long int>() }, { demangled<signed long int>(), mapped_int_name<signed long int>() }, { demangled<unsigned long int>(), mapped_int_name<unsigned long int>() }, { demangled<long>(), mapped_int_name<long>() }, { demangled<signed long>(), mapped_int_name<signed long>() }, { demangled<unsigned long>(), mapped_int_name<unsigned long>() }, { demangled<long long>(), mapped_int_name<long long>() }, { demangled<signed long long>(), mapped_int_name<signed long long>() }, { demangled<unsigned long long>(), mapped_int_name<unsigned long long>()}, { demangled<char16_t>(), mapped_int_name<char16_t>() }, { demangled<char32_t>(), mapped_int_name<char32_t>() }, // string types { demangled<string>(), "@str" }, { demangled<u16string>(), "@u16str" }, { demangled<u32string>(), "@u32str" }, // cppa types { demangled<atom_value>(), "@atom" }, { demangled<util::void_type>(), "@0" }, { demangled<any_tuple>(), "@<>" }, { demangled<actor_ptr>(), "@actor" }, { demangled<group_ptr>(), "@group" }, { demangled<channel_ptr>(), "@channel" }, { demangled<addressed_message>(), "@msg" }, { demangled< intrusive_ptr<process_information> >(), "@process_info" } }; // check if we could find the whole string in our lookup map if (first_run) { string tmp(begin, end); auto i = mapped_demangled_names.find(tmp); if (i != mapped_demangled_names.end()) { return i->second; } } // does [begin, end) represents an empty string? if (begin == end) return ""; // derived reverse_iterator type typedef reverse_iterator<Iterator> reverse_iterator; // a subsequence [begin', end') within [begin, end) typedef pair<Iterator, Iterator> subseq; vector<subseq> substrings; // explode string if we got a list of types int open_brackets = 0; // counts "open" '<' // denotes the begin of a possible subsequence Iterator anchor = begin; for (Iterator i = begin; i != end; /* i is incemented in the loop */) { switch (*i) { case '<': ++open_brackets; ++i; break; case '>': if (--open_brackets < 0) { throw runtime_error("malformed string"); } ++i; break; case ',': if (open_brackets == 0) { substrings.push_back(make_pair(anchor, i)); ++i; anchor = i; } else { ++i; } break; default: ++i; break; } } // call recursively for each list argument if (!substrings.empty()) { string result; substrings.push_back(make_pair(anchor, end)); for (const subseq& sstr : substrings) { if (!result.empty()) result += ","; result += to_uniform_name_impl(sstr.first, sstr.second); } return result; } // we didn't got a list, compute unify name else { // is [begin, end) a template? Iterator substr_begin = find(begin, end, '<'); if (substr_begin == end) { // not a template, return mapping string arg(begin, end); auto mapped = mapped_demangled_names.find(arg); return (mapped == mapped_demangled_names.end()) ? arg : mapped->second; } // skip leading '<' ++substr_begin; // find trailing '>' Iterator substr_end = find(reverse_iterator(end), reverse_iterator(substr_begin), '>') // get as an Iterator .base(); // skip trailing '>' --substr_end; if (substr_end == substr_begin) { throw runtime_error("substr_end == substr_begin"); } string result; // template name (part before leading '<') result.append(begin, substr_begin); // get mappings of all template parameter(s) result += to_uniform_name_impl(substr_begin, substr_end); result.append(substr_end, end); return result; } } template<size_t RawSize> void replace_all(string& str, const char (&before)[RawSize], const char* after) { // always skip the last element in `before`, because the last element // is the null-terminator auto i = search(begin(str), end(str), begin(before), end(before) - 1); while (i != end(str)) { str.replace(i, i + RawSize - 1, after); i = search(begin(str), end(str), begin(before), end(before) - 1); } } const char s_rawstr[] = "std::basic_string<@i8,std::char_traits<@i8>,std::allocator<@i8>"; const char s_str[] = "@str"; const char s_rawan[] = "(anonymous namespace)"; const char s_an[] = "@_"; } // namespace <anonymous> namespace cppa { namespace detail { std::string to_uniform_name(const std::string& dname) { auto r = to_uniform_name_impl(dname.begin(), dname.end(), true); replace_all(r, s_rawstr, s_str); replace_all(r, s_rawan, s_an); return r; } std::string to_uniform_name(const std::type_info& tinfo) { return to_uniform_name(demangle(tinfo.name())); } } } // namespace detail <commit_msg>fixed uniform name for user-defined templates using std::string<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011, 2012 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #include <map> #include <cwchar> #include <limits> #include <vector> #include <typeinfo> #include <stdexcept> #include <algorithm> #include "cppa/atom.hpp" #include "cppa/actor.hpp" #include "cppa/group.hpp" #include "cppa/channel.hpp" #include "cppa/any_tuple.hpp" #include "cppa/any_tuple.hpp" #include "cppa/util/void_type.hpp" #include "cppa/detail/demangle.hpp" #include "cppa/detail/to_uniform_name.hpp" #include "cppa/detail/addressed_message.hpp" namespace { using namespace std; using namespace cppa; using namespace detail; constexpr const char* mapped_int_names[][2] = { { nullptr, nullptr }, // sizeof 0-> invalid { "@i8", "@u8" }, // sizeof 1 -> signed / unsigned int8 { "@i16", "@u16" }, // sizeof 2 -> signed / unsigned int16 { nullptr, nullptr }, // sizeof 3-> invalid { "@i32", "@u32" }, // sizeof 4 -> signed / unsigned int32 { nullptr, nullptr }, // sizeof 5-> invalid { nullptr, nullptr }, // sizeof 6-> invalid { nullptr, nullptr }, // sizeof 7-> invalid { "@i64", "@u64" } // sizeof 8 -> signed / unsigned int64 }; template<typename T> constexpr size_t sign_index() { static_assert(numeric_limits<T>::is_integer, "T is not an integer"); return numeric_limits<T>::is_signed ? 0 : 1; } template<typename T> inline string demangled() { return demangle(typeid(T)); } template<typename T> constexpr const char* mapped_int_name() { return mapped_int_names[sizeof(T)][sign_index<T>()]; } template<typename Iterator> string to_uniform_name_impl(Iterator begin, Iterator end, bool first_run = false) { // all integer type names as uniform representation static map<string, string> mapped_demangled_names = { // integer types { demangled<char>(), mapped_int_name<char>() }, { demangled<signed char>(), mapped_int_name<signed char>() }, { demangled<unsigned char>(), mapped_int_name<unsigned char>() }, { demangled<short>(), mapped_int_name<short>() }, { demangled<signed short>(), mapped_int_name<signed short>() }, { demangled<unsigned short>(), mapped_int_name<unsigned short>() }, { demangled<short int>(), mapped_int_name<short int>() }, { demangled<signed short int>(), mapped_int_name<signed short int>() }, { demangled<unsigned short int>(), mapped_int_name<unsigned short int>()}, { demangled<int>(), mapped_int_name<int>() }, { demangled<signed int>(), mapped_int_name<signed int>() }, { demangled<unsigned int>(), mapped_int_name<unsigned int>() }, { demangled<long int>(), mapped_int_name<long int>() }, { demangled<signed long int>(), mapped_int_name<signed long int>() }, { demangled<unsigned long int>(), mapped_int_name<unsigned long int>() }, { demangled<long>(), mapped_int_name<long>() }, { demangled<signed long>(), mapped_int_name<signed long>() }, { demangled<unsigned long>(), mapped_int_name<unsigned long>() }, { demangled<long long>(), mapped_int_name<long long>() }, { demangled<signed long long>(), mapped_int_name<signed long long>() }, { demangled<unsigned long long>(), mapped_int_name<unsigned long long>()}, { demangled<char16_t>(), mapped_int_name<char16_t>() }, { demangled<char32_t>(), mapped_int_name<char32_t>() }, // string types { demangled<string>(), "@str" }, { demangled<u16string>(), "@u16str" }, { demangled<u32string>(), "@u32str" }, // cppa types { demangled<atom_value>(), "@atom" }, { demangled<util::void_type>(), "@0" }, { demangled<any_tuple>(), "@<>" }, { demangled<actor_ptr>(), "@actor" }, { demangled<group_ptr>(), "@group" }, { demangled<channel_ptr>(), "@channel" }, { demangled<addressed_message>(), "@msg" }, { demangled< intrusive_ptr<process_information> >(), "@process_info" } }; // check if we could find the whole string in our lookup map if (first_run) { string tmp(begin, end); auto i = mapped_demangled_names.find(tmp); if (i != mapped_demangled_names.end()) { return i->second; } } // does [begin, end) represents an empty string? if (begin == end) return ""; // derived reverse_iterator type typedef reverse_iterator<Iterator> reverse_iterator; // a subsequence [begin', end') within [begin, end) typedef pair<Iterator, Iterator> subseq; vector<subseq> substrings; // explode string if we got a list of types int open_brackets = 0; // counts "open" '<' // denotes the begin of a possible subsequence Iterator anchor = begin; for (Iterator i = begin; i != end; /* i is incemented in the loop */) { switch (*i) { case '<': ++open_brackets; ++i; break; case '>': if (--open_brackets < 0) { throw runtime_error("malformed string"); } ++i; break; case ',': if (open_brackets == 0) { substrings.push_back(make_pair(anchor, i)); ++i; anchor = i; } else { ++i; } break; default: ++i; break; } } // call recursively for each list argument if (!substrings.empty()) { string result; substrings.push_back(make_pair(anchor, end)); for (const subseq& sstr : substrings) { if (!result.empty()) result += ","; result += to_uniform_name_impl(sstr.first, sstr.second); } return result; } // we didn't got a list, compute unify name else { // is [begin, end) a template? Iterator substr_begin = find(begin, end, '<'); if (substr_begin == end) { // not a template, return mapping string arg(begin, end); auto mapped = mapped_demangled_names.find(arg); return (mapped == mapped_demangled_names.end()) ? arg : mapped->second; } // skip leading '<' ++substr_begin; // find trailing '>' Iterator substr_end = find(reverse_iterator(end), reverse_iterator(substr_begin), '>') // get as an Iterator .base(); // skip trailing '>' --substr_end; if (substr_end == substr_begin) { throw runtime_error("substr_end == substr_begin"); } string result; // template name (part before leading '<') result.append(begin, substr_begin); // get mappings of all template parameter(s) result += to_uniform_name_impl(substr_begin, substr_end); result.append(substr_end, end); return result; } } template<size_t RawSize> void replace_all(string& str, const char (&before)[RawSize], const char* after) { // end(before) - 1 points to the null-terminator auto i = search(begin(str), end(str), begin(before), end(before) - 1); while (i != end(str)) { str.replace(i, i + RawSize, after); i = search(begin(str), end(str), begin(before), end(before) - 1); } } const char s_rawstr[] = "std::basic_string<@i8,std::char_traits<@i8>,std::allocator<@i8>"; const char s_str[] = "@str"; const char s_rawan[] = "(anonymous namespace)"; const char s_an[] = "@_"; } // namespace <anonymous> namespace cppa { namespace detail { std::string to_uniform_name(const std::string& dname) { auto r = to_uniform_name_impl(dname.begin(), dname.end(), true); replace_all(r, s_rawstr, s_str); replace_all(r, s_rawan, s_an); return r; } std::string to_uniform_name(const std::type_info& tinfo) { return to_uniform_name(demangle(tinfo.name())); } } } // namespace detail <|endoftext|>
<commit_before>/** * \file py_event_manager.cpp * \brief Python wrapper for event_manager, * see event_manager.h * \author Morozov Andrey * \date 07.06.2008 * \copyright This source code is released under the terms of * the BSD License. See LICENSE for more details. * */ #include "stdafx.h" #include "event_manager.h" #include "py_event_manager.h" #include "reservoir.h" #include "facility_manager.h" #include "well_connection.h" #include "calc_model.h" #include "export_python_wrapper.h" #include <boost/python/suite/indexing/map_indexing_suite.hpp> #include <datetime.h> using namespace boost; using namespace boost::posix_time; namespace blue_sky { namespace python { template <typename strategy_t> py_event_manager<strategy_t>::~py_event_manager () { } template <typename strategy_t> py_event_manager<strategy_t>::py_event_manager() : py_objbase(wrapped_t::bs_type()) { } template <typename strategy_t> py_event_manager<strategy_t>::py_event_manager (const sp_em_t &src) : py_objbase (src) { } template <typename strategy_t> py_event_manager<strategy_t>::py_event_manager(const this_t &src) : py_objbase (src.get_spx <wrapped_t> ()) {} template <typename strategy_t> typename py_event_manager<strategy_t>::py_event_base_t * py_event_manager<strategy_t>::create_event (const std::string &date, const std::string &event_name, const std::string &event_params) { return new py_event_base_t (this->template get_spx <wrapped_t> ()->create_event (boost::posix_time::ptime (time_from_string (date)), event_name, event_params)); } template <typename strategy_t> void py_event_manager<strategy_t>::factory_register(const std::string &/*name*/, const event_creater_base_t &/*creater*/) { BS_ASSERT (false && "NOT_IMPL_YET"); } template <typename strategy_t> event_creater_base<strategy_t>::event_creater_base (boost::python::object &pobj) : obj (pobj) {} template <typename strategy_t> typename py_event_manager<strategy_t>::event_list_iterator_t py_event_manager<strategy_t>::el_begin () { return event_list_iterator_t (this->get_spx <wrapped_t> ()); } //event_list_iterator_t el_end (); template <typename strategy_t> typename event_creater_base<strategy_t>::py_event_base_t * event_creater_base<strategy_t>::create () { // CALL PYTHON IMPL (pure virtual) } template <typename strategy_t> void py_export_event_manager_ (const char *name) { using namespace boost::python; class_<py_event_manager <strategy_t>, bases<py_objbase> >(name) .def ("create_event", &py_event_manager <strategy_t>::create_event, return_value_policy <manage_new_object> ()) .def ("el_begin", &py_event_manager <strategy_t>::el_begin) ; } PY_EXPORTER (event_manager_exporter, default_exporter) .add_property ("event_list", &T::event_list) PY_EXPORTER_END; template <typename T> void list_begin (T *t) { } template <typename T> void export_event_list (const char *name) { using namespace boost::python; class_ <T> (name) .def ("begin", list_begin <T>) ; } template <typename T> void export_event_map (const char *name) { using namespace boost::python; class_ <T> (name) .def (map_indexing_suite <T> ()) ; } struct boost_ptime_to_python_datetime { static PyObject * convert (const boost::posix_time::ptime &pt) { boost::gregorian::date date = pt.date (); boost::posix_time::time_duration td = pt.time_of_day (); int year = date.year (); int month = date.month (); int day = date.day (); int hour = td.hours (); int minute = td.minutes (); int second = td.seconds (); return PyDateTime_FromDateAndTime (year, month, day, hour, minute, second, 0); } }; struct boost_ptime_from_python_datetime { boost_ptime_from_python_datetime () { boost::python::converter::registry::push_back ( &convertible, &construct, boost::python::type_id <boost::posix_time::ptime> ()); } static void * convertible (PyObject *obj_ptr) { return PyDateTime_Check (obj_ptr) ? obj_ptr : 0; } static void construct (PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data *data) { const PyDateTime_DateTime *pydate = reinterpret_cast <PyDateTime_DateTime *> (obj_ptr); int year = PyDateTime_GET_YEAR (pydate); int month = PyDateTime_GET_MONTH (pydate); int day = PyDateTime_GET_DAY (pydate); int hour = PyDateTime_TIME_GET_HOUR (pydate); int minute = PyDateTime_TIME_GET_MINUTE (pydate); int second = PyDateTime_TIME_GET_SECOND (pydate); int mcsecond = PyDateTime_TIME_GET_MICROSECOND (pydate); boost::gregorian::date d (year, month, day); boost::posix_time::time_duration td (hour, minute, second, 0); td += boost::posix_time::microseconds (mcsecond); using namespace boost::python; using namespace boost::posix_time; void *storage = ((converter::rvalue_from_python_storage <ptime>*)data)->storage.bytes; new (storage) boost::posix_time::ptime (d, td); data->convertible = storage; } }; void py_export_event_manager () { using namespace boost::python; PyDateTime_IMPORT; boost_ptime_from_python_datetime (); to_python_converter <boost::posix_time::ptime, boost_ptime_to_python_datetime> (); typedef event_base <base_strategy_di> event_base_di_t; typedef std::list <smart_ptr <event_base_di_t> > event_list_di_t; export_event_list <event_list_di_t> ("event_list_di"); export_event_map <std::map <boost::posix_time::ptime, event_list_di_t> > ("event_map_di"); strategy_exporter::export_base <event_manager, event_manager_exporter> ("event_manager"); } template class py_event_manager <base_strategy_fi>; template class py_event_manager <base_strategy_di>; template class py_event_manager <base_strategy_mixi>; } // namespace python } // namespace blue_sky <commit_msg>Edit: Fix datetime to ptime converter<commit_after>/** * \file py_event_manager.cpp * \brief Python wrapper for event_manager, * see event_manager.h * \author Morozov Andrey * \date 07.06.2008 * \copyright This source code is released under the terms of * the BSD License. See LICENSE for more details. * */ #include "stdafx.h" #include "event_manager.h" #include "py_event_manager.h" #include "reservoir.h" #include "facility_manager.h" #include "well_connection.h" #include "calc_model.h" #include "export_python_wrapper.h" #include <boost/python/suite/indexing/map_indexing_suite.hpp> #include <datetime.h> using namespace boost; using namespace boost::posix_time; namespace blue_sky { namespace python { template <typename strategy_t> py_event_manager<strategy_t>::~py_event_manager () { } template <typename strategy_t> py_event_manager<strategy_t>::py_event_manager() : py_objbase(wrapped_t::bs_type()) { } template <typename strategy_t> py_event_manager<strategy_t>::py_event_manager (const sp_em_t &src) : py_objbase (src) { } template <typename strategy_t> py_event_manager<strategy_t>::py_event_manager(const this_t &src) : py_objbase (src.get_spx <wrapped_t> ()) {} template <typename strategy_t> typename py_event_manager<strategy_t>::py_event_base_t * py_event_manager<strategy_t>::create_event (const std::string &date, const std::string &event_name, const std::string &event_params) { return new py_event_base_t (this->template get_spx <wrapped_t> ()->create_event (boost::posix_time::ptime (time_from_string (date)), event_name, event_params)); } template <typename strategy_t> void py_event_manager<strategy_t>::factory_register(const std::string &/*name*/, const event_creater_base_t &/*creater*/) { BS_ASSERT (false && "NOT_IMPL_YET"); } template <typename strategy_t> event_creater_base<strategy_t>::event_creater_base (boost::python::object &pobj) : obj (pobj) {} template <typename strategy_t> typename py_event_manager<strategy_t>::event_list_iterator_t py_event_manager<strategy_t>::el_begin () { return event_list_iterator_t (this->get_spx <wrapped_t> ()); } //event_list_iterator_t el_end (); template <typename strategy_t> typename event_creater_base<strategy_t>::py_event_base_t * event_creater_base<strategy_t>::create () { // CALL PYTHON IMPL (pure virtual) } template <typename strategy_t> void py_export_event_manager_ (const char *name) { using namespace boost::python; class_<py_event_manager <strategy_t>, bases<py_objbase> >(name) .def ("create_event", &py_event_manager <strategy_t>::create_event, return_value_policy <manage_new_object> ()) .def ("el_begin", &py_event_manager <strategy_t>::el_begin) ; } PY_EXPORTER (event_manager_exporter, default_exporter) .add_property ("event_list", &T::event_list) PY_EXPORTER_END; template <typename T> void list_begin (T *t) { } template <typename T> void export_event_list (const char *name) { using namespace boost::python; class_ <T> (name) .def ("begin", list_begin <T>) ; } template <typename T> void export_event_map (const char *name) { using namespace boost::python; class_ <T> (name) .def (map_indexing_suite <T> ()) ; } struct boost_ptime_to_python_datetime { static PyObject * convert (const boost::posix_time::ptime &pt) { boost::gregorian::date date = pt.date (); boost::posix_time::time_duration td = pt.time_of_day (); int year = date.year (); int month = date.month (); int day = date.day (); int hour = td.hours (); int minute = td.minutes (); int second = td.seconds (); return PyDateTime_FromDateAndTime (year, month, day, hour, minute, second, 0); } }; struct boost_ptime_from_python_datetime { boost_ptime_from_python_datetime () { boost::python::converter::registry::push_back ( &convertible, &construct, boost::python::type_id <boost::posix_time::ptime> ()); } static void * convertible (PyObject *obj_ptr) { return PyDateTime_Check (obj_ptr) ? obj_ptr : 0; } static void construct (PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data *data) { const PyDateTime_DateTime *pydate = reinterpret_cast <PyDateTime_DateTime *> (obj_ptr); int year = PyDateTime_GET_YEAR (pydate); int month = PyDateTime_GET_MONTH (pydate); int day = PyDateTime_GET_DAY (pydate); int hour = PyDateTime_DATE_GET_HOUR (pydate); int minute = PyDateTime_DATE_GET_MINUTE (pydate); int second = PyDateTime_DATE_GET_SECOND (pydate); int mcsecond = PyDateTime_DATE_GET_MICROSECOND (pydate); boost::gregorian::date d (year, month, day); boost::posix_time::time_duration td (hour, minute, second, 0); td += boost::posix_time::microseconds (mcsecond); using namespace boost::python; using namespace boost::posix_time; void *storage = ((converter::rvalue_from_python_storage <ptime>*)data)->storage.bytes; new (storage) boost::posix_time::ptime (d, td); data->convertible = storage; } }; void py_export_event_manager () { using namespace boost::python; PyDateTime_IMPORT; boost_ptime_from_python_datetime (); to_python_converter <boost::posix_time::ptime, boost_ptime_to_python_datetime> (); typedef event_base <base_strategy_di> event_base_di_t; typedef std::list <smart_ptr <event_base_di_t> > event_list_di_t; export_event_list <event_list_di_t> ("event_list_di"); export_event_map <std::map <boost::posix_time::ptime, event_list_di_t> > ("event_map_di"); strategy_exporter::export_base <event_manager, event_manager_exporter> ("event_manager"); } template class py_event_manager <base_strategy_fi>; template class py_event_manager <base_strategy_di>; template class py_event_manager <base_strategy_mixi>; } // namespace python } // namespace blue_sky <|endoftext|>
<commit_before>/********************************************************************* *\ * INTEL CORPORATION PROPRIETARY INFORMATION * This software is supplied under the terms of a license agreement or * nondisclosure agreement with Intel Corporation and may not be copied * or disclosed except in accordance with the terms of that agreement. * Copyright (C) 2014 Intel Corporation. All Rights Reserved. ********************************************************************* */ #undef NDEBUG // viewer widget #include "apps/common/widgets/glut3D.h" // ospray, for rendering #include "ospray/ospray.h" #include "model.h" namespace ospray { namespace tachyon { using std::cout; using std::endl; float lightScale = 1.f; const char *renderType = "tachyon"; // const char *renderType = "ao16"; float defaultRadius = .1f; struct TimeStep { std::string modelName; tachyon::Model tm; // tachyon model OSPModel om; // ospray model TimeStep(const std::string &modelName) : modelName(modelName), om(NULL) {}; }; std::vector<TimeStep *> timeStep; int timeStepID = 0; bool doShadows = true; void error(const std::string &vol) { if (vol != "") { cout << "=======================================================" << endl; cout << "ospray::tachView fatal error : " << vol << endl; cout << "=======================================================" << endl; } cout << endl; cout << "Proper usage: " << endl; cout << " ./ospTachyon <inputfile.tach> <options>" << std::endl; cout << "options:" << endl; cout << " <none>" << endl; cout << endl; exit(1); } OSPModel specifyModel(tachyon::Model &tm) { OSPModel ospModel = ospNewModel(); if (tm.numSpheres()) { OSPData sphereData = ospNewData(tm.numSpheres()*sizeof(Sphere)/sizeof(float), OSP_FLOAT,tm.getSpheresPtr()); ospCommit(sphereData); OSPGeometry sphereGeom = ospNewGeometry("spheres"); ospSetData(sphereGeom,"spheres",sphereData); ospSet1i(sphereGeom,"bytes_per_sphere",sizeof(Sphere)); ospSet1i(sphereGeom,"offset_materialID",0*sizeof(float)); ospSet1i(sphereGeom,"offset_center",1*sizeof(float)); ospSet1i(sphereGeom,"offset_radius",4*sizeof(float)); ospCommit(sphereGeom); ospAddGeometry(ospModel,sphereGeom); } if (tm.numCylinders()) { OSPData cylinderData = ospNewData(tm.numCylinders()*sizeof(Cylinder)/sizeof(float), OSP_FLOAT,tm.getCylindersPtr()); ospCommit(cylinderData); OSPGeometry cylinderGeom = ospNewGeometry("cylinders"); ospSetData(cylinderGeom,"cylinders",cylinderData); ospSet1i(cylinderGeom,"bytes_per_cylinder",sizeof(Cylinder)); ospSet1i(cylinderGeom,"offset_materialID",0*sizeof(float)); ospSet1i(cylinderGeom,"offset_v0",1*sizeof(float)); ospSet1i(cylinderGeom,"offset_v1",4*sizeof(float)); ospSet1i(cylinderGeom,"offset_radius",7*sizeof(float)); ospCommit(cylinderGeom); ospAddGeometry(ospModel,cylinderGeom); } cout << "#osp:tachyon: creating " << tm.numVertexArrays() << " vertex arrays" << endl; long numTriangles = 0; for (int vaID=0;vaID<tm.numVertexArrays();vaID++) { const VertexArray *va = tm.getVertexArray(vaID); // if (va != tm.getSTriVA()) // continue; Assert(va); OSPGeometry geom = ospNewTriangleMesh(); numTriangles += va->triangle.size(); if (va->triangle.size()) { OSPData data = ospNewData(va->triangle.size(),OSP_INT3,&va->triangle[0]); ospCommit(data); ospSetData(geom,"triangle",data); } if (va->coord.size()) { OSPData data = ospNewData(va->coord.size(),OSP_FLOAT3A,&va->coord[0]); ospCommit(data); ospSetData(geom,"vertex",data); } if (va->normal.size()) { OSPData data = ospNewData(va->normal.size(),OSP_FLOAT3A,&va->normal[0]); ospCommit(data); ospSetData(geom,"vertex.normal",data); } if (va->color.size()) { OSPData data = ospNewData(va->color.size(),OSP_FLOAT3A,&va->color[0]); ospCommit(data); ospSetData(geom,"vertex.color",data); } if (va->perTriTextureID.size()) { OSPData data = ospNewData(va->perTriTextureID.size(),OSP_UINT, &va->perTriTextureID[0]); ospCommit(data); ospSetData(geom,"prim.materialID",data); } else { ospSet1i(geom,"geom.materialID",va->textureID); } ospCommit(geom); ospAddGeometry(ospModel,geom); } cout << "#osp:tachyon: specifying " << tm.numTextures() << " materials..." << endl; { OSPData data = ospNewData(tm.numTextures()*sizeof(Texture), OSP_UCHAR,tm.getTexturesPtr()); ospCommit(data); ospSetData(ospModel,"textureArray",data); } cout << "#osp:tachyon: specifying " << tm.numPointLights() << " point lights..." << endl; if (tm.numPointLights() > 0) { OSPData data = ospNewData(tm.numPointLights()*sizeof(PointLight), OSP_UCHAR,tm.getPointLightsPtr()); ospCommit(data); ospSetData(ospModel,"pointLights",data); } cout << "#osp:tachyon: specifying " << tm.numDirLights() << " dir lights..." << endl; if (tm.numDirLights() > 0) { OSPData data = ospNewData(tm.numDirLights()*sizeof(DirLight), OSP_UCHAR,tm.getDirLightsPtr()); ospCommit(data); ospSetData(ospModel,"dirLights",data); } std::cout << "=======================================" << std::endl; std::cout << "Tachyon Renderer: Done specifying model" << std::endl; std::cout << "num spheres: " << tm.numSpheres() << std::endl; std::cout << "num cylinders: " << tm.numCylinders() << std::endl; std::cout << "num triangles: " << numTriangles << std::endl; std::cout << "=======================================" << std::endl; ospCommit(ospModel); return ospModel; } using ospray::glut3D::Glut3DWidget; //! volume viewer widget. /*! \internal Note that all handling of camera is almost exactly similar to the code in msgView; might make sense to move that into a common class! */ struct TACHViewer : public Glut3DWidget { /*! construct volume from file name and dimensions \see volview_notes_on_volume_interface */ TACHViewer(OSPModel model, const std::string &modelName) : Glut3DWidget(Glut3DWidget::FRAMEBUFFER_NONE), fb(NULL), renderer(NULL), model(model), modelName(modelName) { camera = ospNewCamera("perspective"); Assert2(camera,"could not create camera"); ospSet3f(camera,"pos",-1,1,-1); ospSet3f(camera,"dir",+1,-1,+1); ospCommit(camera); ospCommit(camera); renderer = ospNewRenderer(renderType); Assert2(renderer,"could not create renderer"); ospSetParam(renderer,"model",model); ospSetParam(renderer,"camera",camera); ospSet1i(renderer,"do_shadows",doShadows); ospCommit(renderer); }; virtual void keypress(char key, const vec2f where) { switch (key) { case 'S': doShadows = !doShadows; cout << "Switching shadows " << (doShadows?"ON":"OFF") << endl; ospSet1i(renderer,"do_shadows",doShadows); ospCommit(renderer); break; case 'L': lightScale *= 1.5f; ospSet1f(renderer,"lightScale",lightScale); PRINT(lightScale); PRINT(renderer); ospCommit(renderer); break; case 'l': lightScale /= 1.5f; PRINT(lightScale); PRINT(renderer); ospSet1f(renderer,"lightScale",lightScale); ospCommit(renderer); break; case '<': setTimeStep((timeStepID+timeStep.size()-1)%timeStep.size()); break; case '>': setTimeStep((timeStepID+1)%timeStep.size()); break; default: Glut3DWidget::keypress(key,where); } } void setTimeStep(size_t newTSID) { timeStepID = newTSID; modelName = timeStep[timeStepID]->modelName; cout << "#osp:tachyon: switching to time step " << timeStepID << " (" << modelName << ")" << endl; model = timeStep[timeStepID]->om; ospSetParam(renderer,"model",model); ospCommit(renderer); } virtual void reshape(const ospray::vec2i &newSize) { Glut3DWidget::reshape(newSize); if (fb) ospFreeFrameBuffer(fb); fb = ospNewFrameBuffer(newSize,OSP_RGBA_I8,OSP_FB_COLOR|OSP_FB_ACCUM); ospSetf(camera,"aspect",viewPort.aspect); ospCommit(camera); } virtual void display() { if (!fb || !renderer) return; if (viewPort.modified) { Assert2(camera,"ospray camera is null"); // PRINT(viewPort); ospSetVec3f(camera,"pos",viewPort.from); ospSetVec3f(camera,"dir",viewPort.at-viewPort.from); ospSetVec3f(camera,"up",viewPort.up); ospSetf(camera,"aspect",viewPort.aspect); ospCommit(camera); viewPort.modified = false; ospFrameBufferClear(fb,OSP_FB_COLOR|OSP_FB_ACCUM); } fps.startRender(); ospRenderFrame(fb,renderer,OSP_FB_COLOR|OSP_FB_ACCUM); fps.doneRender(); ucharFB = (unsigned int *)ospMapFrameBuffer(fb); frameBufferMode = Glut3DWidget::FRAMEBUFFER_UCHAR; Glut3DWidget::display(); ospUnmapFrameBuffer(ucharFB,fb); #if 1 char title[10000]; sprintf(title,"ospray Tachyon viewer (%s) [%f fps]", modelName.c_str(),fps.getFPS()); setTitle(title); #endif forceRedraw(); } OSPModel model; OSPFrameBuffer fb; OSPRenderer renderer; OSPCamera camera; ospray::glut3D::FPSCounter fps; std::string modelName; }; void ospTACHMain(int &ac, const char **&av) { ospLoadModule("tachyon"); for (int i=1;i<ac;i++) { std::string arg = av[i]; if (arg[0] != '-') { timeStep.push_back(new TimeStep(arg)); } else throw std::runtime_error("unknown parameter "+arg); } if (timeStep.empty()) error("no input geometry specifies!?"); std::vector<OSPModel> modelHandle; for (int i=0;i<timeStep.size();i++) { TimeStep *ts = timeStep[i]; importFile(ts->tm,ts->modelName); if (ts->tm.empty()) error(ts->modelName+": no input geometry specified!?"); ts->om = specifyModel(ts->tm); } // ------------------------------------------------------- // parse and set up input(s) // ------------------------------------------------------- // ------------------------------------------------------- // create viewer window // ------------------------------------------------------- TACHViewer window(timeStep[0]->om,timeStep[0]->modelName); window.create("ospTACH: OSPRay Tachyon-model viewer"); printf("Viewer created. Press 'Q' to quit.\n"); window.setWorldBounds(timeStep[0]->tm.getBounds()); ospray::tachyon::Camera *camera = timeStep[0]->tm.getCamera(); if (camera) { window.viewPort.from = camera->center; window.viewPort.at = camera->center+camera->viewDir; window.viewPort.up = camera->upDir; window.computeFrame(); } ospray::glut3D::runGLUT(); } } } int main(int ac, const char **av) { ospInit(&ac,av); ospray::glut3D::initGLUT(&ac,av); ospray::tachyon::ospTACHMain(ac,av); } <commit_msg>added keystrokes to change upvector in tachyon<commit_after>/********************************************************************* *\ * INTEL CORPORATION PROPRIETARY INFORMATION * This software is supplied under the terms of a license agreement or * nondisclosure agreement with Intel Corporation and may not be copied * or disclosed except in accordance with the terms of that agreement. * Copyright (C) 2014 Intel Corporation. All Rights Reserved. ********************************************************************* */ #undef NDEBUG // viewer widget #include "apps/common/widgets/glut3D.h" // ospray, for rendering #include "ospray/ospray.h" #include "model.h" namespace ospray { namespace tachyon { using std::cout; using std::endl; float lightScale = 1.f; const char *renderType = "tachyon"; // const char *renderType = "ao16"; float defaultRadius = .1f; struct TimeStep { std::string modelName; tachyon::Model tm; // tachyon model OSPModel om; // ospray model TimeStep(const std::string &modelName) : modelName(modelName), om(NULL) {}; }; std::vector<TimeStep *> timeStep; int timeStepID = 0; bool doShadows = true; void error(const std::string &vol) { if (vol != "") { cout << "=======================================================" << endl; cout << "ospray::tachView fatal error : " << vol << endl; cout << "=======================================================" << endl; } cout << endl; cout << "Proper usage: " << endl; cout << " ./ospTachyon <inputfile.tach> <options>" << std::endl; cout << "options:" << endl; cout << " <none>" << endl; cout << endl; exit(1); } OSPModel specifyModel(tachyon::Model &tm) { OSPModel ospModel = ospNewModel(); if (tm.numSpheres()) { OSPData sphereData = ospNewData(tm.numSpheres()*sizeof(Sphere)/sizeof(float), OSP_FLOAT,tm.getSpheresPtr()); ospCommit(sphereData); OSPGeometry sphereGeom = ospNewGeometry("spheres"); ospSetData(sphereGeom,"spheres",sphereData); ospSet1i(sphereGeom,"bytes_per_sphere",sizeof(Sphere)); ospSet1i(sphereGeom,"offset_materialID",0*sizeof(float)); ospSet1i(sphereGeom,"offset_center",1*sizeof(float)); ospSet1i(sphereGeom,"offset_radius",4*sizeof(float)); ospCommit(sphereGeom); ospAddGeometry(ospModel,sphereGeom); } if (tm.numCylinders()) { OSPData cylinderData = ospNewData(tm.numCylinders()*sizeof(Cylinder)/sizeof(float), OSP_FLOAT,tm.getCylindersPtr()); ospCommit(cylinderData); OSPGeometry cylinderGeom = ospNewGeometry("cylinders"); ospSetData(cylinderGeom,"cylinders",cylinderData); ospSet1i(cylinderGeom,"bytes_per_cylinder",sizeof(Cylinder)); ospSet1i(cylinderGeom,"offset_materialID",0*sizeof(float)); ospSet1i(cylinderGeom,"offset_v0",1*sizeof(float)); ospSet1i(cylinderGeom,"offset_v1",4*sizeof(float)); ospSet1i(cylinderGeom,"offset_radius",7*sizeof(float)); ospCommit(cylinderGeom); ospAddGeometry(ospModel,cylinderGeom); } cout << "#osp:tachyon: creating " << tm.numVertexArrays() << " vertex arrays" << endl; long numTriangles = 0; for (int vaID=0;vaID<tm.numVertexArrays();vaID++) { const VertexArray *va = tm.getVertexArray(vaID); // if (va != tm.getSTriVA()) // continue; Assert(va); OSPGeometry geom = ospNewTriangleMesh(); numTriangles += va->triangle.size(); if (va->triangle.size()) { OSPData data = ospNewData(va->triangle.size(),OSP_INT3,&va->triangle[0]); ospCommit(data); ospSetData(geom,"triangle",data); } if (va->coord.size()) { OSPData data = ospNewData(va->coord.size(),OSP_FLOAT3A,&va->coord[0]); ospCommit(data); ospSetData(geom,"vertex",data); } if (va->normal.size()) { OSPData data = ospNewData(va->normal.size(),OSP_FLOAT3A,&va->normal[0]); ospCommit(data); ospSetData(geom,"vertex.normal",data); } if (va->color.size()) { OSPData data = ospNewData(va->color.size(),OSP_FLOAT3A,&va->color[0]); ospCommit(data); ospSetData(geom,"vertex.color",data); } if (va->perTriTextureID.size()) { OSPData data = ospNewData(va->perTriTextureID.size(),OSP_UINT, &va->perTriTextureID[0]); ospCommit(data); ospSetData(geom,"prim.materialID",data); } else { ospSet1i(geom,"geom.materialID",va->textureID); } ospCommit(geom); ospAddGeometry(ospModel,geom); } cout << "#osp:tachyon: specifying " << tm.numTextures() << " materials..." << endl; { OSPData data = ospNewData(tm.numTextures()*sizeof(Texture), OSP_UCHAR,tm.getTexturesPtr()); ospCommit(data); ospSetData(ospModel,"textureArray",data); } cout << "#osp:tachyon: specifying " << tm.numPointLights() << " point lights..." << endl; if (tm.numPointLights() > 0) { OSPData data = ospNewData(tm.numPointLights()*sizeof(PointLight), OSP_UCHAR,tm.getPointLightsPtr()); ospCommit(data); ospSetData(ospModel,"pointLights",data); } cout << "#osp:tachyon: specifying " << tm.numDirLights() << " dir lights..." << endl; if (tm.numDirLights() > 0) { OSPData data = ospNewData(tm.numDirLights()*sizeof(DirLight), OSP_UCHAR,tm.getDirLightsPtr()); ospCommit(data); ospSetData(ospModel,"dirLights",data); } std::cout << "=======================================" << std::endl; std::cout << "Tachyon Renderer: Done specifying model" << std::endl; std::cout << "num spheres: " << tm.numSpheres() << std::endl; std::cout << "num cylinders: " << tm.numCylinders() << std::endl; std::cout << "num triangles: " << numTriangles << std::endl; std::cout << "=======================================" << std::endl; ospCommit(ospModel); return ospModel; } using ospray::glut3D::Glut3DWidget; //! volume viewer widget. /*! \internal Note that all handling of camera is almost exactly similar to the code in msgView; might make sense to move that into a common class! */ struct TACHViewer : public Glut3DWidget { /*! construct volume from file name and dimensions \see volview_notes_on_volume_interface */ TACHViewer(OSPModel model, const std::string &modelName) : Glut3DWidget(Glut3DWidget::FRAMEBUFFER_NONE), fb(NULL), renderer(NULL), model(model), modelName(modelName) { camera = ospNewCamera("perspective"); Assert2(camera,"could not create camera"); ospSet3f(camera,"pos",-1,1,-1); ospSet3f(camera,"dir",+1,-1,+1); ospCommit(camera); ospCommit(camera); renderer = ospNewRenderer(renderType); Assert2(renderer,"could not create renderer"); ospSetParam(renderer,"model",model); ospSetParam(renderer,"camera",camera); ospSet1i(renderer,"do_shadows",doShadows); ospCommit(renderer); }; virtual void keypress(char key, const vec2f where) { switch (key) { case 'X': if (viewPort.up == vec3f(1,0,0) || viewPort.up == vec3f(-1.f,0,0)) viewPort.up = - viewPort.up; else viewPort.up = vec3f(1,0,0); viewPort.modified = true; break; case 'Y': if (viewPort.up == vec3f(0,1,0) || viewPort.up == vec3f(0,-1.f,0)) viewPort.up = - viewPort.up; else viewPort.up = vec3f(0,1,0); viewPort.modified = true; break; case 'Z': if (viewPort.up == vec3f(0,0,1) || viewPort.up == vec3f(0,0,-1.f)) viewPort.up = - viewPort.up; else viewPort.up = vec3f(0,0,1); viewPort.modified = true; break; case 'S': doShadows = !doShadows; cout << "Switching shadows " << (doShadows?"ON":"OFF") << endl; ospSet1i(renderer,"do_shadows",doShadows); ospCommit(renderer); break; case 'L': lightScale *= 1.5f; ospSet1f(renderer,"lightScale",lightScale); PRINT(lightScale); PRINT(renderer); ospCommit(renderer); break; case 'l': lightScale /= 1.5f; PRINT(lightScale); PRINT(renderer); ospSet1f(renderer,"lightScale",lightScale); ospCommit(renderer); break; case '<': setTimeStep((timeStepID+timeStep.size()-1)%timeStep.size()); break; case '>': setTimeStep((timeStepID+1)%timeStep.size()); break; default: Glut3DWidget::keypress(key,where); } } void setTimeStep(size_t newTSID) { timeStepID = newTSID; modelName = timeStep[timeStepID]->modelName; cout << "#osp:tachyon: switching to time step " << timeStepID << " (" << modelName << ")" << endl; model = timeStep[timeStepID]->om; ospSetParam(renderer,"model",model); ospCommit(renderer); } virtual void reshape(const ospray::vec2i &newSize) { Glut3DWidget::reshape(newSize); if (fb) ospFreeFrameBuffer(fb); fb = ospNewFrameBuffer(newSize,OSP_RGBA_I8,OSP_FB_COLOR|OSP_FB_ACCUM); ospSetf(camera,"aspect",viewPort.aspect); ospCommit(camera); } virtual void display() { if (!fb || !renderer) return; if (viewPort.modified) { Assert2(camera,"ospray camera is null"); // PRINT(viewPort); ospSetVec3f(camera,"pos",viewPort.from); ospSetVec3f(camera,"dir",viewPort.at-viewPort.from); ospSetVec3f(camera,"up",viewPort.up); ospSetf(camera,"aspect",viewPort.aspect); ospCommit(camera); viewPort.modified = false; ospFrameBufferClear(fb,OSP_FB_COLOR|OSP_FB_ACCUM); } fps.startRender(); ospRenderFrame(fb,renderer,OSP_FB_COLOR|OSP_FB_ACCUM); fps.doneRender(); ucharFB = (unsigned int *)ospMapFrameBuffer(fb); frameBufferMode = Glut3DWidget::FRAMEBUFFER_UCHAR; Glut3DWidget::display(); ospUnmapFrameBuffer(ucharFB,fb); #if 1 char title[10000]; sprintf(title,"ospray Tachyon viewer (%s) [%f fps]", modelName.c_str(),fps.getFPS()); setTitle(title); #endif forceRedraw(); } OSPModel model; OSPFrameBuffer fb; OSPRenderer renderer; OSPCamera camera; ospray::glut3D::FPSCounter fps; std::string modelName; }; void ospTACHMain(int &ac, const char **&av) { ospLoadModule("tachyon"); for (int i=1;i<ac;i++) { std::string arg = av[i]; if (arg[0] != '-') { timeStep.push_back(new TimeStep(arg)); } else throw std::runtime_error("unknown parameter "+arg); } if (timeStep.empty()) error("no input geometry specifies!?"); std::vector<OSPModel> modelHandle; for (int i=0;i<timeStep.size();i++) { TimeStep *ts = timeStep[i]; importFile(ts->tm,ts->modelName); if (ts->tm.empty()) error(ts->modelName+": no input geometry specified!?"); ts->om = specifyModel(ts->tm); } // ------------------------------------------------------- // parse and set up input(s) // ------------------------------------------------------- // ------------------------------------------------------- // create viewer window // ------------------------------------------------------- TACHViewer window(timeStep[0]->om,timeStep[0]->modelName); window.create("ospTACH: OSPRay Tachyon-model viewer"); printf("Viewer created. Press 'Q' to quit.\n"); window.setWorldBounds(timeStep[0]->tm.getBounds()); ospray::tachyon::Camera *camera = timeStep[0]->tm.getCamera(); if (camera) { window.viewPort.from = camera->center; window.viewPort.at = camera->center+camera->viewDir; window.viewPort.up = camera->upDir; window.computeFrame(); } ospray::glut3D::runGLUT(); } } } int main(int ac, const char **av) { ospInit(&ac,av); ospray::glut3D::initGLUT(&ac,av); ospray::tachyon::ospTACHMain(ac,av); } <|endoftext|>
<commit_before>#include "ComboBox.h" #define _CRT_SECURE_NO_WARNINGS int coloredLine; int backgroundLine; DWORD regularAttr; ComboBox::ComboBox(int x, int y, char* options[], int size) { handle = GetStdHandle(STD_OUTPUT_HANDLE); //defualt text width width = 15; coloredLine = -1; backgroundLine = -1; //set in the request position c = { (short)x, (short)y }; //cursor size CONSOLE_CURSOR_INFO cci = { 100, FALSE }; SetConsoleCursorInfo(handle, &cci); //dynamic allocations choosen = (char*)calloc(width, sizeof(char)); listSize = size; list = (char**)calloc(size, sizeof(char*)); int i; for (i = 0; i < size; i++) { list[i] = (char*)calloc(width, sizeof(char)); strcpy_s(list[i], width, options[i]); } //init parameters isOpen = false; init(); } ComboBox::~ComboBox() { //free allocation free(choosen); int i; for (i = 0; i < listSize; i++) { free(list[i]); } } void ComboBox::init() { int i, j; boolean endFlag; //initialize the top box SetConsoleCursorPosition(handle, c); CONSOLE_SCREEN_BUFFER_INFO cbi; GetConsoleScreenBufferInfo(handle, &cbi); regularAttr = cbi.wAttributes; DWORD wAttr2 = cbi.wAttributes | BACKGROUND_BLUE; SetConsoleTextAttribute(handle, wAttr2); for (i = 0; i < width - 1; i++) { choosen[i] = ' '; printf("%c", choosen[i]); } wAttr2 = cbi.wAttributes | BACKGROUND_RED; SetConsoleTextAttribute(handle, wAttr2); choosen[width] = '>'; printf("%c", choosen[width]); //set char ' ' for the printing(on the rest of the options) for (i = 0; i < listSize; i++) { endFlag = false; for (j = 0; j < width; j++) { if (list[i][j] == '\0' || endFlag == true) { list[i][j] = ' '; endFlag = true; } } endFlag = false; } } //show the options - printing them in the correct position void ComboBox::showOptions() { int i; for (i = 0; i < listSize; i++) { printDelimiter(i * 2 + 1); printOption(i * 2 + 2, i); } printDelimiter(i * 2 + 1); } //hide the options - printing ' ' in the correct position void ComboBox::hideOptions() { int i; for (i = 1; i <= 2 * listSize + 1; i++) { printSpace(i); } } //printing the requested option to the top box void ComboBox::chooseOption(int position, int lastColoredLine) { int listNum = position / 2 - 1 , i; SetConsoleCursorPosition(handle, c); CONSOLE_SCREEN_BUFFER_INFO cbi; GetConsoleScreenBufferInfo(handle, &cbi); DWORD wAttr2 = cbi.wAttributes | BACKGROUND_BLUE; SetConsoleTextAttribute(handle, wAttr2); for (i = 0; i < width - 1; i++) { choosen[i] = list[listNum][i]; printf("%c", choosen[i]); } setSelected(lastColoredLine); } void ComboBox::setSelected(int lastColoredLine) { printOption(lastColoredLine * 2 + 2, lastColoredLine); printOption(coloredLine * 2 + 2, coloredLine); } //print delimiter '-' all over the requested line (separate each option) void ComboBox::printDelimiter(int position) { COORD newCoord = { c.X, c.Y + (short)position }; CONSOLE_SCREEN_BUFFER_INFO cbi; int i; SetConsoleCursorPosition(handle, newCoord); GetConsoleScreenBufferInfo(handle, &cbi); SetConsoleTextAttribute(handle, regularAttr); for (i = 0; i < width; i++) { printf("-"); } } //print the option void ComboBox::printOption(int position, int itemNum) { COORD newCoord = { c.X, c.Y + (short)position }; CONSOLE_SCREEN_BUFFER_INFO cbi; int i; SetConsoleCursorPosition(handle, newCoord); GetConsoleScreenBufferInfo(handle, &cbi); SetConsoleTextAttribute(handle, regularAttr); for (i = 0; i < width; i++) { printf("%c", list[itemNum][i]); } } void ComboBox::printOptionHoverd(int position, int lastBackgroundLine) { int lastPos = lastBackgroundLine * 2 + 2, i; COORD newCoord = { c.X, c.Y + (short)position }; COORD lastCoord = { c.X, c.Y + (short)lastPos }; CONSOLE_SCREEN_BUFFER_INFO cbi; DWORD wAttr = BACKGROUND_INTENSITY; SetConsoleCursorPosition(handle, newCoord); GetConsoleScreenBufferInfo(handle, &cbi); if (backgroundLine == lastBackgroundLine) { return; } else { SetConsoleTextAttribute(handle, wAttr); //set hover on the new position for (i = 0; i < width; i++) { printf("%c", list[backgroundLine][i]); } //if (lastPos == 0) return; SetConsoleCursorPosition(handle, lastCoord); SetConsoleTextAttribute(handle, regularAttr); //set non hover on the last position for (i = 0; i < width; i++) { printf("%c", list[lastBackgroundLine][i]); } } } //print ' ' (space) for the hiding functioallity void ComboBox::printSpace(int position) { COORD newCoord = { c.X, c.Y + (short)position }; CONSOLE_SCREEN_BUFFER_INFO cbi; int i; SetConsoleCursorPosition(handle, newCoord); GetConsoleScreenBufferInfo(handle, &cbi); SetConsoleTextAttribute(handle, regularAttr); for (i = 0; i < width; i++) { printf(" "); } } //listening for any mouse click and handle if relevnt void ComboBox::handleInput(INPUT_RECORD iRecord) { handle = GetStdHandle(STD_OUTPUT_HANDLE); switch (iRecord.EventType) { case MOUSE_EVENT: // mouse input MouseEventProc(iRecord.Event.MouseEvent); break; default: break; } } void ComboBox::MouseEventProc(MOUSE_EVENT_RECORD mer) { #ifndef MOUSE_HWHEELED #define MOUSE_HWHEELED 0x0008 #endif switch (mer.dwEventFlags) { case 0: //Right button press if (mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { checkClickedPosition(mer.dwMousePosition); } break; case MOUSE_MOVED: //Right button press setHover(mer.dwMousePosition); break; } } void ComboBox::setHover(COORD dwMousePosition) { int x = dwMousePosition.X, y = dwMousePosition.Y, i, lastBackgroundLine; if (x >= c.X + 2 && x <= c.X + 15 && y >= c.Y && y <= c.Y + listSize * 2) { for (i = 2; i <= 2 * listSize; i += 2) { if (dwMousePosition.Y == c.Y + i) { lastBackgroundLine = backgroundLine; backgroundLine = i / 2 - 1; if (lastBackgroundLine == -1) lastBackgroundLine = 0; printOptionHoverd(i, lastBackgroundLine); } } } } //check if the clicked is relevant for this combo box. //if yes - check the click position and choose the right operation void ComboBox::checkClickedPosition(COORD dwMousePosition) { int lastColoredLine; if (dwMousePosition.X == c.X + width - 1 && dwMousePosition.Y == c.Y) { if (isOpen == true) { isOpen = false; hideOptions(); } else { isOpen = true; showOptions(); } } else if (dwMousePosition.X >= c.X && dwMousePosition.X < c.X + width) { for (int i = 2; i <= 2 * listSize; i += 2) { if (dwMousePosition.Y == c.Y + i) { lastColoredLine = coloredLine; coloredLine = i / 2 - 1; if (lastColoredLine == -1) lastColoredLine = 0; chooseOption(i, lastColoredLine); } } } }<commit_msg>Combobox - comments<commit_after>#include "ComboBox.h" #define _CRT_SECURE_NO_WARNINGS int coloredLine; int backgroundLine; DWORD regularAttr; ComboBox::ComboBox(int x, int y, char* options[], int size) { handle = GetStdHandle(STD_OUTPUT_HANDLE); //defualt text width width = 15; coloredLine = -1; backgroundLine = -1; //set in the request position c = { (short)x, (short)y }; //cursor size CONSOLE_CURSOR_INFO cci = { 100, FALSE }; SetConsoleCursorInfo(handle, &cci); //dynamic allocations choosen = (char*)calloc(width, sizeof(char)); listSize = size; list = (char**)calloc(size, sizeof(char*)); int i; for (i = 0; i < size; i++) { list[i] = (char*)calloc(width, sizeof(char)); strcpy_s(list[i], width, options[i]); } //init parameters isOpen = false; init(); } ComboBox::~ComboBox() { //free allocation free(choosen); int i; for (i = 0; i < listSize; i++) { free(list[i]); } } void ComboBox::init() { int i, j; boolean endFlag; //initialize the top box SetConsoleCursorPosition(handle, c); CONSOLE_SCREEN_BUFFER_INFO cbi; GetConsoleScreenBufferInfo(handle, &cbi); regularAttr = cbi.wAttributes; DWORD wAttr2 = cbi.wAttributes | BACKGROUND_BLUE; SetConsoleTextAttribute(handle, wAttr2); for (i = 0; i < width - 1; i++) { choosen[i] = ' '; printf("%c", choosen[i]); } wAttr2 = cbi.wAttributes | BACKGROUND_RED; SetConsoleTextAttribute(handle, wAttr2); choosen[width] = '>'; printf("%c", choosen[width]); //set char ' ' for the printing(on the rest of the options) for (i = 0; i < listSize; i++) { endFlag = false; for (j = 0; j < width; j++) { if (list[i][j] == '\0' || endFlag == true) { list[i][j] = ' '; endFlag = true; } } endFlag = false; } } //show the options - printing them in the correct position void ComboBox::showOptions() { int i; for (i = 0; i < listSize; i++) { printDelimiter(i * 2 + 1); printOption(i * 2 + 2, i); } printDelimiter(i * 2 + 1); } //hide the options - printing ' ' in the correct position void ComboBox::hideOptions() { int i; for (i = 1; i <= 2 * listSize + 1; i++) { printSpace(i); } } //printing the requested option to the top box void ComboBox::chooseOption(int position, int lastColoredLine) { int listNum = position / 2 - 1 , i; SetConsoleCursorPosition(handle, c); CONSOLE_SCREEN_BUFFER_INFO cbi; GetConsoleScreenBufferInfo(handle, &cbi); DWORD wAttr2 = cbi.wAttributes | BACKGROUND_BLUE; SetConsoleTextAttribute(handle, wAttr2); for (i = 0; i < width - 1; i++) { choosen[i] = list[listNum][i]; printf("%c", choosen[i]); } setSelected(lastColoredLine); } void ComboBox::setSelected(int lastColoredLine) { printOption(lastColoredLine * 2 + 2, lastColoredLine); printOption(coloredLine * 2 + 2, coloredLine); } //print delimiter '-' all over the requested line (separate each option) void ComboBox::printDelimiter(int position) { COORD newCoord = { c.X, c.Y + (short)position }; CONSOLE_SCREEN_BUFFER_INFO cbi; int i; SetConsoleCursorPosition(handle, newCoord); GetConsoleScreenBufferInfo(handle, &cbi); SetConsoleTextAttribute(handle, regularAttr); for (i = 0; i < width; i++) { printf("-"); } } //print the option void ComboBox::printOption(int position, int itemNum) { COORD newCoord = { c.X, c.Y + (short)position }; CONSOLE_SCREEN_BUFFER_INFO cbi; int i; SetConsoleCursorPosition(handle, newCoord); GetConsoleScreenBufferInfo(handle, &cbi); SetConsoleTextAttribute(handle, regularAttr); for (i = 0; i < width; i++) { printf("%c", list[itemNum][i]); } } void ComboBox::printOptionHoverd(int position, int lastBackgroundLine) { int lastPos = lastBackgroundLine * 2 + 2, i; COORD newCoord = { c.X, c.Y + (short)position }; COORD lastCoord = { c.X, c.Y + (short)lastPos }; CONSOLE_SCREEN_BUFFER_INFO cbi; DWORD wAttr = BACKGROUND_INTENSITY; SetConsoleCursorPosition(handle, newCoord); GetConsoleScreenBufferInfo(handle, &cbi); if (backgroundLine == lastBackgroundLine) { return; } else { SetConsoleTextAttribute(handle, wAttr); //set hover on the new position for (i = 0; i < width; i++) { printf("%c", list[backgroundLine][i]); } //if (lastPos == 0) return; SetConsoleCursorPosition(handle, lastCoord); SetConsoleTextAttribute(handle, regularAttr); //set non hover on the last position for (i = 0; i < width; i++) { printf("%c", list[lastBackgroundLine][i]); } } } //print ' ' (space) for the hiding functioallity void ComboBox::printSpace(int position) { COORD newCoord = { c.X, c.Y + (short)position }; CONSOLE_SCREEN_BUFFER_INFO cbi; int i; SetConsoleCursorPosition(handle, newCoord); GetConsoleScreenBufferInfo(handle, &cbi); SetConsoleTextAttribute(handle, regularAttr); for (i = 0; i < width; i++) { printf(" "); } } //listening for any mouse click and handle if relevnt void ComboBox::handleInput(INPUT_RECORD iRecord) { handle = GetStdHandle(STD_OUTPUT_HANDLE); switch (iRecord.EventType) { case MOUSE_EVENT: // mouse input MouseEventProc(iRecord.Event.MouseEvent); break; default: break; } } void ComboBox::MouseEventProc(MOUSE_EVENT_RECORD mer) { #ifndef MOUSE_HWHEELED #define MOUSE_HWHEELED 0x0008 #endif switch (mer.dwEventFlags) { case 0: //Left button press if (mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { checkClickedPosition(mer.dwMousePosition); } break; case MOUSE_MOVED: //Mouse moved setHover(mer.dwMousePosition); break; } } void ComboBox::setHover(COORD dwMousePosition) { int x = dwMousePosition.X, y = dwMousePosition.Y, i, lastBackgroundLine; if (x >= c.X + 2 && x <= c.X + 15 && y >= c.Y && y <= c.Y + listSize * 2) { for (i = 2; i <= 2 * listSize; i += 2) { if (dwMousePosition.Y == c.Y + i) { lastBackgroundLine = backgroundLine; backgroundLine = i / 2 - 1; if (lastBackgroundLine == -1) lastBackgroundLine = 0; printOptionHoverd(i, lastBackgroundLine); } } } } //check if the clicked is relevant for this combo box. //if yes - check the click position and choose the right operation void ComboBox::checkClickedPosition(COORD dwMousePosition) { int lastColoredLine; if (dwMousePosition.X == c.X + width - 1 && dwMousePosition.Y == c.Y) { if (isOpen == true) { isOpen = false; hideOptions(); } else { isOpen = true; showOptions(); } } else if (dwMousePosition.X >= c.X && dwMousePosition.X < c.X + width) { for (int i = 2; i <= 2 * listSize; i += 2) { if (dwMousePosition.Y == c.Y + i) { lastColoredLine = coloredLine; coloredLine = i / 2 - 1; if (lastColoredLine == -1) lastColoredLine = 0; chooseOption(i, lastColoredLine); } } } }<|endoftext|>
<commit_before>/* Binderoo Copyright (c) 2016, Remedy Entertainment All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder (Remedy Entertainment) 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 REMEDY ENTERTAINMENT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------------- #include "binderoo/defs.h" #include "binderoo/hash.h" #include "binderoo/host.h" #include "binderoo/imports.h" #include "binderoo/exports.h" #include "paramhandler.h" #include <cstdio> #include <cstdlib> #include <cstring> //---------------------------------------------------------------------------- static void* BIND_C_CALL test_unaligned_malloc( size_t objSize ) { return malloc( objSize ); } //---------------------------------------------------------------------------- static void BIND_C_CALL test_unaligned_free( void* pObj ) { free( pObj ); } //---------------------------------------------------------------------------- static void* BIND_C_CALL test_malloc( size_t objSize, size_t alignment ) { return _aligned_malloc( objSize, alignment ); } //---------------------------------------------------------------------------- static void BIND_C_CALL test_free( void* pObj ) { _aligned_free( pObj ); } //---------------------------------------------------------------------------- static void* BIND_C_CALL test_calloc( size_t objCount, size_t objSize, size_t alignment ) { return _aligned_malloc( objCount * objSize, alignment ); } //---------------------------------------------------------------------------- static void* BIND_C_CALL test_realloc( void* pObj, size_t newObjSize, size_t alignment ) { return _aligned_realloc( pObj, newObjSize, alignment ); } //---------------------------------------------------------------------------- enum Options : int { None, SearchFolder = 0x01, ListCStyleBindingsForAll = 0x02, ListCStyleBindingsForSpecific = 0x04, FunctionCall = 0x08, FunctionCallParameter = 0x10, }; //---------------------------------------------------------------------------- void printUsageScreen() { printf( "Binderoo Util (C) 2016 Remedy Entertainment Ltd.\n" ); printf( "\n" ); printf( "Usage: binderoo_util [-g class] [-gA] [-f folder]\n" ); printf( "\n" ); printf( " -f folder Add folders to search for DLL (use multiple -f definitions)\n" ); printf( " -g class Generate C++ style bindings for provided class\n" ); printf( " -gA Generate C++ style bindings for all classes in all DLLs\n" ); printf( " -gAV versions As -gA, except with specified versions\n" ); printf( " -c Call a function\n" ); printf( " -p Parameter for function call (use multiple -p definitions)\n" ); printf( "\n" ); } //---------------------------------------------------------------------------- int main( int argc, char** argv ) { if( argc < 2 ) { printUsageScreen(); } else { const int MaxArgCount = 256; binderoo::DString searchFolders[ MaxArgCount ]; binderoo::DString listClasses[ MaxArgCount ]; binderoo::DString functionCall; binderoo::DString functionCallParameters[ MaxArgCount ]; int iErrorParameters[ MaxArgCount ]; int iErrorCount = 0; int iSearchFolderCount = 0; int iListClassCount = 0; int iFunctionCallParameterCount = 0; int eCurrParamMode = Options::None; int eFoundParams = Options::None; const char* pCBindingsForAllVersions = nullptr; for( int iCurrArg = 1; iCurrArg < argc && iSearchFolderCount < MaxArgCount; ++iCurrArg ) { switch( eCurrParamMode ) { case Options::None: { // TODO: Make this less rubbish and less prone to error if( argv[ iCurrArg ][ 0 ] == '-' ) { switch( argv[ iCurrArg ][ 1 ] ) { case 'g': { if( argv[ iCurrArg ][ 2 ] == 'A' ) { eFoundParams |= Options::ListCStyleBindingsForAll; if( argv[ iCurrArg ][ 3 ] == 'V' ) { eCurrParamMode = Options::ListCStyleBindingsForAll; } } else { eFoundParams |= Options::ListCStyleBindingsForSpecific; eCurrParamMode = Options::ListCStyleBindingsForSpecific; } } break; case 'f': eFoundParams |= Options::SearchFolder; eCurrParamMode = Options::SearchFolder; break; case 'c': eFoundParams |= Options::FunctionCall; eCurrParamMode = Options::FunctionCall; break; case 'p': eFoundParams |= Options::FunctionCallParameter; eCurrParamMode = Options::FunctionCallParameter; break; default: iErrorParameters[ iErrorCount++ ] = iCurrArg; break; } } else { iErrorParameters[ iErrorCount++ ] = iCurrArg; } } break; case Options::SearchFolder: searchFolders[ iSearchFolderCount++ ] = binderoo::DString( argv[ iCurrArg ], strlen( argv[ iCurrArg ] ) ); eCurrParamMode = Options::None; break; case Options::ListCStyleBindingsForAll: pCBindingsForAllVersions = argv[ iCurrArg ]; eCurrParamMode = Options::None; break; case Options::ListCStyleBindingsForSpecific: listClasses[ iListClassCount++ ] = binderoo::DString( argv[ iCurrArg ], strlen( argv[ iCurrArg ] ) ); eCurrParamMode = Options::None; break; case Options::FunctionCall: functionCall = binderoo::DString( argv[ iCurrArg ], strlen( argv[ iCurrArg ] ) ); eCurrParamMode = Options::None; break; case Options::FunctionCallParameter: functionCallParameters[ iFunctionCallParameterCount++ ] = binderoo::DString( argv[ iCurrArg ], strlen( argv[ iCurrArg ] ) ); eCurrParamMode = Options::None; break; default: iErrorParameters[ iErrorCount++ ] = iCurrArg; break; } } if( iErrorCount ) { printf( "The following bad parameters found:\n" ); for( int iError = 0; iError < iErrorCount; ++iError ) { printf( " %s\n", argv[ iErrorParameters[ iError ] ] ); } printf( "\n" ); printUsageScreen(); } else if( eFoundParams == Options::None ) { printf( "No commands found!\n\n" ); printUsageScreen(); } else if( iSearchFolderCount == 0 ) { printf( "No search folders provided!\n\n" ); printUsageScreen(); } else { binderoo::HostConfiguration configuration; configuration.strDynamicLibSearchFolders = binderoo::Slice< binderoo::DString >( &searchFolders[ 0 ], (size_t)iSearchFolderCount ); configuration.alloc = &test_malloc; configuration.free = &test_free; configuration.calloc = &test_calloc; configuration.realloc = &test_realloc; configuration.unaligned_alloc = &test_unaligned_malloc; configuration.unaligned_free = &test_unaligned_free; configuration.log_info = nullptr; configuration.log_warning = nullptr; configuration.log_error = nullptr; configuration.bStartInRapidIterationMode = false; binderoo::Host host( configuration ); if( eFoundParams & Options::ListCStyleBindingsForAll ) { const char* pDeclarations = host.generateCPPStyleBindingDeclarationsForAllObjects( pCBindingsForAllVersions ); test_unaligned_free( (void*)pDeclarations ); } if( eFoundParams & Options::FunctionCall ) { ParamHandler handler( binderoo::Slice< binderoo::DString >( &functionCallParameters[ 0 ], (size_t)iFunctionCallParameterCount ) ); handleFunction( functionCall.data(), handler ); } } } } //---------------------------------------------------------------------------- //============================================================================ <commit_msg>Updated copyright notice to cover 2017<commit_after>/* Binderoo Copyright (c) 2016, Remedy Entertainment All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder (Remedy Entertainment) 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 REMEDY ENTERTAINMENT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------------- #include "binderoo/defs.h" #include "binderoo/hash.h" #include "binderoo/host.h" #include "binderoo/imports.h" #include "binderoo/exports.h" #include "paramhandler.h" #include <cstdio> #include <cstdlib> #include <cstring> //---------------------------------------------------------------------------- static void* BIND_C_CALL test_unaligned_malloc( size_t objSize ) { return malloc( objSize ); } //---------------------------------------------------------------------------- static void BIND_C_CALL test_unaligned_free( void* pObj ) { free( pObj ); } //---------------------------------------------------------------------------- static void* BIND_C_CALL test_malloc( size_t objSize, size_t alignment ) { return _aligned_malloc( objSize, alignment ); } //---------------------------------------------------------------------------- static void BIND_C_CALL test_free( void* pObj ) { _aligned_free( pObj ); } //---------------------------------------------------------------------------- static void* BIND_C_CALL test_calloc( size_t objCount, size_t objSize, size_t alignment ) { return _aligned_malloc( objCount * objSize, alignment ); } //---------------------------------------------------------------------------- static void* BIND_C_CALL test_realloc( void* pObj, size_t newObjSize, size_t alignment ) { return _aligned_realloc( pObj, newObjSize, alignment ); } //---------------------------------------------------------------------------- enum Options : int { None, SearchFolder = 0x01, ListCStyleBindingsForAll = 0x02, ListCStyleBindingsForSpecific = 0x04, FunctionCall = 0x08, FunctionCallParameter = 0x10, }; //---------------------------------------------------------------------------- void printUsageScreen() { printf( "Binderoo Util (C) 2016-2017 Remedy Entertainment Ltd.\n" ); printf( "\n" ); printf( "Usage: binderoo_util [-g class] [-gA] [-f folder]\n" ); printf( "\n" ); printf( " -f folder Add folders to search for DLL (use multiple -f definitions)\n" ); printf( " -g class Generate C++ style bindings for provided class\n" ); printf( " -gA Generate C++ style bindings for all classes in all DLLs\n" ); printf( " -gAV versions As -gA, except with specified versions\n" ); printf( " -c Call a function\n" ); printf( " -p Parameter for function call (use multiple -p definitions)\n" ); printf( "\n" ); } //---------------------------------------------------------------------------- int main( int argc, char** argv ) { if( argc < 2 ) { printUsageScreen(); } else { const int MaxArgCount = 256; binderoo::DString searchFolders[ MaxArgCount ]; binderoo::DString listClasses[ MaxArgCount ]; binderoo::DString functionCall; binderoo::DString functionCallParameters[ MaxArgCount ]; int iErrorParameters[ MaxArgCount ]; int iErrorCount = 0; int iSearchFolderCount = 0; int iListClassCount = 0; int iFunctionCallParameterCount = 0; int eCurrParamMode = Options::None; int eFoundParams = Options::None; const char* pCBindingsForAllVersions = nullptr; for( int iCurrArg = 1; iCurrArg < argc && iSearchFolderCount < MaxArgCount; ++iCurrArg ) { switch( eCurrParamMode ) { case Options::None: { // TODO: Make this less rubbish and less prone to error if( argv[ iCurrArg ][ 0 ] == '-' ) { switch( argv[ iCurrArg ][ 1 ] ) { case 'g': { if( argv[ iCurrArg ][ 2 ] == 'A' ) { eFoundParams |= Options::ListCStyleBindingsForAll; if( argv[ iCurrArg ][ 3 ] == 'V' ) { eCurrParamMode = Options::ListCStyleBindingsForAll; } } else { eFoundParams |= Options::ListCStyleBindingsForSpecific; eCurrParamMode = Options::ListCStyleBindingsForSpecific; } } break; case 'f': eFoundParams |= Options::SearchFolder; eCurrParamMode = Options::SearchFolder; break; case 'c': eFoundParams |= Options::FunctionCall; eCurrParamMode = Options::FunctionCall; break; case 'p': eFoundParams |= Options::FunctionCallParameter; eCurrParamMode = Options::FunctionCallParameter; break; default: iErrorParameters[ iErrorCount++ ] = iCurrArg; break; } } else { iErrorParameters[ iErrorCount++ ] = iCurrArg; } } break; case Options::SearchFolder: searchFolders[ iSearchFolderCount++ ] = binderoo::DString( argv[ iCurrArg ], strlen( argv[ iCurrArg ] ) ); eCurrParamMode = Options::None; break; case Options::ListCStyleBindingsForAll: pCBindingsForAllVersions = argv[ iCurrArg ]; eCurrParamMode = Options::None; break; case Options::ListCStyleBindingsForSpecific: listClasses[ iListClassCount++ ] = binderoo::DString( argv[ iCurrArg ], strlen( argv[ iCurrArg ] ) ); eCurrParamMode = Options::None; break; case Options::FunctionCall: functionCall = binderoo::DString( argv[ iCurrArg ], strlen( argv[ iCurrArg ] ) ); eCurrParamMode = Options::None; break; case Options::FunctionCallParameter: functionCallParameters[ iFunctionCallParameterCount++ ] = binderoo::DString( argv[ iCurrArg ], strlen( argv[ iCurrArg ] ) ); eCurrParamMode = Options::None; break; default: iErrorParameters[ iErrorCount++ ] = iCurrArg; break; } } if( iErrorCount ) { printf( "The following bad parameters found:\n" ); for( int iError = 0; iError < iErrorCount; ++iError ) { printf( " %s\n", argv[ iErrorParameters[ iError ] ] ); } printf( "\n" ); printUsageScreen(); } else if( eFoundParams == Options::None ) { printf( "No commands found!\n\n" ); printUsageScreen(); } else if( iSearchFolderCount == 0 ) { printf( "No search folders provided!\n\n" ); printUsageScreen(); } else { binderoo::HostConfiguration configuration; configuration.strDynamicLibSearchFolders = binderoo::Slice< binderoo::DString >( &searchFolders[ 0 ], (size_t)iSearchFolderCount ); configuration.alloc = &test_malloc; configuration.free = &test_free; configuration.calloc = &test_calloc; configuration.realloc = &test_realloc; configuration.unaligned_alloc = &test_unaligned_malloc; configuration.unaligned_free = &test_unaligned_free; configuration.log_info = nullptr; configuration.log_warning = nullptr; configuration.log_error = nullptr; configuration.bStartInRapidIterationMode = false; binderoo::Host host( configuration ); if( eFoundParams & Options::ListCStyleBindingsForAll ) { const char* pDeclarations = host.generateCPPStyleBindingDeclarationsForAllObjects( pCBindingsForAllVersions ); test_unaligned_free( (void*)pDeclarations ); } if( eFoundParams & Options::FunctionCall ) { ParamHandler handler( binderoo::Slice< binderoo::DString >( &functionCallParameters[ 0 ], (size_t)iFunctionCallParameterCount ) ); handleFunction( functionCall.data(), handler ); } } } } //---------------------------------------------------------------------------- //============================================================================ <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include "zlib.h" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" using namespace libtorrent; namespace { enum { minimum_tracker_response_length = 3, http_buffer_size = 2048 }; enum { FTEXT = 0x01, FHCRC = 0x02, FEXTRA = 0x04, FNAME = 0x08, FCOMMENT = 0x10, FRESERVED = 0xe0, GZIP_MAGIC0 = 0x1f, GZIP_MAGIC1 = 0x8b }; } namespace libtorrent { // returns -1 if gzip header is invalid or the header size in bytes int gzip_header(const char* buf, int size) { assert(buf != 0); assert(size > 0); const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf); const int total_size = size; // The zip header cannot be shorter than 10 bytes if (size < 10) return -1; // check the magic header of gzip if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1; int method = buffer[2]; int flags = buffer[3]; // check for reserved flag and make sure it's compressed with the correct metod if (method != Z_DEFLATED || (flags & FRESERVED) != 0) return -1; // skip time, xflags, OS code size -= 10; buffer += 10; if (flags & FEXTRA) { int extra_len; if (size < 2) return -1; extra_len = (buffer[1] << 8) | buffer[0]; if (size < (extra_len+2)) return -1; size -= (extra_len + 2); buffer += (extra_len + 2); } if (flags & FNAME) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FCOMMENT) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FHCRC) { if (size < 2) return -1; size -= 2; buffer += 2; } return total_size - size; } bool inflate_gzip( std::vector<char>& buffer , request_callback* requester , int maximum_tracker_response_length) { assert(maximum_tracker_response_length > 0); int header_len = gzip_header(&buffer[0], (int)buffer.size()); if (header_len < 0) { requester->tracker_request_error(200, "invalid gzip header in tracker response"); return true; } // start off wth one kilobyte and grow // if needed std::vector<char> inflate_buffer(1024); // initialize the zlib-stream z_stream str; // subtract 8 from the end of the buffer since that's CRC32 and input size // and those belong to the gzip file str.avail_in = (int)buffer.size() - header_len - 8; str.next_in = reinterpret_cast<Bytef*>(&buffer[header_len]); str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[0]); str.avail_out = (int)inflate_buffer.size(); str.zalloc = Z_NULL; str.zfree = Z_NULL; str.opaque = 0; // -15 is really important. It will make inflate() not look for a zlib header // and just deflate the buffer if (inflateInit2(&str, -15) != Z_OK) { requester->tracker_request_error(200, "gzip out of memory"); return true; } // inflate and grow inflate_buffer as needed int ret = inflate(&str, Z_SYNC_FLUSH); while (ret == Z_OK) { if (str.avail_out == 0) { if (inflate_buffer.size() >= (unsigned)maximum_tracker_response_length) { inflateEnd(&str); requester->tracker_request_error(200, "tracker response too large"); return true; } int new_size = (int)inflate_buffer.size() * 2; if (new_size > maximum_tracker_response_length) new_size = maximum_tracker_response_length; int old_size = (int)inflate_buffer.size(); inflate_buffer.resize(new_size); str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[old_size]); str.avail_out = new_size - old_size; } ret = inflate(&str, Z_SYNC_FLUSH); } inflate_buffer.resize(inflate_buffer.size() - str.avail_out); inflateEnd(&str); if (ret != Z_STREAM_END) { requester->tracker_request_error(200, "gzip error"); return true; } // commit the resulting buffer std::swap(buffer, inflate_buffer); return false; } std::string base64encode(const std::string& s) { static const char base64_table[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; unsigned char inbuf[3]; unsigned char outbuf[4]; std::string ret; for (std::string::const_iterator i = s.begin(); i != s.end();) { // available input is 1,2 or 3 bytes // since we read 3 bytes at a time at most int available_input = std::min(3, (int)std::distance(i, s.end())); // clear input buffer std::fill(inbuf, inbuf+3, 0); // read a chunk of input into inbuf for (int j = 0; j < available_input; ++j) { inbuf[j] = *i; ++i; } // encode inbuf to outbuf outbuf[0] = (inbuf[0] & 0xfc) >> 2; outbuf[1] = ((inbuf[0] & 0x03) << 4) | ((inbuf [1] & 0xf0) >> 4); outbuf[2] = ((inbuf[1] & 0x0f) << 2) | ((inbuf [2] & 0xc0) >> 6); outbuf[3] = inbuf[2] & 0x3f; // write output for (int j = 0; j < available_input+1; ++j) { ret += base64_table[outbuf[j]]; } // write pad for (int j = 0; j < 3 - available_input; ++j) { ret += '='; } } return ret; } void tracker_manager::tick() { std::vector<boost::shared_ptr<tracker_connection> >::iterator i; for (i = m_connections.begin(); i != m_connections.end(); ++i) { boost::shared_ptr<tracker_connection>& c = *i; try { if (!c->tick()) continue; } catch (const std::exception& e) { if (c->requester()) c->requester()->tracker_request_error(-1, e.what()); } if (c->requester()) c->requester()->m_manager = 0; m_connections.erase(i); --i; // compensate for the remove } } void tracker_manager::queue_request( tracker_request req , request_callback* c , std::string const& password) { assert(req.num_want >= 0); if (req.event == tracker_request::stopped) req.num_want = 0; try { std::string hostname; // hostname only std::string protocol; // should be http int port = 80; // PARSE URL std::string::iterator start = req.url.begin(); std::string::iterator end = std::find(req.url.begin(), req.url.end(), ':'); protocol = std::string(start, end); if (end == req.url.end()) throw std::runtime_error("invalid url"); ++end; if (end == req.url.end()) throw std::runtime_error("invalid url"); if (*end != '/') throw std::runtime_error("invalid url"); ++end; if (end == req.url.end()) throw std::runtime_error("invalid url"); if (*end != '/') throw std::runtime_error("invalid url"); ++end; start = end; end = std::find(start, req.url.end(), '/'); std::string::const_iterator port_pos = std::find(start, req.url.end(), ':'); if (port_pos < end) { hostname.assign(start, port_pos); ++port_pos; try { port = boost::lexical_cast<int>(std::string(port_pos, end)); } catch(boost::bad_lexical_cast&) { throw std::runtime_error("invalid url"); } } else { hostname.assign(start, end); } start = end; std::string request_string = std::string(start, req.url.end()); boost::shared_ptr<tracker_connection> con; if (protocol == "http") { con.reset(new http_tracker_connection( req , hostname , port , request_string , c , m_settings , password)); } else if (protocol == "udp") { con.reset(new udp_tracker_connection( req , hostname , port , c , m_settings)); } else { throw std::runtime_error("unkown protocol in tracker url"); } m_connections.push_back(con); if (con->requester()) con->requester()->m_manager = this; } catch (std::exception& e) { if (c) c->tracker_request_error(-1, e.what()); } } void tracker_manager::abort_request(request_callback* c) { assert(c != 0); std::vector<boost::shared_ptr<tracker_connection> >::iterator i; for (i = m_connections.begin(); i != m_connections.end(); ++i) { if ((*i)->requester() == c) { m_connections.erase(i); break; } } } void tracker_manager::abort_all_requests() { // removes all connections from m_connections // except those with a requester == 0 (since those are // 'event=stopped'-requests) std::vector<boost::shared_ptr<tracker_connection> > keep_connections; for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i = m_connections.begin(); i != m_connections.end(); ++i) { if ((*i)->requester() == 0) keep_connections.push_back(*i); } std::swap(m_connections, keep_connections); } bool tracker_manager::send_finished() const { for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i = m_connections.begin(); i != m_connections.end(); ++i) { if (!(*i)->send_finished()) return false; } return true; } } <commit_msg>*** empty log message ***<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include "zlib.h" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" using namespace libtorrent; namespace { enum { minimum_tracker_response_length = 3, http_buffer_size = 2048 }; enum { FTEXT = 0x01, FHCRC = 0x02, FEXTRA = 0x04, FNAME = 0x08, FCOMMENT = 0x10, FRESERVED = 0xe0, GZIP_MAGIC0 = 0x1f, GZIP_MAGIC1 = 0x8b }; } namespace libtorrent { // returns -1 if gzip header is invalid or the header size in bytes int gzip_header(const char* buf, int size) { assert(buf != 0); assert(size > 0); const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf); const int total_size = size; // The zip header cannot be shorter than 10 bytes if (size < 10) return -1; // check the magic header of gzip if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1; int method = buffer[2]; int flags = buffer[3]; // check for reserved flag and make sure it's compressed with the correct metod if (method != Z_DEFLATED || (flags & FRESERVED) != 0) return -1; // skip time, xflags, OS code size -= 10; buffer += 10; if (flags & FEXTRA) { int extra_len; if (size < 2) return -1; extra_len = (buffer[1] << 8) | buffer[0]; if (size < (extra_len+2)) return -1; size -= (extra_len + 2); buffer += (extra_len + 2); } if (flags & FNAME) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FCOMMENT) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FHCRC) { if (size < 2) return -1; size -= 2; buffer += 2; } return total_size - size; } bool inflate_gzip( std::vector<char>& buffer , request_callback* requester , int maximum_tracker_response_length) { assert(maximum_tracker_response_length > 0); int header_len = gzip_header(&buffer[0], (int)buffer.size()); if (header_len < 0) { requester->tracker_request_error(200, "invalid gzip header in tracker response"); return true; } // start off wth one kilobyte and grow // if needed std::vector<char> inflate_buffer(1024); // initialize the zlib-stream z_stream str; // subtract 8 from the end of the buffer since that's CRC32 and input size // and those belong to the gzip file str.avail_in = (int)buffer.size() - header_len - 8; str.next_in = reinterpret_cast<Bytef*>(&buffer[header_len]); str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[0]); str.avail_out = (int)inflate_buffer.size(); str.zalloc = Z_NULL; str.zfree = Z_NULL; str.opaque = 0; // -15 is really important. It will make inflate() not look for a zlib header // and just deflate the buffer if (inflateInit2(&str, -15) != Z_OK) { requester->tracker_request_error(200, "gzip out of memory"); return true; } // inflate and grow inflate_buffer as needed int ret = inflate(&str, Z_SYNC_FLUSH); while (ret == Z_OK) { if (str.avail_out == 0) { if (inflate_buffer.size() >= (unsigned)maximum_tracker_response_length) { inflateEnd(&str); requester->tracker_request_error(200, "tracker response too large"); return true; } int new_size = (int)inflate_buffer.size() * 2; if (new_size > maximum_tracker_response_length) new_size = maximum_tracker_response_length; int old_size = (int)inflate_buffer.size(); inflate_buffer.resize(new_size); str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[old_size]); str.avail_out = new_size - old_size; } ret = inflate(&str, Z_SYNC_FLUSH); } inflate_buffer.resize(inflate_buffer.size() - str.avail_out); inflateEnd(&str); if (ret != Z_STREAM_END) { requester->tracker_request_error(200, "gzip error"); return true; } // commit the resulting buffer std::swap(buffer, inflate_buffer); return false; } std::string base64encode(const std::string& s) { static const char base64_table[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; unsigned char inbuf[3]; unsigned char outbuf[4]; std::string ret; for (std::string::const_iterator i = s.begin(); i != s.end();) { // available input is 1,2 or 3 bytes // since we read 3 bytes at a time at most int available_input = std::min(3, (int)std::distance(i, s.end())); // clear input buffer std::fill(inbuf, inbuf+3, 0); // read a chunk of input into inbuf for (int j = 0; j < available_input; ++j) { inbuf[j] = *i; ++i; } // encode inbuf to outbuf outbuf[0] = (inbuf[0] & 0xfc) >> 2; outbuf[1] = ((inbuf[0] & 0x03) << 4) | ((inbuf [1] & 0xf0) >> 4); outbuf[2] = ((inbuf[1] & 0x0f) << 2) | ((inbuf [2] & 0xc0) >> 6); outbuf[3] = inbuf[2] & 0x3f; // write output for (int j = 0; j < available_input+1; ++j) { ret += base64_table[outbuf[j]]; } // write pad for (int j = 0; j < 3 - available_input; ++j) { ret += '='; } } return ret; } void tracker_manager::tick() { std::vector<boost::shared_ptr<tracker_connection> >::iterator i; for (i = m_connections.begin(); i != m_connections.end(); ++i) { boost::shared_ptr<tracker_connection>& c = *i; try { if (!c->tick()) continue; } catch (const std::exception& e) { if (c->requester()) c->requester()->tracker_request_error(-1, e.what()); } if (c->requester()) c->requester()->m_manager = 0; m_connections.erase(i); --i; // compensate for the remove } } void tracker_manager::queue_request( tracker_request req , request_callback* c , std::string const& password) { assert(req.num_want >= 0); if (req.event == tracker_request::stopped) req.num_want = 0; try { std::string hostname; // hostname only std::string protocol; // should be http int port = 80; // PARSE URL std::string::iterator start = req.url.begin(); std::string::iterator end = std::find(req.url.begin(), req.url.end(), ':'); protocol = std::string(start, end); if (end == req.url.end()) throw std::runtime_error("invalid url"); ++end; if (end == req.url.end()) throw std::runtime_error("invalid url"); if (*end != '/') throw std::runtime_error("invalid url"); ++end; if (end == req.url.end()) throw std::runtime_error("invalid url"); if (*end != '/') throw std::runtime_error("invalid url"); ++end; start = end; end = std::find(start, req.url.end(), '/'); std::string::iterator port_pos = std::find(start, req.url.end(), ':'); if (port_pos < end) { hostname.assign(start, port_pos); ++port_pos; try { port = boost::lexical_cast<int>(std::string(port_pos, end)); } catch(boost::bad_lexical_cast&) { throw std::runtime_error("invalid url"); } } else { hostname.assign(start, end); } start = end; std::string request_string = std::string(start, req.url.end()); boost::shared_ptr<tracker_connection> con; if (protocol == "http") { con.reset(new http_tracker_connection( req , hostname , port , request_string , c , m_settings , password)); } else if (protocol == "udp") { con.reset(new udp_tracker_connection( req , hostname , port , c , m_settings)); } else { throw std::runtime_error("unkown protocol in tracker url"); } m_connections.push_back(con); if (con->requester()) con->requester()->m_manager = this; } catch (std::exception& e) { if (c) c->tracker_request_error(-1, e.what()); } } void tracker_manager::abort_request(request_callback* c) { assert(c != 0); std::vector<boost::shared_ptr<tracker_connection> >::iterator i; for (i = m_connections.begin(); i != m_connections.end(); ++i) { if ((*i)->requester() == c) { m_connections.erase(i); break; } } } void tracker_manager::abort_all_requests() { // removes all connections from m_connections // except those with a requester == 0 (since those are // 'event=stopped'-requests) std::vector<boost::shared_ptr<tracker_connection> > keep_connections; for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i = m_connections.begin(); i != m_connections.end(); ++i) { if ((*i)->requester() == 0) keep_connections.push_back(*i); } std::swap(m_connections, keep_connections); } bool tracker_manager::send_finished() const { for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i = m_connections.begin(); i != m_connections.end(); ++i) { if (!(*i)->send_finished()) return false; } return true; } } <|endoftext|>
<commit_before>#include "RuleScope.h" #include "moses/StaticData.h" #include "moses/Word.h" namespace Moses { RuleAmbiguity::RuleAmbiguity(const std::string &line) :StatelessFeatureFunction(1, line) ,m_sourceSyntax(true) { } bool IsAmbiguous(const Word &word, bool sourceSyntax) { const Word &inputDefaultNonTerminal = StaticData::Instance().GetInputDefaultNonTerminal(); return word.IsNonTerminal() && (!sourceSyntax || word == inputDefaultNonTerminal); } void RuleAmbiguity::Evaluate(const Phrase &source , const TargetPhrase &targetPhrase , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection &estimatedFutureScore) const { // source can't be empty, right? float score = 0; int count = 0; for (size_t i = 0; i < source.GetSize() - 0; ++i) { const Word &word = source.GetWord(i); bool ambiguous = IsAmbiguous(word, m_sourceSyntax); if (ambiguous) { ++count; } else { if (count > 0) { score += count; } count = -1; } } // 1st & last always adjacent to ambiguity ++count; if (count > 0) { score += count; } scoreBreakdown.PlusEquals(this, score); } void RuleAmbiguity::SetParameter(const std::string& key, const std::string& value) { if (key == "source-syntax") { m_sourceSyntax = Scan<bool>(value); } else { StatelessFeatureFunction::SetParameter(key, value); } } } <commit_msg>add FF RuleAmbiguity<commit_after>#include "RuleAmbiguity.h" #include "moses/StaticData.h" #include "moses/Word.h" namespace Moses { RuleAmbiguity::RuleAmbiguity(const std::string &line) :StatelessFeatureFunction(1, line) ,m_sourceSyntax(true) { } bool IsAmbiguous(const Word &word, bool sourceSyntax) { const Word &inputDefaultNonTerminal = StaticData::Instance().GetInputDefaultNonTerminal(); return word.IsNonTerminal() && (!sourceSyntax || word == inputDefaultNonTerminal); } void RuleAmbiguity::Evaluate(const Phrase &source , const TargetPhrase &targetPhrase , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection &estimatedFutureScore) const { // source can't be empty, right? float score = 0; int count = 0; for (size_t i = 0; i < source.GetSize() - 0; ++i) { const Word &word = source.GetWord(i); bool ambiguous = IsAmbiguous(word, m_sourceSyntax); if (ambiguous) { ++count; } else { if (count > 0) { score += count; } count = -1; } } // 1st & last always adjacent to ambiguity ++count; if (count > 0) { score += count; } scoreBreakdown.PlusEquals(this, score); } void RuleAmbiguity::SetParameter(const std::string& key, const std::string& value) { if (key == "source-syntax") { m_sourceSyntax = Scan<bool>(value); } else { StatelessFeatureFunction::SetParameter(key, value); } } } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff/ // Copyright Holders: Felix Albrecht, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_LA_SOLVER_HH #define DUNE_STUFF_LA_SOLVER_HH #include <string> #include <vector> #include <dune/stuff/common/type_utils.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configtree.hh> #include "container/interfaces.hh" #include "container/dunedynamic.hh" #include "container/eigen.hh" namespace Dune { namespace Stuff { namespace Exceptions { class linear_solver_failed_bc_matrix_did_not_fulfill_requirements : public linear_solver_failed {}; class linear_solver_failed_bc_it_did_not_converge : public linear_solver_failed {}; class linear_solver_failed_bc_it_was_not_set_up_correctly : public linear_solver_failed {}; class linear_solver_failed_bc_the_solution_does_not_solve_the_system : public linear_solver_failed {}; } // namespace Exceptions namespace LA { class SolverUtils { protected: static void check_given(const std::string& type, const std::vector< std::string >& opts) { if (std::find(opts.begin(), opts.end(), type) == opts.end()) { std::stringstream ss; for (auto opt : opts) ss << opt << " "; DUNE_THROW_COLORFULLY(Exceptions::configuration_error, "Given type '" << type << "' not supported (see below for a list of supported ones). " << "Call options() first!\n" << ss.str()); } } }; template< class MatrixImp > class Solver { static_assert(AlwaysFalse< MatrixImp >::value, "This is the unspecialized version of LA::Solver< ... >. Please include the correct header for your matrix implementation!"); public: typedef MatrixImp MatrixType; Solver(const MatrixType& /*matrix*/) { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } static std::vector< std::string > options() { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } static Common::ConfigTree options(const std::string& /*type*/) { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } /** * Throws any of the above exceptions, if there was a problem. If none was thrown we beleive that a suitable solution * was found (given the current options). */ template< class RhsType, class SolutionType > void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/) const { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } template< class RhsType, class SolutionType > void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/, const std::string& /*type*/) const { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } template< class RhsType, class SolutionType > void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/, const Common::ConfigTree& /*options*/) const { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } }; // class Solver } // namespace LA } // namespace Stuff } // namespace Dune #include "solver/dunedynamic.hh" #include "solver/eigen.hh" #include "solver/istl.hh" #endif // DUNE_STUFF_LA_SOLVER_HH <commit_msg>[la.solver] update includes<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff/ // Copyright Holders: Felix Albrecht, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_LA_SOLVER_HH #define DUNE_STUFF_LA_SOLVER_HH #include <string> #include <vector> #include <dune/stuff/common/type_utils.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configtree.hh> namespace Dune { namespace Stuff { namespace Exceptions { class linear_solver_failed_bc_matrix_did_not_fulfill_requirements : public linear_solver_failed {}; class linear_solver_failed_bc_it_did_not_converge : public linear_solver_failed {}; class linear_solver_failed_bc_it_was_not_set_up_correctly : public linear_solver_failed {}; class linear_solver_failed_bc_the_solution_does_not_solve_the_system : public linear_solver_failed {}; } // namespace Exceptions namespace LA { class SolverUtils { protected: static void check_given(const std::string& type, const std::vector< std::string >& opts) { if (std::find(opts.begin(), opts.end(), type) == opts.end()) { std::stringstream ss; for (auto opt : opts) ss << opt << " "; DUNE_THROW_COLORFULLY(Exceptions::configuration_error, "Given type '" << type << "' not supported (see below for a list of supported ones). " << "Call options() first!\n" << ss.str()); } } }; template< class MatrixImp > class Solver { static_assert(AlwaysFalse< MatrixImp >::value, "This is the unspecialized version of LA::Solver< ... >. Please include the correct header for your matrix implementation!"); public: typedef MatrixImp MatrixType; Solver(const MatrixType& /*matrix*/) { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } static std::vector< std::string > options() { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } static Common::ConfigTree options(const std::string& /*type*/) { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } /** * Throws any of the above exceptions, if there was a problem. If none was thrown we beleive that a suitable solution * was found (given the current options). */ template< class RhsType, class SolutionType > void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/) const { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } template< class RhsType, class SolutionType > void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/, const std::string& /*type*/) const { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } template< class RhsType, class SolutionType > void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/, const Common::ConfigTree& /*options*/) const { DUNE_THROW_COLORFULLY(NotImplemented, "This is the unspecialized version of LA::Solver< ... >. " "Please include the correct header for your matrix implementation '" << Common::Typename< MatrixType >::value() << "'!"); } }; // class Solver } // namespace LA } // namespace Stuff } // namespace Dune #include "solver/common.hh" #include "solver/eigen.hh" #include "solver/istl.hh" #endif // DUNE_STUFF_LA_SOLVER_HH <|endoftext|>
<commit_before> #include "Math/RMinimizer.h" #include "Math/IFunction.h" #include <TVectorD.h> #include "Math/BasicMinimizer.h" //#include "Math/MultiNumGradFunction.h" namespace ROOT { namespace Math{ const ROOT::Math::IMultiGenFunction *gFunction; const ROOT::Math::IMultiGradFunction *gGradFunction; double minfunction(TVectorD x){ return (*gFunction)(x.GetMatrixArray()); } TVectorD mingradfunction(const double * y){ double * z; return gGradFunction->Gradient(y,z); } RMinimizer::RMinimizer(Option_t *method){ fMethod=method; if (fMethod.empty() ) fMethod="BFGS"; } void RMinimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) { // set the function to minimizer // need to calculate numerically the derivatives: do via class MultiNumGradFunction gFunction = &func; //ROOT::Math::MultiNumGradFunction gradFunc(func); // function is cloned inside so can be delete afterwards // called base class method setfunction // (note: write explicitly otherwise it will call back itself) BasicMinimizer::SetFunction(func); } //SetFunctions bool RMinimizer::Minimize() { (gFunction)= ObjFunction(); (gGradFunction) = GradObjFunction(); /* *"Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent" (Brent only for 1D minimization) */ //std::cout<<"Number of dimension ="<< NDim() << std::endl; //pass function to R ROOT::R::TRInterface &r=gR->Instance(); r["minfunction"] = ROOT::R::TRFunction((minfunction)); r["gradFunc"] = ROOT::R::TRFunction((mingradfunction)); r["method"] = fMethod.c_str(); std::vector<double> stepSizes(StepSizes(), StepSizes()+NDim()); std::vector<double> values(X(), X()+NDim()); r["stepsizes"] = stepSizes; r["initialparams"] = values; //find minimum in R TString cmd = TString::Format("result <- optim( initialparams, minfunction,method='%s',control = list(ndeps=stepsizes,maxit=%d,trace=%d,abstol=%e))",fMethod.c_str(),MaxIterations(),PrintLevel(),Tolerance()); //std::cout << "Calling R with command " << cmd << std::endl; r.Parse(cmd.Data()); //get result from R TVectorD vector=r.ParseEval("result$par").ToVector<Double_t>(); const double *min=vector.GetMatrixArray(); //std::cout.precision(8); //print results //std::cout<<"-----------------------------------------"<<std::endl; //std::cout<<"Minimum x="<<min[0]<<" y="<<min[1]<<std::endl; SetFinalValues(min); SetMinValue((*gFunction)(min)); //std::cout<<"Value at minimum ="<<MinValue()<<std::endl; r.Parse("optimHess(result$par, minfunction, gradFunc)"); TString cmd2 = TString::Format("hresult <- optim( initialparams, minfunction,NULL, method='%s',hessian = TRUE, control = list(ndeps=stepsizes,maxit=%d,trace=%d,abstol=%e))",fMethod.c_str(),MaxIterations(),PrintLevel(),Tolerance()); r.Parse(cmd2.Data()); //getting the min calculated with the gradient TVectorD hmin=r.ParseEval("hresult$par").ToVector<Double_t>(); return kTRUE; } } } <commit_msg>bug fixes<commit_after> #include "Math/RMinimizer.h" #include "Math/IFunction.h" #include <TVectorD.h> #include "Math/BasicMinimizer.h" //#include "Math/MultiNumGradFunction.h" namespace ROOT { namespace Math{ const ROOT::Math::IMultiGenFunction *gFunction; const ROOT::Math::IMultiGradFunction *gGradFunction; double minfunction(TVectorD x){ return (*gFunction)(x.GetMatrixArray()); } TVectorD mingradfunction(const double * y){ double * z; gGradFunction->Gradient(y,z); return z; } RMinimizer::RMinimizer(Option_t *method){ fMethod=method; if (fMethod.empty() ) fMethod="BFGS"; } void RMinimizer::SetFunction(const ROOT::Math::IMultiGenFunction & func) { // set the function to minimizer // need to calculate numerically the derivatives: do via class MultiNumGradFunction gFunction = &func; //ROOT::Math::MultiNumGradFunction gradFunc(func); // function is cloned inside so can be delete afterwards // called base class method setfunction // (note: write explicitly otherwise it will call back itself) BasicMinimizer::SetFunction(func); } //SetFunctions bool RMinimizer::Minimize() { (gFunction)= ObjFunction(); (gGradFunction) = GradObjFunction(); /* *"Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent" (Brent only for 1D minimization) */ //std::cout<<"Number of dimension ="<< NDim() << std::endl; //pass function to R ROOT::R::TRInterface &r=gR->Instance(); r["minfunction"] = ROOT::R::TRFunction((minfunction)); r["gradFunc"] = ROOT::R::TRFunction((mingradfunction)); r["method"] = fMethod.c_str(); std::vector<double> stepSizes(StepSizes(), StepSizes()+NDim()); std::vector<double> values(X(), X()+NDim()); r["stepsizes"] = stepSizes; r["initialparams"] = values; //find minimum in R TString cmd = TString::Format("result <- optim( initialparams, minfunction,method='%s',control = list(ndeps=stepsizes,maxit=%d,trace=%d,abstol=%e))",fMethod.c_str(),MaxIterations(),PrintLevel(),Tolerance()); //std::cout << "Calling R with command " << cmd << std::endl; r.Parse(cmd.Data()); //get result from R TVectorD vector=r.ParseEval("result$par").ToVector<Double_t>(); const double *min=vector.GetMatrixArray(); //std::cout.precision(8); //print results //std::cout<<"-----------------------------------------"<<std::endl; //std::cout<<"Minimum x="<<min[0]<<" y="<<min[1]<<std::endl; SetFinalValues(min); SetMinValue((*gFunction)(min)); //std::cout<<"Value at minimum ="<<MinValue()<<std::endl; r.Parse("optimHess(result$par, minfunction, gradFunc)"); TString cmd2 = TString::Format("hresult <- optim( initialparams, minfunction,NULL, method='%s',hessian = TRUE, control = list(ndeps=stepsizes,maxit=%d,trace=%d,abstol=%e))",fMethod.c_str(),MaxIterations(),PrintLevel(),Tolerance()); r.Parse(cmd2.Data()); //getting the min calculated with the gradient TVectorD hmin=r.ParseEval("hresult$par").ToVector<Double_t>(); return kTRUE; } } } <|endoftext|>
<commit_before>// @(#)root/meta:$Name: $:$Id: TGenericClassInfo.cxx,v 1.17 2007/01/31 19:59:53 pcanal Exp $ // Author: Philippe Canal 08/05/2002 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TClass.h" #include "TStreamerInfo.h" #include "TStreamer.h" #include "TVirtualIsAProxy.h" #include "TVirtualCollectionProxy.h" #include "TCollectionProxyInfo.h" namespace ROOT { const TInitBehavior *DefineBehavior(void * /*parent_type*/, void * /*actual_type*/) { // This function loads the default behavior for the // loading of classes. static TDefaultInitBehavior theDefault; return &theDefault; } TGenericClassInfo::TGenericClassInfo(const char *fullClassname, const char *declFileName, Int_t declFileLine, const type_info &info, const TInitBehavior *action, void *showmembers, VoidFuncPtr_t dictionary, TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof) : fAction(action), fClass(0), fClassName(fullClassname), fDeclFileName(declFileName), fDeclFileLine(declFileLine), fDictionary(dictionary), fInfo(info), fImplFileName(0), fImplFileLine(0), fIsA(isa), fShowMembers(showmembers), fVersion(1), fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0), fCollectionProxy(0), fSizeof(sizof) { // Constructor. Init(pragmabits); } TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version, const char *declFileName, Int_t declFileLine, const type_info &info, const TInitBehavior *action, void* showmembers, VoidFuncPtr_t dictionary, TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof) : fAction(action), fClass(0), fClassName(fullClassname), fDeclFileName(declFileName), fDeclFileLine(declFileLine), fDictionary(dictionary), fInfo(info), fImplFileName(0), fImplFileLine(0), fIsA(isa), fShowMembers(showmembers), fVersion(version), fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0), fCollectionProxy(0), fSizeof(sizof), fCollectionProxyInfo(0), fCollectionStreamerInfo(0) { // Constructor with version number. Init(pragmabits); } TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version, const char *declFileName, Int_t declFileLine, const type_info &info, const TInitBehavior *action, VoidFuncPtr_t dictionary, TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof) : fAction(action), fClass(0), fClassName(fullClassname), fDeclFileName(declFileName), fDeclFileLine(declFileLine), fDictionary(dictionary), fInfo(info), fImplFileName(0), fImplFileLine(0), fIsA(isa), fShowMembers(0), fVersion(version), fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0), fCollectionProxy(0), fSizeof(sizof), fCollectionProxyInfo(0), fCollectionStreamerInfo(0) { // Constructor with version number and no showmembers. Init(pragmabits); } class TForNamespace {}; // Dummy class to give a typeid to namespace (See also TClassTable.cc) TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version, const char *declFileName, Int_t declFileLine, const TInitBehavior *action, VoidFuncPtr_t dictionary, Int_t pragmabits) : fAction(action), fClass(0), fClassName(fullClassname), fDeclFileName(declFileName), fDeclFileLine(declFileLine), fDictionary(dictionary), fInfo(typeid(TForNamespace)), fImplFileName(0), fImplFileLine(0), fIsA(0), fShowMembers(0), fVersion(version), fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0), fCollectionProxy(0), fSizeof(0), fCollectionProxyInfo(0), fCollectionStreamerInfo(0) { // Constructor for namespace Init(pragmabits); } /* TGenericClassInfo::TGenericClassInfo(const TGenericClassInfo& gci) : fAction(gci.fAction), fClass(gci.fClass), fClassName(gci.fClassName), fDeclFileName(gci.fDeclFileName), fDeclFileLine(gci.fDeclFileLine), fDictionary(gci.fDictionary), fInfo(gci.fInfo), fImplFileName(gci.fImplFileName), fImplFileLine(gci.fImplFileLine), fIsA(gci.fIsA), fShowMembers(gci.fShowMembers), fVersion(gci.fVersion), fNew(gci.fNew), fNewArray(gci.fNewArray), fDelete(gci.fDelete), fDeleteArray(gci.fDeleteArray), fDestructor(gci.fDestructor), fStreamer(gci.fStreamer), fCollectionProxy(gci.fCollectionProxy), fSizeof(gci.fSizeof) { } TGenericClassInfo& TGenericClassInfo::operator=(const TGenericClassInfo& gci) { if(this!=&gci) { fAction=gci.fAction; fClass=gci.fClass; fClassName=gci.fClassName; fDeclFileName=gci.fDeclFileName; fDeclFileLine=gci.fDeclFileLine; fDictionary=gci.fDictionary; fInfo=gci.fInfo; fImplFileName=gci.fImplFileName; fImplFileLine=gci.fImplFileLine; fIsA=gci.fIsA; fShowMembers=gci.fShowMembers; fVersion=gci.fVersion; fNew=gci.fNew; fNewArray=gci.fNewArray; fDelete=gci.fDelete; fDeleteArray=gci.fDeleteArray; fDestructor=gci.fDestructor; fStreamer=gci.fStreamer; fCollectionProxy=gci.fCollectionProxy; fSizeof=gci.fSizeof; } return *this; } */ void TGenericClassInfo::Init(Int_t pragmabits) { // Initilization routine. if (fVersion==-2) fVersion = TStreamerInfo::Class_Version(); if (!fAction) return; GetAction().Register(fClassName, fVersion, fInfo, // typeid(RootClass), fDictionary, pragmabits); } TGenericClassInfo::~TGenericClassInfo() { // Destructor. delete fCollectionProxyInfo; delete fCollectionStreamerInfo; if (!fClass) delete fIsA; // fIsA is adopted by the class if any. fIsA = 0; if (!gROOT) return; if (fAction) GetAction().Unregister(GetClassName()); } const TInitBehavior &TGenericClassInfo::GetAction() const { // Return the creator action. return *fAction; } TClass *TGenericClassInfo::GetClass() { // Generate and return the TClass object. if (!fClass && fAction) { fClass = GetAction().CreateClass(GetClassName(), GetVersion(), GetInfo(), GetIsA(), (ShowMembersFunc_t)GetShowMembers(), GetDeclFileName(), GetImplFileName(), GetDeclFileLine(), GetImplFileLine()); fClass->SetNew(fNew); fClass->SetNewArray(fNewArray); fClass->SetDelete(fDelete); fClass->SetDeleteArray(fDeleteArray); fClass->SetDestructor(fDestructor); fClass->AdoptStreamer(fStreamer); fStreamer = 0; // If IsZombie is true, something went wront and we will not be // able to properly copy the collection proxy if (!fClass->IsZombie()) { if (fCollectionProxy) fClass->CopyCollectionProxy(*fCollectionProxy); else if (fCollectionProxyInfo) { fClass->SetCollectionProxy(*fCollectionProxyInfo); } } fClass->SetClassSize(fSizeof); } return fClass; } const char *TGenericClassInfo::GetClassName() const { // Return the class name return fClassName; } TCollectionProxyInfo *TGenericClassInfo::GetCollectionProxyInfo() const { // Return the set of info we have for the CollectionProxy, if any return fCollectionProxyInfo; } TCollectionProxyInfo *TGenericClassInfo::GetCollectionStreamerInfo() const { // Return the set of info we have for the Collection Streamer, if any return fCollectionProxyInfo; } const type_info &TGenericClassInfo::GetInfo() const { // Return the typeifno value return fInfo; } void *TGenericClassInfo::GetShowMembers() const { // Return the point of the ShowMembers function return fShowMembers; } void TGenericClassInfo::SetFromTemplate() { // Import the information from the class template. TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0); if (info) SetImplFile(info->GetTitle(), info->GetUniqueID()); } Int_t TGenericClassInfo::SetImplFile(const char *file, Int_t line) { // Set the name of the implementation file. fImplFileName = file; fImplFileLine = line; if (fClass) fClass->AddImplFile(file,line); return 0; } Int_t TGenericClassInfo::SetDeclFile(const char *file, Int_t line) { // Set the name of the declaration file. fDeclFileName = file; fDeclFileLine = line; if (fClass) fClass->SetDeclFile(file,line); return 0; } Short_t TGenericClassInfo::SetVersion(Short_t version) { // Set a class version number. ROOT::ResetClassVersion(fClass, GetClassName(),version); fVersion = version; return version; } void TGenericClassInfo::AdoptCollectionProxyInfo(TCollectionProxyInfo *info) { // Set the info for the CollectionProxy fCollectionProxyInfo = info; } void TGenericClassInfo::AdoptCollectionStreamerInfo(TCollectionProxyInfo *info) { // Set the info for the Collection Streamer fCollectionProxyInfo = info; } Short_t TGenericClassInfo::AdoptStreamer(TClassStreamer *streamer) { // Set a Streamer object. The streamer object is now 'owned' // by the TGenericClassInfo. delete fStreamer; fStreamer = 0; if (fClass) { fClass->AdoptStreamer(streamer); } else { fStreamer = streamer; } return 0; } Short_t TGenericClassInfo::AdoptCollectionProxy(TVirtualCollectionProxy *collProxy) { // Set the CollectProxy object. The CollectionProxy object is now 'owned' // by the TGenericClassInfo. delete fCollectionProxy; fCollectionProxy = 0; fCollectionProxy = collProxy; if (fClass && fCollectionProxy && !fClass->IsZombie()) { fClass->CopyCollectionProxy(*fCollectionProxy); } return 0; } Short_t TGenericClassInfo::SetStreamer(ClassStreamerFunc_t streamer) { // Set a Streamer function. delete fStreamer; fStreamer = 0; if (fClass) { fClass->AdoptStreamer(new TClassStreamer(streamer)); } else { fStreamer = new TClassStreamer(streamer); } return 0; } const char *TGenericClassInfo::GetDeclFileName() const { // Get the name of the declaring header file. return fDeclFileName; } Int_t TGenericClassInfo::GetDeclFileLine() const { // Get the declaring line number. return fDeclFileLine; } const char *TGenericClassInfo::GetImplFileName() { // Get the implementation filename. if (!fImplFileName) SetFromTemplate(); return fImplFileName; } Int_t TGenericClassInfo::GetImplFileLine() { // Get the ClassImp line number. if (!fImplFileLine) SetFromTemplate(); return fImplFileLine; } Int_t TGenericClassInfo::GetVersion() const { // Return the class version number. return fVersion; } TClass *TGenericClassInfo::IsA(const void *obj) { // Return the actual type of the object. return (*GetIsA())(obj); } TVirtualIsAProxy* TGenericClassInfo::GetIsA() const { // Return the IsA proxy. return fIsA; } void TGenericClassInfo::SetNew(NewFunc_t newFunc) { // Install a new wrapper around 'new'. fNew = newFunc; if (fClass) fClass->SetNew(fNew); } void TGenericClassInfo::SetNewArray(NewArrFunc_t newArrayFunc) { // Install a new wrapper around 'new []'. fNewArray = newArrayFunc; if (fClass) fClass->SetNewArray(fNewArray); } void TGenericClassInfo::SetDelete(DelFunc_t deleteFunc) { // Install a new wrapper around 'delete'. fDelete = deleteFunc; if (fClass) fClass->SetDelete(fDelete); } void TGenericClassInfo::SetDeleteArray(DelArrFunc_t deleteArrayFunc) { // Install a new wrapper around 'delete []'. fDeleteArray = deleteArrayFunc; if (fClass) fClass->SetDeleteArray(fDeleteArray); } void TGenericClassInfo::SetDestructor(DesFunc_t destructorFunc) { // Install a new wrapper around the destructor. fDestructor = destructorFunc; if (fClass) fClass->SetDestructor(fDestructor); } NewFunc_t TGenericClassInfo::GetNew() const { // Get the wrapper around 'new'. return fNew; } NewArrFunc_t TGenericClassInfo::GetNewArray() const { // Get the wrapper around 'new []'. return fNewArray; } DelFunc_t TGenericClassInfo::GetDelete() const { // Get the wrapper around 'delete'. return fDelete; } DelArrFunc_t TGenericClassInfo::GetDeleteArray() const { // Get the wrapper around 'delete []'. return fDeleteArray; } DesFunc_t TGenericClassInfo::GetDestructor() const { // Get the wrapper around the destructor. return fDestructor; } } <commit_msg>-use TVirtualStreamerinfo instead of TStreamerInfo.<commit_after>// @(#)root/meta:$Name: $:$Id: TGenericClassInfo.cxx,v 1.18 2007/02/01 21:59:28 pcanal Exp $ // Author: Philippe Canal 08/05/2002 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TClass.h" #include "TVirtualStreamerInfo.h" #include "TStreamer.h" #include "TVirtualIsAProxy.h" #include "TVirtualCollectionProxy.h" #include "TCollectionProxyInfo.h" namespace ROOT { const TInitBehavior *DefineBehavior(void * /*parent_type*/, void * /*actual_type*/) { // This function loads the default behavior for the // loading of classes. static TDefaultInitBehavior theDefault; return &theDefault; } TGenericClassInfo::TGenericClassInfo(const char *fullClassname, const char *declFileName, Int_t declFileLine, const type_info &info, const TInitBehavior *action, void *showmembers, VoidFuncPtr_t dictionary, TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof) : fAction(action), fClass(0), fClassName(fullClassname), fDeclFileName(declFileName), fDeclFileLine(declFileLine), fDictionary(dictionary), fInfo(info), fImplFileName(0), fImplFileLine(0), fIsA(isa), fShowMembers(showmembers), fVersion(1), fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0), fCollectionProxy(0), fSizeof(sizof) { // Constructor. Init(pragmabits); } TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version, const char *declFileName, Int_t declFileLine, const type_info &info, const TInitBehavior *action, void* showmembers, VoidFuncPtr_t dictionary, TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof) : fAction(action), fClass(0), fClassName(fullClassname), fDeclFileName(declFileName), fDeclFileLine(declFileLine), fDictionary(dictionary), fInfo(info), fImplFileName(0), fImplFileLine(0), fIsA(isa), fShowMembers(showmembers), fVersion(version), fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0), fCollectionProxy(0), fSizeof(sizof), fCollectionProxyInfo(0), fCollectionStreamerInfo(0) { // Constructor with version number. Init(pragmabits); } TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version, const char *declFileName, Int_t declFileLine, const type_info &info, const TInitBehavior *action, VoidFuncPtr_t dictionary, TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof) : fAction(action), fClass(0), fClassName(fullClassname), fDeclFileName(declFileName), fDeclFileLine(declFileLine), fDictionary(dictionary), fInfo(info), fImplFileName(0), fImplFileLine(0), fIsA(isa), fShowMembers(0), fVersion(version), fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0), fCollectionProxy(0), fSizeof(sizof), fCollectionProxyInfo(0), fCollectionStreamerInfo(0) { // Constructor with version number and no showmembers. Init(pragmabits); } class TForNamespace {}; // Dummy class to give a typeid to namespace (See also TClassTable.cc) TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version, const char *declFileName, Int_t declFileLine, const TInitBehavior *action, VoidFuncPtr_t dictionary, Int_t pragmabits) : fAction(action), fClass(0), fClassName(fullClassname), fDeclFileName(declFileName), fDeclFileLine(declFileLine), fDictionary(dictionary), fInfo(typeid(TForNamespace)), fImplFileName(0), fImplFileLine(0), fIsA(0), fShowMembers(0), fVersion(version), fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0), fCollectionProxy(0), fSizeof(0), fCollectionProxyInfo(0), fCollectionStreamerInfo(0) { // Constructor for namespace Init(pragmabits); } /* TGenericClassInfo::TGenericClassInfo(const TGenericClassInfo& gci) : fAction(gci.fAction), fClass(gci.fClass), fClassName(gci.fClassName), fDeclFileName(gci.fDeclFileName), fDeclFileLine(gci.fDeclFileLine), fDictionary(gci.fDictionary), fInfo(gci.fInfo), fImplFileName(gci.fImplFileName), fImplFileLine(gci.fImplFileLine), fIsA(gci.fIsA), fShowMembers(gci.fShowMembers), fVersion(gci.fVersion), fNew(gci.fNew), fNewArray(gci.fNewArray), fDelete(gci.fDelete), fDeleteArray(gci.fDeleteArray), fDestructor(gci.fDestructor), fStreamer(gci.fStreamer), fCollectionProxy(gci.fCollectionProxy), fSizeof(gci.fSizeof) { } TGenericClassInfo& TGenericClassInfo::operator=(const TGenericClassInfo& gci) { if(this!=&gci) { fAction=gci.fAction; fClass=gci.fClass; fClassName=gci.fClassName; fDeclFileName=gci.fDeclFileName; fDeclFileLine=gci.fDeclFileLine; fDictionary=gci.fDictionary; fInfo=gci.fInfo; fImplFileName=gci.fImplFileName; fImplFileLine=gci.fImplFileLine; fIsA=gci.fIsA; fShowMembers=gci.fShowMembers; fVersion=gci.fVersion; fNew=gci.fNew; fNewArray=gci.fNewArray; fDelete=gci.fDelete; fDeleteArray=gci.fDeleteArray; fDestructor=gci.fDestructor; fStreamer=gci.fStreamer; fCollectionProxy=gci.fCollectionProxy; fSizeof=gci.fSizeof; } return *this; } */ void TGenericClassInfo::Init(Int_t pragmabits) { // Initilization routine. //TVirtualStreamerInfo::Class_Version MUST be the same as TStreamerInfo::Class_Version if (fVersion==-2) fVersion = TVirtualStreamerInfo::Class_Version(); if (!fAction) return; GetAction().Register(fClassName, fVersion, fInfo, // typeid(RootClass), fDictionary, pragmabits); } TGenericClassInfo::~TGenericClassInfo() { // Destructor. delete fCollectionProxyInfo; delete fCollectionStreamerInfo; if (!fClass) delete fIsA; // fIsA is adopted by the class if any. fIsA = 0; if (!gROOT) return; if (fAction) GetAction().Unregister(GetClassName()); } const TInitBehavior &TGenericClassInfo::GetAction() const { // Return the creator action. return *fAction; } TClass *TGenericClassInfo::GetClass() { // Generate and return the TClass object. if (!fClass && fAction) { fClass = GetAction().CreateClass(GetClassName(), GetVersion(), GetInfo(), GetIsA(), (ShowMembersFunc_t)GetShowMembers(), GetDeclFileName(), GetImplFileName(), GetDeclFileLine(), GetImplFileLine()); fClass->SetNew(fNew); fClass->SetNewArray(fNewArray); fClass->SetDelete(fDelete); fClass->SetDeleteArray(fDeleteArray); fClass->SetDestructor(fDestructor); fClass->AdoptStreamer(fStreamer); fStreamer = 0; // If IsZombie is true, something went wront and we will not be // able to properly copy the collection proxy if (!fClass->IsZombie()) { if (fCollectionProxy) fClass->CopyCollectionProxy(*fCollectionProxy); else if (fCollectionProxyInfo) { fClass->SetCollectionProxy(*fCollectionProxyInfo); } } fClass->SetClassSize(fSizeof); } return fClass; } const char *TGenericClassInfo::GetClassName() const { // Return the class name return fClassName; } TCollectionProxyInfo *TGenericClassInfo::GetCollectionProxyInfo() const { // Return the set of info we have for the CollectionProxy, if any return fCollectionProxyInfo; } TCollectionProxyInfo *TGenericClassInfo::GetCollectionStreamerInfo() const { // Return the set of info we have for the Collection Streamer, if any return fCollectionProxyInfo; } const type_info &TGenericClassInfo::GetInfo() const { // Return the typeifno value return fInfo; } void *TGenericClassInfo::GetShowMembers() const { // Return the point of the ShowMembers function return fShowMembers; } void TGenericClassInfo::SetFromTemplate() { // Import the information from the class template. TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0); if (info) SetImplFile(info->GetTitle(), info->GetUniqueID()); } Int_t TGenericClassInfo::SetImplFile(const char *file, Int_t line) { // Set the name of the implementation file. fImplFileName = file; fImplFileLine = line; if (fClass) fClass->AddImplFile(file,line); return 0; } Int_t TGenericClassInfo::SetDeclFile(const char *file, Int_t line) { // Set the name of the declaration file. fDeclFileName = file; fDeclFileLine = line; if (fClass) fClass->SetDeclFile(file,line); return 0; } Short_t TGenericClassInfo::SetVersion(Short_t version) { // Set a class version number. ROOT::ResetClassVersion(fClass, GetClassName(),version); fVersion = version; return version; } void TGenericClassInfo::AdoptCollectionProxyInfo(TCollectionProxyInfo *info) { // Set the info for the CollectionProxy fCollectionProxyInfo = info; } void TGenericClassInfo::AdoptCollectionStreamerInfo(TCollectionProxyInfo *info) { // Set the info for the Collection Streamer fCollectionProxyInfo = info; } Short_t TGenericClassInfo::AdoptStreamer(TClassStreamer *streamer) { // Set a Streamer object. The streamer object is now 'owned' // by the TGenericClassInfo. delete fStreamer; fStreamer = 0; if (fClass) { fClass->AdoptStreamer(streamer); } else { fStreamer = streamer; } return 0; } Short_t TGenericClassInfo::AdoptCollectionProxy(TVirtualCollectionProxy *collProxy) { // Set the CollectProxy object. The CollectionProxy object is now 'owned' // by the TGenericClassInfo. delete fCollectionProxy; fCollectionProxy = 0; fCollectionProxy = collProxy; if (fClass && fCollectionProxy && !fClass->IsZombie()) { fClass->CopyCollectionProxy(*fCollectionProxy); } return 0; } Short_t TGenericClassInfo::SetStreamer(ClassStreamerFunc_t streamer) { // Set a Streamer function. delete fStreamer; fStreamer = 0; if (fClass) { fClass->AdoptStreamer(new TClassStreamer(streamer)); } else { fStreamer = new TClassStreamer(streamer); } return 0; } const char *TGenericClassInfo::GetDeclFileName() const { // Get the name of the declaring header file. return fDeclFileName; } Int_t TGenericClassInfo::GetDeclFileLine() const { // Get the declaring line number. return fDeclFileLine; } const char *TGenericClassInfo::GetImplFileName() { // Get the implementation filename. if (!fImplFileName) SetFromTemplate(); return fImplFileName; } Int_t TGenericClassInfo::GetImplFileLine() { // Get the ClassImp line number. if (!fImplFileLine) SetFromTemplate(); return fImplFileLine; } Int_t TGenericClassInfo::GetVersion() const { // Return the class version number. return fVersion; } TClass *TGenericClassInfo::IsA(const void *obj) { // Return the actual type of the object. return (*GetIsA())(obj); } TVirtualIsAProxy* TGenericClassInfo::GetIsA() const { // Return the IsA proxy. return fIsA; } void TGenericClassInfo::SetNew(NewFunc_t newFunc) { // Install a new wrapper around 'new'. fNew = newFunc; if (fClass) fClass->SetNew(fNew); } void TGenericClassInfo::SetNewArray(NewArrFunc_t newArrayFunc) { // Install a new wrapper around 'new []'. fNewArray = newArrayFunc; if (fClass) fClass->SetNewArray(fNewArray); } void TGenericClassInfo::SetDelete(DelFunc_t deleteFunc) { // Install a new wrapper around 'delete'. fDelete = deleteFunc; if (fClass) fClass->SetDelete(fDelete); } void TGenericClassInfo::SetDeleteArray(DelArrFunc_t deleteArrayFunc) { // Install a new wrapper around 'delete []'. fDeleteArray = deleteArrayFunc; if (fClass) fClass->SetDeleteArray(fDeleteArray); } void TGenericClassInfo::SetDestructor(DesFunc_t destructorFunc) { // Install a new wrapper around the destructor. fDestructor = destructorFunc; if (fClass) fClass->SetDestructor(fDestructor); } NewFunc_t TGenericClassInfo::GetNew() const { // Get the wrapper around 'new'. return fNew; } NewArrFunc_t TGenericClassInfo::GetNewArray() const { // Get the wrapper around 'new []'. return fNewArray; } DelFunc_t TGenericClassInfo::GetDelete() const { // Get the wrapper around 'delete'. return fDelete; } DelArrFunc_t TGenericClassInfo::GetDeleteArray() const { // Get the wrapper around 'delete []'. return fDeleteArray; } DesFunc_t TGenericClassInfo::GetDestructor() const { // Get the wrapper around the destructor. return fDestructor; } } <|endoftext|>
<commit_before>#ifndef ENUMERABLE__H__ #define ENUMERABLE__H__ #include <iterbase.hpp> #include <utility> #include <iterator> #include <functional> // enumerate functionality for python-style for-each enumerate loops // for (auto e : enumerate(vec)) { // std::cout << e.index // << ": " // << e.element // << '\n'; // } namespace iter { //Forward declarations of Enumerable and enumerate template <typename Container> class Enumerable; template <typename T> Enumerable<std::initializer_list<T>> enumerate( std::initializer_list<T> &&); template <typename Container> Enumerable<Container> enumerate(Container &&); template <typename Container> class Enumerable : public IterBase<Container>{ private: Container & container; // The only thing allowed to directly instantiate an Enumerable is // the enumerate function friend Enumerable enumerate<Container>(Container &&); template <typename T> friend Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> &&); using typename IterBase<Container>::contained_iter_type; using typename IterBase<Container>::contained_iter_ret; Enumerable(Container & container) : container(container) { } public: // Value constructor for use only in the enumerate function Enumerable () = delete; Enumerable & operator=(const Enumerable &) = delete; Enumerable(const Enumerable &) = default; // "yielded" by the Enumerable::Iterator. Has a .index, and a // .element referencing the value yielded by the subiterator class IterYield { public: std::size_t index; contained_iter_ret element; IterYield(std::size_t i, contained_iter_ret elem) : index(i), element(elem) { } }; // Holds an iterator of the contained type and a size_t for the // index. Each call to ++ increments both of these data members. // Each dereference returns an IterYield. class Iterator { private: contained_iter_type sub_iter; std::size_t index; public: Iterator (contained_iter_type si) : sub_iter(si), index(0) { } IterYield operator*() const { return IterYield(this->index, *this->sub_iter); } Iterator & operator++() { ++this->sub_iter; ++this->index; return *this; } bool operator!=(const Iterator & other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() const { return Iterator(std::begin(this->container)); } Iterator end() const { return Iterator(std::end(this->container)); } }; // Helper function to instantiate an Enumerable template <typename Container> Enumerable<Container> enumerate(Container && container) { return Enumerable<Container>(std::forward<Container>(container)); } template <typename T> Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> && il) { return Enumerable<std::initializer_list<T>>(il); } } #endif //ifndef ENUMERABLE__H__ <commit_msg>added include in enumerate<commit_after>#ifndef ENUMERABLE__H__ #define ENUMERABLE__H__ #include <iterbase.hpp> #include <utility> #include <iterator> #include <functional> #include <initializer_list> // enumerate functionality for python-style for-each enumerate loops // for (auto e : enumerate(vec)) { // std::cout << e.index // << ": " // << e.element // << '\n'; // } namespace iter { //Forward declarations of Enumerable and enumerate template <typename Container> class Enumerable; template <typename T> Enumerable<std::initializer_list<T>> enumerate( std::initializer_list<T> &&); template <typename Container> Enumerable<Container> enumerate(Container &&); template <typename Container> class Enumerable : public IterBase<Container>{ private: Container & container; // The only thing allowed to directly instantiate an Enumerable is // the enumerate function friend Enumerable enumerate<Container>(Container &&); template <typename T> friend Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> &&); using typename IterBase<Container>::contained_iter_type; using typename IterBase<Container>::contained_iter_ret; Enumerable(Container & container) : container(container) { } public: // Value constructor for use only in the enumerate function Enumerable () = delete; Enumerable & operator=(const Enumerable &) = delete; Enumerable(const Enumerable &) = default; // "yielded" by the Enumerable::Iterator. Has a .index, and a // .element referencing the value yielded by the subiterator class IterYield { public: std::size_t index; contained_iter_ret element; IterYield(std::size_t i, contained_iter_ret elem) : index(i), element(elem) { } }; // Holds an iterator of the contained type and a size_t for the // index. Each call to ++ increments both of these data members. // Each dereference returns an IterYield. class Iterator { private: contained_iter_type sub_iter; std::size_t index; public: Iterator (contained_iter_type si) : sub_iter(si), index(0) { } IterYield operator*() const { return IterYield(this->index, *this->sub_iter); } Iterator & operator++() { ++this->sub_iter; ++this->index; return *this; } bool operator!=(const Iterator & other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() const { return Iterator(std::begin(this->container)); } Iterator end() const { return Iterator(std::end(this->container)); } }; // Helper function to instantiate an Enumerable template <typename Container> Enumerable<Container> enumerate(Container && container) { return Enumerable<Container>(std::forward<Container>(container)); } template <typename T> Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> && il) { return Enumerable<std::initializer_list<T>>(il); } } #endif //ifndef ENUMERABLE__H__ <|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. #include "net/base/dnsrr_resolver.h" #if defined(OS_POSIX) #include <resolv.h> #endif #include "base/string_piece.h" #include "base/task.h" #include "base/worker_pool.h" #include "net/base/dns_reload_timer.h" #include "net/base/dns_util.h" #include "net/base/net_errors.h" namespace net { static const uint16 kClassIN = 1; #if defined(OS_POSIX) // A Buffer is used for walking over a DNS packet. class Buffer { public: Buffer(const uint8* p, unsigned len) : p_(p), packet_(p), len_(len), packet_len_(len) { } bool U8(uint8* v) { if (len_ < 1) return false; *v = *p_; p_++; len_--; return true; } bool U16(uint16* v) { if (len_ < 2) return false; *v = static_cast<uint16>(p_[0]) << 8 | static_cast<uint16>(p_[1]); p_ += 2; len_ -= 2; return true; } bool U32(uint32* v) { if (len_ < 4) return false; *v = static_cast<uint32>(p_[0]) << 24 | static_cast<uint32>(p_[1]) << 16 | static_cast<uint32>(p_[2]) << 8 | static_cast<uint32>(p_[3]); p_ += 4; len_ -= 4; return true; } bool Skip(unsigned n) { if (len_ < n) return false; p_ += n; len_ -= n; return true; } bool Block(base::StringPiece* out, unsigned len) { if (len_ < len) return false; *out = base::StringPiece(reinterpret_cast<const char*>(p_), len); p_ += len; len_ -= len; return true; } // DNSName parses a (possibly compressed) DNS name from the packet. If |name| // is not NULL, then the name is written into it. See RFC 1035 section 4.1.4. bool DNSName(std::string* name) { unsigned jumps = 0; const uint8* p = p_; unsigned len = len_; if (name) name->clear(); for (;;) { if (len < 1) return false; uint8 d = *p; p++; len--; // The two couple of bits of the length give the type of the length. It's // either a direct length or a pointer to the remainder of the name. if ((d & 0xc0) == 0xc0) { // This limit matches the depth limit in djbdns. if (jumps > 100) return false; if (len < 1) return false; uint16 offset = static_cast<uint16>(d) << 8 | static_cast<uint16>(p[0]); offset &= 0x3ff; p++; len--; if (jumps == 0) { p_ = p; len_ = len; } jumps++; if (offset >= packet_len_) return false; p = &packet_[offset]; } else if ((d & 0xc0) == 0) { uint8 label_len = d; if (len < label_len) return false; if (name && label_len) { if (!name->empty()) name->append("."); name->append(reinterpret_cast<const char*>(p), label_len); } p += label_len; len -= label_len; if (jumps == 0) { p_ = p; len_ = len; } if (label_len == 0) break; } else { return false; } } return true; } private: const uint8* p_; const uint8* const packet_; unsigned len_; const unsigned packet_len_; }; bool DnsRRResolver::Response::ParseFromResponse(const uint8* p, unsigned len, uint16 rrtype_requested) { name.clear(); ttl = 0; dnssec = false; rrdatas.clear(); signatures.clear(); // RFC 1035 section 4.4.1 uint8 flags2; Buffer buf(p, len); if (!buf.Skip(2) || // skip id !buf.Skip(1) || // skip first flags byte !buf.U8(&flags2)) { return false; } // Bit 5 is the Authenticated Data (AD) bit. See // http://tools.ietf.org/html/rfc2535#section-6.1 if (flags2 & 32) { // AD flag is set. We'll trust it if it came from a local nameserver. // Currently the resolv structure is IPv4 only, so we can't test for IPv6 // loopback addresses. if (_res.nscount == 1 && memcmp(&_res.nsaddr_list[0].sin_addr, "\x7f\x00\x00\x01" /* 127.0.0.1 */, 4) == 0) { dnssec = true; } } uint16 query_count, answer_count, authority_count, additional_count; if (!buf.U16(&query_count) || !buf.U16(&answer_count) || !buf.U16(&authority_count) || !buf.U16(&additional_count)) { return false; } if (query_count != 1) return false; uint16 type, klass; if (!buf.DNSName(NULL) || !buf.U16(&type) || !buf.U16(&klass) || type != rrtype_requested || klass != kClassIN) { return false; } if (answer_count < 1) return false; for (uint32 i = 0; i < answer_count; i++) { std::string* name = NULL; if (i == 0) name = &this->name; uint32 ttl; uint16 rrdata_len; if (!buf.DNSName(name) || !buf.U16(&type) || !buf.U16(&klass) || !buf.U32(&ttl) || !buf.U16(&rrdata_len)) { return false; } base::StringPiece rrdata; if (!buf.Block(&rrdata, rrdata_len)) return false; if (klass == kClassIN && type == rrtype_requested) { if (i == 0) this->ttl = ttl; rrdatas.push_back(std::string(rrdata.data(), rrdata.size())); } else if (klass == kClassIN && type == kDNS_RRSIG) { signatures.push_back(std::string(rrdata.data(), rrdata.size())); } } return true; } class ResolveTask : public Task { public: ResolveTask(const std::string& name, uint16 rrtype, uint16 flags, CompletionCallback* callback, DnsRRResolver::Response* response) : name_(name), rrtype_(rrtype), flags_(flags), callback_(callback), response_(response) { } virtual void Run() { // Runs on a worker thread. if ((_res.options & RES_INIT) == 0) { if (res_ninit(&_res) != 0) return Failure(); } unsigned long saved_options = _res.options; bool r = Do(); #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) if (!r && DnsReloadTimerHasExpired()) { res_nclose(&_res); if (res_ninit(&_res) == 0) r = Do(); } #endif _res.options = saved_options; int error = r ? OK : ERR_NAME_NOT_RESOLVED; callback_->Run(error); } bool Do() { // For DNSSEC, a 4K buffer is suggested static const unsigned kMaxDNSPayload = 4096; #ifndef RES_USE_DNSSEC // Some versions of libresolv don't have support for the DO bit. In this // case, we proceed without it. static const int RES_USE_DNSSEC = 0; #endif // We set the options explicitly. Note that this removes several default // options: RES_DEFNAMES and RES_DNSRCH (see res_init(3)). _res.options = RES_INIT | RES_RECURSE | RES_USE_EDNS0 | RES_USE_DNSSEC; uint8 answer[kMaxDNSPayload]; int len = res_search(name_.c_str(), kClassIN, rrtype_, answer, sizeof(answer)); if (len == -1) return false; return response_->ParseFromResponse(answer, len, rrtype_); } private: DISALLOW_COPY_AND_ASSIGN(ResolveTask); void Failure() { callback_->Run(ERR_NAME_NOT_RESOLVED); } const std::string name_; const uint16 rrtype_; const uint16 flags_; CompletionCallback* const callback_; DnsRRResolver::Response* const response_; }; #else // OS_POSIX // On non-Linux platforms we fail everything for now. class ResolveTask : public Task { public: ResolveTask(const std::string& name, uint16 rrtype, uint16 flags, CompletionCallback* callback, DnsRRResolver::Response* response) : callback_(callback) { } virtual void Run() { callback_->Run(ERR_NAME_NOT_RESOLVED); } private: CompletionCallback* const callback_; DISALLOW_COPY_AND_ASSIGN(ResolveTask); }; #endif // static bool DnsRRResolver::Resolve(const std::string& name, uint16 rrtype, uint16 flags, CompletionCallback* callback, Response* response) { if (!callback || !response || name.empty()) return false; // Don't allow queries of type ANY if (rrtype == kDNS_ANY) return false; ResolveTask* task = new ResolveTask(name, rrtype, flags, callback, response); return WorkerPool::PostTask(FROM_HERE, task, true /* task is slow */); } } // namespace net <commit_msg>Build fix for old glibc (<= 2.5) systems.<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. #include "net/base/dnsrr_resolver.h" #if defined(OS_POSIX) #include <resolv.h> #endif #include "base/string_piece.h" #include "base/task.h" #include "base/worker_pool.h" #include "net/base/dns_reload_timer.h" #include "net/base/dns_util.h" #include "net/base/net_errors.h" namespace net { static const uint16 kClassIN = 1; #if defined(OS_POSIX) // A Buffer is used for walking over a DNS packet. class Buffer { public: Buffer(const uint8* p, unsigned len) : p_(p), packet_(p), len_(len), packet_len_(len) { } bool U8(uint8* v) { if (len_ < 1) return false; *v = *p_; p_++; len_--; return true; } bool U16(uint16* v) { if (len_ < 2) return false; *v = static_cast<uint16>(p_[0]) << 8 | static_cast<uint16>(p_[1]); p_ += 2; len_ -= 2; return true; } bool U32(uint32* v) { if (len_ < 4) return false; *v = static_cast<uint32>(p_[0]) << 24 | static_cast<uint32>(p_[1]) << 16 | static_cast<uint32>(p_[2]) << 8 | static_cast<uint32>(p_[3]); p_ += 4; len_ -= 4; return true; } bool Skip(unsigned n) { if (len_ < n) return false; p_ += n; len_ -= n; return true; } bool Block(base::StringPiece* out, unsigned len) { if (len_ < len) return false; *out = base::StringPiece(reinterpret_cast<const char*>(p_), len); p_ += len; len_ -= len; return true; } // DNSName parses a (possibly compressed) DNS name from the packet. If |name| // is not NULL, then the name is written into it. See RFC 1035 section 4.1.4. bool DNSName(std::string* name) { unsigned jumps = 0; const uint8* p = p_; unsigned len = len_; if (name) name->clear(); for (;;) { if (len < 1) return false; uint8 d = *p; p++; len--; // The two couple of bits of the length give the type of the length. It's // either a direct length or a pointer to the remainder of the name. if ((d & 0xc0) == 0xc0) { // This limit matches the depth limit in djbdns. if (jumps > 100) return false; if (len < 1) return false; uint16 offset = static_cast<uint16>(d) << 8 | static_cast<uint16>(p[0]); offset &= 0x3ff; p++; len--; if (jumps == 0) { p_ = p; len_ = len; } jumps++; if (offset >= packet_len_) return false; p = &packet_[offset]; } else if ((d & 0xc0) == 0) { uint8 label_len = d; if (len < label_len) return false; if (name && label_len) { if (!name->empty()) name->append("."); name->append(reinterpret_cast<const char*>(p), label_len); } p += label_len; len -= label_len; if (jumps == 0) { p_ = p; len_ = len; } if (label_len == 0) break; } else { return false; } } return true; } private: const uint8* p_; const uint8* const packet_; unsigned len_; const unsigned packet_len_; }; bool DnsRRResolver::Response::ParseFromResponse(const uint8* p, unsigned len, uint16 rrtype_requested) { name.clear(); ttl = 0; dnssec = false; rrdatas.clear(); signatures.clear(); // RFC 1035 section 4.4.1 uint8 flags2; Buffer buf(p, len); if (!buf.Skip(2) || // skip id !buf.Skip(1) || // skip first flags byte !buf.U8(&flags2)) { return false; } // Bit 5 is the Authenticated Data (AD) bit. See // http://tools.ietf.org/html/rfc2535#section-6.1 if (flags2 & 32) { // AD flag is set. We'll trust it if it came from a local nameserver. // Currently the resolv structure is IPv4 only, so we can't test for IPv6 // loopback addresses. if (_res.nscount == 1 && memcmp(&_res.nsaddr_list[0].sin_addr, "\x7f\x00\x00\x01" /* 127.0.0.1 */, 4) == 0) { dnssec = true; } } uint16 query_count, answer_count, authority_count, additional_count; if (!buf.U16(&query_count) || !buf.U16(&answer_count) || !buf.U16(&authority_count) || !buf.U16(&additional_count)) { return false; } if (query_count != 1) return false; uint16 type, klass; if (!buf.DNSName(NULL) || !buf.U16(&type) || !buf.U16(&klass) || type != rrtype_requested || klass != kClassIN) { return false; } if (answer_count < 1) return false; for (uint32 i = 0; i < answer_count; i++) { std::string* name = NULL; if (i == 0) name = &this->name; uint32 ttl; uint16 rrdata_len; if (!buf.DNSName(name) || !buf.U16(&type) || !buf.U16(&klass) || !buf.U32(&ttl) || !buf.U16(&rrdata_len)) { return false; } base::StringPiece rrdata; if (!buf.Block(&rrdata, rrdata_len)) return false; if (klass == kClassIN && type == rrtype_requested) { if (i == 0) this->ttl = ttl; rrdatas.push_back(std::string(rrdata.data(), rrdata.size())); } else if (klass == kClassIN && type == kDNS_RRSIG) { signatures.push_back(std::string(rrdata.data(), rrdata.size())); } } return true; } class ResolveTask : public Task { public: ResolveTask(const std::string& name, uint16 rrtype, uint16 flags, CompletionCallback* callback, DnsRRResolver::Response* response) : name_(name), rrtype_(rrtype), flags_(flags), callback_(callback), response_(response) { } virtual void Run() { // Runs on a worker thread. if ((_res.options & RES_INIT) == 0) { if (res_ninit(&_res) != 0) return Failure(); } unsigned long saved_options = _res.options; bool r = Do(); #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) if (!r && DnsReloadTimerHasExpired()) { res_nclose(&_res); if (res_ninit(&_res) == 0) r = Do(); } #endif _res.options = saved_options; int error = r ? OK : ERR_NAME_NOT_RESOLVED; callback_->Run(error); } bool Do() { // For DNSSEC, a 4K buffer is suggested static const unsigned kMaxDNSPayload = 4096; #ifndef RES_USE_DNSSEC // Some versions of libresolv don't have support for the DO bit. In this // case, we proceed without it. static const int RES_USE_DNSSEC = 0; #endif #ifndef RES_USE_EDNS0 // Some versions of glibc are so old that they don't support EDNS0 either. // http://code.google.com/p/chromium/issues/detail?id=51676 static const int RES_USE_EDNS0 = 0; #endif // We set the options explicitly. Note that this removes several default // options: RES_DEFNAMES and RES_DNSRCH (see res_init(3)). _res.options = RES_INIT | RES_RECURSE | RES_USE_EDNS0 | RES_USE_DNSSEC; uint8 answer[kMaxDNSPayload]; int len = res_search(name_.c_str(), kClassIN, rrtype_, answer, sizeof(answer)); if (len == -1) return false; return response_->ParseFromResponse(answer, len, rrtype_); } private: DISALLOW_COPY_AND_ASSIGN(ResolveTask); void Failure() { callback_->Run(ERR_NAME_NOT_RESOLVED); } const std::string name_; const uint16 rrtype_; const uint16 flags_; CompletionCallback* const callback_; DnsRRResolver::Response* const response_; }; #else // OS_POSIX // On non-Linux platforms we fail everything for now. class ResolveTask : public Task { public: ResolveTask(const std::string& name, uint16 rrtype, uint16 flags, CompletionCallback* callback, DnsRRResolver::Response* response) : callback_(callback) { } virtual void Run() { callback_->Run(ERR_NAME_NOT_RESOLVED); } private: CompletionCallback* const callback_; DISALLOW_COPY_AND_ASSIGN(ResolveTask); }; #endif // static bool DnsRRResolver::Resolve(const std::string& name, uint16 rrtype, uint16 flags, CompletionCallback* callback, Response* response) { if (!callback || !response || name.empty()) return false; // Don't allow queries of type ANY if (rrtype == kDNS_ANY) return false; ResolveTask* task = new ResolveTask(name, rrtype, flags, callback, response); return WorkerPool::PostTask(FROM_HERE, task, true /* task is slow */); } } // namespace net <|endoftext|>
<commit_before>// Time: O(n * n!) // Space: O(n) // Time: O(n * n!) // Space: O(n) class Solution { public: vector<string> generatePalindromes(string s) { if (s.empty()) { return {}; } unordered_map<char, int> cnt; for (const auto& c : s) { ++cnt[c]; } string mid, chars; for (const auto& kvp : cnt) { if (kvp.second % 2) { if (mid.empty()) { mid.append(1, kvp.first); } else { // The count of the middle char is at most one. return {}; } } chars.append(kvp.second / 2, kvp.first); } return permuteUnique(mid, chars); } vector<string> permuteUnique(const string& mid, string& s) { vector<string> result; vector<bool> used(s.length(), false); string ans; sort(s.begin(), s.end()); permuteUniqueRecu(mid, s, &used, &ans, &result); return result; } void permuteUniqueRecu(const string& mid, const string& s, vector<bool> *used, string *ans, vector<string> *result) { if (ans->length() == s.length()) { string reverse_ans(ans->crbegin(), ans->crend()); result->emplace_back(*ans + mid + reverse_ans); return; } for (int i = 0; i < s.length(); ++i) { if (!(*used)[i] && !(i != 0 && s[i - 1] == s[i] && (*used)[i - 1])) { (*used)[i] = true; ans->push_back(s[i]); permuteUniqueRecu(mid, s, used, ans, result); ans->pop_back(); (*used)[i] = false; } } } }; class Solution2 { public: vector<string> generatePalindromes(string s) { if (s.empty()) { return {}; } unordered_map<char, int> cnt; for (const auto& c : s) { ++cnt[c]; } string mid, chars; for (const auto& kvp : cnt) { if (kvp.second % 2) { if (mid.empty()) { mid.push_back(kvp.first); } else { // The count of the middle char is at most one. return {}; } } chars.append(kvp.second / 2, kvp.first); } vector<string> result; sort(chars.begin(), chars.end()); do { string reverse_chars(chars.crbegin(), chars.crend()); result.emplace_back(chars + mid + reverse_chars); } while (next_permutation(chars.begin(), chars.end())); return result; } }; <commit_msg>Update palindrome-permutation-ii.cpp<commit_after>// Time: O(n * n!) // Space: O(n) class Solution { public: vector<string> generatePalindromes(string s) { if (s.empty()) { return {}; } unordered_map<char, int> cnt; for (const auto& c : s) { ++cnt[c]; } string mid, chars; for (const auto& kvp : cnt) { if (kvp.second % 2) { if (mid.empty()) { mid.append(1, kvp.first); } else { // The count of the middle char is at most one. return {}; } } chars.append(kvp.second / 2, kvp.first); } return permuteUnique(mid, chars); } vector<string> permuteUnique(const string& mid, string& s) { vector<string> result; vector<bool> used(s.length(), false); string ans; sort(s.begin(), s.end()); permuteUniqueRecu(mid, s, &used, &ans, &result); return result; } void permuteUniqueRecu(const string& mid, const string& s, vector<bool> *used, string *ans, vector<string> *result) { if (ans->length() == s.length()) { string reverse_ans(ans->crbegin(), ans->crend()); result->emplace_back(*ans + mid + reverse_ans); return; } for (int i = 0; i < s.length(); ++i) { if (!(*used)[i] && !(i != 0 && s[i - 1] == s[i] && (*used)[i - 1])) { (*used)[i] = true; ans->push_back(s[i]); permuteUniqueRecu(mid, s, used, ans, result); ans->pop_back(); (*used)[i] = false; } } } }; class Solution2 { public: vector<string> generatePalindromes(string s) { if (s.empty()) { return {}; } unordered_map<char, int> cnt; for (const auto& c : s) { ++cnt[c]; } string mid, chars; for (const auto& kvp : cnt) { if (kvp.second % 2) { if (mid.empty()) { mid.push_back(kvp.first); } else { // The count of the middle char is at most one. return {}; } } chars.append(kvp.second / 2, kvp.first); } vector<string> result; sort(chars.begin(), chars.end()); do { string reverse_chars(chars.crbegin(), chars.crend()); result.emplace_back(chars + mid + reverse_chars); } while (next_permutation(chars.begin(), chars.end())); return result; } }; <|endoftext|>
<commit_before>#include <ctime> #include <sstream> #include <filesystem> namespace filesystem = std::experimental::filesystem::v1; #include <fmt/format.h> #include <GLFW/glfw3.h> #include "Common/Platform.hpp" #include "Debug/Log.hpp" #include "xdCore.hpp" #include "XMLResource.hpp" XDAY_API xdCore Core; static void error_callback(int error, const char* description) { Msg("GLFW Error: Code: {}, Means: {}", error, description); } bool xdCore::isGlobalDebug() { #ifdef DEBUG return true; #else return false; #endif } xdCore::xdCore() { EngineName = "X-Day Engine"; EngineVersion = "1.0"; CalculateBuildId(); } void xdCore::InitializeArguments(int argc, char* argv[]) { std::vector<std::string> args; for (int i = 0; i < argc; ++i) { args.push_back(argv[i]); } Params = move(args); for (auto&& str : Core.Params) { ParamsString += str + " "; } ParamsString.pop_back(); // remove the last " " } void xdCore::Initialize(std::string&& _appname) { Msg("{} {} (build {})", EngineName, EngineVersion, buildId); Log("Core: Initializing", false); FindParam("--p_name") ? AppName = ReturnParam("--p_name") : AppName = _appname; FindParam("--p_game") ? GameModule = ReturnParam("--p_game") : GameModule = "xdGame"; AppPath = filesystem::absolute(Params.front()); WorkPath = filesystem::current_path(); BinPath = WorkPath.string() + "/bin/"; FindParam("--p_datapath") ? DataPath = ReturnParam("--p_datapath") : DataPath = WorkPath.string() + "/appdata/"; FindParam("--p_respath") ? ResourcesPath = ReturnParam("--p_respath") : ResourcesPath = WorkPath.string() + "/resources/"; LogsPath = DataPath.string() + "/logs/"; SavesPath = DataPath.string() + "/saves/"; InitializeResources(); CreateDirIfNotExist(DataPath); CreateDirIfNotExist(LogsPath); CreateDirIfNotExist(SavesPath); CreateDirIfNotExist(ResourcesPath); CreateDirIfNotExist(ArchivesPath); CreateDirIfNotExist(ConfigsPath); CreateDirIfNotExist(ModelsPath); CreateDirIfNotExist(SoundsPath); CreateDirIfNotExist(TexturesPath); buildString = fmt::format("{} build {}, {}, {}", GetModuleName("xdCore"), buildId, buildDate, buildTime); GLFWVersionString = fmt::format("GLFW {}", glfwGetVersionString()); glfwSetErrorCallback(error_callback); Log("Core: Initialized", false); GlobalLog->InitLog(); } void xdCore::InitializeResources() { ArchivesPath = ResourcesPath.string() + "/archives/"; ConfigsPath = ResourcesPath.string() + "/configs/"; ModelsPath = ResourcesPath.string() + "/models/"; SoundsPath = ResourcesPath.string() + "/sounds/"; TexturesPath = ResourcesPath.string() + "/textures/"; xdXMLResource resource_initializer(Core.ResourcesPath, "resources.xml"); if (!resource_initializer.isErrored()) resource_initializer.ParseResources(); } // Finds command line parameters and returns true if param exists bool xdCore::FindParam(std::string&& Param) const { if (ParamsString.find(Param) != std::string::npos) return true; return false; } // Finds command line parameter and returns it's value. // If parameter isn't found it returns empty string. // Do not use ReturnParam() if FindParam() returns false // else you will get an unexpected behavior std::string xdCore::ReturnParam(std::string&& Param) const { bool found = false; for (auto i : Params) { if (found && i.find("--p_") != std::string::npos) { Msg("xdCore::ReturnParam: wrong construction \"{0} {1}\" used instead of \"{0} *value* {1}\"", Param, i); break; } if (found) return i; if (i.find(Param) == std::string::npos) continue; found = true; } Msg("xdCore::ReturnParam: returning empty string for param {}", Param); return ""; } void xdCore::CreateDirIfNotExist(const filesystem::path& p) const { if (!filesystem::exists(p)) filesystem::create_directory(p); } // Returns given module name with configuration and architecture const std::string xdCore::GetModuleName(std::string&& xdModule) { #ifdef DEBUG #ifdef XD_X64 return xdModule + "_Dx64"; #else return xdModule + "_Dx86"; #endif #elif NDEBUG #ifdef XD_X64 return xdModule + "_Rx64"; #else return xdModule + "_Rx86"; #endif #endif } void xdCore::CalculateBuildId() { // All started in ~01.01.2017 std::tm startDate_tm; { // Start date and time startDate_tm.tm_mday = 1; startDate_tm.tm_mon = 0; startDate_tm.tm_year = 2017 - 1900; startDate_tm.tm_hour = 12; //random hour(don't remember exact hour) startDate_tm.tm_min = 0; startDate_tm.tm_sec = 0; } std::tm buildDate_tm; { // Build date std::string stringMonth; std::istringstream buffer(buildDate); buffer >> stringMonth >> buildDate_tm.tm_mday >> buildDate_tm.tm_year; buildDate_tm.tm_year -= 1900; const char* monthId[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; for (int i = 0; i < 12; i++) { if (stringMonth.compare(monthId[i])) continue; buildDate_tm.tm_mon = i; break; } } { // Build time std::string timeBuffer(buildTime); std::replace(timeBuffer.begin(), timeBuffer.end(), ':', ' '); // Costyl (TM) std::istringstream buffer2(timeBuffer); buffer2 >> buildDate_tm.tm_hour >> buildDate_tm.tm_min >> buildDate_tm.tm_sec; } buildId = -difftime(std::mktime(&startDate_tm), std::mktime(&buildDate_tm)) / 86400; } <commit_msg>Optimize InitializeArguments()<commit_after>#include <ctime> #include <sstream> #include <filesystem> namespace filesystem = std::experimental::filesystem::v1; #include <fmt/format.h> #include <GLFW/glfw3.h> #include "Common/Platform.hpp" #include "Debug/Log.hpp" #include "xdCore.hpp" #include "XMLResource.hpp" XDAY_API xdCore Core; static void error_callback(int error, const char* description) { Msg("GLFW Error: Code: {}, Means: {}", error, description); } bool xdCore::isGlobalDebug() { #ifdef DEBUG return true; #else return false; #endif } xdCore::xdCore() { EngineName = "X-Day Engine"; EngineVersion = "1.0"; CalculateBuildId(); } void xdCore::InitializeArguments(int argc, char* argv[]) { for (int i = 0; i < argc; ++i) { Params.push_back(argv[i]); } for (auto&& str : Core.Params) { ParamsString += str + " "; } ParamsString.pop_back(); // remove the last " " } void xdCore::Initialize(std::string&& _appname) { Msg("{} {} (build {})", EngineName, EngineVersion, buildId); Log("Core: Initializing", false); FindParam("--p_name") ? AppName = ReturnParam("--p_name") : AppName = _appname; FindParam("--p_game") ? GameModule = ReturnParam("--p_game") : GameModule = "xdGame"; AppPath = filesystem::absolute(Params.front()); WorkPath = filesystem::current_path(); BinPath = WorkPath.string() + "/bin/"; FindParam("--p_datapath") ? DataPath = ReturnParam("--p_datapath") : DataPath = WorkPath.string() + "/appdata/"; FindParam("--p_respath") ? ResourcesPath = ReturnParam("--p_respath") : ResourcesPath = WorkPath.string() + "/resources/"; LogsPath = DataPath.string() + "/logs/"; SavesPath = DataPath.string() + "/saves/"; InitializeResources(); CreateDirIfNotExist(DataPath); CreateDirIfNotExist(LogsPath); CreateDirIfNotExist(SavesPath); CreateDirIfNotExist(ResourcesPath); CreateDirIfNotExist(ArchivesPath); CreateDirIfNotExist(ConfigsPath); CreateDirIfNotExist(ModelsPath); CreateDirIfNotExist(SoundsPath); CreateDirIfNotExist(TexturesPath); buildString = fmt::format("{} build {}, {}, {}", GetModuleName("xdCore"), buildId, buildDate, buildTime); GLFWVersionString = fmt::format("GLFW {}", glfwGetVersionString()); glfwSetErrorCallback(error_callback); Log("Core: Initialized", false); GlobalLog->InitLog(); } void xdCore::InitializeResources() { ArchivesPath = ResourcesPath.string() + "/archives/"; ConfigsPath = ResourcesPath.string() + "/configs/"; ModelsPath = ResourcesPath.string() + "/models/"; SoundsPath = ResourcesPath.string() + "/sounds/"; TexturesPath = ResourcesPath.string() + "/textures/"; xdXMLResource resource_initializer(Core.ResourcesPath, "resources.xml"); if (!resource_initializer.isErrored()) resource_initializer.ParseResources(); } // Finds command line parameters and returns true if param exists bool xdCore::FindParam(std::string&& Param) const { if (ParamsString.find(Param) != std::string::npos) return true; return false; } // Finds command line parameter and returns it's value. // If parameter isn't found it returns empty string. // Do not use ReturnParam() if FindParam() returns false // else you will get an unexpected behavior std::string xdCore::ReturnParam(std::string&& Param) const { bool found = false; for (auto i : Params) { if (found && i.find("--p_") != std::string::npos) { Msg("xdCore::ReturnParam: wrong construction \"{0} {1}\" used instead of \"{0} *value* {1}\"", Param, i); break; } if (found) return i; if (i.find(Param) == std::string::npos) continue; found = true; } Msg("xdCore::ReturnParam: returning empty string for param {}", Param); return ""; } void xdCore::CreateDirIfNotExist(const filesystem::path& p) const { if (!filesystem::exists(p)) filesystem::create_directory(p); } // Returns given module name with configuration and architecture const std::string xdCore::GetModuleName(std::string&& xdModule) { #ifdef DEBUG #ifdef XD_X64 return xdModule + "_Dx64"; #else return xdModule + "_Dx86"; #endif #elif NDEBUG #ifdef XD_X64 return xdModule + "_Rx64"; #else return xdModule + "_Rx86"; #endif #endif } void xdCore::CalculateBuildId() { // All started in ~01.01.2017 std::tm startDate_tm; { // Start date and time startDate_tm.tm_mday = 1; startDate_tm.tm_mon = 0; startDate_tm.tm_year = 2017 - 1900; startDate_tm.tm_hour = 12; //random hour(don't remember exact hour) startDate_tm.tm_min = 0; startDate_tm.tm_sec = 0; } std::tm buildDate_tm; { // Build date std::string stringMonth; std::istringstream buffer(buildDate); buffer >> stringMonth >> buildDate_tm.tm_mday >> buildDate_tm.tm_year; buildDate_tm.tm_year -= 1900; const char* monthId[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; for (int i = 0; i < 12; i++) { if (stringMonth.compare(monthId[i])) continue; buildDate_tm.tm_mon = i; break; } } { // Build time std::string timeBuffer(buildTime); std::replace(timeBuffer.begin(), timeBuffer.end(), ':', ' '); // Costyl (TM) std::istringstream buffer2(timeBuffer); buffer2 >> buildDate_tm.tm_hour >> buildDate_tm.tm_min >> buildDate_tm.tm_sec; } buildId = -difftime(std::mktime(&startDate_tm), std::mktime(&buildDate_tm)) / 86400; } <|endoftext|>
<commit_before>/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdHistogramModel.h" /*****************************************************************************/ /* INCLUDE SECTION */ // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) #include "mvdVectorImageModel.h" namespace mvd { /* TRANSLATOR mvd::HistogramModel Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*****************************************************************************/ /* CLASS IMPLEMENTATION SECTION */ /*******************************************************************************/ HistogramModel ::HistogramModel( QObject* parent ) : AbstractModel( parent ), m_Histograms(), m_MinPixel(), m_MaxPixel() { } /*******************************************************************************/ HistogramModel ::~HistogramModel() { } /*******************************************************************************/ double HistogramModel ::Percentile( CountType band, MeasurementType intensity, Bound bound ) const { // Get histogram of band. Histogram::Pointer histogram( m_Histograms->GetNthElement( band ) ); // Contruct 1D measurement vector. Histogram::MeasurementVectorType measurement( 1 ); measurement[ 0 ] = intensity; // Due to float/double conversion, it can happen // that the minimum or maximum value go slightly outside the histogram // Clamping the value solves the issue and avoid RangeError measurement[0] = itk::NumericTraits<MeasurementType>::Clamp( measurement[0], histogram->GetBinMin(0, 0), histogram->GetBinMax(0, histogram->GetSize(0) - 1) ); // Get the index of measurement in 1D-histogram. Histogram::IndexType index; if( !histogram->GetIndex( measurement, index ) ) throw itk::RangeError( __FILE__, __LINE__ ); assert( Histogram::IndexType::GetIndexDimension()==1 ); // Min/max intensities of bin. MeasurementType minI = histogram->GetBinMin( 0, index[ 0 ] ); MeasurementType maxI = histogram->GetBinMax( 0, index[ 0 ] ); // Min/max frequencies of Histogram::FrequencyType frequency( histogram->GetFrequency( index ) ); // Initialize result. double percent = frequency * ( intensity - minI ) / ( maxI - minI ); // Number of bins of histogram. Histogram::SizeType::SizeValueType binCount = histogram->Size(); // Initialize bound indices. assert( index[ 0 ]>=0 ); Histogram::SizeType::SizeValueType index0 = index[ 0 ]; Histogram::SizeType::SizeValueType i0 = 0; Histogram::SizeType::SizeValueType iN = binCount; switch( bound ) { case BOUND_LOWER: i0 = 0; iN = index[ 0 ]; break; case BOUND_UPPER: i0 = index0 < binCount ? index0 + 1 : binCount; iN = binCount; break; default: assert( false && "Implement case statement of switch instruction." ); break; }; // Traverse lower/upper bound. Histogram::SizeType::SizeValueType i; for( i=i0; i<iN; ++i ) percent += histogram->GetFrequency( i, 0 ); // Calculate frequency rate. percent /= histogram->GetTotalFrequency(); // Return frequency rate. return percent; } /*******************************************************************************/ void HistogramModel ::virtual_BuildModel( void* context ) { // template_BuildModel_I< VectorImageModel::SourceImageType >(); template_BuildModel_M< VectorImageModel >(); // template_BuildModel< otb::Image< FixedArray< double, 4 >, 2 > >(); // template_BuildModel< otb::Image< itk::FixedArray< float, 4 >, 2 > >(); /* template_BuildModel< otb::VectorImage< float, 2 > >(); template_BuildModel< otb::Image< float, 2 > >(); */ } /*******************************************************************************/ /* SLOTS */ /*******************************************************************************/ /*******************************************************************************/ } // end namespace 'mvd' <commit_msg>BUG: fix percentile computation for BOUND_UPPER mode<commit_after>/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdHistogramModel.h" /*****************************************************************************/ /* INCLUDE SECTION */ // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) #include "mvdVectorImageModel.h" namespace mvd { /* TRANSLATOR mvd::HistogramModel Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*****************************************************************************/ /* CLASS IMPLEMENTATION SECTION */ /*******************************************************************************/ HistogramModel ::HistogramModel( QObject* parent ) : AbstractModel( parent ), m_Histograms(), m_MinPixel(), m_MaxPixel() { } /*******************************************************************************/ HistogramModel ::~HistogramModel() { } /*******************************************************************************/ double HistogramModel ::Percentile( CountType band, MeasurementType intensity, Bound bound ) const { // Get histogram of band. Histogram::Pointer histogram( m_Histograms->GetNthElement( band ) ); // Contruct 1D measurement vector. Histogram::MeasurementVectorType measurement( 1 ); measurement[ 0 ] = intensity; // Due to float/double conversion, it can happen // that the minimum or maximum value go slightly outside the histogram // Clamping the value solves the issue and avoid RangeError measurement[0] = itk::NumericTraits<MeasurementType>::Clamp( measurement[0], histogram->GetBinMin(0, 0), histogram->GetBinMax(0, histogram->GetSize(0) - 1) ); // Get the index of measurement in 1D-histogram. Histogram::IndexType index; if( !histogram->GetIndex( measurement, index ) ) throw itk::RangeError( __FILE__, __LINE__ ); assert( Histogram::IndexType::GetIndexDimension()==1 ); // Min/max intensities of bin. MeasurementType minI = histogram->GetBinMin( 0, index[ 0 ] ); MeasurementType maxI = histogram->GetBinMax( 0, index[ 0 ] ); // Frequency of current bin Histogram::FrequencyType frequency( histogram->GetFrequency( index ) ); // Initialize result (contribution of current bin) double percent = frequency * ( intensity - (bound == BOUND_LOWER ? minI : maxI) ) / ( maxI - minI ); // Number of bins of histogram. Histogram::SizeType::SizeValueType binCount = histogram->Size(); // Initialize bound indices. assert( index[ 0 ]>=0 ); Histogram::SizeType::SizeValueType index0 = index[ 0 ]; Histogram::SizeType::SizeValueType i0 = 0; Histogram::SizeType::SizeValueType iN = binCount; switch( bound ) { case BOUND_LOWER: i0 = 0; iN = index[ 0 ]; break; case BOUND_UPPER: i0 = index0 < binCount ? index0 + 1 : binCount; iN = binCount; break; default: assert( false && "Implement case statement of switch instruction." ); break; }; // Traverse lower/upper bound (contribution of other bins) Histogram::SizeType::SizeValueType i; for( i=i0; i<iN; ++i ) percent += histogram->GetFrequency( i, 0 ); // Calculate frequency rate. percent /= histogram->GetTotalFrequency(); // Return frequency rate. return percent; } /*******************************************************************************/ void HistogramModel ::virtual_BuildModel( void* context ) { // template_BuildModel_I< VectorImageModel::SourceImageType >(); template_BuildModel_M< VectorImageModel >(); // template_BuildModel< otb::Image< FixedArray< double, 4 >, 2 > >(); // template_BuildModel< otb::Image< itk::FixedArray< float, 4 >, 2 > >(); /* template_BuildModel< otb::VectorImage< float, 2 > >(); template_BuildModel< otb::Image< float, 2 > >(); */ } /*******************************************************************************/ /* SLOTS */ /*******************************************************************************/ /*******************************************************************************/ } // end namespace 'mvd' <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "config.h" #ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS # define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 0 #endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_DEBUG_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_DEBUG_LOGGING 0 #endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 0 #endif #include <string> #include <vector> #include <map> #include <random> #include <fstream> #include <limits> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/float_cmp.hh> # include <dune/common/fvector.hh> # include <dune/common/fmatrix.hh> # include <dune/common/parallel/mpihelper.hh> # if HAVE_DUNE_FEM # include <dune/fem/misc/mpimanager.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/test/gtest/gtest.h> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/timedlogging.hh> #include <dune/stuff/common/convergence-study.hh> #include "common.hh" #if HAVE_TBB # include <thread> # include <tbb/task_scheduler_init.h> #endif class DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!") errors_are_not_as_expected : public Dune::Exception {}; std::vector< double > DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!") truncate_vector(const std::vector< double >& in, const size_t size) { assert(size <= in.size()); if (size == in.size()) return in; else { std::vector< double > ret(size); for (size_t ii = 0; ii < size; ++ii) ret[ii] = in[ii]; return ret; } } // ... truncate_vector(...) int main(int argc, char** argv) { #if DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS try { #endif testing::InitGoogleTest(&argc, argv); DSC_CONFIG.read_options(argc, argv); #if HAVE_DUNE_FEM Dune::Fem::MPIManager::initialize(argc, argv); #else Dune::MPIHelper::instance(argc, argv); #endif DSC::Logger().create( #if DUNE_STUFF_TEST_MAIN_ENABLE_DEBUG_LOGGING DSC::LOG_CONSOLE | DSC::LOG_INFO | DSC::LOG_DEBUG | DSC::LOG_ERROR #elif DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING DSC::LOG_CONSOLE | DSC::LOG_INFO | DSC::LOG_ERROR #else DSC::LOG_CONSOLE | DSC::LOG_ERROR #endif , "", "", ""); DSC::TimedLogger().create( #if DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING std::numeric_limits< ssize_t >::max(), #else -1, #endif #if DUNE_STUFF_TEST_MAIN_ENABLE_DEBUG_LOGGING std::numeric_limits< ssize_t >::max() #else -1 #endif ); #if HAVE_TBB tbb::task_scheduler_init tbb_init(DSC_CONFIG_GET("threading.max_count", 1)); #endif return RUN_ALL_TESTS(); #if DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS } catch (Dune::Exception& e) { std::cerr << "\nDune reported error: " << e.what() << std::endl; std::abort(); } catch (std::exception& e) { std::cerr << "\n" << e.what() << std::endl; std::abort(); } catch (...) { std::cerr << "Unknown exception thrown!" << std::endl; std::abort(); } // try #endif // DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS } // ... main(...) <commit_msg>[test.main] allow to toggle logging and timedlogging independently<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "config.h" #ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS # define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 0 #endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_DEBUG_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_DEBUG_LOGGING 0 #endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 0 #endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_TIMED_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_TIMED_LOGGING 0 #endif #include <string> #include <vector> #include <map> #include <random> #include <fstream> #include <limits> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/float_cmp.hh> # include <dune/common/fvector.hh> # include <dune/common/fmatrix.hh> # include <dune/common/parallel/mpihelper.hh> # if HAVE_DUNE_FEM # include <dune/fem/misc/mpimanager.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/test/gtest/gtest.h> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/timedlogging.hh> #include <dune/stuff/common/convergence-study.hh> #include "common.hh" #if HAVE_TBB # include <thread> # include <tbb/task_scheduler_init.h> #endif class DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!") errors_are_not_as_expected : public Dune::Exception {}; std::vector< double > DUNE_DEPRECATED_MSG("Use the expectation macros of the gtest test suite (20.08.2014)!") truncate_vector(const std::vector< double >& in, const size_t size) { assert(size <= in.size()); if (size == in.size()) return in; else { std::vector< double > ret(size); for (size_t ii = 0; ii < size; ++ii) ret[ii] = in[ii]; return ret; } } // ... truncate_vector(...) int main(int argc, char** argv) { #if DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS try { #endif testing::InitGoogleTest(&argc, argv); DSC_CONFIG.read_options(argc, argv); #if HAVE_DUNE_FEM Dune::Fem::MPIManager::initialize(argc, argv); #else Dune::MPIHelper::instance(argc, argv); #endif DSC::Logger().create( #if DUNE_STUFF_TEST_MAIN_ENABLE_DEBUG_LOGGING DSC::LOG_CONSOLE | DSC::LOG_INFO | DSC::LOG_DEBUG | DSC::LOG_ERROR #elif DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING DSC::LOG_CONSOLE | DSC::LOG_INFO | DSC::LOG_ERROR #else DSC::LOG_CONSOLE | DSC::LOG_ERROR #endif , "", "", ""); DSC::TimedLogger().create( #if DUNE_STUFF_TEST_MAIN_ENABLE_TIMED_LOGGING && DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING std::numeric_limits< ssize_t >::max(), #else -1, #endif #if DUNE_STUFF_TEST_MAIN_ENABLE_TIMED_LOGGING && DUNE_STUFF_TEST_MAIN_ENABLE_DEBUG_LOGGING std::numeric_limits< ssize_t >::max() #else -1 #endif ); #if HAVE_TBB tbb::task_scheduler_init tbb_init(DSC_CONFIG_GET("threading.max_count", 1)); #endif return RUN_ALL_TESTS(); #if DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS } catch (Dune::Exception& e) { std::cerr << "\nDune reported error: " << e.what() << std::endl; std::abort(); } catch (std::exception& e) { std::cerr << "\n" << e.what() << std::endl; std::abort(); } catch (...) { std::cerr << "Unknown exception thrown!" << std::endl; std::abort(); } // try #endif // DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS } // ... main(...) <|endoftext|>
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #include <stdexcept> #include "VorbisClip.hpp" #include "Audio.hpp" #include "mixer/Data.hpp" #include "mixer/Stream.hpp" #include "utils/Utils.hpp" #if defined(_MSC_VER) # pragma warning( push ) # pragma warning( disable : 4100 ) # pragma warning( disable : 4244 ) # pragma warning( disable : 4245 ) # pragma warning( disable : 4456 ) # pragma warning( disable : 4457 ) #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wcomma" # pragma GCC diagnostic ignored "-Wconditional-uninitialized" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wsign-conversion" # pragma GCC diagnostic ignored "-Wunused-parameter" #endif #include "stb_vorbis.c" #if defined(_MSC_VER) # pragma warning( pop ) #elif defined(__GNUC__) # pragma GCC diagnostic pop #endif namespace ouzel { namespace audio { class VorbisData; class VorbisStream final: public mixer::Stream { public: VorbisStream(VorbisData& vorbisData); ~VorbisStream() { if (vorbisStream) stb_vorbis_close(vorbisStream); } void reset() final { stb_vorbis_seek_start(vorbisStream); } void getSamples(uint32_t frames, std::vector<float>& samples) final; private: stb_vorbis* vorbisStream = nullptr; }; class VorbisData final: public mixer::Data { public: VorbisData(const std::vector<uint8_t>& initData): data(initData) { stb_vorbis* vorbisStream = stb_vorbis_open_memory(data.data(), static_cast<int>(data.size()), nullptr, nullptr); if (!vorbisStream) throw std::runtime_error("Failed to load Vorbis stream"); stb_vorbis_info info = stb_vorbis_get_info(vorbisStream); channels = static_cast<uint16_t>(info.channels); sampleRate = info.sample_rate; stb_vorbis_close(vorbisStream); } auto& getData() const noexcept { return data; } std::unique_ptr<mixer::Stream> createStream() final { return std::make_unique<VorbisStream>(*this); } private: std::vector<uint8_t> data; }; VorbisStream::VorbisStream(VorbisData& vorbisData): Stream(vorbisData) { vorbisStream = stb_vorbis_open_memory(vorbisData.getData().data(), static_cast<int>(vorbisData.getData().size()), nullptr, nullptr); } void VorbisStream::getSamples(uint32_t frames, std::vector<float>& samples) { uint32_t neededSize = frames * data.getChannels(); samples.resize(neededSize); int resultFrames = 0; if (neededSize > 0) { if (vorbisStream->eof) reset(); std::vector<float*> channelData(data.getChannels()); switch (data.getChannels()) { case 1: channelData[0] = &samples[0]; break; case 2: channelData[0] = &samples[0 * frames]; channelData[1] = &samples[1 * frames]; break; case 4: channelData[0] = &samples[0 * frames]; channelData[1] = &samples[1 * frames]; channelData[2] = &samples[2 * frames]; channelData[3] = &samples[3 * frames]; break; case 6: channelData[0] = &samples[0 * frames]; channelData[1] = &samples[2 * frames]; channelData[2] = &samples[1 * frames]; channelData[3] = &samples[4 * frames]; channelData[4] = &samples[5 * frames]; channelData[5] = &samples[3 * frames]; break; default: throw std::runtime_error("Unsupported channel count"); } resultFrames = stb_vorbis_get_samples_float(vorbisStream, data.getChannels(), channelData.data(), static_cast<int>(frames)); } if (vorbisStream->eof) { playing = false; // TODO: fire event reset(); } for (uint32_t channel = 0; channel < data.getChannels(); ++channel) for (uint32_t frame = static_cast<uint32_t>(resultFrames); frame < frames; ++frame) samples[channel * frames + frame] = 0.0F; } VorbisClip::VorbisClip(Audio& initAudio, const std::vector<uint8_t>& initData): Sound(initAudio, initAudio.initData(std::unique_ptr<mixer::Data>(data = new VorbisData(initData))), Sound::Format::Vorbis) { } } // namespace audio } // namespace ouzel <commit_msg>Disable more warnings for stb_vorbis.c<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #include <stdexcept> #include "VorbisClip.hpp" #include "Audio.hpp" #include "mixer/Data.hpp" #include "mixer/Stream.hpp" #include "utils/Utils.hpp" #if defined(_MSC_VER) # pragma warning( push ) # pragma warning( disable : 4100 ) # pragma warning( disable : 4244 ) # pragma warning( disable : 4245 ) # pragma warning( disable : 4456 ) # pragma warning( disable : 4457 ) #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wcomma" # pragma GCC diagnostic ignored "-Wconditional-uninitialized" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wsign-conversion" # pragma GCC diagnostic ignored "-Wtype-limits" # pragma GCC diagnostic ignored "-Wunused-function" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wunused-value" #endif #include "stb_vorbis.c" #if defined(_MSC_VER) # pragma warning( pop ) #elif defined(__GNUC__) # pragma GCC diagnostic pop #endif namespace ouzel { namespace audio { class VorbisData; class VorbisStream final: public mixer::Stream { public: VorbisStream(VorbisData& vorbisData); ~VorbisStream() { if (vorbisStream) stb_vorbis_close(vorbisStream); } void reset() final { stb_vorbis_seek_start(vorbisStream); } void getSamples(uint32_t frames, std::vector<float>& samples) final; private: stb_vorbis* vorbisStream = nullptr; }; class VorbisData final: public mixer::Data { public: VorbisData(const std::vector<uint8_t>& initData): data(initData) { stb_vorbis* vorbisStream = stb_vorbis_open_memory(data.data(), static_cast<int>(data.size()), nullptr, nullptr); if (!vorbisStream) throw std::runtime_error("Failed to load Vorbis stream"); stb_vorbis_info info = stb_vorbis_get_info(vorbisStream); channels = static_cast<uint16_t>(info.channels); sampleRate = info.sample_rate; stb_vorbis_close(vorbisStream); } auto& getData() const noexcept { return data; } std::unique_ptr<mixer::Stream> createStream() final { return std::make_unique<VorbisStream>(*this); } private: std::vector<uint8_t> data; }; VorbisStream::VorbisStream(VorbisData& vorbisData): Stream(vorbisData) { vorbisStream = stb_vorbis_open_memory(vorbisData.getData().data(), static_cast<int>(vorbisData.getData().size()), nullptr, nullptr); } void VorbisStream::getSamples(uint32_t frames, std::vector<float>& samples) { uint32_t neededSize = frames * data.getChannels(); samples.resize(neededSize); int resultFrames = 0; if (neededSize > 0) { if (vorbisStream->eof) reset(); std::vector<float*> channelData(data.getChannels()); switch (data.getChannels()) { case 1: channelData[0] = &samples[0]; break; case 2: channelData[0] = &samples[0 * frames]; channelData[1] = &samples[1 * frames]; break; case 4: channelData[0] = &samples[0 * frames]; channelData[1] = &samples[1 * frames]; channelData[2] = &samples[2 * frames]; channelData[3] = &samples[3 * frames]; break; case 6: channelData[0] = &samples[0 * frames]; channelData[1] = &samples[2 * frames]; channelData[2] = &samples[1 * frames]; channelData[3] = &samples[4 * frames]; channelData[4] = &samples[5 * frames]; channelData[5] = &samples[3 * frames]; break; default: throw std::runtime_error("Unsupported channel count"); } resultFrames = stb_vorbis_get_samples_float(vorbisStream, data.getChannels(), channelData.data(), static_cast<int>(frames)); } if (vorbisStream->eof) { playing = false; // TODO: fire event reset(); } for (uint32_t channel = 0; channel < data.getChannels(); ++channel) for (uint32_t frame = static_cast<uint32_t>(resultFrames); frame < frames; ++frame) samples[channel * frames + frame] = 0.0F; } VorbisClip::VorbisClip(Audio& initAudio, const std::vector<uint8_t>& initData): Sound(initAudio, initAudio.initData(std::unique_ptr<mixer::Data>(data = new VorbisData(initData))), Sound::Format::Vorbis) { } } // namespace audio } // namespace ouzel <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/renderer_font_platform_win.h" #include <dwrite.h> #include <string> #include <vector> #include <wrl/implements.h> #include <wrl/wrappers/corewrappers.h> #include "base/debug/alias.h" #include "base/debug/crash_logging.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/files/memory_mapped_file.h" #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/win/iat_patch_function.h" #include "base/win/registry.h" #include "base/win/scoped_comptr.h" namespace { namespace mswr = Microsoft::WRL; namespace mswrw = Microsoft::WRL::Wrappers; static const char kFontKeyName[] = "font_key_name"; class FontCollectionLoader : public mswr::RuntimeClass<mswr::RuntimeClassFlags<mswr::ClassicCom>, IDWriteFontCollectionLoader> { public: // IDWriteFontCollectionLoader methods. virtual HRESULT STDMETHODCALLTYPE CreateEnumeratorFromKey(IDWriteFactory* factory, void const* key, UINT32 key_size, IDWriteFontFileEnumerator** file_enumerator); static HRESULT Initialize(IDWriteFactory* factory); UINT32 GetFontMapSize(); std::wstring GetFontNameFromKey(UINT32 idx); bool LoadFontListFromRegistry(); FontCollectionLoader() {}; virtual ~FontCollectionLoader() {}; private: mswr::ComPtr<IDWriteFontFileLoader> file_loader_; std::vector<std::wstring> reg_fonts_; }; mswr::ComPtr<FontCollectionLoader> g_font_loader; class FontFileStream : public mswr::RuntimeClass<mswr::RuntimeClassFlags<mswr::ClassicCom>, IDWriteFontFileStream> { public: // IDWriteFontFileStream methods. virtual HRESULT STDMETHODCALLTYPE ReadFileFragment(void const** fragment_start, UINT64 file_offset, UINT64 fragment_size, void** context) { if (!memory_.get() || !memory_->IsValid() || file_offset >= memory_->length() || (file_offset + fragment_size) > memory_->length()) return E_FAIL; *fragment_start = static_cast<BYTE const*>(memory_->data()) + static_cast<size_t>(file_offset); *context = NULL; return S_OK; } virtual void STDMETHODCALLTYPE ReleaseFileFragment(void* context) {} virtual HRESULT STDMETHODCALLTYPE GetFileSize(UINT64* file_size) { if (!memory_.get() || !memory_->IsValid()) return E_FAIL; *file_size = memory_->length(); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetLastWriteTime(UINT64* last_write_time) { if (!memory_.get() || !memory_->IsValid()) return E_FAIL; // According to MSDN article http://goo.gl/rrSYzi the "last modified time" // is used by DirectWrite font selection algorithms to determine whether // one font resource is more up to date than another one. // So by returning 0 we are assuming that it will treat all fonts to be // equally up to date. // TODO(shrikant): We should further investigate this. *last_write_time = 0; return S_OK; } FontFileStream::FontFileStream() : font_key_(0) { }; HRESULT RuntimeClassInitialize(UINT32 font_key) { base::FilePath path; PathService::Get(base::DIR_WINDOWS_FONTS, &path); std::wstring font_key_name(g_font_loader->GetFontNameFromKey(font_key)); path = path.Append(font_key_name.c_str()); memory_.reset(new base::MemoryMappedFile()); // Put some debug information on stack. WCHAR font_name[256]; path.value().copy(font_name, arraysize(font_name)); base::debug::Alias(font_name); if (!memory_->Initialize(path)) { memory_.reset(); return E_FAIL; } font_key_ = font_key; base::debug::SetCrashKeyValue(kFontKeyName, base::WideToUTF8(font_key_name)); return S_OK; } virtual ~FontFileStream() {} UINT32 font_key_; scoped_ptr<base::MemoryMappedFile> memory_; }; class FontFileLoader : public mswr::RuntimeClass<mswr::RuntimeClassFlags<mswr::ClassicCom>, IDWriteFontFileLoader> { public: // IDWriteFontFileLoader methods. virtual HRESULT STDMETHODCALLTYPE CreateStreamFromKey(void const* ref_key, UINT32 ref_key_size, IDWriteFontFileStream** stream) { if (ref_key_size != sizeof(UINT32)) return E_FAIL; UINT32 font_key = *static_cast<const UINT32*>(ref_key); mswr::ComPtr<FontFileStream> font_stream; HRESULT hr = mswr::MakeAndInitialize<FontFileStream>(&font_stream, font_key); if (SUCCEEDED(hr)) { *stream = font_stream.Detach(); return S_OK; } return E_FAIL; } FontFileLoader() {} virtual ~FontFileLoader() {} }; class FontFileEnumerator : public mswr::RuntimeClass<mswr::RuntimeClassFlags<mswr::ClassicCom>, IDWriteFontFileEnumerator> { public: // IDWriteFontFileEnumerator methods. virtual HRESULT STDMETHODCALLTYPE MoveNext(BOOL* has_current_file) { *has_current_file = FALSE; if (current_file_) current_file_.ReleaseAndGetAddressOf(); if (font_idx_ < g_font_loader->GetFontMapSize()) { HRESULT hr = factory_->CreateCustomFontFileReference(&font_idx_, sizeof(UINT32), file_loader_.Get(), current_file_.GetAddressOf()); DCHECK(SUCCEEDED(hr)); *has_current_file = TRUE; font_idx_++; } return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetCurrentFontFile(IDWriteFontFile** font_file) { if (!current_file_) { *font_file = NULL; return E_FAIL; } *font_file = current_file_.Detach(); return S_OK; } FontFileEnumerator(const void* keys, UINT32 buffer_size, IDWriteFactory* factory, IDWriteFontFileLoader* file_loader) : factory_(factory), file_loader_(file_loader), font_idx_(0) {} virtual ~FontFileEnumerator() {} mswr::ComPtr<IDWriteFactory> factory_; mswr::ComPtr<IDWriteFontFile> current_file_; mswr::ComPtr<IDWriteFontFileLoader> file_loader_; UINT32 font_idx_; }; // IDWriteFontCollectionLoader methods. HRESULT STDMETHODCALLTYPE FontCollectionLoader::CreateEnumeratorFromKey( IDWriteFactory* factory, void const* key, UINT32 key_size, IDWriteFontFileEnumerator** file_enumerator) { *file_enumerator = mswr::Make<FontFileEnumerator>( key, key_size, factory, file_loader_.Get()).Detach(); return S_OK; } // static HRESULT FontCollectionLoader::Initialize(IDWriteFactory* factory) { DCHECK(g_font_loader == NULL); g_font_loader = mswr::Make<FontCollectionLoader>(); if (!g_font_loader) { DCHECK(FALSE); return E_FAIL; } CHECK(g_font_loader->LoadFontListFromRegistry()); g_font_loader->file_loader_ = mswr::Make<FontFileLoader>().Detach(); factory->RegisterFontFileLoader(g_font_loader->file_loader_.Get()); factory->RegisterFontCollectionLoader(g_font_loader.Get()); return S_OK; } UINT32 FontCollectionLoader::GetFontMapSize() { return reg_fonts_.size(); } std::wstring FontCollectionLoader::GetFontNameFromKey(UINT32 idx) { DCHECK(idx < reg_fonts_.size()); return reg_fonts_[idx]; } bool FontCollectionLoader::LoadFontListFromRegistry() { const wchar_t kFontsRegistry[] = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"; CHECK(reg_fonts_.empty()); base::win::RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, kFontsRegistry, KEY_READ) != ERROR_SUCCESS) { return false; } std::wstring name; std::wstring value; for (DWORD idx = 0; idx < regkey.GetValueCount(); idx++) { if (regkey.GetValueNameAt(idx, &name) == ERROR_SUCCESS && regkey.ReadValue(name.c_str(), &value) == ERROR_SUCCESS) { base::FilePath path(value.c_str()); // We need to check if file name is the only component that exists, // we will ignore all other registry entries. std::vector<base::FilePath::StringType> components; path.GetComponents(&components); if (components.size() == 1) { reg_fonts_.push_back(value.c_str()); } } } return true; } } // namespace namespace content { mswr::ComPtr<IDWriteFontCollection> g_font_collection; IDWriteFontCollection* GetCustomFontCollection(IDWriteFactory* factory) { if (g_font_collection.Get() != NULL) return g_font_collection.Get(); base::TimeTicks start_tick = base::TimeTicks::Now(); FontCollectionLoader::Initialize(factory); HRESULT hr = factory->CreateCustomFontCollection( g_font_loader.Get(), NULL, 0, g_font_collection.GetAddressOf()); base::TimeDelta time_delta = base::TimeTicks::Now() - start_tick; int64 delta = time_delta.ToInternalValue(); base::debug::Alias(&delta); UINT32 size = g_font_loader->GetFontMapSize(); base::debug::Alias(&size); CHECK(SUCCEEDED(hr)); CHECK(g_font_collection.Get() != NULL); base::debug::ClearCrashKey(kFontKeyName); return g_font_collection.Get(); } } // namespace content <commit_msg>Added restricted font fallback to custom font collection loader. After few experiments/crashes it seems that some users have enormous number of fonts in the registry. On suspect that we have for failing to load collection is that direct write cache is unable to load/handle those many fonts. In this CL we are trying to see if we can put arbitrary limit on number of fonts that could be loaded. We also added a fallback mechanism where in if loading from registry fails, we will try to load only default fonts. Definition of 'default' is taken from file prefs_tab_helper.cc ~ kDefaultFonts.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/renderer_font_platform_win.h" #include <dwrite.h> #include <string> #include <vector> #include <wrl/implements.h> #include <wrl/wrappers/corewrappers.h> #include "base/debug/alias.h" #include "base/debug/crash_logging.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/files/memory_mapped_file.h" #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/win/iat_patch_function.h" #include "base/win/registry.h" #include "base/win/scoped_comptr.h" namespace { namespace mswr = Microsoft::WRL; namespace mswrw = Microsoft::WRL::Wrappers; static const char kFontKeyName[] = "font_key_name"; class FontCollectionLoader : public mswr::RuntimeClass<mswr::RuntimeClassFlags<mswr::ClassicCom>, IDWriteFontCollectionLoader> { public: // IDWriteFontCollectionLoader methods. virtual HRESULT STDMETHODCALLTYPE CreateEnumeratorFromKey(IDWriteFactory* factory, void const* key, UINT32 key_size, IDWriteFontFileEnumerator** file_enumerator); static HRESULT Initialize(IDWriteFactory* factory); UINT32 GetFontMapSize(); std::wstring GetFontNameFromKey(UINT32 idx); bool LoadFontListFromRegistry(); bool LoadRestrictedFontList(); FontCollectionLoader() {}; virtual ~FontCollectionLoader() {}; private: mswr::ComPtr<IDWriteFontFileLoader> file_loader_; std::vector<std::wstring> reg_fonts_; }; mswr::ComPtr<FontCollectionLoader> g_font_loader; class FontFileStream : public mswr::RuntimeClass<mswr::RuntimeClassFlags<mswr::ClassicCom>, IDWriteFontFileStream> { public: // IDWriteFontFileStream methods. virtual HRESULT STDMETHODCALLTYPE ReadFileFragment(void const** fragment_start, UINT64 file_offset, UINT64 fragment_size, void** context) { if (!memory_.get() || !memory_->IsValid() || file_offset >= memory_->length() || (file_offset + fragment_size) > memory_->length()) return E_FAIL; *fragment_start = static_cast<BYTE const*>(memory_->data()) + static_cast<size_t>(file_offset); *context = NULL; return S_OK; } virtual void STDMETHODCALLTYPE ReleaseFileFragment(void* context) {} virtual HRESULT STDMETHODCALLTYPE GetFileSize(UINT64* file_size) { if (!memory_.get() || !memory_->IsValid()) return E_FAIL; *file_size = memory_->length(); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetLastWriteTime(UINT64* last_write_time) { if (!memory_.get() || !memory_->IsValid()) return E_FAIL; // According to MSDN article http://goo.gl/rrSYzi the "last modified time" // is used by DirectWrite font selection algorithms to determine whether // one font resource is more up to date than another one. // So by returning 0 we are assuming that it will treat all fonts to be // equally up to date. // TODO(shrikant): We should further investigate this. *last_write_time = 0; return S_OK; } FontFileStream::FontFileStream() : font_key_(0) { }; HRESULT RuntimeClassInitialize(UINT32 font_key) { base::FilePath path; PathService::Get(base::DIR_WINDOWS_FONTS, &path); std::wstring font_key_name(g_font_loader->GetFontNameFromKey(font_key)); path = path.Append(font_key_name.c_str()); memory_.reset(new base::MemoryMappedFile()); // Put some debug information on stack. WCHAR font_name[256]; path.value().copy(font_name, arraysize(font_name)); base::debug::Alias(font_name); if (!memory_->Initialize(path)) { memory_.reset(); return E_FAIL; } font_key_ = font_key; base::debug::SetCrashKeyValue(kFontKeyName, base::WideToUTF8(font_key_name)); return S_OK; } virtual ~FontFileStream() {} UINT32 font_key_; scoped_ptr<base::MemoryMappedFile> memory_; }; class FontFileLoader : public mswr::RuntimeClass<mswr::RuntimeClassFlags<mswr::ClassicCom>, IDWriteFontFileLoader> { public: // IDWriteFontFileLoader methods. virtual HRESULT STDMETHODCALLTYPE CreateStreamFromKey(void const* ref_key, UINT32 ref_key_size, IDWriteFontFileStream** stream) { if (ref_key_size != sizeof(UINT32)) return E_FAIL; UINT32 font_key = *static_cast<const UINT32*>(ref_key); mswr::ComPtr<FontFileStream> font_stream; HRESULT hr = mswr::MakeAndInitialize<FontFileStream>(&font_stream, font_key); if (SUCCEEDED(hr)) { *stream = font_stream.Detach(); return S_OK; } return E_FAIL; } FontFileLoader() {} virtual ~FontFileLoader() {} }; class FontFileEnumerator : public mswr::RuntimeClass<mswr::RuntimeClassFlags<mswr::ClassicCom>, IDWriteFontFileEnumerator> { public: // IDWriteFontFileEnumerator methods. virtual HRESULT STDMETHODCALLTYPE MoveNext(BOOL* has_current_file) { *has_current_file = FALSE; if (current_file_) current_file_.ReleaseAndGetAddressOf(); if (font_idx_ < g_font_loader->GetFontMapSize()) { HRESULT hr = factory_->CreateCustomFontFileReference(&font_idx_, sizeof(UINT32), file_loader_.Get(), current_file_.GetAddressOf()); DCHECK(SUCCEEDED(hr)); *has_current_file = TRUE; font_idx_++; } return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetCurrentFontFile(IDWriteFontFile** font_file) { if (!current_file_) { *font_file = NULL; return E_FAIL; } *font_file = current_file_.Detach(); return S_OK; } FontFileEnumerator(const void* keys, UINT32 buffer_size, IDWriteFactory* factory, IDWriteFontFileLoader* file_loader) : factory_(factory), file_loader_(file_loader), font_idx_(0) {} virtual ~FontFileEnumerator() {} mswr::ComPtr<IDWriteFactory> factory_; mswr::ComPtr<IDWriteFontFile> current_file_; mswr::ComPtr<IDWriteFontFileLoader> file_loader_; UINT32 font_idx_; }; // IDWriteFontCollectionLoader methods. HRESULT STDMETHODCALLTYPE FontCollectionLoader::CreateEnumeratorFromKey( IDWriteFactory* factory, void const* key, UINT32 key_size, IDWriteFontFileEnumerator** file_enumerator) { *file_enumerator = mswr::Make<FontFileEnumerator>( key, key_size, factory, file_loader_.Get()).Detach(); return S_OK; } // static HRESULT FontCollectionLoader::Initialize(IDWriteFactory* factory) { DCHECK(g_font_loader == NULL); g_font_loader = mswr::Make<FontCollectionLoader>(); if (!g_font_loader) { DCHECK(FALSE); return E_FAIL; } CHECK(g_font_loader->LoadFontListFromRegistry()); g_font_loader->file_loader_ = mswr::Make<FontFileLoader>().Detach(); factory->RegisterFontFileLoader(g_font_loader->file_loader_.Get()); factory->RegisterFontCollectionLoader(g_font_loader.Get()); return S_OK; } UINT32 FontCollectionLoader::GetFontMapSize() { return reg_fonts_.size(); } std::wstring FontCollectionLoader::GetFontNameFromKey(UINT32 idx) { DCHECK(idx < reg_fonts_.size()); return reg_fonts_[idx]; } bool FontCollectionLoader::LoadFontListFromRegistry() { const wchar_t kFontsRegistry[] = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"; CHECK(reg_fonts_.empty()); base::win::RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, kFontsRegistry, KEY_READ) != ERROR_SUCCESS) { return false; } std::wstring name; std::wstring value; for (DWORD idx = 0; idx < regkey.GetValueCount(); idx++) { if (regkey.GetValueNameAt(idx, &name) == ERROR_SUCCESS && regkey.ReadValue(name.c_str(), &value) == ERROR_SUCCESS) { base::FilePath path(value.c_str()); // We need to check if file name is the only component that exists, // we will ignore all other registry entries. std::vector<base::FilePath::StringType> components; path.GetComponents(&components); if (components.size() == 1) { reg_fonts_.push_back(value.c_str()); } } } return true; } // This list is mainly based on prefs/prefs_tab_helper.cc kFontDefaults. const wchar_t* kRestrictedFontSet[] = { L"times.ttf", // IDS_STANDARD_FONT_FAMILY L"timesbd.ttf", // IDS_STANDARD_FONT_FAMILY L"timesbi.ttf", // IDS_STANDARD_FONT_FAMILY L"timesi.ttf", // IDS_STANDARD_FONT_FAMILY L"cour.ttf", // IDS_FIXED_FONT_FAMILY L"courbd.ttf", // IDS_FIXED_FONT_FAMILY L"courbi.ttf", // IDS_FIXED_FONT_FAMILY L"couri.ttf", // IDS_FIXED_FONT_FAMILY L"consola.ttf", // IDS_FIXED_FONT_FAMILY_ALT_WIN L"consolab.ttf", // IDS_FIXED_FONT_FAMILY_ALT_WIN L"consolai.ttf", // IDS_FIXED_FONT_FAMILY_ALT_WIN L"consolaz.ttf", // IDS_FIXED_FONT_FAMILY_ALT_WIN L"arial.ttf", // IDS_SANS_SERIF_FONT_FAMILY L"arialbd.ttf", // IDS_SANS_SERIF_FONT_FAMILY L"arialbi.ttf", // IDS_SANS_SERIF_FONT_FAMILY L"ariali.ttf", // IDS_SANS_SERIF_FONT_FAMILY L"comic.ttf", // IDS_CURSIVE_FONT_FAMILY L"comicbd.ttf", // IDS_CURSIVE_FONT_FAMILY L"comici.ttf", // IDS_CURSIVE_FONT_FAMILY L"comicz.ttf", // IDS_CURSIVE_FONT_FAMILY L"impact.ttf", // IDS_FANTASY_FONT_FAMILY L"segoeui.ttf", // IDS_PICTOGRAPH_FONT_FAMILY L"segoeuib.ttf", // IDS_PICTOGRAPH_FONT_FAMILY L"segoeuii.ttf", // IDS_PICTOGRAPH_FONT_FAMILY L"msgothic.ttc", // IDS_STANDARD_FONT_FAMILY_JAPANESE L"msmincho.ttc", // IDS_SERIF_FONT_FAMILY_JAPANESE L"gulim.ttc", // IDS_FIXED_FONT_FAMILY_KOREAN L"batang.ttc", // IDS_SERIF_FONT_FAMILY_KOREAN L"simsun.ttc", // IDS_STANDARD_FONT_FAMILY_SIMPLIFIED_HAN L"mingliu.ttc", // IDS_SERIF_FONT_FAMILY_TRADITIONAL_HAN }; bool FontCollectionLoader::LoadRestrictedFontList() { reg_fonts_.clear(); reg_fonts_.assign(kRestrictedFontSet, kRestrictedFontSet + _countof(kRestrictedFontSet)); return true; } } // namespace namespace content { mswr::ComPtr<IDWriteFontCollection> g_font_collection; IDWriteFontCollection* GetCustomFontCollection(IDWriteFactory* factory) { if (g_font_collection.Get() != NULL) return g_font_collection.Get(); base::TimeTicks start_tick = base::TimeTicks::Now(); FontCollectionLoader::Initialize(factory); // We try here to put arbitrary limit on max number of fonts that could // be loaded, otherwise we fallback to restricted set of fonts. const UINT32 kMaxFontThreshold = 1000; HRESULT hr = E_FAIL; if (g_font_loader->GetFontMapSize() < kMaxFontThreshold) { hr = factory->CreateCustomFontCollection( g_font_loader.Get(), NULL, 0, g_font_collection.GetAddressOf()); } bool loadingRestricted = false; if (FAILED(hr) || !g_font_collection.Get()) { // We will try here just one more time with restricted font set. g_font_loader->LoadRestrictedFontList(); hr = factory->CreateCustomFontCollection( g_font_loader.Get(), NULL, 0, g_font_collection.GetAddressOf()); } base::TimeDelta time_delta = base::TimeTicks::Now() - start_tick; int64 delta = time_delta.ToInternalValue(); base::debug::Alias(&delta); UINT32 size = g_font_loader->GetFontMapSize(); base::debug::Alias(&size); base::debug::Alias(&loadingRestricted); CHECK(SUCCEEDED(hr)); CHECK(g_font_collection.Get() != NULL); base::debug::ClearCrashKey(kFontKeyName); return g_font_collection.Get(); } } // namespace content <|endoftext|>
<commit_before>// Copyright (c) 2012 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 "content/shell/shell_content_renderer_client.h" #include "base/callback.h" #include "base/command_line.h" #include "base/debug/debugger.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_switches.h" #include "content/public/renderer/render_view.h" #include "content/public/test/layouttest_support.h" #include "content/shell/shell_render_process_observer.h" #include "content/shell/shell_switches.h" #include "content/shell/webkit_test_runner.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginParams.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTestProxy.h" #include "v8/include/v8.h" using WebKit::WebFrame; using WebKit::WebPlugin; using WebKit::WebPluginParams; using WebTestRunner::WebTestDelegate; using WebTestRunner::WebTestProxyBase; namespace content { ShellContentRendererClient::ShellContentRendererClient() { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) { EnableWebTestProxyCreation( base::Bind(&ShellContentRendererClient::WebTestProxyCreated, base::Unretained(this))); } } ShellContentRendererClient::~ShellContentRendererClient() { } void ShellContentRendererClient::RenderThreadStarted() { shell_observer_.reset(new ShellRenderProcessObserver()); #if defined(OS_MACOSX) // We need to call this once before the sandbox was initialized to cache the // value. base::debug::BeingDebugged(); #endif } void ShellContentRendererClient::RenderViewCreated(RenderView* render_view) { WebKitTestRunner* test_runner = WebKitTestRunner::Get(render_view); test_runner->Reset(); render_view->GetWebView()->setSpellCheckClient( test_runner->proxy()->spellCheckClient()); WebTestDelegate* delegate = ShellRenderProcessObserver::GetInstance()->test_delegate(); if (delegate == static_cast<WebTestDelegate*>(test_runner)) ShellRenderProcessObserver::GetInstance()->SetMainWindow(render_view); } bool ShellContentRendererClient::OverrideCreatePlugin( RenderView* render_view, WebFrame* frame, const WebPluginParams& params, WebPlugin** plugin) { std::string mime_type = params.mimeType.utf8(); if (mime_type == content::kBrowserPluginMimeType) { // Allow browser plugin in content_shell only if it is forced by flag. // Returning true here disables the plugin. return !CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableBrowserPluginForAllViewTypes); } return false; } void ShellContentRendererClient::WebTestProxyCreated(RenderView* render_view, WebTestProxyBase* proxy) { WebKitTestRunner* test_runner = new WebKitTestRunner(render_view); test_runner->set_proxy(proxy); if (!ShellRenderProcessObserver::GetInstance()->test_delegate()) ShellRenderProcessObserver::GetInstance()->SetTestDelegate(test_runner); proxy->setInterfaces( ShellRenderProcessObserver::GetInstance()->test_interfaces()); test_runner->proxy()->setDelegate( ShellRenderProcessObserver::GetInstance()->test_delegate()); } } // namespace content <commit_msg>Fix content_browsertests<commit_after>// Copyright (c) 2012 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 "content/shell/shell_content_renderer_client.h" #include "base/callback.h" #include "base/command_line.h" #include "base/debug/debugger.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_switches.h" #include "content/public/renderer/render_view.h" #include "content/public/test/layouttest_support.h" #include "content/shell/shell_render_process_observer.h" #include "content/shell/shell_switches.h" #include "content/shell/webkit_test_runner.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginParams.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTestProxy.h" #include "v8/include/v8.h" using WebKit::WebFrame; using WebKit::WebPlugin; using WebKit::WebPluginParams; using WebTestRunner::WebTestDelegate; using WebTestRunner::WebTestProxyBase; namespace content { ShellContentRendererClient::ShellContentRendererClient() { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) { EnableWebTestProxyCreation( base::Bind(&ShellContentRendererClient::WebTestProxyCreated, base::Unretained(this))); } } ShellContentRendererClient::~ShellContentRendererClient() { } void ShellContentRendererClient::RenderThreadStarted() { shell_observer_.reset(new ShellRenderProcessObserver()); #if defined(OS_MACOSX) // We need to call this once before the sandbox was initialized to cache the // value. base::debug::BeingDebugged(); #endif } void ShellContentRendererClient::RenderViewCreated(RenderView* render_view) { if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) return; WebKitTestRunner* test_runner = WebKitTestRunner::Get(render_view); test_runner->Reset(); render_view->GetWebView()->setSpellCheckClient( test_runner->proxy()->spellCheckClient()); WebTestDelegate* delegate = ShellRenderProcessObserver::GetInstance()->test_delegate(); if (delegate == static_cast<WebTestDelegate*>(test_runner)) ShellRenderProcessObserver::GetInstance()->SetMainWindow(render_view); } bool ShellContentRendererClient::OverrideCreatePlugin( RenderView* render_view, WebFrame* frame, const WebPluginParams& params, WebPlugin** plugin) { std::string mime_type = params.mimeType.utf8(); if (mime_type == content::kBrowserPluginMimeType) { // Allow browser plugin in content_shell only if it is forced by flag. // Returning true here disables the plugin. return !CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableBrowserPluginForAllViewTypes); } return false; } void ShellContentRendererClient::WebTestProxyCreated(RenderView* render_view, WebTestProxyBase* proxy) { WebKitTestRunner* test_runner = new WebKitTestRunner(render_view); test_runner->set_proxy(proxy); if (!ShellRenderProcessObserver::GetInstance()->test_delegate()) ShellRenderProcessObserver::GetInstance()->SetTestDelegate(test_runner); proxy->setInterfaces( ShellRenderProcessObserver::GetInstance()->test_interfaces()); test_runner->proxy()->setDelegate( ShellRenderProcessObserver::GetInstance()->test_delegate()); } } // namespace content <|endoftext|>
<commit_before>/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* * stringutils.C * * Created on: Apr 9, 2013 * Author: xaxaxa */ #include <cpoll/cpoll.H> #include "include/stringutils.H" #include "include/split.H" using namespace CP; namespace cppsp { inline char hexCharToInt(char ch) { if (ch <= '9') return ch - '0'; else if (ch <= 'Z') return ch - 'A' + 10; else return ch - 'a' + 10; } inline char intToHexChar(char i) { if (i < 10) return i + '0'; else return i - 10 + 'A'; } void urlDecode(const char* in, int inLen, StreamWriter& sw) { const char* end = in + inLen; const char* ptr = in; while (true) { if (ptr >= end) goto E; const char* next = (const char*) memchr(ptr, '%', end - ptr); if (next == NULL) break; sw.write(ptr, next - ptr); if (next + 2 >= end) { sw.write(next, end - next); goto E; } char tmp = hexCharToInt(next[1]) << 4 | hexCharToInt(next[2]); sw.write(tmp); ptr = next + 3; } if (ptr < end) sw.write(ptr, end - ptr); E: ; } String urlDecode(const char* in, int inLen, StringPool& sp) { char* ch = sp.beginAdd(inLen); //output size will never exceed input size char* c = ch; const char* end = in + inLen; const char* ptr = in; while (true) { if (ptr >= end) goto E; const char* next = (const char*) memchr(ptr, '%', end - ptr); if (next == NULL) break; memcpy(c, ptr, next - ptr); c += (next - ptr); if (next + 2 >= end) { memcpy(c, next, end - next); c += (end - next); goto E; } *c = hexCharToInt(next[1]) << 4 | hexCharToInt(next[2]); c++; ptr = next + 3; } if (ptr < end) { memcpy(c, ptr, end - ptr); c += (end - ptr); } sp.endAdd(c - ch); return {ch,c-ch}; E: ; return {(char*)nullptr,0}; } void urlEncode(const char* in, int inLen, CP::StreamWriter& sw) { int last_i = 0; const char* c = in; char ch[3]; ch[0] = '%'; for (int i = 0; i < inLen; i++) { if ((48 <= c[i] && c[i] <= 57) || //0-9 (65 <= c[i] && c[i] <= 90) || //abc...xyz (97 <= c[i] && c[i] <= 122) || //ABC...XYZ (c[i] == '~' || c[i] == '!' || c[i] == '*' || c[i] == '(' || c[i] == ')' || c[i] == '\'')) continue; if (i > last_i) sw.write(in + last_i, i - last_i); last_i = i + 1; ch[1] = intToHexChar(c[i] >> 4); ch[2] = intToHexChar(c[i] & (char) 0xF); sw.write(ch, 3); } if (inLen > last_i) sw.write(in + last_i, inLen - last_i); } std::string urlDecode(const char* in, int inLen) { StringStream ss; { StreamWriter sw(ss); urlDecode(in, inLen, sw); } return ss.str(); } std::string urlEncode(const char* in, int inLen) { StringStream ss; { StreamWriter sw(ss); urlEncode(in, inLen, sw); } return ss.str(); } std::string htmlEscape(const char* in, int inLen) { StringStream ss; { StreamWriter sw(ss); htmlEscape(in, inLen, sw); } return ss.str(); } std::string htmlAttributeEscape(const char* in, int inLen) { StringStream ss; { StreamWriter sw(ss); htmlAttributeEscape(in, inLen, sw); } return ss.str(); } void parseQueryString(const char* in, int inLen, queryStringCallback cb, bool decode) { if (decode) { MemoryStream ms; StreamWriter sw(ms); split spl(in, inLen, '&'); while (spl.read()) { const char* s = spl.value.d; int l = spl.value.len; const char* _end = s + l; const char* tmp = (const char*) memchr(s, '=', l); if (tmp == NULL) { urlDecode(s, l, sw); sw.flush(); cb((const char*) ms.data(), ms.length(), nullptr, 0); ms.clear(); } else { urlDecode(s, tmp - s, sw); sw.flush(); int i = ms.length(); urlDecode(tmp + 1, _end - tmp - 1, sw); sw.flush(); cb((const char*) ms.data(), i, (const char*) (ms.data() + i), ms.length() - i); ms.clear(); } } } else { split spl(in, inLen, '&'); while (spl.read()) { const char* s = spl.value.d; int l = spl.value.len; const char* _end = s + l; const char* tmp = (const char*) memchr(s, '=', l); if (tmp == NULL) cb(s, l, nullptr, 0); else cb(s, tmp - s, tmp + 1, _end - tmp - 1); } } } void htmlEscape(const char* in, int inLen, CP::StreamWriter& sw) { int sz = 0; for (int i = 0; i < inLen; i++) { switch (in[i]) { case '&': sz += 5; break; case '<': sz += 4; break; case '>': sz += 4; break; default: sz++; break; } } char* data = sw.beginWrite(sz); char* c = data; for (int i = 0; i < inLen; i++) { switch (in[i]) { case '&': c[0] = '&'; c[1] = 'a'; c[2] = 'm'; c[3] = 'p'; c[4] = ';'; c += 5; break; case '<': c[0] = '&'; c[1] = 'l'; c[2] = 't'; c[3] = ';'; c += 4; break; case '>': c[0] = '&'; c[1] = 'g'; c[2] = 't'; c[3] = ';'; c += 4; break; default: *(c++) = in[i]; } } sw.endWrite(sz); } void htmlAttributeEscape(const char* in, int inLen, CP::StreamWriter& sw) { int last_i = 0; const char* tmp; for (int i = 0; i < inLen; i++) { switch (in[i]) { case '&': tmp = "&amp;"; break; case '<': tmp = "&lt;"; break; case '>': tmp = "&gt;"; break; case '"': tmp = "&quot;"; break; case '\'': tmp = "&apos;"; break; default: continue; } if (i > last_i) sw.write(in + last_i, i - last_i); last_i = i + 1; sw.write(tmp); } if (inLen > last_i) sw.write(in + last_i, inLen - last_i); } int ci_compare(String s1, String s2) { if (s1.length() > s2.length()) return 1; if (s1.length() < s2.length()) return -1; if (s1.length() == 0) return 0; char a, b; for (int i = 0; i < s1.length(); i++) { a = tolower(s1.data()[i]); b = tolower(s2.data()[i]); if (a < b) return -1; if (a > b) return 1; } return 0; } static inline int itoa1(int i, char* b) { static char const digit[] = "0123456789"; char* p = b; //negative detection is not needed for this specific use-case //(writing the content-length header) p += (i == 0 ? 0 : int(log10f(i))) + 1; *p = '\0'; int l = p - b; do { //Move back, inserting digits as u go *--p = digit[i % 10]; i = i / 10; } while (i); return l; } //pads beginning with 0s //i: input number //d: # of digits static inline int itoa2(int i, int d, char* b) { static char const digit[] = "0123456789"; for (int x = d - 1; x >= 0; x--) { b[x] = digit[i % 10]; i /= 10; } return d; } int rfctime(const tm& time, char* c) { static const char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char* months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; char* s = c; //AAA, AA AAA ???? AA:AA:AA GMT\0 const char* day = days[time.tm_wday]; //copy 4 bytes (includes extra null byte) *(int*) c = (*(int*) day) | int(',') << 24; c += 4; *(c++) = ' '; c += itoa1(time.tm_mday, c); *(c++) = ' '; const char* month = months[time.tm_mon]; *(c++) = *(month++); *(c++) = *(month++); *(c++) = *(month++); *(c++) = ' '; c += itoa1(time.tm_year + 1900, c); *(c++) = ' '; c += itoa2(time.tm_hour, 2, c); *(c++) = ':'; c += itoa2(time.tm_min, 2, c); *(c++) = ':'; c += itoa2(time.tm_sec, 2, c); *(c++) = ' '; *(c++) = 'G'; *(c++) = 'M'; *(c++) = 'T'; *(c++) = '\0'; return int(c - s) - 1; } } <commit_msg>verify Fixed cpoll_cppsp's fortunes test<commit_after>/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* * stringutils.C * * Created on: Apr 9, 2013 * Author: xaxaxa */ #include <cpoll/cpoll.H> #include "include/stringutils.H" #include "include/split.H" using namespace CP; namespace cppsp { inline char hexCharToInt(char ch) { if (ch <= '9') return ch - '0'; else if (ch <= 'Z') return ch - 'A' + 10; else return ch - 'a' + 10; } inline char intToHexChar(char i) { if (i < 10) return i + '0'; else return i - 10 + 'A'; } void urlDecode(const char* in, int inLen, StreamWriter& sw) { const char* end = in + inLen; const char* ptr = in; while (true) { if (ptr >= end) goto E; const char* next = (const char*) memchr(ptr, '%', end - ptr); if (next == NULL) break; sw.write(ptr, next - ptr); if (next + 2 >= end) { sw.write(next, end - next); goto E; } char tmp = hexCharToInt(next[1]) << 4 | hexCharToInt(next[2]); sw.write(tmp); ptr = next + 3; } if (ptr < end) sw.write(ptr, end - ptr); E: ; } String urlDecode(const char* in, int inLen, StringPool& sp) { char* ch = sp.beginAdd(inLen); //output size will never exceed input size char* c = ch; const char* end = in + inLen; const char* ptr = in; while (true) { if (ptr >= end) goto E; const char* next = (const char*) memchr(ptr, '%', end - ptr); if (next == NULL) break; memcpy(c, ptr, next - ptr); c += (next - ptr); if (next + 2 >= end) { memcpy(c, next, end - next); c += (end - next); goto E; } *c = hexCharToInt(next[1]) << 4 | hexCharToInt(next[2]); c++; ptr = next + 3; } if (ptr < end) { memcpy(c, ptr, end - ptr); c += (end - ptr); } sp.endAdd(c - ch); return {ch,c-ch}; E: ; return {(char*)nullptr,0}; } void urlEncode(const char* in, int inLen, CP::StreamWriter& sw) { int last_i = 0; const char* c = in; char ch[3]; ch[0] = '%'; for (int i = 0; i < inLen; i++) { if ((48 <= c[i] && c[i] <= 57) || //0-9 (65 <= c[i] && c[i] <= 90) || //abc...xyz (97 <= c[i] && c[i] <= 122) || //ABC...XYZ (c[i] == '~' || c[i] == '!' || c[i] == '*' || c[i] == '(' || c[i] == ')' || c[i] == '\'')) continue; if (i > last_i) sw.write(in + last_i, i - last_i); last_i = i + 1; ch[1] = intToHexChar(c[i] >> 4); ch[2] = intToHexChar(c[i] & (char) 0xF); sw.write(ch, 3); } if (inLen > last_i) sw.write(in + last_i, inLen - last_i); } std::string urlDecode(const char* in, int inLen) { StringStream ss; { StreamWriter sw(ss); urlDecode(in, inLen, sw); } return ss.str(); } std::string urlEncode(const char* in, int inLen) { StringStream ss; { StreamWriter sw(ss); urlEncode(in, inLen, sw); } return ss.str(); } std::string htmlEscape(const char* in, int inLen) { StringStream ss; { StreamWriter sw(ss); htmlEscape(in, inLen, sw); } return ss.str(); } std::string htmlAttributeEscape(const char* in, int inLen) { StringStream ss; { StreamWriter sw(ss); htmlAttributeEscape(in, inLen, sw); } return ss.str(); } void parseQueryString(const char* in, int inLen, queryStringCallback cb, bool decode) { if (decode) { MemoryStream ms; StreamWriter sw(ms); split spl(in, inLen, '&'); while (spl.read()) { const char* s = spl.value.d; int l = spl.value.len; const char* _end = s + l; const char* tmp = (const char*) memchr(s, '=', l); if (tmp == NULL) { urlDecode(s, l, sw); sw.flush(); cb((const char*) ms.data(), ms.length(), nullptr, 0); ms.clear(); } else { urlDecode(s, tmp - s, sw); sw.flush(); int i = ms.length(); urlDecode(tmp + 1, _end - tmp - 1, sw); sw.flush(); cb((const char*) ms.data(), i, (const char*) (ms.data() + i), ms.length() - i); ms.clear(); } } } else { split spl(in, inLen, '&'); while (spl.read()) { const char* s = spl.value.d; int l = spl.value.len; const char* _end = s + l; const char* tmp = (const char*) memchr(s, '=', l); if (tmp == NULL) cb(s, l, nullptr, 0); else cb(s, tmp - s, tmp + 1, _end - tmp - 1); } } } void htmlEscape(const char* in, int inLen, CP::StreamWriter& sw) { int sz = 0; for (int i = 0; i < inLen; i++) { switch (in[i]) { case '&': sz += 5; break; case '<': sz += 4; break; case '>': sz += 4; break; case '\'': sz += 6; break; default: sz++; break; } } char* data = sw.beginWrite(sz); char* c = data; for (int i = 0; i < inLen; i++) { switch (in[i]) { case '&': c[0] = '&'; c[1] = 'a'; c[2] = 'm'; c[3] = 'p'; c[4] = ';'; c += 5; break; case '<': c[0] = '&'; c[1] = 'l'; c[2] = 't'; c[3] = ';'; c += 4; break; case '>': c[0] = '&'; c[1] = 'g'; c[2] = 't'; c[3] = ';'; c += 4; break; case '\'': c[0] = '&'; c[1] = 'a'; c[2] = 'p'; c[3] = 'o'; c[4] = 's'; c[5] = ';'; c += 6; break; default: *(c++) = in[i]; } } sw.endWrite(sz); } void htmlAttributeEscape(const char* in, int inLen, CP::StreamWriter& sw) { int last_i = 0; const char* tmp; for (int i = 0; i < inLen; i++) { switch (in[i]) { case '&': tmp = "&amp;"; break; case '<': tmp = "&lt;"; break; case '>': tmp = "&gt;"; break; case '"': tmp = "&quot;"; break; case '\'': tmp = "&apos;"; break; default: continue; } if (i > last_i) sw.write(in + last_i, i - last_i); last_i = i + 1; sw.write(tmp); } if (inLen > last_i) sw.write(in + last_i, inLen - last_i); } int ci_compare(String s1, String s2) { if (s1.length() > s2.length()) return 1; if (s1.length() < s2.length()) return -1; if (s1.length() == 0) return 0; char a, b; for (int i = 0; i < s1.length(); i++) { a = tolower(s1.data()[i]); b = tolower(s2.data()[i]); if (a < b) return -1; if (a > b) return 1; } return 0; } static inline int itoa1(int i, char* b) { static char const digit[] = "0123456789"; char* p = b; //negative detection is not needed for this specific use-case //(writing the content-length header) p += (i == 0 ? 0 : int(log10f(i))) + 1; *p = '\0'; int l = p - b; do { //Move back, inserting digits as u go *--p = digit[i % 10]; i = i / 10; } while (i); return l; } //pads beginning with 0s //i: input number //d: # of digits static inline int itoa2(int i, int d, char* b) { static char const digit[] = "0123456789"; for (int x = d - 1; x >= 0; x--) { b[x] = digit[i % 10]; i /= 10; } return d; } int rfctime(const tm& time, char* c) { static const char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char* months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; char* s = c; //AAA, AA AAA ???? AA:AA:AA GMT\0 const char* day = days[time.tm_wday]; //copy 4 bytes (includes extra null byte) *(int*) c = (*(int*) day) | int(',') << 24; c += 4; *(c++) = ' '; c += itoa1(time.tm_mday, c); *(c++) = ' '; const char* month = months[time.tm_mon]; *(c++) = *(month++); *(c++) = *(month++); *(c++) = *(month++); *(c++) = ' '; c += itoa1(time.tm_year + 1900, c); *(c++) = ' '; c += itoa2(time.tm_hour, 2, c); *(c++) = ':'; c += itoa2(time.tm_min, 2, c); *(c++) = ':'; c += itoa2(time.tm_sec, 2, c); *(c++) = ' '; *(c++) = 'G'; *(c++) = 'M'; *(c++) = 'T'; *(c++) = '\0'; return int(c - s) - 1; } } <|endoftext|>
<commit_before>#ifndef HASHEROBJ #define HASHEROBJ #include "header.h" #include "iotools.h" //#include "path_manager.hpp" #include <stdio.h> #include <opencv2/opencv.hpp> #include <fstream> using namespace std; using namespace cv; class HasherObject { public: // What should the parameters be here? HasherObject() { // set default values feature_dim = 4096; bit_num = 256; int_num = bit_num/32; // l2-norm features norm = true; // number of features to retrieve for reranking // would be overwritten based on ratio and data_num top_feature = 2000; ratio = 0.001f; // number of features indexed data_num = 0; // initialize path manager pm.set_paths(norm, bit_num); // initialize timing t[0] = 0.0; reset_timings(); // initialize output buffer to speed up writing out results outputfile.rdbuf()->pubsetbuf(buffer, length); }; // What need to be freed/closed? ~HasherObject() { itq.release(); W.release(); mvec.release(); top_feature_mat.release(); postrank.clear(); hamming.clear(); // accum? // query_codes? }; void reset_timings() { for (int _t=1; _t<8; _t++) t[_t] = 0.0; } int initialize() { double t_start = get_wall_time(); int status = read_update_files(); if (status != 0) return status; fill_data_nums_accum(); status = load_itq_model(); if (status != 0) return status; status = load_hashcodes(); if (status != 0) return status; double t_init = get_wall_time() - t_start; cout << "[initialize] Done in " << t_init << "s." << endl; return 0; }; int read_update_files(); // Load DB hashcodes from files listed in update_file int load_hashcodes(); // Load ITQ model int load_itq_model(); // io from disk Mat read_feats_from_disk(string filename); //Mat read_hashcodes_from_disk(string filename); void set_query_feats_from_disk(string filename); // compute hashcodes from feats unsigned int* compute_hashcodes_from_feats(Mat feats); // query methods // use member query_feats, assumes set_query_feats_from_disk have been called before void find_knn(); vector< vector< pair<float, int> > > find_knn_nodiskout(); void find_knn_from_feats(Mat query_feats); //Mat find_knn_from_hashcodes(Mat query_hashcodes); void set_paths(); // To force top_feature. // To be called after fill_data_nums_accum void set_topk(int _top_k) { top_feature = _top_k; }; void set_ratio(float _ratio) { ratio = _ratio; set_top_feature(); }; void set_bit_num(int _bit_num) { bit_num = _bit_num; int_num = bit_num/32; }; void set_norm(int _norm) { norm = _norm; }; void set_feature_dim(int _feature_dim) { feature_dim = _feature_dim; }; void set_base_modelpath(string _base_modelpath){ pm.base_modelpath = _base_modelpath; }; string get_base_modelpath() { return pm.base_modelpath; }; void set_base_updatepath(string _base_updatepath) { pm.base_updatepath = _base_updatepath; }; string get_base_updatepath() { return pm.base_updatepath; }; void set_outputfile(string _outname){ outname = _outname; }; void init_feature_mat() { top_feature_mat.create(top_feature, feature_dim, CV_32F); }; void fill_data_nums_accum(); void clean_compfeat_files(); // // io from memory // Need to use boost::python converter for cv::Mat? // maybe later... // Mat get_feats_from_memory(void* data); // Mat get_hashcodes_from_memory(void* data); private: // parameters values float ratio; int feature_dim; int int_num; // only these two parameters influence filenames int bit_num; int norm; // number of features to retrieve for reranking int top_feature; // number of features indexed unsigned long long int data_num; // number of samples in each update files int* accum; // Hashing related things // contains the hashcodes Mat itq; // contains the projections vectors Mat W; // contains the mean vectors Mat mvec; // Initializing features structures and files streams Mat top_feature_mat; // timing double t[8]; // To manage paths/strings PathManager pm; // List of data files vector<string> update_hash_files; vector<string> update_compfeature_files; vector<string> update_compidx_files; // Compressed features index and data vector<ifstream*> read_in_compidx; vector<ifstream*> read_in_compfeatures; // List of number of features per update file vector<unsigned long long int> data_nums; // Internal structure to store query features and hashcodes Mat query_feats; unsigned int* query_codes; vector<mypair> hamming; vector<mypairf> postrank; int query_num; // Output streams string outname; ofstream outputfile; ofstream outputfile_hamming; // Use a single ifstream and read_size to read things ifstream read_in; size_t read_size; void set_top_feature() { top_feature = (int)ceil(data_num*ratio); cout << "Will retrieve the top " << top_feature << " features." << endl; init_top_features_mat(); }; void init_top_features_mat() { top_feature_mat.release(); top_feature_mat.create(top_feature, feature_dim, CV_32F); postrank.clear(); postrank.reserve(top_feature); }; // To be used to speed up writing out results //static const unsigned int length = 8192; static const unsigned int length = 16384; char buffer[length]; void init_output_files(); void close_output_files(); void init_output_files(string outname); void write_to_output_file(vector<mypairf> postrank, vector<mypair> hamming); vector<mypair> compute_hamming_dist_onehash(unsigned int* query); vector<mypairf> rerank_knn_onesample(float* query_feature, vector<mypair> top_hamming); }; #endif <commit_msg>print timing<commit_after>#ifndef HASHEROBJ #define HASHEROBJ #include "header.h" #include "iotools.h" //#include "path_manager.hpp" #include <stdio.h> #include <opencv2/opencv.hpp> #include <fstream> using namespace std; using namespace cv; class HasherObject { public: // What should the parameters be here? HasherObject() { // set default values feature_dim = 4096; bit_num = 256; int_num = bit_num/32; // l2-norm features norm = true; // number of features to retrieve for reranking // would be overwritten based on ratio and data_num top_feature = 2000; ratio = 0.001f; // number of features indexed data_num = 0; // initialize path manager pm.set_paths(norm, bit_num); // initialize timing t[0] = 0.0; reset_timings(); // initialize output buffer to speed up writing out results outputfile.rdbuf()->pubsetbuf(buffer, length); }; // What need to be freed/closed? ~HasherObject() { itq.release(); W.release(); mvec.release(); top_feature_mat.release(); postrank.clear(); hamming.clear(); // accum? // query_codes? }; void reset_timings() { for (int _t=1; _t<8; _t++) t[_t] = 0.0; } int initialize() { double t_start = get_wall_time(); int status = read_update_files(); if (status != 0) return status; fill_data_nums_accum(); status = load_itq_model(); if (status != 0) return status; status = load_hashcodes(); if (status != 0) return status; double t_init = get_wall_time() - t_start; cout << "[initialize] Done in " << t_init << "s." << endl; return 0; }; int read_update_files(); // Load DB hashcodes from files listed in update_file int load_hashcodes(); // Load ITQ model int load_itq_model(); // io from disk Mat read_feats_from_disk(string filename); //Mat read_hashcodes_from_disk(string filename); void set_query_feats_from_disk(string filename); // compute hashcodes from feats unsigned int* compute_hashcodes_from_feats(Mat feats); // query methods // use member query_feats, assumes set_query_feats_from_disk have been called before void find_knn(); vector< vector< pair<float, int> > > find_knn_nodiskout(); void find_knn_from_feats(Mat query_feats); //Mat find_knn_from_hashcodes(Mat query_hashcodes); void set_paths(); // To force top_feature. // To be called after fill_data_nums_accum void set_topk(int _top_k) { top_feature = _top_k; }; void set_ratio(float _ratio) { ratio = _ratio; set_top_feature(); }; void set_bit_num(int _bit_num) { bit_num = _bit_num; int_num = bit_num/32; }; void set_norm(int _norm) { norm = _norm; }; void set_feature_dim(int _feature_dim) { feature_dim = _feature_dim; }; void set_base_modelpath(string _base_modelpath){ pm.base_modelpath = _base_modelpath; }; string get_base_modelpath() { return pm.base_modelpath; }; void set_base_updatepath(string _base_updatepath) { pm.base_updatepath = _base_updatepath; }; string get_base_updatepath() { return pm.base_updatepath; }; void set_outputfile(string _outname){ outname = _outname; }; void init_feature_mat() { top_feature_mat.create(top_feature, feature_dim, CV_32F); }; void fill_data_nums_accum(); void clean_compfeat_files(); // // io from memory // Need to use boost::python converter for cv::Mat? // maybe later... // Mat get_feats_from_memory(void* data); // Mat get_hashcodes_from_memory(void* data); private: // parameters values float ratio; int feature_dim; int int_num; // only these two parameters influence filenames int bit_num; int norm; // number of features to retrieve for reranking int top_feature; // number of features indexed unsigned long long int data_num; // number of samples in each update files int* accum; // Hashing related things // contains the hashcodes Mat itq; // contains the projections vectors Mat W; // contains the mean vectors Mat mvec; // Initializing features structures and files streams Mat top_feature_mat; // timing double t[8]; // To manage paths/strings PathManager pm; // List of data files vector<string> update_hash_files; vector<string> update_compfeature_files; vector<string> update_compidx_files; // Compressed features index and data vector<ifstream*> read_in_compidx; vector<ifstream*> read_in_compfeatures; // List of number of features per update file vector<unsigned long long int> data_nums; // Internal structure to store query features and hashcodes Mat query_feats; unsigned int* query_codes; vector<mypair> hamming; vector<mypairf> postrank; int query_num; // Output streams string outname; ofstream outputfile; ofstream outputfile_hamming; // Use a single ifstream and read_size to read things ifstream read_in; size_t read_size; void set_top_feature() { top_feature = (int)ceil(data_num*ratio); cout << "Will retrieve the top " << top_feature << " features." << endl; init_top_features_mat(); }; void init_top_features_mat() { top_feature_mat.release(); top_feature_mat.create(top_feature, feature_dim, CV_32F); postrank.clear(); postrank.reserve(top_feature); }; // To be used to speed up writing out results //static const unsigned int length = 8192; static const unsigned int length = 16384; char buffer[length]; void init_output_files(); void close_output_files(); void print_timing(); void init_output_files(string outname); void write_to_output_file(vector<mypairf> postrank, vector<mypair> hamming); vector<mypair> compute_hamming_dist_onehash(unsigned int* query); vector<mypairf> rerank_knn_onesample(float* query_feature, vector<mypair> top_hamming); }; #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Gabe Black * Ali Saidi */ #ifndef __ARCH_SPARC_REGFILE_HH__ #define __ARCH_SPARC_REGFILE_HH__ #include "arch/sparc/floatregfile.hh" #include "arch/sparc/intregfile.hh" #include "arch/sparc/isa_traits.hh" #include "arch/sparc/miscregfile.hh" #include "arch/sparc/types.hh" #include "sim/host.hh" #include <string> class Checkpoint; namespace SparcISA { class RegFile { protected: Addr pc; // Program Counter Addr npc; // Next Program Counter Addr nnpc; public: Addr readPC(); void setPC(Addr val); Addr readNextPC(); void setNextPC(Addr val); Addr readNextNPC(); void setNextNPC(Addr val); protected: IntRegFile intRegFile; // integer register file FloatRegFile floatRegFile; // floating point register file MiscRegFile miscRegFile; // control register file public: void clear(); int FlattenIntIndex(int reg); MiscReg readMiscRegNoEffect(int miscReg); MiscReg readMiscReg(int miscReg, ThreadContext *tc); void setMiscRegNoEffect(int miscReg, const MiscReg &val); void setMiscReg(int miscReg, const MiscReg &val, ThreadContext * tc); int instAsid() { return miscRegFile.getInstAsid(); } int dataAsid() { return miscRegFile.getDataAsid(); } FloatReg readFloatReg(int floatReg, int width); FloatReg readFloatReg(int floatReg); FloatRegBits readFloatRegBits(int floatReg, int width); FloatRegBits readFloatRegBits(int floatReg); void setFloatReg(int floatReg, const FloatReg &val, int width); void setFloatReg(int floatReg, const FloatReg &val); void setFloatRegBits(int floatReg, const FloatRegBits &val, int width); void setFloatRegBits(int floatReg, const FloatRegBits &val); IntReg readIntReg(int intReg); void setIntReg(int intReg, const IntReg &val); void serialize(std::ostream &os); void unserialize(Checkpoint *cp, const std::string &section); public: void changeContext(RegContextParam param, RegContextVal val); }; int flattenIntIndex(ThreadContext * tc, int reg); int flattenFloatIndex(ThreadContext * tc, int reg) { return reg; } void copyRegs(ThreadContext *src, ThreadContext *dest); void copyMiscRegs(ThreadContext *src, ThreadContext *dest); } // namespace SparcISA #endif <commit_msg>SPARC: Fix linking error from new flattenFloatIndex function.<commit_after>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Gabe Black * Ali Saidi */ #ifndef __ARCH_SPARC_REGFILE_HH__ #define __ARCH_SPARC_REGFILE_HH__ #include "arch/sparc/floatregfile.hh" #include "arch/sparc/intregfile.hh" #include "arch/sparc/isa_traits.hh" #include "arch/sparc/miscregfile.hh" #include "arch/sparc/types.hh" #include "sim/host.hh" #include <string> class Checkpoint; namespace SparcISA { class RegFile { protected: Addr pc; // Program Counter Addr npc; // Next Program Counter Addr nnpc; public: Addr readPC(); void setPC(Addr val); Addr readNextPC(); void setNextPC(Addr val); Addr readNextNPC(); void setNextNPC(Addr val); protected: IntRegFile intRegFile; // integer register file FloatRegFile floatRegFile; // floating point register file MiscRegFile miscRegFile; // control register file public: void clear(); int FlattenIntIndex(int reg); MiscReg readMiscRegNoEffect(int miscReg); MiscReg readMiscReg(int miscReg, ThreadContext *tc); void setMiscRegNoEffect(int miscReg, const MiscReg &val); void setMiscReg(int miscReg, const MiscReg &val, ThreadContext * tc); int instAsid() { return miscRegFile.getInstAsid(); } int dataAsid() { return miscRegFile.getDataAsid(); } FloatReg readFloatReg(int floatReg, int width); FloatReg readFloatReg(int floatReg); FloatRegBits readFloatRegBits(int floatReg, int width); FloatRegBits readFloatRegBits(int floatReg); void setFloatReg(int floatReg, const FloatReg &val, int width); void setFloatReg(int floatReg, const FloatReg &val); void setFloatRegBits(int floatReg, const FloatRegBits &val, int width); void setFloatRegBits(int floatReg, const FloatRegBits &val); IntReg readIntReg(int intReg); void setIntReg(int intReg, const IntReg &val); void serialize(std::ostream &os); void unserialize(Checkpoint *cp, const std::string &section); public: void changeContext(RegContextParam param, RegContextVal val); }; int flattenIntIndex(ThreadContext * tc, int reg); static inline int flattenFloatIndex(ThreadContext * tc, int reg) { return reg; } void copyRegs(ThreadContext *src, ThreadContext *dest); void copyMiscRegs(ThreadContext *src, ThreadContext *dest); } // namespace SparcISA #endif <|endoftext|>
<commit_before>#include <iostream> #include "Compiler.h" #include "ErrorCode.h" namespace lyrics { const u16string Scanner::BREAK = u"break"; const u16string Scanner::CASE = u"case"; const u16string Scanner::CLASS = u"class"; const u16string Scanner::DO = u"do"; const u16string Scanner::END = u"end"; const u16string Scanner::ELSE = u"else"; const u16string Scanner::ELSEIF = u"elseif"; const u16string Scanner::FALSE = u"false"; const u16string Scanner::FOR = u"for"; const u16string Scanner::IF = u"if"; const u16string Scanner::IMPORT = u"import"; const u16string Scanner::IN = u"in"; const u16string Scanner::NIL = u"nil"; const u16string Scanner::OUT = u"out"; const u16string Scanner::PACKAGE = u"package"; const u16string Scanner::PROC = u"proc"; const u16string Scanner::REDO = u"redo"; const u16string Scanner::RETURN = u"return"; const u16string Scanner::THEN = u"then"; const u16string Scanner::TRUE = u"true"; const u16string Scanner::WHEN = u"when"; const u16string Scanner::WHILE = u"while"; }; namespace { void Error( const lyrics::ErrorCode errorCode ); }; int main( int argc, char *argv[] ) { if ( argc < 2 ) { Error( lyrics::ErrorCode::NO_INPUT_FILE ); return 0; } lyrics::Compiler compiler; for ( int i = 1; i < argc; i++ ) { if ( !compiler.Compile( argv[i] ) ) { // TODO: return 0; } } return 0; } namespace { void Error( const lyrics::ErrorCode errorCode ) { using std::cout; using std::cerr; constexpr char ERROR[] = "Error"; switch ( errorCode ) { case lyrics::ErrorCode::NO_INPUT_FILE: cout << ERROR << ' ' << static_cast<unsigned int>( errorCode ) << ": " << "No input file."; break; default: cerr << ERROR << ' ' << static_cast<unsigned int>( errorCode ); break; } } };<commit_msg>#include <string><commit_after>#include <iostream> #include <string> #include "Compiler.h" #include "ErrorCode.h" namespace lyrics { const u16string Scanner::BREAK = u"break"; const u16string Scanner::CASE = u"case"; const u16string Scanner::CLASS = u"class"; const u16string Scanner::DO = u"do"; const u16string Scanner::END = u"end"; const u16string Scanner::ELSE = u"else"; const u16string Scanner::ELSEIF = u"elseif"; const u16string Scanner::FALSE = u"false"; const u16string Scanner::FOR = u"for"; const u16string Scanner::IF = u"if"; const u16string Scanner::IMPORT = u"import"; const u16string Scanner::IN = u"in"; const u16string Scanner::NIL = u"nil"; const u16string Scanner::OUT = u"out"; const u16string Scanner::PACKAGE = u"package"; const u16string Scanner::PROC = u"proc"; const u16string Scanner::REDO = u"redo"; const u16string Scanner::RETURN = u"return"; const u16string Scanner::THEN = u"then"; const u16string Scanner::TRUE = u"true"; const u16string Scanner::WHEN = u"when"; const u16string Scanner::WHILE = u"while"; }; namespace { void Error( const lyrics::ErrorCode errorCode ); }; int main( int argc, char *argv[] ) { if ( argc < 2 ) { Error( lyrics::ErrorCode::NO_INPUT_FILE ); return 0; } lyrics::Compiler compiler; for ( int i = 1; i < argc; i++ ) { if ( !compiler.Compile( argv[i] ) ) { // TODO: return 0; } } return 0; } namespace { void Error( const lyrics::ErrorCode errorCode ) { using std::cout; using std::cerr; constexpr char ERROR[] = "Error"; switch ( errorCode ) { case lyrics::ErrorCode::NO_INPUT_FILE: cout << ERROR << ' ' << static_cast<unsigned int>( errorCode ) << ": " << "No input file."; break; default: cerr << ERROR << ' ' << static_cast<unsigned int>( errorCode ); break; } } };<|endoftext|>
<commit_before>// // Created by joe on 10/21/16. // #include "calcc/asttools/compiler.h" #include "calcc/global_llvm.h" using namespace calcc::ast; using namespace calcc; using namespace std; using namespace llvm; static llvm::BasicBlock* BB; Type *toType(VAL_TYPE vt) { switch (vt) { case VAL_INT: return Type::getInt64Ty(calcc::C); case VAL_BOOL: return Type::getInt1Ty(calcc::C); default: throw error::scanner("Unknown type error"); } } Expr* Compiler::scan(FDecl *e, valmap &out) { // Setup Parameters std::vector<Type *> params; vector<VDecl*> p = e->getParams(); for (int i = 0; i<p.size(); ++i) params.push_back(toType(p[i]->getValType())); FunctionType *FT = FunctionType::get(toType(e->getValType()), params, false); Function *F = Function::Create(FT, Function::ExternalLinkage, "f", &*calcc::M); BB = BasicBlock::Create(calcc::C, "entry", F); auto it = F->arg_begin(); for (int i = 0; i<p.size(); ++i, ++it) p[i]->setVPtr(new ValPtr(&*it)); calcc::Builder.SetInsertPoint(BB); ValPtr* ret = (ValPtr*)Scanner::run(e->getBody(), out); // Setup Return calcc::Builder.CreateRet(ret->getValue()); return e; } Expr* Compiler::scan(IntLiteral *e, valmap &out) { return new ValPtr(llvm::ConstantInt::get(C, e->getValue())); } Expr* Compiler::scan(BinaryOp *e, valmap &out) { ValPtr* lhs = (ValPtr*)Scanner::run(e->getLHS(), out); ValPtr* rhs = (ValPtr*)Scanner::run(e->getRHS(), out); switch (e->getOP()) { case BINOP_PLUS: return new ValPtr(Builder.CreateAdd(lhs->getValue(),rhs->getValue())); case BINOP_MINUS: return new ValPtr(Builder.CreateSub(lhs->getValue(),rhs->getValue())); case BINOP_MULT: return new ValPtr(Builder.CreateMul(lhs->getValue(),rhs->getValue())); case BINOP_DIV: return new ValPtr(Builder.CreateSDiv(lhs->getValue(),rhs->getValue())); case BINOP_MOD: return new ValPtr(Builder.CreateSRem(lhs->getValue(),rhs->getValue())); case BINOP_EQ: return new ValPtr(Builder.CreateICmpEQ(lhs->getValue(),rhs->getValue())); case BINOP_NE: return new ValPtr(Builder.CreateICmpNE(lhs->getValue(),rhs->getValue())); case BINOP_LT: return new ValPtr(Builder.CreateICmpSLT(lhs->getValue(),rhs->getValue())); case BINOP_LE: return new ValPtr(Builder.CreateICmpSLE(lhs->getValue(),rhs->getValue())); case BINOP_GT: return new ValPtr(Builder.CreateICmpSGT(lhs->getValue(),rhs->getValue())); case BINOP_GE: return new ValPtr(Builder.CreateICmpSGE(lhs->getValue(),rhs->getValue())); default: throw error::scanner("Unknown binary op type"); } return NULL; } Expr* Compiler::scan(If *e, valmap &out) { ValPtr* cnd = (ValPtr*)Scanner::run(e->getCnd(), out); Function *F = BB->getParent(); BasicBlock* entry = BB; BasicBlock* ethnB = BasicBlock::Create(calcc::C, "thenIf", F); BB = ethnB; calcc::Builder.SetInsertPoint(BB); ValPtr* thn = (ValPtr*)Scanner::run(e->getThn(), out); BasicBlock* thnB = BB; BasicBlock* eelsB = BasicBlock::Create(calcc::C, "elseIf", F); BB = eelsB; calcc::Builder.SetInsertPoint(BB); ValPtr* els = (ValPtr*)Scanner::run(e->getEls(), out); BasicBlock* elsB = BB; BasicBlock* after = BasicBlock::Create(calcc::C, "afterIf", F); Builder.SetInsertPoint(entry); Builder.CreateCondBr(cnd->getValue(),ethnB,eelsB); Builder.SetInsertPoint(thnB); Builder.CreateBr(after); Builder.SetInsertPoint(elsB); Builder.CreateBr(after); BB = after; calcc::Builder.SetInsertPoint(BB); PHINode* ret = Builder.CreatePHI(toType(e->getValType()),2); ret->addIncoming(thn->getValue(), thnB); ret->addIncoming(els->getValue(), elsB); return new ValPtr(ret); } Expr* Compiler::scan(Ref *e, valmap &out) { Decl* d = e->getDecl(); if (d->getExprType() == EXPR_FDECL) throw error::scanner("Can't refer to a FDecl yet"); VDecl* vd = (VDecl*) d; return vd->getVPtr(); } Expr* Compiler::scan(ValPtr *e, valmap &out) { return e; } Expr* Compiler::scan(VDecl *e, valmap &out) { throw error::scanner("Error: trying to compile a VDecl"); return e; } <commit_msg>clean up if logic<commit_after>// // Created by joe on 10/21/16. // #include "calcc/asttools/compiler.h" #include "calcc/global_llvm.h" using namespace calcc::ast; using namespace calcc; using namespace std; using namespace llvm; static llvm::BasicBlock* BB; void setCurrentBlock(llvm::BasicBlock* b) { BB = b; calcc::Builder.SetInsertPoint(BB); } Type *toType(VAL_TYPE vt) { switch (vt) { case VAL_INT: return Type::getInt64Ty(calcc::C); case VAL_BOOL: return Type::getInt1Ty(calcc::C); default: throw error::scanner("Unknown type error"); } } Expr* Compiler::scan(FDecl *e, valmap &out) { // Setup Parameters std::vector<Type *> params; vector<VDecl*> p = e->getParams(); for (int i = 0; i<p.size(); ++i) params.push_back(toType(p[i]->getValType())); FunctionType *FT = FunctionType::get(toType(e->getValType()), params, false); Function *F = Function::Create(FT, Function::ExternalLinkage, "f", &*calcc::M); setCurrentBlock(BasicBlock::Create(calcc::C, "entry", F)); auto it = F->arg_begin(); for (int i = 0; i<p.size(); ++i, ++it) p[i]->setVPtr(new ValPtr(&*it)); ValPtr* ret = (ValPtr*)Scanner::run(e->getBody(), out); // Setup Return calcc::Builder.CreateRet(ret->getValue()); return e; } Expr* Compiler::scan(IntLiteral *e, valmap &out) { return new ValPtr(llvm::ConstantInt::get(C, e->getValue())); } Expr* Compiler::scan(BinaryOp *e, valmap &out) { ValPtr* lhs = (ValPtr*)Scanner::run(e->getLHS(), out); ValPtr* rhs = (ValPtr*)Scanner::run(e->getRHS(), out); switch (e->getOP()) { case BINOP_PLUS: return new ValPtr(Builder.CreateAdd(lhs->getValue(),rhs->getValue())); case BINOP_MINUS: return new ValPtr(Builder.CreateSub(lhs->getValue(),rhs->getValue())); case BINOP_MULT: return new ValPtr(Builder.CreateMul(lhs->getValue(),rhs->getValue())); case BINOP_DIV: return new ValPtr(Builder.CreateSDiv(lhs->getValue(),rhs->getValue())); case BINOP_MOD: return new ValPtr(Builder.CreateSRem(lhs->getValue(),rhs->getValue())); case BINOP_EQ: return new ValPtr(Builder.CreateICmpEQ(lhs->getValue(),rhs->getValue())); case BINOP_NE: return new ValPtr(Builder.CreateICmpNE(lhs->getValue(),rhs->getValue())); case BINOP_LT: return new ValPtr(Builder.CreateICmpSLT(lhs->getValue(),rhs->getValue())); case BINOP_LE: return new ValPtr(Builder.CreateICmpSLE(lhs->getValue(),rhs->getValue())); case BINOP_GT: return new ValPtr(Builder.CreateICmpSGT(lhs->getValue(),rhs->getValue())); case BINOP_GE: return new ValPtr(Builder.CreateICmpSGE(lhs->getValue(),rhs->getValue())); default: throw error::scanner("Unknown binary op type"); } return NULL; } Expr* Compiler::scan(If *e, valmap &out) { ValPtr* cnd = (ValPtr*)Scanner::run(e->getCnd(), out); Function *F = BB->getParent(); BasicBlock* thnB = BasicBlock::Create(calcc::C, "thenIf", F); BasicBlock* elsB = BasicBlock::Create(calcc::C, "elseIf", F); BasicBlock* aftB = BasicBlock::Create(calcc::C, "afterIf", F); Builder.CreateCondBr(cnd->getValue(),thnB,elsB); setCurrentBlock(thnB); ValPtr* thn = (ValPtr*)Scanner::run(e->getThn(), out); Builder.CreateBr(aftB); thnB = BB; setCurrentBlock(elsB); ValPtr* els = (ValPtr*)Scanner::run(e->getEls(), out); Builder.CreateBr(aftB); elsB = BB; setCurrentBlock(aftB); PHINode* ret = Builder.CreatePHI(toType(e->getValType()),2); ret->addIncoming(thn->getValue(), thnB); ret->addIncoming(els->getValue(), elsB); return new ValPtr(ret); } Expr* Compiler::scan(Ref *e, valmap &out) { Decl* d = e->getDecl(); if (d->getExprType() == EXPR_FDECL) throw error::scanner("Can't refer to a FDecl yet"); VDecl* vd = (VDecl*) d; return vd->getVPtr(); } Expr* Compiler::scan(ValPtr *e, valmap &out) { return e; } Expr* Compiler::scan(VDecl *e, valmap &out) { throw error::scanner("Error: trying to compile a VDecl"); return e; } <|endoftext|>
<commit_before>// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Implementation of the Mp3AudioSource class. * @see audio/sources/mp3.hpp */ #include <cassert> #include <cstdint> #include <cstdlib> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> extern "C" { #include <mpg123.h> } #include "../../errors.hpp" #include "../../messages.h" #include "../audio_source.hpp" #include "../sample_formats.hpp" #include "mp3.hpp" // Fix for the ancient 2010 version of mpg123 carried by Ubuntu 12.04 and pals, // which doesn't have 24-bit support // See http://www.mpg123.de/cgi-bin/scm/mpg123/trunk/NEWS?pathrev=2791 #if MPG123_API_VERSION < 28 // Let us be able to omit the check for 24-bit formats later. #define HAVE_MPG123_24BIT 1 // Make the use of this when divining formats a no-op. #define MPG123_ENC_SIGNED_24 0 #endif // This value is somewhat arbitrary, but corresponds to the minimum buffer size // used by ffmpeg, so it's probably sensible. const size_t Mp3AudioSource::BUFFER_SIZE = 16384; Mp3AudioSource::Mp3AudioSource(const std::string &path) : AudioSource(path), buffer(BUFFER_SIZE), context(nullptr) { this->context = mpg123_new(nullptr, nullptr); mpg123_format_none(this->context); const long *rates = nullptr; size_t nrates = 0; mpg123_rates(&rates, &nrates); for (size_t r = 0; r < nrates; r++) { Debug() << "trying to enable formats at " << rates[r] << std::endl; AddFormat(rates[r]); } if (mpg123_open(this->context, path.c_str()) == MPG123_ERR) { throw FileError("mp3: can't open " + path + ": " + mpg123_strerror(this->context)); } Debug() << "mp3: sample rate:" << this->SampleRate() << std::endl; Debug() << "mp3: bytes per sample:" << this->BytesPerSample() << std::endl; Debug() << "mp3: channels:" << (int)this->ChannelCount() << std::endl; Debug() << "mp3: playd format:" << (int)this->OutputSampleFormat() << std::endl; } Mp3AudioSource::~Mp3AudioSource() { mpg123_delete(this->context); this->context = nullptr; } void Mp3AudioSource::AddFormat(long rate) { // The requested encodings correspond to the sample formats available in // the SampleFormat enum. if (mpg123_format(this->context, rate, MPG123_STEREO | MPG123_MONO, (MPG123_ENC_UNSIGNED_8 | MPG123_ENC_SIGNED_8 | MPG123_ENC_SIGNED_16 | MPG123_ENC_SIGNED_24 | MPG123_ENC_SIGNED_32 | MPG123_ENC_FLOAT_32)) == MPG123_ERR) { // Ignore the error for now -- another sample rate may be // available. // If no sample rates work, loading a file will fail anyway. Debug() << "can't support" << rate << std::endl; }; } std::uint8_t Mp3AudioSource::ChannelCount() const { assert(this->context != nullptr); int chans = 0; mpg123_getformat(this->context, nullptr, &chans, nullptr); assert(chans != 0); return static_cast<std::uint8_t>(chans); } std::uint32_t Mp3AudioSource::SampleRate() const { assert(this->context != nullptr); long rate = 0; mpg123_getformat(this->context, &rate, nullptr, nullptr); assert(0 < rate); // INT32_MAX isn't a typo; if we compare against UINT32_MAX, we'll // set off sign-compare errors, and the sample rate shouldn't be above // INT32_MAX anyroad. assert(rate <= INT32_MAX); return static_cast<std::uint32_t>(rate); } std::uint64_t Mp3AudioSource::Seek(std::uint64_t in_samples) { assert(this->context != nullptr); // See BytesPerSample() for an explanation of this ChannelCount(). auto mono_samples = in_samples * this->ChannelCount(); // Have we tried to seek past the end of the file? auto clen = static_cast<unsigned long>(mpg123_length(this->context)); if (clen < mono_samples) { Debug() << "mp3: seek at" << mono_samples << "past EOF at" << clen << std::endl; throw SeekError(MSG_SEEK_FAIL); } if (mpg123_seek(this->context, mono_samples, SEEK_SET) == MPG123_ERR) { Debug() << "mp3: seek failed:" << mpg123_strerror(this->context) << std::endl; throw SeekError(MSG_SEEK_FAIL); } // The actual seek position may not be the same as the requested // position. // mpg123_tell gives us the exact mono-samples position. return mpg123_tell(this->context) / this->ChannelCount(); } Mp3AudioSource::DecodeResult Mp3AudioSource::Decode() { assert(this->context != nullptr); auto buf = reinterpret_cast<unsigned char *>(&this->buffer.front()); size_t rbytes = 0; int err = mpg123_read(this->context, buf, this->buffer.size(), &rbytes); DecodeVector decoded; DecodeState decode_state; if (err == MPG123_DONE) { Debug() << "mp3: end of file" << std::endl; decode_state = DecodeState::END_OF_FILE; } else if (err != MPG123_OK && err != MPG123_NEW_FORMAT) { Debug() << "mp3: decode error:" << mpg123_strerror(this->context) << std::endl; decode_state = DecodeState::END_OF_FILE; } else { decode_state = DecodeState::DECODING; // Copy only the bit of the buffer occupied by decoded data auto front = this->buffer.begin(); decoded = DecodeVector(front, front + rbytes); } return std::make_pair(decode_state, decoded); } SampleFormat Mp3AudioSource::OutputSampleFormat() const { assert(this->context != nullptr); int encoding = 0; mpg123_getformat(this->context, nullptr, nullptr, &encoding); switch (encoding) { case MPG123_ENC_UNSIGNED_8: return SampleFormat::PACKED_UNSIGNED_INT_8; case MPG123_ENC_SIGNED_8: return SampleFormat::PACKED_SIGNED_INT_8; case MPG123_ENC_SIGNED_16: return SampleFormat::PACKED_SIGNED_INT_16; #ifdef HAVE_MPG123_24BIT case MPG123_ENC_SIGNED_24: return SampleFormat::PACKED_SIGNED_INT_24; #endif case MPG123_ENC_SIGNED_32: return SampleFormat::PACKED_SIGNED_INT_32; case MPG123_ENC_FLOAT_32: return SampleFormat::PACKED_FLOAT_32; default: // We shouldn't get here, if the format was set up // correctly earlier. assert(false); } } <commit_msg>Fix up a couple of compile errors.<commit_after>// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Implementation of the Mp3AudioSource class. * @see audio/sources/mp3.hpp */ #include <cassert> #include <cstdint> #include <cstdio> #include <cstdlib> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> extern "C" { #include <mpg123.h> } #include "../../errors.hpp" #include "../../messages.h" #include "../audio_source.hpp" #include "../sample_formats.hpp" #include "mp3.hpp" // Fix for the ancient 2010 version of mpg123 carried by Ubuntu 12.04 and pals, // which doesn't have 24-bit support // See http://www.mpg123.de/cgi-bin/scm/mpg123/trunk/NEWS?pathrev=2791 #if MPG123_API_VERSION < 28 // Let us be able to omit the check for 24-bit formats later. #define HAVE_MPG123_24BIT 1 // Make the use of this when divining formats a no-op. #define MPG123_ENC_SIGNED_24 0 #endif // This value is somewhat arbitrary, but corresponds to the minimum buffer size // used by ffmpeg, so it's probably sensible. const size_t Mp3AudioSource::BUFFER_SIZE = 16384; Mp3AudioSource::Mp3AudioSource(const std::string &path) : AudioSource(path), buffer(BUFFER_SIZE), context(nullptr) { this->context = mpg123_new(nullptr, nullptr); mpg123_format_none(this->context); const long *rates = nullptr; size_t nrates = 0; mpg123_rates(&rates, &nrates); for (size_t r = 0; r < nrates; r++) { Debug() << "trying to enable formats at " << rates[r] << std::endl; AddFormat(rates[r]); } if (mpg123_open(this->context, path.c_str()) == MPG123_ERR) { throw FileError("mp3: can't open " + path + ": " + mpg123_strerror(this->context)); } Debug() << "mp3: sample rate:" << this->SampleRate() << std::endl; Debug() << "mp3: bytes per sample:" << this->BytesPerSample() << std::endl; Debug() << "mp3: channels:" << (int)this->ChannelCount() << std::endl; Debug() << "mp3: playd format:" << (int)this->OutputSampleFormat() << std::endl; } Mp3AudioSource::~Mp3AudioSource() { mpg123_delete(this->context); this->context = nullptr; } void Mp3AudioSource::AddFormat(long rate) { // The requested encodings correspond to the sample formats available in // the SampleFormat enum. if (mpg123_format(this->context, rate, MPG123_STEREO | MPG123_MONO, (MPG123_ENC_UNSIGNED_8 | MPG123_ENC_SIGNED_8 | MPG123_ENC_SIGNED_16 | MPG123_ENC_SIGNED_24 | MPG123_ENC_SIGNED_32 | MPG123_ENC_FLOAT_32)) == MPG123_ERR) { // Ignore the error for now -- another sample rate may be // available. // If no sample rates work, loading a file will fail anyway. Debug() << "can't support" << rate << std::endl; }; } std::uint8_t Mp3AudioSource::ChannelCount() const { assert(this->context != nullptr); int chans = 0; mpg123_getformat(this->context, nullptr, &chans, nullptr); assert(chans != 0); return static_cast<std::uint8_t>(chans); } std::uint32_t Mp3AudioSource::SampleRate() const { assert(this->context != nullptr); long rate = 0; mpg123_getformat(this->context, &rate, nullptr, nullptr); assert(0 < rate); // INT32_MAX isn't a typo; if we compare against UINT32_MAX, we'll // set off sign-compare errors, and the sample rate shouldn't be above // INT32_MAX anyroad. assert(rate <= INT32_MAX); return static_cast<std::uint32_t>(rate); } std::uint64_t Mp3AudioSource::Seek(std::uint64_t in_samples) { assert(this->context != nullptr); // See BytesPerSample() for an explanation of this ChannelCount(). auto mono_samples = in_samples * this->ChannelCount(); // Have we tried to seek past the end of the file? auto clen = static_cast<unsigned long>(mpg123_length(this->context)); if (clen < mono_samples) { Debug() << "mp3: seek at" << mono_samples << "past EOF at" << clen << std::endl; throw SeekError(MSG_SEEK_FAIL); } if (mpg123_seek(this->context, mono_samples, SEEK_SET) == MPG123_ERR) { Debug() << "mp3: seek failed:" << mpg123_strerror(this->context) << std::endl; throw SeekError(MSG_SEEK_FAIL); } // The actual seek position may not be the same as the requested // position. // mpg123_tell gives us the exact mono-samples position. return mpg123_tell(this->context) / this->ChannelCount(); } Mp3AudioSource::DecodeResult Mp3AudioSource::Decode() { assert(this->context != nullptr); auto buf = reinterpret_cast<unsigned char *>(&this->buffer.front()); size_t rbytes = 0; int err = mpg123_read(this->context, buf, this->buffer.size(), &rbytes); DecodeVector decoded; DecodeState decode_state; if (err == MPG123_DONE) { Debug() << "mp3: end of file" << std::endl; decode_state = DecodeState::END_OF_FILE; } else if (err != MPG123_OK && err != MPG123_NEW_FORMAT) { Debug() << "mp3: decode error:" << mpg123_strerror(this->context) << std::endl; decode_state = DecodeState::END_OF_FILE; } else { decode_state = DecodeState::DECODING; // Copy only the bit of the buffer occupied by decoded data auto front = this->buffer.begin(); decoded = DecodeVector(front, front + rbytes); } return std::make_pair(decode_state, decoded); } SampleFormat Mp3AudioSource::OutputSampleFormat() const { assert(this->context != nullptr); int encoding = 0; mpg123_getformat(this->context, nullptr, nullptr, &encoding); switch (encoding) { case MPG123_ENC_UNSIGNED_8: return SampleFormat::PACKED_UNSIGNED_INT_8; case MPG123_ENC_SIGNED_8: return SampleFormat::PACKED_SIGNED_INT_8; case MPG123_ENC_SIGNED_16: return SampleFormat::PACKED_SIGNED_INT_16; #ifdef HAVE_MPG123_24BIT case MPG123_ENC_SIGNED_24: return SampleFormat::PACKED_SIGNED_INT_24; #endif case MPG123_ENC_SIGNED_32: return SampleFormat::PACKED_SIGNED_INT_32; case MPG123_ENC_FLOAT_32: return SampleFormat::PACKED_FLOAT_32; default: // We shouldn't get here, if the format was set up // correctly earlier. assert(false); return SampleFormat::PACKED_UNSIGNED_INT_8; } } <|endoftext|>
<commit_before>#ifndef EFFOLKRONIUM_RANDOM_HPP #define EFFOLKRONIUM_RANDOM_HPP #include <random> #include <type_traits> #include <cassert> #include <initializer_list> #include <iterator> // std::next #include <utility> // std::declval namespace effolkronium { namespace details { /// Key type for getting common type numbers or objects struct common{ }; /// True if type T is applicable by the std::uniform_int_distribution template<typename T> struct is_uniform_int { static constexpr bool value = std::is_same<T, short>::value || std::is_same<T, int>::value || std::is_same<T, long>::value || std::is_same<T, long long>::value || std::is_same<T, unsigned short>::value || std::is_same<T, unsigned int>::value || std::is_same<T, unsigned long>::value || std::is_same<T, unsigned long long>::value; }; /// True if type T is applicable by a std::uniform_real_distribution template<typename T> struct is_uniform_real { static constexpr bool value = std::is_same<T, float>::value || std::is_same<T, double>::value || std::is_same<T, long double>::value; }; /// True if type T is plain byte template<typename T> struct is_byte { static constexpr bool value = std::is_same<T, signed char>::value || std::is_same<T, unsigned char>::value; }; /// True if type T is plain number type template<typename T> struct is_supported_number { static constexpr bool value = is_byte <T>::value || is_uniform_real<T>::value || is_uniform_int <T>::value; }; } /** * \brief Base template class for random * \param Engine A random engine with interface like in the std::mt19937 */ template<typename Engine> class basic_random_static { public: /// Type of used random number engine using engine_type = Engine; /// Key type for getting common type numbers or objects using common = details::common; /** * \brief Generate a random integer number in a [from; to] range * by std::uniform_int_distribution * \param from The first limit number of a random range * \param to The second limit number of a random range * \return A random integer number in a [from; to] range * \note Allow both: 'from' <= 'to' and 'from' >= 'to' * \note Prevent implicit type conversion */ template<typename A> static typename std::enable_if<details::is_uniform_int<A>::value , A>::type get( A from, A to ) noexcept { if( from < to ) // Allow range from higher to lower return std::uniform_int_distribution<A>{ from, to }( engine ); return std::uniform_int_distribution<A>{ to, from }( engine ); } /** * \brief Generate a random real number in a [from; to] range * by std::uniform_real_distribution * \param from The first limit number of a random range * \param to The second limit number of a random range * \return A random real number in a [from; to] range * \note Allow both: 'from' <= 'to' and 'from' >= 'to' * \note Prevent implicit type conversion */ template<typename A> static typename std::enable_if<details::is_uniform_real<A>::value , A>::type get( A from, A to ) noexcept { if( from < to ) // Allow range from higher to lower return std::uniform_real_distribution<A>{ from, to }( engine ); return std::uniform_real_distribution<A>{ to, from }( engine ); } /** * \brief Generate a random byte number in a [from; to] range * \param from The first limit number of a random range * \param to The second limit number of a random range * \return A random byte number in a [from; to] range * \note Allow both: 'from' <= 'to' and 'from' >= 'to' * \note Prevent implicit type conversion */ template<typename A> static typename std::enable_if<details::is_byte<A>::value , A>::type get( A from, A to ) noexcept { // Choose between short and unsigned short for byte conversion using short_t = typename std::conditional< std::is_signed<A>::value, short, unsigned short>::type; return static_cast<A>( get( static_cast<short_t>( from ), static_cast<short_t>( to ) ) ); } /** * \brief Generate a random common_type number in a [from; to] range * \param Key The Key type for this version of 'get' method * Type should be '(THIS_TYPE)::common' struct * \param from The first limit number of a random range * \param to The second limit number of a random range * \return A random common_type number in a [from; to] range * \note Allow both: 'from' <= 'to' and 'from' >= 'to' * \note Allow implicit type conversion * \note Prevent implicit type conversion from singed to unsigned types * Why? std::common_type<Unsigned, Signed> chooses unsigned value, * then Signed value will be converted to Unsigned value * which gives us a wrong range for random values. * https://stackoverflow.com/a/5416498/5734836 */ template<typename Key, typename A, typename B, typename C = typename std::common_type<A, B>::type> static typename std::enable_if< std::is_same<Key, common>::value && details::is_supported_number<A>::value && details::is_supported_number<B>::value // Prevent implicit type conversion from singed to unsigned types && std::is_signed<A>::value != std::is_unsigned<B>::value , C>::type get( A from, B to ) noexcept { return get( static_cast<C>( from ), static_cast<C>( to ) ); } /** * \brief Generate a bool value with specific probability * by std::bernoulli_distribution * \param probability The probability of generating true in [0; 1] range * 0 means always false, 1 means always true * \return 'true' with 'probability' probability ('false' otherwise) */ template<typename T> static typename std::enable_if<std::is_same<T, bool>::value , bool>::type get( const double probability = 0.5 ) noexcept { assert( 0 <= probability && 1 >= probability ); // out of [0; 1] range return std::bernoulli_distribution{ probability }( engine ); } /** * \param init_list initilizer_list with values * \return Random value from initilizer_list by value * \note Should be 1 or more elements in initilizer_list */ template<typename T> static T get( std::initializer_list<T> init_list ) noexcept( noexcept( T{ std::declval<T>( ) } ) ) { assert( 0u != init_list.size( ) ); return *std::next( init_list.begin( ), get<typename std::initializer_list<T>::size_type>( 0u, typename std::iterator_traits< decltype( init_list.begin( ) )>::difference_type( init_list.size( ) - 1u ) ) ); } private: /// The random number engine static Engine engine; }; template<typename Engine> Engine basic_random_static<Engine>::engine( std::random_device{ }( ) ); /** * \brief The basic static random alias based on a std::default_random_engine * \note It uses static methods API and data with static storage * \note Not thread safe but more prefomance */ using random_static = basic_random_static<std::default_random_engine>; } // namespace effolkronium #endif // #ifndef EFFOLKRONIUM_RANDOM_HPP<commit_msg>Try to fix warning error<commit_after>#ifndef EFFOLKRONIUM_RANDOM_HPP #define EFFOLKRONIUM_RANDOM_HPP #include <random> #include <type_traits> #include <cassert> #include <initializer_list> #include <iterator> // std::next #include <utility> // std::declval namespace effolkronium { namespace details { /// Key type for getting common type numbers or objects struct common{ }; /// True if type T is applicable by the std::uniform_int_distribution template<typename T> struct is_uniform_int { static constexpr bool value = std::is_same<T, short>::value || std::is_same<T, int>::value || std::is_same<T, long>::value || std::is_same<T, long long>::value || std::is_same<T, unsigned short>::value || std::is_same<T, unsigned int>::value || std::is_same<T, unsigned long>::value || std::is_same<T, unsigned long long>::value; }; /// True if type T is applicable by a std::uniform_real_distribution template<typename T> struct is_uniform_real { static constexpr bool value = std::is_same<T, float>::value || std::is_same<T, double>::value || std::is_same<T, long double>::value; }; /// True if type T is plain byte template<typename T> struct is_byte { static constexpr bool value = std::is_same<T, signed char>::value || std::is_same<T, unsigned char>::value; }; /// True if type T is plain number type template<typename T> struct is_supported_number { static constexpr bool value = is_byte <T>::value || is_uniform_real<T>::value || is_uniform_int <T>::value; }; } /** * \brief Base template class for random * \param Engine A random engine with interface like in the std::mt19937 */ template<typename Engine> class basic_random_static { public: /// Type of used random number engine using engine_type = Engine; /// Key type for getting common type numbers or objects using common = details::common; /** * \brief Generate a random integer number in a [from; to] range * by std::uniform_int_distribution * \param from The first limit number of a random range * \param to The second limit number of a random range * \return A random integer number in a [from; to] range * \note Allow both: 'from' <= 'to' and 'from' >= 'to' * \note Prevent implicit type conversion */ template<typename A> static typename std::enable_if<details::is_uniform_int<A>::value , A>::type get( A from, A to ) noexcept { if( from < to ) // Allow range from higher to lower return std::uniform_int_distribution<A>{ from, to }( engine ); return std::uniform_int_distribution<A>{ to, from }( engine ); } /** * \brief Generate a random real number in a [from; to] range * by std::uniform_real_distribution * \param from The first limit number of a random range * \param to The second limit number of a random range * \return A random real number in a [from; to] range * \note Allow both: 'from' <= 'to' and 'from' >= 'to' * \note Prevent implicit type conversion */ template<typename A> static typename std::enable_if<details::is_uniform_real<A>::value , A>::type get( A from, A to ) noexcept { if( from < to ) // Allow range from higher to lower return std::uniform_real_distribution<A>{ from, to }( engine ); return std::uniform_real_distribution<A>{ to, from }( engine ); } /** * \brief Generate a random byte number in a [from; to] range * \param from The first limit number of a random range * \param to The second limit number of a random range * \return A random byte number in a [from; to] range * \note Allow both: 'from' <= 'to' and 'from' >= 'to' * \note Prevent implicit type conversion */ template<typename A> static typename std::enable_if<details::is_byte<A>::value , A>::type get( A from, A to ) noexcept { // Choose between short and unsigned short for byte conversion using short_t = typename std::conditional< std::is_signed<A>::value, short, unsigned short>::type; return static_cast<A>( get( static_cast<short_t>( from ), static_cast<short_t>( to ) ) ); } /** * \brief Generate a random common_type number in a [from; to] range * \param Key The Key type for this version of 'get' method * Type should be '(THIS_TYPE)::common' struct * \param from The first limit number of a random range * \param to The second limit number of a random range * \return A random common_type number in a [from; to] range * \note Allow both: 'from' <= 'to' and 'from' >= 'to' * \note Allow implicit type conversion * \note Prevent implicit type conversion from singed to unsigned types * Why? std::common_type<Unsigned, Signed> chooses unsigned value, * then Signed value will be converted to Unsigned value * which gives us a wrong range for random values. * https://stackoverflow.com/a/5416498/5734836 */ template<typename Key, typename A, typename B, typename C = typename std::common_type<A, B>::type> static typename std::enable_if< std::is_same<Key, common>::value && details::is_supported_number<A>::value && details::is_supported_number<B>::value // Prevent implicit type conversion from singed to unsigned types && std::is_signed<A>::value != std::is_unsigned<B>::value , C>::type get( A from, B to ) noexcept { return get( static_cast<C>( from ), static_cast<C>( to ) ); } /** * \brief Generate a bool value with specific probability * by std::bernoulli_distribution * \param probability The probability of generating true in [0; 1] range * 0 means always false, 1 means always true * \return 'true' with 'probability' probability ('false' otherwise) */ template<typename T> static typename std::enable_if<std::is_same<T, bool>::value , bool>::type get( const double probability = 0.5 ) noexcept { assert( 0 <= probability && 1 >= probability ); // out of [0; 1] range return std::bernoulli_distribution{ probability }( engine ); } /** * \param init_list initilizer_list with values * \return Random value from initilizer_list by value * \note Should be 1 or more elements in initilizer_list */ template<typename T> static T get( std::initializer_list<T> init_list ) noexcept( noexcept( T{ std::declval<T>( ) } ) ) { assert( 0u != init_list.size( ) ); return *std::next( init_list.begin( ), typename std::iterator_traits< decltype( init_list.begin( ) )>::difference_type( get<typename std::initializer_list<T>::size_type>( 0u, init_list.size( ) - 1u ) ) ); } private: /// The random number engine static Engine engine; }; template<typename Engine> Engine basic_random_static<Engine>::engine( std::random_device{ }( ) ); /** * \brief The basic static random alias based on a std::default_random_engine * \note It uses static methods API and data with static storage * \note Not thread safe but more prefomance */ using random_static = basic_random_static<std::default_random_engine>; } // namespace effolkronium #endif // #ifndef EFFOLKRONIUM_RANDOM_HPP<|endoftext|>
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include "bench.h" #include "bloom.h" #include "hash.h" #include "uint256.h" #include "utiltime.h" #include "crypto/ripemd160.h" #include "crypto/sha1.h" #include "crypto/sha256.h" #include "crypto/sha512.h" /* Number of bytes to hash per iteration */ static const uint64_t BUFFER_SIZE = 1000*1000; static void RIPEMD160(benchmark::State& state) { uint8_t hash[CRIPEMD160::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CRIPEMD160().Write(in.data(), in.size()).Finalize(hash); } static void SHA1(benchmark::State& state) { uint8_t hash[CSHA1::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA1().Write(in.data(), in.size()).Finalize(hash); } static void SHA256(benchmark::State& state) { uint8_t hash[CSHA256::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA256().Write(in.data(), in.size()).Finalize(hash); } static void SHA256_32b(benchmark::State& state) { std::vector<uint8_t> in(32,0); while (state.KeepRunning()) { for (int i = 0; i < 1000000; i++) { CSHA256().Write(in.data(), in.size()).Finalize(&in[0]); } } } static void SHA512(benchmark::State& state) { uint8_t hash[CSHA512::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA512().Write(in.data(), in.size()).Finalize(hash); } static void SipHash_32b(benchmark::State& state) { uint256 x; while (state.KeepRunning()) { for (int i = 0; i < 1000000; i++) { *((uint64_t*)x.begin()) = SipHashUint256(0, i, x); } } } BENCHMARK(RIPEMD160); BENCHMARK(SHA1); BENCHMARK(SHA256); BENCHMARK(SHA512); BENCHMARK(SHA256_32b); BENCHMARK(SipHash_32b); <commit_msg>Add DSHA256 and X11 benchmarks, refactor names of other algo benchmarks to group them together (#1925)<commit_after>// Copyright (c) 2016 The Bitcoin Core developers // Copyright (c) 2018 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include "bench.h" #include "bloom.h" #include "hash.h" #include "uint256.h" #include "utiltime.h" #include "crypto/ripemd160.h" #include "crypto/sha1.h" #include "crypto/sha256.h" #include "crypto/sha512.h" /* Number of bytes to hash per iteration */ static const uint64_t BUFFER_SIZE = 1000*1000; static void HASH_RIPEMD160(benchmark::State& state) { uint8_t hash[CRIPEMD160::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CRIPEMD160().Write(in.data(), in.size()).Finalize(hash); } static void HASH_SHA1(benchmark::State& state) { uint8_t hash[CSHA1::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA1().Write(in.data(), in.size()).Finalize(hash); } static void HASH_SHA256(benchmark::State& state) { uint8_t hash[CSHA256::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA256().Write(in.data(), in.size()).Finalize(hash); } static void HASH_SHA256_0032b(benchmark::State& state) { std::vector<uint8_t> in(32,0); while (state.KeepRunning()) { for (int i = 0; i < 1000000; i++) { CSHA256().Write(in.data(), in.size()).Finalize(&in[0]); } } } static void HASH_DSHA256(benchmark::State& state) { uint8_t hash[CSHA256::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CHash256().Write(in.data(), in.size()).Finalize(hash); } static void HASH_DSHA256_0032b(benchmark::State& state) { std::vector<uint8_t> in(32,0); while (state.KeepRunning()) { for (int i = 0; i < 1000000; i++) { CHash256().Write(in.data(), in.size()).Finalize(&in[0]); } } } static void HASH_SHA512(benchmark::State& state) { uint8_t hash[CSHA512::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA512().Write(in.data(), in.size()).Finalize(hash); } static void HASH_SipHash_0032b(benchmark::State& state) { uint256 x; while (state.KeepRunning()) { for (int i = 0; i < 1000000; i++) { *((uint64_t*)x.begin()) = SipHashUint256(0, i, x); } } } static void HASH_DSHA256_0032b_single(benchmark::State& state) { std::vector<uint8_t> in(32,0); while (state.KeepRunning()) CHash256().Write(in.data(), in.size()).Finalize(&in[0]); } static void HASH_DSHA256_0080b_single(benchmark::State& state) { std::vector<uint8_t> in(80,0); while (state.KeepRunning()) CHash256().Write(in.data(), in.size()).Finalize(&in[0]); } static void HASH_DSHA256_0128b_single(benchmark::State& state) { std::vector<uint8_t> in(128,0); while (state.KeepRunning()) CHash256().Write(in.data(), in.size()).Finalize(&in[0]); } static void HASH_DSHA256_0512b_single(benchmark::State& state) { std::vector<uint8_t> in(512,0); while (state.KeepRunning()) CHash256().Write(in.data(), in.size()).Finalize(&in[0]); } static void HASH_DSHA256_1024b_single(benchmark::State& state) { std::vector<uint8_t> in(1024,0); while (state.KeepRunning()) CHash256().Write(in.data(), in.size()).Finalize(&in[0]); } static void HASH_DSHA256_2048b_single(benchmark::State& state) { std::vector<uint8_t> in(2048,0); while (state.KeepRunning()) CHash256().Write(in.data(), in.size()).Finalize(&in[0]); } static void HASH_X11(benchmark::State& state) { uint256 hash; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) hash = HashX11(in.begin(), in.end()); } static void HASH_X11_0032b_single(benchmark::State& state) { uint256 hash; std::vector<uint8_t> in(32,0); while (state.KeepRunning()) hash = HashX11(in.begin(), in.end()); } static void HASH_X11_0080b_single(benchmark::State& state) { uint256 hash; std::vector<uint8_t> in(80,0); while (state.KeepRunning()) hash = HashX11(in.begin(), in.end()); } static void HASH_X11_0128b_single(benchmark::State& state) { uint256 hash; std::vector<uint8_t> in(128,0); while (state.KeepRunning()) hash = HashX11(in.begin(), in.end()); } static void HASH_X11_0512b_single(benchmark::State& state) { uint256 hash; std::vector<uint8_t> in(512,0); while (state.KeepRunning()) hash = HashX11(in.begin(), in.end()); } static void HASH_X11_1024b_single(benchmark::State& state) { uint256 hash; std::vector<uint8_t> in(1024,0); while (state.KeepRunning()) hash = HashX11(in.begin(), in.end()); } static void HASH_X11_2048b_single(benchmark::State& state) { uint256 hash; std::vector<uint8_t> in(2048,0); while (state.KeepRunning()) hash = HashX11(in.begin(), in.end()); } BENCHMARK(HASH_RIPEMD160); BENCHMARK(HASH_SHA1); BENCHMARK(HASH_SHA256); BENCHMARK(HASH_DSHA256); BENCHMARK(HASH_SHA512); BENCHMARK(HASH_X11); BENCHMARK(HASH_SHA256_0032b); BENCHMARK(HASH_DSHA256_0032b); BENCHMARK(HASH_SipHash_0032b); BENCHMARK(HASH_DSHA256_0032b_single); BENCHMARK(HASH_DSHA256_0080b_single); BENCHMARK(HASH_DSHA256_0128b_single); BENCHMARK(HASH_DSHA256_0512b_single); BENCHMARK(HASH_DSHA256_1024b_single); BENCHMARK(HASH_DSHA256_2048b_single); BENCHMARK(HASH_X11_0032b_single); BENCHMARK(HASH_X11_0080b_single); BENCHMARK(HASH_X11_0128b_single); BENCHMARK(HASH_X11_0512b_single); BENCHMARK(HASH_X11_1024b_single); BENCHMARK(HASH_X11_2048b_single); <|endoftext|>
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include "bench.h" #include "bloom.h" #include "utiltime.h" #include "crypto/ripemd160.h" #include "crypto/sha1.h" #include "crypto/sha256.h" #include "crypto/sha512.h" /* Number of bytes to hash per iteration */ static const uint64_t BUFFER_SIZE = 1000*1000; static void RIPEMD160(benchmark::State& state) { uint8_t hash[CRIPEMD160::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CRIPEMD160().Write(begin_ptr(in), in.size()).Finalize(hash); } static void SHA1(benchmark::State& state) { uint8_t hash[CSHA1::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA1().Write(begin_ptr(in), in.size()).Finalize(hash); } static void SHA256(benchmark::State& state) { uint8_t hash[CSHA256::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA256().Write(begin_ptr(in), in.size()).Finalize(hash); } static void SHA512(benchmark::State& state) { uint8_t hash[CSHA512::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA512().Write(begin_ptr(in), in.size()).Finalize(hash); } BENCHMARK(RIPEMD160); BENCHMARK(SHA1); BENCHMARK(SHA256); BENCHMARK(SHA512); <commit_msg>Benchmark SipHash<commit_after>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include "bench.h" #include "bloom.h" #include "hash.h" #include "uint256.h" #include "utiltime.h" #include "crypto/ripemd160.h" #include "crypto/sha1.h" #include "crypto/sha256.h" #include "crypto/sha512.h" /* Number of bytes to hash per iteration */ static const uint64_t BUFFER_SIZE = 1000*1000; static void RIPEMD160(benchmark::State& state) { uint8_t hash[CRIPEMD160::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CRIPEMD160().Write(begin_ptr(in), in.size()).Finalize(hash); } static void SHA1(benchmark::State& state) { uint8_t hash[CSHA1::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA1().Write(begin_ptr(in), in.size()).Finalize(hash); } static void SHA256(benchmark::State& state) { uint8_t hash[CSHA256::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA256().Write(begin_ptr(in), in.size()).Finalize(hash); } static void SHA256_32b(benchmark::State& state) { std::vector<uint8_t> in(32,0); while (state.KeepRunning()) { for (int i = 0; i < 1000000; i++) { CSHA256().Write(begin_ptr(in), in.size()).Finalize(&in[0]); } } } static void SHA512(benchmark::State& state) { uint8_t hash[CSHA512::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE,0); while (state.KeepRunning()) CSHA512().Write(begin_ptr(in), in.size()).Finalize(hash); } static void SipHash_32b(benchmark::State& state) { uint256 x; while (state.KeepRunning()) { for (int i = 0; i < 1000000; i++) { *((uint64_t*)x.begin()) = SipHashUint256(0, i, x); } } } BENCHMARK(RIPEMD160); BENCHMARK(SHA1); BENCHMARK(SHA256); BENCHMARK(SHA512); BENCHMARK(SHA256_32b); BENCHMARK(SipHash_32b); <|endoftext|>
<commit_before>#include <ncurses.h> #include <iostream> #include <unistd.h> #include "display/Screen.h" #include "display/Window.h" #include "display/WindowManager.h" #include "map/Level.h" #include "map/filters/DrunkardsWalkFilter.h" #include "actor/Actor.h" #include "core/Rand.h" void pause_curses(Screen& screen) { screen.pause(); std::cout << "Paused ncurses..." << std::endl; sleep(4); std::cout << "Resuming..." << std::endl; sleep(1); } bool move_pc(Actor& pc, Level& level, int& pc_x, int& pc_y, int dx, int dy) { int new_x = pc_x + dx; int new_y = pc_y + dy; //Make sure it's in bounds if(0 <= new_x && new_x < level.getWidth() && 0 <= new_y && new_y < level.getHeight()) { //Make sure it's passable terrain if(level[new_x][new_y].getPassable()) { //Remove the PC from its old position level[pc_x][pc_y].removeActor(); //Adjust PC's x,y coordinates pc_x += dx; pc_y += dy; //Place the PC at the new x,y coordinates level[pc_x][pc_y].addActor(&pc); return true; } } return false; } int main() { Screen screen; int screen_y = screen.getHeight(); int screen_x = screen.getWidth(); //Make a map double the screen size int map_y = screen_y * 2; int map_x = screen_x * 2; //Generate a map Level cave(map_x, map_y); DrunkardsWalkFilter walk; walk.setSeed(time(NULL)); walk.apply(cave); //Find a random FloorTile to put our PC on int pc_x, pc_y; Actor pc('@', "PC", 0x01); Rand rand(time(NULL)); do { pc_x = rand.randInt(0, cave.getWidth()-1); pc_y = rand.randInt(0, cave.getHeight()-1); } while(cave[pc_x][pc_y] != FloorTile); cave[pc_x][pc_y].addActor(&pc); //Now put the map into our map window... Window level_window(&cave); //...and create a viewport looking into it. Window map(&level_window, screen_x-20, screen_y-3, 20, 3); Window top(screen_x, 3, 0, 0); Window left(20, screen_y-2, 0, 2); top.addBorder(); left.addBorder(); //map.addBorder(); //Dare I try it? //Push our windows into our WindowManager WindowManager wm; wm.addWindow(&top); wm.addWindow(&left); wm.addWindow(&map); wm.getWindow(0)->add(1, 0, "Message Panel"); wm.getWindow(1)->add(1, 0, "Stat Panel"); //Center the map viewport on the PC map.center(pc_x, pc_y); //Let's display some map display stats //Display our view's X and Y coordinates wm.getWindow(1)->add(1, 2, "View Position:"); wm.getWindow(1)->add(1, 3, "X: "); wm.getWindow(1)->addInt(4, 3, map.getViewX()); wm.getWindow(1)->add(1, 4, "Y: "); wm.getWindow(1)->addInt(4, 4, map.getViewY()); //Display map size wm.getWindow(1)->add(1, 6, "Map Size:"); wm.getWindow(1)->add(1, 7, "W:"); wm.getWindow(1)->addInt(4, 7, cave.getWidth()); wm.getWindow(1)->add(1, 8, "H:"); wm.getWindow(1)->addInt(4, 8, cave.getHeight()); //Display viewport size wm.getWindow(1)->add(1, 9, "View Size:"); wm.getWindow(1)->add(1, 10, "W:"); wm.getWindow(1)->addInt(4, 10, map.getViewWidth()); wm.getWindow(1)->add(1, 11, "H:"); wm.getWindow(1)->addInt(4, 11, map.getViewHeight()); //Display PC's location wm.getWindow(1)->add(1, 12, "PC Position:"); wm.getWindow(1)->add(1, 13, "X: "); wm.getWindow(1)->addInt(4, 13, pc_x); wm.getWindow(1)->add(1, 14, "Y: "); wm.getWindow(1)->addInt(4, 14, pc_y); //Now display everything wm.refresh(); //Now we enter the "game loop" int ch; int dx, dy; bool run = true; while(run) { ch = getch(); //Display the key code wm.getWindow(0)->add(8, 1, " "); wm.getWindow(0)->addInt(8, 1, ch); dx = 0; dy = 0; wm.getWindow(0)->add(1, 1, " "); switch(ch) { case KEY_UP: wm.getWindow(0)->add(1, 1, "Up"); dy = -1; break; case KEY_DOWN: wm.getWindow(0)->add(1, 1, "Down"); dy = 1; break; case KEY_LEFT: wm.getWindow(0)->add(1, 1, "Left"); dx = -1; break; case KEY_RIGHT: wm.getWindow(0)->add(1, 1, "Right"); dx = 1; break; case '8': move_pc(pc, cave, pc_x, pc_y, 0, -1); break; case '2': move_pc(pc, cave, pc_x, pc_y, 0, 1); break; case '4': move_pc(pc, cave, pc_x, pc_y, -1, 0); break; case '6': move_pc(pc, cave, pc_x, pc_y, 1, 0); break; case 'c': case 'C': wm.getWindow(2)->center(pc_x, pc_y); break; case 'p': case 'P': pause_curses(screen); break; case 'q': case 'Q': run = false; break; } //Move the viewport map.moveBy(dx, dy); //Display our view's X and Y coordinates wm.getWindow(1)->add(1, 3, "X: "); wm.getWindow(1)->addInt(4, 3, map.getViewX()); wm.getWindow(1)->add(1, 4, "Y: "); wm.getWindow(1)->addInt(4, 4, map.getViewY()); //Re-display PC's position wm.getWindow(1)->add(1, 13, "X: "); wm.getWindow(1)->addInt(4, 13, pc_x); wm.getWindow(1)->add(1, 14, "Y: "); wm.getWindow(1)->addInt(4, 14, pc_y); //Refresh the display wm.refresh(); } } <commit_msg>InterfaceTest now allows diagonal movement of the PC.<commit_after>#include <ncurses.h> #include <iostream> #include <unistd.h> #include "display/Screen.h" #include "display/Window.h" #include "display/WindowManager.h" #include "map/Level.h" #include "map/filters/DrunkardsWalkFilter.h" #include "actor/Actor.h" #include "core/Rand.h" void pause_curses(Screen& screen) { screen.pause(); std::cout << "Paused ncurses..." << std::endl; sleep(4); std::cout << "Resuming..." << std::endl; sleep(1); } bool move_pc(Actor& pc, Level& level, int& pc_x, int& pc_y, int dx, int dy) { int new_x = pc_x + dx; int new_y = pc_y + dy; //Make sure it's in bounds if(0 <= new_x && new_x < level.getWidth() && 0 <= new_y && new_y < level.getHeight()) { //Make sure it's passable terrain if(level[new_x][new_y].getPassable()) { //Remove the PC from its old position level[pc_x][pc_y].removeActor(); //Adjust PC's x,y coordinates pc_x += dx; pc_y += dy; //Place the PC at the new x,y coordinates level[pc_x][pc_y].addActor(&pc); return true; } } return false; } int main() { Screen screen; int screen_y = screen.getHeight(); int screen_x = screen.getWidth(); //Make a map double the screen size int map_y = screen_y * 2; int map_x = screen_x * 2; //Generate a map Level cave(map_x, map_y); DrunkardsWalkFilter walk; walk.setSeed(time(NULL)); walk.apply(cave); //Find a random FloorTile to put our PC on int pc_x, pc_y; Actor pc('@', "PC", 0x01); Rand rand(time(NULL)); do { pc_x = rand.randInt(0, cave.getWidth()-1); pc_y = rand.randInt(0, cave.getHeight()-1); } while(cave[pc_x][pc_y] != FloorTile); cave[pc_x][pc_y].addActor(&pc); //Now put the map into our map window... Window level_window(&cave); //...and create a viewport looking into it. Window map(&level_window, screen_x-20, screen_y-3, 20, 3); Window top(screen_x, 3, 0, 0); Window left(20, screen_y-2, 0, 2); top.addBorder(); left.addBorder(); //map.addBorder(); //Dare I try it? //Push our windows into our WindowManager WindowManager wm; wm.addWindow(&top); wm.addWindow(&left); wm.addWindow(&map); wm.getWindow(0)->add(1, 0, "Message Panel"); wm.getWindow(1)->add(1, 0, "Stat Panel"); //Center the map viewport on the PC map.center(pc_x, pc_y); //Let's display some map display stats //Display our view's X and Y coordinates wm.getWindow(1)->add(1, 2, "View Position:"); wm.getWindow(1)->add(1, 3, "X: "); wm.getWindow(1)->addInt(4, 3, map.getViewX()); wm.getWindow(1)->add(1, 4, "Y: "); wm.getWindow(1)->addInt(4, 4, map.getViewY()); //Display map size wm.getWindow(1)->add(1, 6, "Map Size:"); wm.getWindow(1)->add(1, 7, "W:"); wm.getWindow(1)->addInt(4, 7, cave.getWidth()); wm.getWindow(1)->add(1, 8, "H:"); wm.getWindow(1)->addInt(4, 8, cave.getHeight()); //Display viewport size wm.getWindow(1)->add(1, 9, "View Size:"); wm.getWindow(1)->add(1, 10, "W:"); wm.getWindow(1)->addInt(4, 10, map.getViewWidth()); wm.getWindow(1)->add(1, 11, "H:"); wm.getWindow(1)->addInt(4, 11, map.getViewHeight()); //Display PC's location wm.getWindow(1)->add(1, 12, "PC Position:"); wm.getWindow(1)->add(1, 13, "X: "); wm.getWindow(1)->addInt(4, 13, pc_x); wm.getWindow(1)->add(1, 14, "Y: "); wm.getWindow(1)->addInt(4, 14, pc_y); //Now display everything wm.refresh(); //Now we enter the "game loop" int ch; int dx, dy; bool run = true; while(run) { ch = getch(); //Display the key code wm.getWindow(0)->add(8, 1, " "); wm.getWindow(0)->addInt(8, 1, ch); dx = 0; dy = 0; wm.getWindow(0)->add(1, 1, " "); switch(ch) { //Viewport movement case KEY_UP: wm.getWindow(0)->add(1, 1, "Up"); dy = -1; break; case KEY_DOWN: wm.getWindow(0)->add(1, 1, "Down"); dy = 1; break; case KEY_LEFT: wm.getWindow(0)->add(1, 1, "Left"); dx = -1; break; case KEY_RIGHT: wm.getWindow(0)->add(1, 1, "Right"); dx = 1; break; //Orthogonal movement case '8': move_pc(pc, cave, pc_x, pc_y, 0, -1); break; case '2': move_pc(pc, cave, pc_x, pc_y, 0, 1); break; case '4': move_pc(pc, cave, pc_x, pc_y, -1, 0); break; case '6': move_pc(pc, cave, pc_x, pc_y, 1, 0); break; //Diagonal movement case '7': move_pc(pc, cave, pc_x, pc_y, -1, -1); break; case '9': move_pc(pc, cave, pc_x, pc_y, 1, -1); break; case '1': move_pc(pc, cave, pc_x, pc_y, -1, 1); break; case '3': move_pc(pc, cave, pc_x, pc_y, 1, 1); break; //Other commands case 'c': case 'C': //Center the view on the PC wm.getWindow(2)->center(pc_x, pc_y); break; case 'p': case 'P': //Pause ncurses (just a useless demo of the ability) pause_curses(screen); break; case 'q': case 'Q': //Quit run = false; break; } //Move the viewport map.moveBy(dx, dy); //Display our view's X and Y coordinates wm.getWindow(1)->add(1, 3, "X: "); wm.getWindow(1)->addInt(4, 3, map.getViewX()); wm.getWindow(1)->add(1, 4, "Y: "); wm.getWindow(1)->addInt(4, 4, map.getViewY()); //Re-display PC's position wm.getWindow(1)->add(1, 13, "X: "); wm.getWindow(1)->addInt(4, 13, pc_x); wm.getWindow(1)->add(1, 14, "Y: "); wm.getWindow(1)->addInt(4, 14, pc_y); //Refresh the display wm.refresh(); } } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #ifdef LEAN_USE_LUA #include <lua.hpp> #include "util/debug.h" #include "util/name.h" namespace lean { static int name_gc(lua_State * L); static int name_tostring(lua_State * L); static int name_eq(lua_State * L); static int name_lt(lua_State * L); static const struct luaL_Reg name_m[] = { {"__gc", name_gc}, {"__tostring", name_tostring}, {"__eq", name_eq}, {"__lt", name_lt}, {0, 0} }; static int mk_name(lua_State * L) { int nargs = lua_gettop(L); if (nargs != 1 && nargs != 2) return luaL_error(L, "function 'name' expects 1 or 2 arguments"); if (nargs == 1) { char const * str = luaL_checkstring(L, 1); void * mem = lua_newuserdata(L, sizeof(name)); new (mem) name(str); } else { lean_assert(nargs == 2); name * prefix; if (lua_isstring(L, 1)) { char const * str = luaL_checkstring(L, 1); prefix = new name(str); } else { prefix = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); } if (lua_isstring(L, 2)) { char const * str = luaL_checkstring(L, 2); void * mem = lua_newuserdata(L, sizeof(name)); new (mem) name(*prefix, str); } else { int idx = luaL_checkinteger(L, 2); void * mem = lua_newuserdata(L, sizeof(name)); new (mem) name(*prefix, idx); } } luaL_getmetatable(L, "name.mt"); lua_setmetatable(L, -2); return 1; } static int name_gc(lua_State * L) { name * n = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); n->~name(); return 0; } static int name_tostring(lua_State * L) { name * n = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); lua_pushfstring(L, n->to_string().c_str()); return 1; } static int name_eq(lua_State * L) { name * n1 = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); name * n2 = static_cast<name*>(luaL_checkudata(L, 2, "name.mt")); lua_pushboolean(L, *n1 == *n2); return 1; } static int name_lt(lua_State * L) { name * n1 = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); name * n2 = static_cast<name*>(luaL_checkudata(L, 2, "name.mt")); lua_pushboolean(L, *n1 < *n2); return 1; } void init_name(lua_State * L) { luaL_newmetatable(L, "name.mt"); luaL_setfuncs(L, name_m, 0); lua_pushcfunction(L, mk_name); lua_setglobal(L, "name"); } } #endif <commit_msg>fix(lua/name): fix memory leak<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #ifdef LEAN_USE_LUA #include <lua.hpp> #include "util/debug.h" #include "util/name.h" namespace lean { static int name_gc(lua_State * L); static int name_tostring(lua_State * L); static int name_eq(lua_State * L); static int name_lt(lua_State * L); static const struct luaL_Reg name_m[] = { {"__gc", name_gc}, {"__tostring", name_tostring}, {"__eq", name_eq}, {"__lt", name_lt}, {0, 0} }; static int mk_name(lua_State * L) { int nargs = lua_gettop(L); if (nargs != 1 && nargs != 2) return luaL_error(L, "function 'name' expects 1 or 2 arguments"); if (nargs == 1) { char const * str = luaL_checkstring(L, 1); void * mem = lua_newuserdata(L, sizeof(name)); new (mem) name(str); } else { lean_assert(nargs == 2); name tmp; name * prefix; if (lua_isstring(L, 1)) { char const * str = luaL_checkstring(L, 1); tmp = name(str); prefix = &tmp; } else { prefix = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); } if (lua_isstring(L, 2)) { char const * str = luaL_checkstring(L, 2); void * mem = lua_newuserdata(L, sizeof(name)); new (mem) name(*prefix, str); } else { int idx = luaL_checkinteger(L, 2); void * mem = lua_newuserdata(L, sizeof(name)); new (mem) name(*prefix, idx); } } luaL_getmetatable(L, "name.mt"); lua_setmetatable(L, -2); return 1; } static int name_gc(lua_State * L) { name * n = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); n->~name(); return 0; } static int name_tostring(lua_State * L) { name * n = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); lua_pushfstring(L, n->to_string().c_str()); return 1; } static int name_eq(lua_State * L) { name * n1 = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); name * n2 = static_cast<name*>(luaL_checkudata(L, 2, "name.mt")); lua_pushboolean(L, *n1 == *n2); return 1; } static int name_lt(lua_State * L) { name * n1 = static_cast<name*>(luaL_checkudata(L, 1, "name.mt")); name * n2 = static_cast<name*>(luaL_checkudata(L, 2, "name.mt")); lua_pushboolean(L, *n1 < *n2); return 1; } void init_name(lua_State * L) { luaL_newmetatable(L, "name.mt"); luaL_setfuncs(L, name_m, 0); lua_pushcfunction(L, mk_name); lua_setglobal(L, "name"); } } #endif <|endoftext|>
<commit_before>/* * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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 * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "user_cache.h" #include "user_def.h" #include "session.h" static char zero_hash[SCRAMBLE_SIZE]; void authenticate(const char *user_name, uint32_t len, const char *tuple, const char * /* tuple_end */) { struct user_def *user = user_cache_find_by_name(user_name, len); struct session *session = current_session(); uint32_t part_count; uint32_t scramble_len; const char *scramble; /* * Allow authenticating back to GUEST user without * checking a password. This is useful for connection * pooling. */ if (user->uid == GUEST && memcmp(user->hash2, zero_hash, SCRAMBLE_SIZE)) { /* No password is set for GUEST, OK. */ goto ok; } part_count = mp_decode_array(&tuple); if (part_count < 2) { /* Expected at least: authentication mechanism and data. */ tnt_raise(ClientError, ER_INVALID_MSGPACK, "authentication request body"); } mp_next(&tuple); /* Skip authentication mechanism. */ scramble = mp_decode_str(&tuple, &scramble_len); if (scramble_len != SCRAMBLE_SIZE) { /* Authentication mechanism, data. */ tnt_raise(ClientError, ER_INVALID_MSGPACK, "invalid scramble size"); } if (scramble_check(scramble, session->salt, user->hash2)) tnt_raise(ClientError, ER_PASSWORD_MISMATCH, user->name); ok: current_user_init(&session->user, user); } <commit_msg>Stricten the AUTH package format for GUEST user.<commit_after>/* * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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 * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "user_cache.h" #include "user_def.h" #include "session.h" static char zero_hash[SCRAMBLE_SIZE]; void authenticate(const char *user_name, uint32_t len, const char *tuple, const char * /* tuple_end */) { struct user_def *user = user_cache_find_by_name(user_name, len); struct session *session = current_session(); uint32_t part_count; uint32_t scramble_len; const char *scramble; /* * Allow authenticating back to GUEST user without * checking a password. This is useful for connection * pooling. */ part_count = mp_decode_array(&tuple); if (part_count == 0 && user->uid == GUEST && memcmp(user->hash2, zero_hash, SCRAMBLE_SIZE)) { /* No password is set for GUEST, OK. */ goto ok; } if (part_count < 2) { /* Expected at least: authentication mechanism and data. */ tnt_raise(ClientError, ER_INVALID_MSGPACK, "authentication request body"); } mp_next(&tuple); /* Skip authentication mechanism. */ scramble = mp_decode_str(&tuple, &scramble_len); if (scramble_len != SCRAMBLE_SIZE) { /* Authentication mechanism, data. */ tnt_raise(ClientError, ER_INVALID_MSGPACK, "invalid scramble size"); } if (scramble_check(scramble, session->salt, user->hash2)) tnt_raise(ClientError, ER_PASSWORD_MISMATCH, user->name); ok: current_user_init(&session->user, user); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QGraphicsItem> #include <QDebug> #include <QGraphicsItemAnimation> #include <QTimeLine> #include <QGraphicsOpacityEffect> #include <QPropertyAnimation> #include <QMediaPlayer> #include "qgameitem.h" class CustomItem : public QGraphicsPixmapItem { private: QApplication *app; MainWindow *window; public: void mousePressEvent(QGraphicsSceneMouseEvent *event) { qDebug() << "Custom item clicked."; setPixmap(QPixmap(":images/button_ok_click.png")); window->switchToMain(); } void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { setPixmap(QPixmap(":images/button_ok.png")); } void setApplication(QApplication* app) { this->app = app; } void setMainWindow(MainWindow *window) { this->window = window; } }; // Constructor & Destructor MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setupScenes(); ui->graphicsView->setScene(logo); } MainWindow::~MainWindow() { delete ui; } // Methods // Utility Functions void MainWindow::switchScene(int scenetype) { using namespace SceneType; QGraphicsScene* scene; switch(scenetype) { case LOGO: scene = logo; break; case MAIN: scene = menu; break; case READY: scene = ready; break; case INGAME: scene = ingame; break; case CREDIT: scene = credit; break; } ui->graphicsView->setScene(scene); } void MainWindow::setApplication(QApplication* app) { this->app = app; } void MainWindow::setupScenes() { logo = new QGraphicsScene(0, 0, 1280, 720, this); menu = new QGraphicsScene(0, 0, 1280, 720, this); ready = new QGraphicsScene(0, 0, 1280, 720, this); ingame = new QGraphicsScene(0, 0, 1280, 720, this); credit = new QGraphicsScene(0,0,1280,720,this); // setup for ready QGraphicsPixmapItem *ready_logo = logo->addPixmap(QPixmap(":images/logo/logo_background.png")); ready_logo->setPos(0, 0); // setup for ingame QGraphicsPixmapItem *game_board = ingame->addPixmap(QPixmap(":images/ingame/background.png")); game_board->setPos(0,0); } <commit_msg>Changed Some Templets for mainwindow<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "qgameitem.h" #include "scene/creditscene.h" #include "scene/logoscene.h" #include "scene/mainscene.h" #include "scene/readyscene.h" #include <QGraphicsItem> #include <QDebug> #include <QGraphicsItemAnimation> #include <QTimeLine> #include <QGraphicsOpacityEffect> #include <QPropertyAnimation> #include <QMediaPlayer> class CustomItem : public QGraphicsPixmapItem { private: QApplication *app; MainWindow *window; public: void mousePressEvent(QGraphicsSceneMouseEvent *event) { qDebug() << "Custom item clicked."; setPixmap(QPixmap(":images/button_ok_click.png")); window->switchToMain(); } void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { setPixmap(QPixmap(":images/button_ok.png")); } void setApplication(QApplication* app) { this->app = app; } void setMainWindow(MainWindow *window) { this->window = window; } }; // Constructor & Destructor MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setupScenes(); ui->graphicsView->setScene(logo); } MainWindow::~MainWindow() { delete ui; } // Methods // Utility Functions void MainWindow::switchScene(int scenetype) { using namespace SceneType; QGraphicsScene* scene; switch(scenetype) { case LOGO: scene = logo; break; case MAIN: scene = menu; break; case READY: scene = ready; break; case INGAME: scene = ingame; break; case CREDIT: scene = credit; break; } ui->graphicsView->setScene(scene); } void MainWindow::setApplication(QApplication* app) { this->app = app; } void MainWindow::setupScenes() { logo = new LogoScene(0, 0, 1280, 720, this); menu = new MainScene(0, 0, 1280, 720, this); ready = new QGraphicsScene(0, 0, 1280, 720, this); ingame = new QGraphicsScene(0, 0, 1280, 720, this); credit = new QGraphicsScene(0,0,1280,720,this); // setup for ready QGraphicsPixmapItem *ready_logo = ready->addPixmap(QPixmap(":images/logo/logo_background.png")); ready_logo->setPos(0, 0); // setup for ingame QGraphicsPixmapItem *game_board = ingame->addPixmap(QPixmap(":images/ingame/background.png")); game_board->setPos(0,0); } <|endoftext|>
<commit_before>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #ifdef SK_HAS_HEIF_LIBRARY #include "SkCodec.h" #include "SkCodecPriv.h" #include "SkColorPriv.h" #include "SkColorSpace_Base.h" #include "SkEndian.h" #include "SkStream.h" #include "SkHeifCodec.h" #define FOURCC(c1, c2, c3, c4) \ ((c1) << 24 | (c2) << 16 | (c3) << 8 | (c4)) bool SkHeifCodec::IsHeif(const void* buffer, size_t bytesRead) { // Parse the ftyp box up to bytesRead to determine if this is HEIF. // Any valid ftyp box should have at least 8 bytes. if (bytesRead < 8) { return false; } uint32_t* ptr = (uint32_t*)buffer; uint64_t chunkSize = SkEndian_SwapBE32(ptr[0]); uint32_t chunkType = SkEndian_SwapBE32(ptr[1]); if (chunkType != FOURCC('f', 't', 'y', 'p')) { return false; } off64_t offset = 8; if (chunkSize == 1) { // This indicates that the next 8 bytes represent the chunk size, // and chunk data comes after that. if (bytesRead < 16) { return false; } auto* chunkSizePtr = SkTAddOffset<const uint64_t>(buffer, offset); chunkSize = SkEndian_SwapBE64(*chunkSizePtr); if (chunkSize < 16) { // The smallest valid chunk is 16 bytes long in this case. return false; } offset += 8; } else if (chunkSize < 8) { // The smallest valid chunk is 8 bytes long. return false; } if (chunkSize > bytesRead) { chunkSize = bytesRead; } off64_t chunkDataSize = chunkSize - offset; // It should at least have major brand (4-byte) and minor version (4-bytes). // The rest of the chunk (if any) is a list of (4-byte) compatible brands. if (chunkDataSize < 8) { return false; } uint32_t numCompatibleBrands = (chunkDataSize - 8) / 4; for (size_t i = 0; i < numCompatibleBrands + 2; ++i) { if (i == 1) { // Skip this index, it refers to the minorVersion, // not a brand. continue; } auto* brandPtr = SkTAddOffset<const uint32_t>(buffer, offset + 4 * i); uint32_t brand = SkEndian_SwapBE32(*brandPtr); if (brand == FOURCC('m', 'i', 'f', '1') || brand == FOURCC('h', 'e', 'i', 'c')) { return true; } } return false; } static SkCodec::Origin get_orientation(const HeifFrameInfo& frameInfo) { switch (frameInfo.mRotationAngle) { case 0: return SkCodec::kTopLeft_Origin; case 90: return SkCodec::kRightTop_Origin; case 180: return SkCodec::kBottomRight_Origin; case 270: return SkCodec::kLeftBottom_Origin; } return SkCodec::kDefault_Origin; } struct SkHeifStreamWrapper : public HeifStream { SkHeifStreamWrapper(SkStream* stream) : fStream(stream) {} ~SkHeifStreamWrapper() override {} size_t read(void* buffer, size_t size) override { return fStream->read(buffer, size); } bool rewind() override { return fStream->rewind(); } bool seek(size_t position) override { return fStream->seek(position); } bool hasLength() const override { return fStream->hasLength(); } size_t getLength() const override { return fStream->getLength(); } private: std::unique_ptr<SkStream> fStream; }; std::unique_ptr<SkCodec> SkHeifCodec::MakeFromStream( std::unique_ptr<SkStream> stream, Result* result) { std::unique_ptr<HeifDecoder> heifDecoder(createHeifDecoder()); if (heifDecoder.get() == nullptr) { *result = kInternalError; return nullptr; } HeifFrameInfo frameInfo; if (!heifDecoder->init(new SkHeifStreamWrapper(stream.release()), &frameInfo)) { *result = kInvalidInput; return nullptr; } SkEncodedInfo info = SkEncodedInfo::Make( SkEncodedInfo::kYUV_Color, SkEncodedInfo::kOpaque_Alpha, 8); Origin orientation = get_orientation(frameInfo); sk_sp<SkColorSpace> colorSpace = nullptr; if ((frameInfo.mIccSize > 0) && (frameInfo.mIccData != nullptr)) { SkColorSpace_Base::ICCTypeFlag iccType = SkColorSpace_Base::kRGB_ICCTypeFlag; colorSpace = SkColorSpace_Base::MakeICC( frameInfo.mIccData.get(), frameInfo.mIccSize, iccType); } if (!colorSpace) { colorSpace = SkColorSpace::MakeSRGB(); } *result = kSuccess; return std::unique_ptr<SkCodec>(new SkHeifCodec(frameInfo.mWidth, frameInfo.mHeight, info, heifDecoder.release(), std::move(colorSpace), orientation)); } SkHeifCodec::SkHeifCodec(int width, int height, const SkEncodedInfo& info, HeifDecoder* heifDecoder, sk_sp<SkColorSpace> colorSpace, Origin origin) : INHERITED(width, height, info, SkColorSpaceXform::kRGBA_8888_ColorFormat, nullptr, std::move(colorSpace), origin) , fHeifDecoder(heifDecoder) , fSwizzleSrcRow(nullptr) , fColorXformSrcRow(nullptr) {} /* * Checks if the conversion between the input image and the requested output * image has been implemented * Sets the output color format */ bool SkHeifCodec::setOutputColorFormat(const SkImageInfo& dstInfo) { if (kUnknown_SkAlphaType == dstInfo.alphaType()) { return false; } if (kOpaque_SkAlphaType != dstInfo.alphaType()) { SkCodecPrintf("Warning: an opaque image should be decoded as opaque " "- it is being decoded as non-opaque, which will draw slower\n"); } switch (dstInfo.colorType()) { case kRGBA_8888_SkColorType: return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888); case kBGRA_8888_SkColorType: return fHeifDecoder->setOutputColor(kHeifColorFormat_BGRA_8888); case kRGB_565_SkColorType: if (this->colorXform()) { return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888); } else { return fHeifDecoder->setOutputColor(kHeifColorFormat_RGB565); } case kRGBA_F16_SkColorType: SkASSERT(this->colorXform()); if (!dstInfo.colorSpace()->gammaIsLinear()) { return false; } return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888); default: return false; } } int SkHeifCodec::readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count, const Options& opts) { // When fSwizzleSrcRow is non-null, it means that we need to swizzle. In this case, // we will always decode into fSwizzlerSrcRow before swizzling into the next buffer. // We can never swizzle "in place" because the swizzler may perform sampling and/or // subsetting. // When fColorXformSrcRow is non-null, it means that we need to color xform and that // we cannot color xform "in place" (many times we can, but not when the dst is F16). // In this case, we will color xform from fColorXformSrcRow into the dst. uint8_t* decodeDst = (uint8_t*) dst; uint32_t* swizzleDst = (uint32_t*) dst; size_t decodeDstRowBytes = rowBytes; size_t swizzleDstRowBytes = rowBytes; int dstWidth = opts.fSubset ? opts.fSubset->width() : dstInfo.width(); if (fSwizzleSrcRow && fColorXformSrcRow) { decodeDst = fSwizzleSrcRow; swizzleDst = fColorXformSrcRow; decodeDstRowBytes = 0; swizzleDstRowBytes = 0; dstWidth = fSwizzler->swizzleWidth(); } else if (fColorXformSrcRow) { decodeDst = (uint8_t*) fColorXformSrcRow; swizzleDst = fColorXformSrcRow; decodeDstRowBytes = 0; swizzleDstRowBytes = 0; } else if (fSwizzleSrcRow) { decodeDst = fSwizzleSrcRow; decodeDstRowBytes = 0; dstWidth = fSwizzler->swizzleWidth(); } for (int y = 0; y < count; y++) { if (!fHeifDecoder->getScanline(decodeDst)) { return y; } if (fSwizzler) { fSwizzler->swizzle(swizzleDst, decodeDst); } if (this->colorXform()) { this->applyColorXform(dst, swizzleDst, dstWidth, kOpaque_SkAlphaType); dst = SkTAddOffset<void>(dst, rowBytes); } decodeDst = SkTAddOffset<uint8_t>(decodeDst, decodeDstRowBytes); swizzleDst = SkTAddOffset<uint32_t>(swizzleDst, swizzleDstRowBytes); } return count; } /* * Performs the heif decode */ SkCodec::Result SkHeifCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t dstRowBytes, const Options& options, int* rowsDecoded) { if (options.fSubset) { // Not supporting subsets on this path for now. // TODO: if the heif has tiles, we can support subset here, but // need to retrieve tile config from metadata retriever first. return kUnimplemented; } // Check if we can decode to the requested destination and set the output color space if (!this->setOutputColorFormat(dstInfo)) { return kInvalidConversion; } if (!fHeifDecoder->decode(&fFrameInfo)) { return kInvalidInput; } this->allocateStorage(dstInfo); int rows = this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options); if (rows < dstInfo.height()) { *rowsDecoded = rows; return kIncompleteInput; } return kSuccess; } void SkHeifCodec::allocateStorage(const SkImageInfo& dstInfo) { int dstWidth = dstInfo.width(); size_t swizzleBytes = 0; if (fSwizzler) { swizzleBytes = fFrameInfo.mBytesPerPixel * fFrameInfo.mWidth; dstWidth = fSwizzler->swizzleWidth(); SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes)); } size_t xformBytes = 0; if (this->colorXform() && (kRGBA_F16_SkColorType == dstInfo.colorType() || kRGB_565_SkColorType == dstInfo.colorType())) { xformBytes = dstWidth * sizeof(uint32_t); } size_t totalBytes = swizzleBytes + xformBytes; fStorage.reset(totalBytes); if (totalBytes > 0) { fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr; fColorXformSrcRow = (xformBytes > 0) ? SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr; } } void SkHeifCodec::initializeSwizzler( const SkImageInfo& dstInfo, const Options& options) { SkEncodedInfo swizzlerInfo = this->getEncodedInfo(); SkImageInfo swizzlerDstInfo = dstInfo; if (this->colorXform()) { // The color xform will be expecting RGBA 8888 input. swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_8888_SkColorType); } fSwizzler.reset(SkSwizzler::CreateSwizzler(swizzlerInfo, nullptr, swizzlerDstInfo, options, nullptr, true)); SkASSERT(fSwizzler); } SkSampler* SkHeifCodec::getSampler(bool createIfNecessary) { if (!createIfNecessary || fSwizzler) { SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow)); return fSwizzler.get(); } this->initializeSwizzler(this->dstInfo(), this->options()); this->allocateStorage(this->dstInfo()); return fSwizzler.get(); } SkCodec::Result SkHeifCodec::onStartScanlineDecode( const SkImageInfo& dstInfo, const Options& options) { // Check if we can decode to the requested destination and set the output color space if (!this->setOutputColorFormat(dstInfo)) { return kInvalidConversion; } // TODO: For now, just decode the whole thing even when there is a subset. // If the heif image has tiles, we could potentially do this much faster, // but the tile configuration needs to be retrieved from the metadata. if (!fHeifDecoder->decode(&fFrameInfo)) { return kInvalidInput; } this->allocateStorage(dstInfo); return kSuccess; } int SkHeifCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) { return this->readRows(this->dstInfo(), dst, dstRowBytes, count, this->options()); } bool SkHeifCodec::onSkipScanlines(int count) { return count == (int) fHeifDecoder->skipScanlines(count); } #endif // SK_HAS_HEIF_LIBRARY <commit_msg>Initialize the swizzler if there is a subset<commit_after>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #ifdef SK_HAS_HEIF_LIBRARY #include "SkCodec.h" #include "SkCodecPriv.h" #include "SkColorPriv.h" #include "SkColorSpace_Base.h" #include "SkEndian.h" #include "SkStream.h" #include "SkHeifCodec.h" #define FOURCC(c1, c2, c3, c4) \ ((c1) << 24 | (c2) << 16 | (c3) << 8 | (c4)) bool SkHeifCodec::IsHeif(const void* buffer, size_t bytesRead) { // Parse the ftyp box up to bytesRead to determine if this is HEIF. // Any valid ftyp box should have at least 8 bytes. if (bytesRead < 8) { return false; } uint32_t* ptr = (uint32_t*)buffer; uint64_t chunkSize = SkEndian_SwapBE32(ptr[0]); uint32_t chunkType = SkEndian_SwapBE32(ptr[1]); if (chunkType != FOURCC('f', 't', 'y', 'p')) { return false; } off64_t offset = 8; if (chunkSize == 1) { // This indicates that the next 8 bytes represent the chunk size, // and chunk data comes after that. if (bytesRead < 16) { return false; } auto* chunkSizePtr = SkTAddOffset<const uint64_t>(buffer, offset); chunkSize = SkEndian_SwapBE64(*chunkSizePtr); if (chunkSize < 16) { // The smallest valid chunk is 16 bytes long in this case. return false; } offset += 8; } else if (chunkSize < 8) { // The smallest valid chunk is 8 bytes long. return false; } if (chunkSize > bytesRead) { chunkSize = bytesRead; } off64_t chunkDataSize = chunkSize - offset; // It should at least have major brand (4-byte) and minor version (4-bytes). // The rest of the chunk (if any) is a list of (4-byte) compatible brands. if (chunkDataSize < 8) { return false; } uint32_t numCompatibleBrands = (chunkDataSize - 8) / 4; for (size_t i = 0; i < numCompatibleBrands + 2; ++i) { if (i == 1) { // Skip this index, it refers to the minorVersion, // not a brand. continue; } auto* brandPtr = SkTAddOffset<const uint32_t>(buffer, offset + 4 * i); uint32_t brand = SkEndian_SwapBE32(*brandPtr); if (brand == FOURCC('m', 'i', 'f', '1') || brand == FOURCC('h', 'e', 'i', 'c')) { return true; } } return false; } static SkCodec::Origin get_orientation(const HeifFrameInfo& frameInfo) { switch (frameInfo.mRotationAngle) { case 0: return SkCodec::kTopLeft_Origin; case 90: return SkCodec::kRightTop_Origin; case 180: return SkCodec::kBottomRight_Origin; case 270: return SkCodec::kLeftBottom_Origin; } return SkCodec::kDefault_Origin; } struct SkHeifStreamWrapper : public HeifStream { SkHeifStreamWrapper(SkStream* stream) : fStream(stream) {} ~SkHeifStreamWrapper() override {} size_t read(void* buffer, size_t size) override { return fStream->read(buffer, size); } bool rewind() override { return fStream->rewind(); } bool seek(size_t position) override { return fStream->seek(position); } bool hasLength() const override { return fStream->hasLength(); } size_t getLength() const override { return fStream->getLength(); } private: std::unique_ptr<SkStream> fStream; }; std::unique_ptr<SkCodec> SkHeifCodec::MakeFromStream( std::unique_ptr<SkStream> stream, Result* result) { std::unique_ptr<HeifDecoder> heifDecoder(createHeifDecoder()); if (heifDecoder.get() == nullptr) { *result = kInternalError; return nullptr; } HeifFrameInfo frameInfo; if (!heifDecoder->init(new SkHeifStreamWrapper(stream.release()), &frameInfo)) { *result = kInvalidInput; return nullptr; } SkEncodedInfo info = SkEncodedInfo::Make( SkEncodedInfo::kYUV_Color, SkEncodedInfo::kOpaque_Alpha, 8); Origin orientation = get_orientation(frameInfo); sk_sp<SkColorSpace> colorSpace = nullptr; if ((frameInfo.mIccSize > 0) && (frameInfo.mIccData != nullptr)) { SkColorSpace_Base::ICCTypeFlag iccType = SkColorSpace_Base::kRGB_ICCTypeFlag; colorSpace = SkColorSpace_Base::MakeICC( frameInfo.mIccData.get(), frameInfo.mIccSize, iccType); } if (!colorSpace) { colorSpace = SkColorSpace::MakeSRGB(); } *result = kSuccess; return std::unique_ptr<SkCodec>(new SkHeifCodec(frameInfo.mWidth, frameInfo.mHeight, info, heifDecoder.release(), std::move(colorSpace), orientation)); } SkHeifCodec::SkHeifCodec(int width, int height, const SkEncodedInfo& info, HeifDecoder* heifDecoder, sk_sp<SkColorSpace> colorSpace, Origin origin) : INHERITED(width, height, info, SkColorSpaceXform::kRGBA_8888_ColorFormat, nullptr, std::move(colorSpace), origin) , fHeifDecoder(heifDecoder) , fSwizzleSrcRow(nullptr) , fColorXformSrcRow(nullptr) {} /* * Checks if the conversion between the input image and the requested output * image has been implemented * Sets the output color format */ bool SkHeifCodec::setOutputColorFormat(const SkImageInfo& dstInfo) { if (kUnknown_SkAlphaType == dstInfo.alphaType()) { return false; } if (kOpaque_SkAlphaType != dstInfo.alphaType()) { SkCodecPrintf("Warning: an opaque image should be decoded as opaque " "- it is being decoded as non-opaque, which will draw slower\n"); } switch (dstInfo.colorType()) { case kRGBA_8888_SkColorType: return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888); case kBGRA_8888_SkColorType: return fHeifDecoder->setOutputColor(kHeifColorFormat_BGRA_8888); case kRGB_565_SkColorType: if (this->colorXform()) { return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888); } else { return fHeifDecoder->setOutputColor(kHeifColorFormat_RGB565); } case kRGBA_F16_SkColorType: SkASSERT(this->colorXform()); if (!dstInfo.colorSpace()->gammaIsLinear()) { return false; } return fHeifDecoder->setOutputColor(kHeifColorFormat_RGBA_8888); default: return false; } } int SkHeifCodec::readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count, const Options& opts) { // When fSwizzleSrcRow is non-null, it means that we need to swizzle. In this case, // we will always decode into fSwizzlerSrcRow before swizzling into the next buffer. // We can never swizzle "in place" because the swizzler may perform sampling and/or // subsetting. // When fColorXformSrcRow is non-null, it means that we need to color xform and that // we cannot color xform "in place" (many times we can, but not when the dst is F16). // In this case, we will color xform from fColorXformSrcRow into the dst. uint8_t* decodeDst = (uint8_t*) dst; uint32_t* swizzleDst = (uint32_t*) dst; size_t decodeDstRowBytes = rowBytes; size_t swizzleDstRowBytes = rowBytes; int dstWidth = opts.fSubset ? opts.fSubset->width() : dstInfo.width(); if (fSwizzleSrcRow && fColorXformSrcRow) { decodeDst = fSwizzleSrcRow; swizzleDst = fColorXformSrcRow; decodeDstRowBytes = 0; swizzleDstRowBytes = 0; dstWidth = fSwizzler->swizzleWidth(); } else if (fColorXformSrcRow) { decodeDst = (uint8_t*) fColorXformSrcRow; swizzleDst = fColorXformSrcRow; decodeDstRowBytes = 0; swizzleDstRowBytes = 0; } else if (fSwizzleSrcRow) { decodeDst = fSwizzleSrcRow; decodeDstRowBytes = 0; dstWidth = fSwizzler->swizzleWidth(); } for (int y = 0; y < count; y++) { if (!fHeifDecoder->getScanline(decodeDst)) { return y; } if (fSwizzler) { fSwizzler->swizzle(swizzleDst, decodeDst); } if (this->colorXform()) { this->applyColorXform(dst, swizzleDst, dstWidth, kOpaque_SkAlphaType); dst = SkTAddOffset<void>(dst, rowBytes); } decodeDst = SkTAddOffset<uint8_t>(decodeDst, decodeDstRowBytes); swizzleDst = SkTAddOffset<uint32_t>(swizzleDst, swizzleDstRowBytes); } return count; } /* * Performs the heif decode */ SkCodec::Result SkHeifCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t dstRowBytes, const Options& options, int* rowsDecoded) { if (options.fSubset) { // Not supporting subsets on this path for now. // TODO: if the heif has tiles, we can support subset here, but // need to retrieve tile config from metadata retriever first. return kUnimplemented; } // Check if we can decode to the requested destination and set the output color space if (!this->setOutputColorFormat(dstInfo)) { return kInvalidConversion; } if (!fHeifDecoder->decode(&fFrameInfo)) { return kInvalidInput; } fSwizzler.reset(nullptr); this->allocateStorage(dstInfo); int rows = this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options); if (rows < dstInfo.height()) { *rowsDecoded = rows; return kIncompleteInput; } return kSuccess; } void SkHeifCodec::allocateStorage(const SkImageInfo& dstInfo) { int dstWidth = dstInfo.width(); size_t swizzleBytes = 0; if (fSwizzler) { swizzleBytes = fFrameInfo.mBytesPerPixel * fFrameInfo.mWidth; dstWidth = fSwizzler->swizzleWidth(); SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes)); } size_t xformBytes = 0; if (this->colorXform() && (kRGBA_F16_SkColorType == dstInfo.colorType() || kRGB_565_SkColorType == dstInfo.colorType())) { xformBytes = dstWidth * sizeof(uint32_t); } size_t totalBytes = swizzleBytes + xformBytes; fStorage.reset(totalBytes); if (totalBytes > 0) { fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr; fColorXformSrcRow = (xformBytes > 0) ? SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr; } } void SkHeifCodec::initializeSwizzler( const SkImageInfo& dstInfo, const Options& options) { SkEncodedInfo swizzlerInfo = this->getEncodedInfo(); SkImageInfo swizzlerDstInfo = dstInfo; if (this->colorXform()) { // The color xform will be expecting RGBA 8888 input. swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_8888_SkColorType); } fSwizzler.reset(SkSwizzler::CreateSwizzler(swizzlerInfo, nullptr, swizzlerDstInfo, options, nullptr, true)); SkASSERT(fSwizzler); } SkSampler* SkHeifCodec::getSampler(bool createIfNecessary) { if (!createIfNecessary || fSwizzler) { SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow)); return fSwizzler.get(); } this->initializeSwizzler(this->dstInfo(), this->options()); this->allocateStorage(this->dstInfo()); return fSwizzler.get(); } SkCodec::Result SkHeifCodec::onStartScanlineDecode( const SkImageInfo& dstInfo, const Options& options) { // Check if we can decode to the requested destination and set the output color space if (!this->setOutputColorFormat(dstInfo)) { return kInvalidConversion; } // TODO: For now, just decode the whole thing even when there is a subset. // If the heif image has tiles, we could potentially do this much faster, // but the tile configuration needs to be retrieved from the metadata. if (!fHeifDecoder->decode(&fFrameInfo)) { return kInvalidInput; } if (options.fSubset) { this->initializeSwizzler(dstInfo, options); } else { fSwizzler.reset(nullptr); } this->allocateStorage(dstInfo); return kSuccess; } int SkHeifCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) { return this->readRows(this->dstInfo(), dst, dstRowBytes, count, this->options()); } bool SkHeifCodec::onSkipScanlines(int count) { return count == (int) fHeifDecoder->skipScanlines(count); } #endif // SK_HAS_HEIF_LIBRARY <|endoftext|>
<commit_before>#include <signal.h> #include <stdlib.h> #include <errno.h> #include "l7vsd.h" static void sig_exit_handler(int sig); static int set_sighandler(int sig, void (*handler)(int)); static int set_sighandlers(); static void usage(FILE* p); static bool exit_requested = false; static int received_sig = 0; namespace l7vsd{ l7vs::Logger l7vs::Logger::instance; l7vs::Parameter l7vs::Parameter::instance; void l7vsd::run() { } };// namespace l7vsd static void sig_exit_handler(int sig) { received_sig = sig; exit_requested = true; } static int set_sighandler(int sig, void (*handler)(int)) { struct sigaction act; int ret; ret = sigaction(sig, NULL, &act); if (ret < 0) { //LOGGER_PUT_LOG_ERROR(LOG_CAT_L7VSD_SYSTEM_SIGNAL,1, "sigaction on signal %d failed", sig); return ret; } act.sa_flags &= ~SA_RESETHAND; act.sa_handler = handler; ret = sigaction(sig, &act, NULL); if (ret < 0) { //LOGGER_PUT_LOG_ERROR(LOG_CAT_L7VSD_SYSTEM_SIGNAL,2, "sigaction on signal %d failed", sig); return ret; } return 0; } static int set_sighandlers() { int ret; #define SET_SIGHANDLER(sig, handler) \ do { \ ret = set_sighandler((sig), (handler)); \ if (ret < 0) { \ return ret; \ } \ } while (0) SET_SIGHANDLER(SIGHUP, sig_exit_handler); SET_SIGHANDLER(SIGINT, sig_exit_handler); SET_SIGHANDLER(SIGQUIT, sig_exit_handler); SET_SIGHANDLER(SIGTERM, sig_exit_handler); SET_SIGHANDLER(SIGUSR1, SIG_IGN); SET_SIGHANDLER(SIGUSR2, SIG_IGN); SET_SIGHANDLER(SIGALRM, SIG_IGN); SET_SIGHANDLER(SIGCHLD, SIG_IGN); #undef SET_SIGHANDLER return 0; } static void usage(FILE* p) { } #ifndef TEST_CASE int main( int argc, char* argv[] ){ try{ } catch( ... ){ } return 0; } #else int main(){ return 0;} #endif //TEST_CASE <commit_msg>l7svd.cpp修正<commit_after>#include <signal.h> #include <stdlib.h> #include <errno.h> #include "l7vsd.h" static void sig_exit_handler(int sig); static int set_sighandler(int sig, void (*handler)(int)); static int set_sighandlers(); static void usage(FILE* p); static bool exit_requested = false; static int received_sig = 0; namespace l7vsd{ l7vs::Logger l7vs::Logger::instance; l7vs::Parameter l7vs::Parameter::instance; void l7vsd::start() { } };// namespace l7vsd static void sig_exit_handler(int sig) { received_sig = sig; exit_requested = true; } static int set_sighandler(int sig, void (*handler)(int)) { struct sigaction act; int ret; ret = sigaction(sig, NULL, &act); if (ret < 0) { //LOGGER_PUT_LOG_ERROR(LOG_CAT_L7VSD_SYSTEM_SIGNAL,1, "sigaction on signal %d failed", sig); return ret; } act.sa_flags &= ~SA_RESETHAND; act.sa_handler = handler; ret = sigaction(sig, &act, NULL); if (ret < 0) { //LOGGER_PUT_LOG_ERROR(LOG_CAT_L7VSD_SYSTEM_SIGNAL,2, "sigaction on signal %d failed", sig); return ret; } return 0; } static int set_sighandlers() { int ret; #define SET_SIGHANDLER(sig, handler) \ do { \ ret = set_sighandler((sig), (handler)); \ if (ret < 0) { \ return ret; \ } \ } while (0) SET_SIGHANDLER(SIGHUP, sig_exit_handler); SET_SIGHANDLER(SIGINT, sig_exit_handler); SET_SIGHANDLER(SIGQUIT, sig_exit_handler); SET_SIGHANDLER(SIGTERM, sig_exit_handler); SET_SIGHANDLER(SIGUSR1, SIG_IGN); SET_SIGHANDLER(SIGUSR2, SIG_IGN); SET_SIGHANDLER(SIGALRM, SIG_IGN); SET_SIGHANDLER(SIGCHLD, SIG_IGN); #undef SET_SIGHANDLER return 0; } static void usage(FILE* p) { } #ifndef TEST_CASE int main( int argc, char* argv[] ){ try{ if (0 > set_sighandlers()) { exit(-1); } l7vsd::l7vsd l7vsd_; l7vsd_.start(); } catch( ... ){ } return 0; } #else int main(){ return 0;} #endif //TEST_CASE <|endoftext|>
<commit_before>/* Copyright 2012 Dietrich Epp <depp@zdome.net> */ #include "level.hpp" #include "gamescreen.hpp" using namespace LD24; Level::~Level() { } void Level::nextLevel() { screen.nextLevel(); } void Level::setTipFlags(unsigned flags) { if (flags == m_tipflag) return; levelTips.clear(); for (int i = 0; i < 32; ++i) { if (flags & (1u << i)) levelTips.push_back(m_allTips[i]); } } void Level::addTip(int index) { setTipFlags(m_tipflag | (1u << index)); } void Level::removeTip(int index) { setTipFlags(m_tipflag & ~(1u << index)); } <commit_msg>Fix problems with multiple tips<commit_after>/* Copyright 2012 Dietrich Epp <depp@zdome.net> */ #include "level.hpp" #include "gamescreen.hpp" using namespace LD24; Level::~Level() { } void Level::nextLevel() { screen.nextLevel(); } void Level::setTipFlags(unsigned flags) { if (flags == m_tipflag) return; levelTips.clear(); for (int i = 0; i < 32; ++i) { if (flags & (1u << i)) levelTips.push_back(m_allTips[i]); } m_tipflag = flags; } void Level::addTip(int index) { setTipFlags(m_tipflag | (1u << index)); } void Level::removeTip(int index) { setTipFlags(m_tipflag & ~(1u << index)); } <|endoftext|>
<commit_before>/* ** Copyright 2011 Merethis ** ** This file is part of Centreon Clib. ** ** Centreon Clib is free software: you can redistribute it ** and/or modify it under the terms of the GNU Affero General Public ** License as published by the Free Software Foundation, either version ** 3 of the License, or (at your option) any later version. ** ** Centreon Clib is distributed in the hope that it will be ** useful, but WITHOUT ANY WARRANTY; without even the implied warranty ** of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public ** License along with Centreon Clib. If not, see ** <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <errno.h> #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) # include <pthread_np.h> #endif // FreeBSD or OpenBSD or NetBSD #include <stdlib.h> #include <string.h> #include <time.h> #include "com/centreon/exceptions/basic.hh" #include "com/centreon/concurrency/locker.hh" #include "com/centreon/concurrency/thread.hh" using namespace com::centreon::concurrency; /** * Default constructor. */ thread::thread() { } /** * Default destructor. */ thread::~thread() throw () { } /** * Execute the running method in the new thread. */ void thread::exec() { int ret(pthread_create(&_th, NULL, &_execute, this)); if (ret) throw (basic_error() << "failed to create thread:" << strerror(ret)); } /** * Get the current thread id. * * @return The current thread id. */ thread_id thread::get_current_id() throw () { return (pthread_self()); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] msecs Time to sleep in milliseconds. */ void thread::msleep(unsigned long msecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. time_t sec(msecs / 1000); msecs -= sec * 1000; ts.tv_sec += sec; ts.tv_nsec += msecs * 1000 * 1000; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] nsecs Time to sleep in nanoseconds. */ void thread::nsleep(unsigned long nsecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. ts.tv_nsec += nsecs; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] secs Time to sleep in seconds. */ void thread::sleep(unsigned long secs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. ts.tv_sec += secs; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] usecs Time to sleep in micoseconds. */ void thread::usleep(unsigned long usecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. time_t sec(usecs / (1000 * 1000)); usecs -= sec * (1000 * 1000); ts.tv_sec += sec; ts.tv_nsec += usecs * 1000; // Sleep the calling thread. _sleep(&ts); } /** * Wait the end of the thread. */ void thread::wait() { locker lock(&_mtx); // Wait the end of the thread. int ret(pthread_join(_th, NULL)); if (ret && ret != ESRCH) throw (basic_error() << "failed to wait thread:" << strerror(ret)); } /** * This is an overload of wait. * * @param[in] timeout Define the timeout to wait the end of * the thread. * * @return True if the thread end before timeout, otherwise false. */ bool thread::wait(unsigned long timeout) { locker lock(&_mtx); // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed to wait thread:" << strerror(errno)); // Transforms unnecessary microseconds into seconds. time_t sec(ts.tv_nsec / 1000000); ts.tv_nsec -= sec * 1000000; ts.tv_sec += sec; // Add timeout. sec = timeout / 1000; timeout -= sec * 1000; ts.tv_sec += sec; ts.tv_nsec += timeout * 1000000; // Wait the end of the thread or timeout. int ret(pthread_timedjoin_np(_th, NULL, &ts)); if (!ret || ret == ESRCH) return (true); if (ret == ETIMEDOUT) return (false); throw (basic_error() << "failed to wait thread:" << strerror(ret)); } /** * Causes the calling thread to relinquish the CPU. * @remark This function is static. */ void thread::yield() throw () { sched_yield(); } /** * Default copy constructor. * * @param[in] right The object to copy. */ thread::thread(thread const& right) { _internal_copy(right); } /** * Default copy operator. * * @param[in] right The object to copy. * * @return This object. */ thread& thread::operator=(thread const& right) { return (_internal_copy(right)); } /** * The thread start routine. * @remark This function is static. * * @param[in] data This thread object. * * @return always return zero. */ void* thread::_execute(void* data) { thread* self(static_cast<thread*>(data)); if (self) self->_run(); return (0); } /** * Internal copy. * * @param[in] right The object to copy. * * @return This object. */ thread& thread::_internal_copy(thread const& right) { (void)right; assert(!"impossible to copy thread"); abort(); return (*this); } /** * Internal sleep, Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] ts Time to sleep with timespec struct. */ void thread::_sleep(timespec* ts) { int ret(0); // Create mutex. pthread_mutex_t mtx; pthread_mutex_init(&mtx, NULL); // Create condition variable. pthread_cond_t cnd; pthread_cond_init(&cnd, NULL); // Lock the mutex. if ((ret = pthread_mutex_lock(&mtx))) throw (basic_error() << "impossible to sleep:" << strerror(ret)); // Wait the timeout of the condition variable. if ((ret = pthread_cond_timedwait(&cnd, &mtx, ts)) && ret != ETIMEDOUT) throw (basic_error() << "impossible to sleep:" << strerror(ret)); // Release mutex. if ((ret = pthread_mutex_unlock(&mtx))) throw (basic_error() << "impossible in sleep:" << strerror(ret)); // Cleanup. pthread_cond_destroy(&cnd); pthread_mutex_destroy(&mtx); } <commit_msg>On OpenBSD (at least), pthread.h must be included before pthread_np.h.<commit_after>/* ** Copyright 2011 Merethis ** ** This file is part of Centreon Clib. ** ** Centreon Clib is free software: you can redistribute it ** and/or modify it under the terms of the GNU Affero General Public ** License as published by the Free Software Foundation, either version ** 3 of the License, or (at your option) any later version. ** ** Centreon Clib is distributed in the hope that it will be ** useful, but WITHOUT ANY WARRANTY; without even the implied warranty ** of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public ** License along with Centreon Clib. If not, see ** <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <errno.h> #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) # include <pthread.h> # include <pthread_np.h> #endif // FreeBSD or OpenBSD or NetBSD #include <stdlib.h> #include <string.h> #include <time.h> #include "com/centreon/exceptions/basic.hh" #include "com/centreon/concurrency/locker.hh" #include "com/centreon/concurrency/thread.hh" using namespace com::centreon::concurrency; /** * Default constructor. */ thread::thread() { } /** * Default destructor. */ thread::~thread() throw () { } /** * Execute the running method in the new thread. */ void thread::exec() { int ret(pthread_create(&_th, NULL, &_execute, this)); if (ret) throw (basic_error() << "failed to create thread:" << strerror(ret)); } /** * Get the current thread id. * * @return The current thread id. */ thread_id thread::get_current_id() throw () { return (pthread_self()); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] msecs Time to sleep in milliseconds. */ void thread::msleep(unsigned long msecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. time_t sec(msecs / 1000); msecs -= sec * 1000; ts.tv_sec += sec; ts.tv_nsec += msecs * 1000 * 1000; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] nsecs Time to sleep in nanoseconds. */ void thread::nsleep(unsigned long nsecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. ts.tv_nsec += nsecs; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] secs Time to sleep in seconds. */ void thread::sleep(unsigned long secs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. ts.tv_sec += secs; // Sleep the calling thread. _sleep(&ts); } /** * Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] usecs Time to sleep in micoseconds. */ void thread::usleep(unsigned long usecs) { // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed sleep thread:" << strerror(errno)); // Add timeout. time_t sec(usecs / (1000 * 1000)); usecs -= sec * (1000 * 1000); ts.tv_sec += sec; ts.tv_nsec += usecs * 1000; // Sleep the calling thread. _sleep(&ts); } /** * Wait the end of the thread. */ void thread::wait() { locker lock(&_mtx); // Wait the end of the thread. int ret(pthread_join(_th, NULL)); if (ret && ret != ESRCH) throw (basic_error() << "failed to wait thread:" << strerror(ret)); } /** * This is an overload of wait. * * @param[in] timeout Define the timeout to wait the end of * the thread. * * @return True if the thread end before timeout, otherwise false. */ bool thread::wait(unsigned long timeout) { locker lock(&_mtx); // Get the current time. timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) throw (basic_error() << "failed to wait thread:" << strerror(errno)); // Transforms unnecessary microseconds into seconds. time_t sec(ts.tv_nsec / 1000000); ts.tv_nsec -= sec * 1000000; ts.tv_sec += sec; // Add timeout. sec = timeout / 1000; timeout -= sec * 1000; ts.tv_sec += sec; ts.tv_nsec += timeout * 1000000; // Wait the end of the thread or timeout. int ret(pthread_timedjoin_np(_th, NULL, &ts)); if (!ret || ret == ESRCH) return (true); if (ret == ETIMEDOUT) return (false); throw (basic_error() << "failed to wait thread:" << strerror(ret)); } /** * Causes the calling thread to relinquish the CPU. * @remark This function is static. */ void thread::yield() throw () { sched_yield(); } /** * Default copy constructor. * * @param[in] right The object to copy. */ thread::thread(thread const& right) { _internal_copy(right); } /** * Default copy operator. * * @param[in] right The object to copy. * * @return This object. */ thread& thread::operator=(thread const& right) { return (_internal_copy(right)); } /** * The thread start routine. * @remark This function is static. * * @param[in] data This thread object. * * @return always return zero. */ void* thread::_execute(void* data) { thread* self(static_cast<thread*>(data)); if (self) self->_run(); return (0); } /** * Internal copy. * * @param[in] right The object to copy. * * @return This object. */ thread& thread::_internal_copy(thread const& right) { (void)right; assert(!"impossible to copy thread"); abort(); return (*this); } /** * Internal sleep, Makes the calling thread sleep untils timeout. * @remark This function is static. * * @param[in] ts Time to sleep with timespec struct. */ void thread::_sleep(timespec* ts) { int ret(0); // Create mutex. pthread_mutex_t mtx; pthread_mutex_init(&mtx, NULL); // Create condition variable. pthread_cond_t cnd; pthread_cond_init(&cnd, NULL); // Lock the mutex. if ((ret = pthread_mutex_lock(&mtx))) throw (basic_error() << "impossible to sleep:" << strerror(ret)); // Wait the timeout of the condition variable. if ((ret = pthread_cond_timedwait(&cnd, &mtx, ts)) && ret != ETIMEDOUT) throw (basic_error() << "impossible to sleep:" << strerror(ret)); // Release mutex. if ((ret = pthread_mutex_unlock(&mtx))) throw (basic_error() << "impossible in sleep:" << strerror(ret)); // Cleanup. pthread_cond_destroy(&cnd); pthread_mutex_destroy(&mtx); } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ #define _POSIX_SOURCE #include "condor_common.h" #include "condor_constants.h" #include "condor_io.h" #include "condor_debug.h" #include "condor_md.h" #include "condor_rw.h" unsigned long num_created = 0; unsigned long num_deleted = 0; void sanity_check() { dprintf(D_ALWAYS, "IO: Buffer management:\n"); dprintf(D_ALWAYS, "IO: created: %lu\n", num_created); dprintf(D_ALWAYS, "IO: deleted: %lu\n\n", num_deleted); } Buf::Buf( int sz ) { _dta = NULL; _dta_maxsz = sz; _dta_sz = 0; _dta_pt = 0; _next = NULL; num_created++; p_sock = NULL; } Buf::~Buf() { dealloc_buf(); num_deleted++; } void Buf::alloc_buf() { if( !_dta ) { _dta = new char[_dta_maxsz]; } } void Buf::dealloc_buf() { if (_dta) { delete [] _dta; _dta = NULL; } } void Buf::grow_buf(int new_sz) { if (new_sz < _dta_maxsz) return; char * new_dta = new char[new_sz]; if (_dta) { memcpy(new_dta, _dta, _dta_sz); delete [] _dta; } _dta = new_dta; _dta_maxsz = new_sz; } int Buf::write( char const *peer_description, SOCKET sockd, int sz, int timeout, bool non_blocking ) { int nw; alloc_buf(); if (sz < 0 || sz > num_untouched()) { sz = num_untouched(); } nw = condor_write(peer_description,sockd, &_dta[num_touched()], sz , timeout, 0, non_blocking); if (nw < 0) { dprintf( D_ALWAYS, "Buf::write(): condor_write() failed\n" ); return -1; } _dta_pt += nw; return nw; } int Buf::flush( char const *peer_description, SOCKET sockd, void *hdr, int sz, int timeout, bool non_blocking ) { /* DEBUG SESSION int dbg_fd; */ alloc_buf(); if (sz > max_size()) return -1; if (hdr && sz > 0){ memcpy(_dta, hdr, sz); } rewind(); /* DEBUG SESSION if ((dbg_fd = safe_open_wrapper_follow("trace.snd", O_WRONLY|O_APPEND|O_CREAT, 0700)) < 0){ dprintf(D_ALWAYS, "IO: Error opening trace file\n"); exit(1); } if (write(dbg_fd, _dta, _dta_maxsz) != _dta_maxsz){ dprintf(D_ALWAYS, "IO: ERROR LOGGING\n"); return FALSE; } ::close(dbg_fd); */ sz = write(peer_description,sockd, -1, timeout, non_blocking); if (!non_blocking || consumed()) { reset(); } return sz; } int Buf::read( char const *peer_description, SOCKET sockd, int sz, int timeout, bool non_blocking ) { int nr; alloc_buf(); if (sz < 0 || sz > num_free()){ dprintf(D_ALWAYS, "IO: Buffer too small\n"); return -1; /* sz = num_free(); */ } nr = condor_read(peer_description,sockd,&_dta[num_used()],sz,timeout, 0, non_blocking); if (nr < 0) { dprintf( D_ALWAYS, "Buf::read(): condor_read() failed\n" ); return nr; } _dta_sz += nr; /* DEBUG SESSION if ((dbg_fd = safe_open_wrapper_follow("trace.rcv", O_WRONLY|O_APPEND|O_CREAT, 0700)) < 0){ dprintf(D_ALWAYS, "IO: Error opening trace file\n"); exit(1); } if (write(dbg_fd, _dta, _dta_maxsz) != _dta_maxsz){ dprintf(D_ALWAYS, "IO: ERROR LOGGING\n"); return FALSE; } ::close(dbg_fd); */ return nr; } int Buf::put_max( const void *dta, int sz ) { alloc_buf(); if (sz > num_free()) sz = num_free(); memcpy(&_dta[num_used()], dta, sz); _dta_sz += sz; return sz; } int Buf::put_force( const void *dta, int sz ) { int free = num_free(); int needed = sz - free; if (needed > 0) { grow_buf(_dta_maxsz + needed); } memcpy(&_dta[num_used()], dta, sz); _dta_sz += sz; return sz; } int Buf::get_max( void *dta, int sz ) { alloc_buf(); if (sz > num_untouched()) sz = num_untouched(); memcpy(dta, &_dta[num_touched()], sz); _dta_pt += sz; return sz; } int Buf::find( char delim ) { char *tmp; alloc_buf(); if (!(tmp = (char *)memchr(&_dta[num_touched()], delim, num_untouched()))){ return -1; } return (tmp - &_dta[num_touched()]); } int Buf::peek( char &c ) { if (empty() || consumed()) return FALSE; alloc_buf(); c = _dta[num_touched()]; return TRUE; } int Buf::seek( int pos ) { int tmp; alloc_buf(); tmp = _dta_pt; _dta_pt = (pos < 0) ? 0 : ((pos < _dta_maxsz) ? pos : _dta_maxsz-1); if (_dta_pt > _dta_sz) _dta_sz = _dta_pt; return tmp; } bool Buf::computeMD(char * checkSUM, Condor_MD_MAC * checker) { alloc_buf(); // I absolutely hate this! 21 checker->addMD((unsigned char *) &(_dta[21]), _dta_sz - 21); unsigned char * md = checker->computeMD(); if (md) { memcpy(checkSUM, md, MAC_SIZE); free(md); return true; } return false; } bool Buf::verifyMD(char * checkSUM, Condor_MD_MAC * checker) { alloc_buf(); checker->addMD((unsigned char *) &(_dta[0]), _dta_sz); return checker->verifyMD((unsigned char *) checkSUM); } void Buf::swap(Buf &other) { char * tmp_dta = _dta; int tmp_dta_sz = _dta_sz; int tmp_dta_maxsz = _dta_maxsz; int tmp_dta_pt = _dta_pt; // NOTE: This will not work with a buf in ChainBuf // because we need to fixup anything pointing to us! Buf *tmp_next = _next; Sock *tmp_sock = p_sock; _dta = other._dta; _dta_sz = other._dta_sz; _dta_maxsz = other._dta_maxsz; _dta_pt = other._dta_pt; _next = other._next; p_sock = other.p_sock; other._dta = tmp_dta; other._dta_sz = tmp_dta_sz; other._dta_maxsz = tmp_dta_maxsz; other._dta_pt = tmp_dta_pt; other._next = tmp_next; other.p_sock = tmp_sock; } void ChainBuf::reset() { Buf *trav; Buf *trav_n; if (_tmp) { delete [] _tmp; _tmp = (char *)0; } for(trav=_head; trav; trav=trav_n){ trav_n = trav->next(); delete trav; } _head = _tail = _curr = (Buf *)0; } int dbg_count = 0; int ChainBuf::get( void *dta, int sz ) { int last_incr; int nr; if (dbg_count++ > 307){ dbg_count--; } for(nr=0; _curr; _curr=_curr->next()){ last_incr = _curr->get_max(&((char *)dta)[nr], sz-nr); nr += last_incr; if (nr == sz) break; } return nr; } int ChainBuf::put( Buf *dta ) { if (_tmp) { delete [] _tmp; _tmp = (char *)0; } if (!_tail){ _head = _tail = _curr = dta; dta->set_next((Buf *)0); } else{ _tail->set_next(dta); _tail = dta; _tail->set_next((Buf *)0); } return TRUE; } int ChainBuf::get_tmp( void *&ptr, char delim ) { int nr; int tr; Buf *trav; if (_tmp) { delete [] _tmp; _tmp = (char *)0; } if (!_curr) return -1; /* case 1: in one buffer */ if ((tr = _curr->find(delim)) >= 0){ ptr = _curr->get_ptr(); nr = _curr->seek(0); _curr->seek(nr+tr+1); return tr+1; } /* case 2: string is in >1 buffers. */ nr = _curr->num_untouched(); if (!_curr->next()) return -1; for(trav = _curr->next(); trav; trav = trav->next()){ if ((tr = trav->find(delim)) < 0){ nr += trav->num_untouched(); } else{ nr += tr; if (!(_tmp = new char[nr+1])) return -1; get(_tmp, nr+1); ptr = _tmp; return nr+1; } } return -1; } int ChainBuf::peek( char &c ) { if (_tmp) { delete [] _tmp; _tmp = (char *)0; } if (!_curr) return FALSE; if (!_curr->peek(c)){ if (!(_curr = _curr->next())) return FALSE; return _curr->peek(c); } return TRUE; } <commit_msg>Remove silliness that does nothing (useful) on receipt of a TCP packet.<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ #define _POSIX_SOURCE #include "condor_common.h" #include "condor_constants.h" #include "condor_io.h" #include "condor_debug.h" #include "condor_md.h" #include "condor_rw.h" unsigned long num_created = 0; unsigned long num_deleted = 0; void sanity_check() { dprintf(D_ALWAYS, "IO: Buffer management:\n"); dprintf(D_ALWAYS, "IO: created: %lu\n", num_created); dprintf(D_ALWAYS, "IO: deleted: %lu\n\n", num_deleted); } Buf::Buf( int sz ) { _dta = NULL; _dta_maxsz = sz; _dta_sz = 0; _dta_pt = 0; _next = NULL; num_created++; p_sock = NULL; } Buf::~Buf() { dealloc_buf(); num_deleted++; } void Buf::alloc_buf() { if( !_dta ) { _dta = new char[_dta_maxsz]; } } void Buf::dealloc_buf() { if (_dta) { delete [] _dta; _dta = NULL; } } void Buf::grow_buf(int new_sz) { if (new_sz < _dta_maxsz) return; char * new_dta = new char[new_sz]; if (_dta) { memcpy(new_dta, _dta, _dta_sz); delete [] _dta; } _dta = new_dta; _dta_maxsz = new_sz; } int Buf::write( char const *peer_description, SOCKET sockd, int sz, int timeout, bool non_blocking ) { int nw; alloc_buf(); if (sz < 0 || sz > num_untouched()) { sz = num_untouched(); } nw = condor_write(peer_description,sockd, &_dta[num_touched()], sz , timeout, 0, non_blocking); if (nw < 0) { dprintf( D_ALWAYS, "Buf::write(): condor_write() failed\n" ); return -1; } _dta_pt += nw; return nw; } int Buf::flush( char const *peer_description, SOCKET sockd, void *hdr, int sz, int timeout, bool non_blocking ) { /* DEBUG SESSION int dbg_fd; */ alloc_buf(); if (sz > max_size()) return -1; if (hdr && sz > 0){ memcpy(_dta, hdr, sz); } rewind(); /* DEBUG SESSION if ((dbg_fd = safe_open_wrapper_follow("trace.snd", O_WRONLY|O_APPEND|O_CREAT, 0700)) < 0){ dprintf(D_ALWAYS, "IO: Error opening trace file\n"); exit(1); } if (write(dbg_fd, _dta, _dta_maxsz) != _dta_maxsz){ dprintf(D_ALWAYS, "IO: ERROR LOGGING\n"); return FALSE; } ::close(dbg_fd); */ sz = write(peer_description,sockd, -1, timeout, non_blocking); if (!non_blocking || consumed()) { reset(); } return sz; } int Buf::read( char const *peer_description, SOCKET sockd, int sz, int timeout, bool non_blocking ) { int nr; alloc_buf(); if (sz < 0 || sz > num_free()){ dprintf(D_ALWAYS, "IO: Buffer too small\n"); return -1; /* sz = num_free(); */ } nr = condor_read(peer_description,sockd,&_dta[num_used()],sz,timeout, 0, non_blocking); if (nr < 0) { dprintf( D_ALWAYS, "Buf::read(): condor_read() failed\n" ); return nr; } _dta_sz += nr; /* DEBUG SESSION if ((dbg_fd = safe_open_wrapper_follow("trace.rcv", O_WRONLY|O_APPEND|O_CREAT, 0700)) < 0){ dprintf(D_ALWAYS, "IO: Error opening trace file\n"); exit(1); } if (write(dbg_fd, _dta, _dta_maxsz) != _dta_maxsz){ dprintf(D_ALWAYS, "IO: ERROR LOGGING\n"); return FALSE; } ::close(dbg_fd); */ return nr; } int Buf::put_max( const void *dta, int sz ) { alloc_buf(); if (sz > num_free()) sz = num_free(); memcpy(&_dta[num_used()], dta, sz); _dta_sz += sz; return sz; } int Buf::put_force( const void *dta, int sz ) { int free = num_free(); int needed = sz - free; if (needed > 0) { grow_buf(_dta_maxsz + needed); } memcpy(&_dta[num_used()], dta, sz); _dta_sz += sz; return sz; } int Buf::get_max( void *dta, int sz ) { alloc_buf(); if (sz > num_untouched()) sz = num_untouched(); memcpy(dta, &_dta[num_touched()], sz); _dta_pt += sz; return sz; } int Buf::find( char delim ) { char *tmp; alloc_buf(); if (!(tmp = (char *)memchr(&_dta[num_touched()], delim, num_untouched()))){ return -1; } return (tmp - &_dta[num_touched()]); } int Buf::peek( char &c ) { if (empty() || consumed()) return FALSE; alloc_buf(); c = _dta[num_touched()]; return TRUE; } int Buf::seek( int pos ) { int tmp; alloc_buf(); tmp = _dta_pt; _dta_pt = (pos < 0) ? 0 : ((pos < _dta_maxsz) ? pos : _dta_maxsz-1); if (_dta_pt > _dta_sz) _dta_sz = _dta_pt; return tmp; } bool Buf::computeMD(char * checkSUM, Condor_MD_MAC * checker) { alloc_buf(); // I absolutely hate this! 21 checker->addMD((unsigned char *) &(_dta[21]), _dta_sz - 21); unsigned char * md = checker->computeMD(); if (md) { memcpy(checkSUM, md, MAC_SIZE); free(md); return true; } return false; } bool Buf::verifyMD(char * checkSUM, Condor_MD_MAC * checker) { alloc_buf(); checker->addMD((unsigned char *) &(_dta[0]), _dta_sz); return checker->verifyMD((unsigned char *) checkSUM); } void Buf::swap(Buf &other) { char * tmp_dta = _dta; int tmp_dta_sz = _dta_sz; int tmp_dta_maxsz = _dta_maxsz; int tmp_dta_pt = _dta_pt; // NOTE: This will not work with a buf in ChainBuf // because we need to fixup anything pointing to us! Buf *tmp_next = _next; Sock *tmp_sock = p_sock; _dta = other._dta; _dta_sz = other._dta_sz; _dta_maxsz = other._dta_maxsz; _dta_pt = other._dta_pt; _next = other._next; p_sock = other.p_sock; other._dta = tmp_dta; other._dta_sz = tmp_dta_sz; other._dta_maxsz = tmp_dta_maxsz; other._dta_pt = tmp_dta_pt; other._next = tmp_next; other.p_sock = tmp_sock; } void ChainBuf::reset() { Buf *trav; Buf *trav_n; if (_tmp) { delete [] _tmp; _tmp = (char *)0; } for(trav=_head; trav; trav=trav_n){ trav_n = trav->next(); delete trav; } _head = _tail = _curr = (Buf *)0; } int ChainBuf::get( void *dta, int sz ) { int last_incr; int nr; for(nr=0; _curr; _curr=_curr->next()){ last_incr = _curr->get_max(&((char *)dta)[nr], sz-nr); nr += last_incr; if (nr == sz) break; } return nr; } int ChainBuf::put( Buf *dta ) { if (_tmp) { delete [] _tmp; _tmp = (char *)0; } if (!_tail){ _head = _tail = _curr = dta; dta->set_next((Buf *)0); } else{ _tail->set_next(dta); _tail = dta; _tail->set_next((Buf *)0); } return TRUE; } int ChainBuf::get_tmp( void *&ptr, char delim ) { int nr; int tr; Buf *trav; if (_tmp) { delete [] _tmp; _tmp = (char *)0; } if (!_curr) return -1; /* case 1: in one buffer */ if ((tr = _curr->find(delim)) >= 0){ ptr = _curr->get_ptr(); nr = _curr->seek(0); _curr->seek(nr+tr+1); return tr+1; } /* case 2: string is in >1 buffers. */ nr = _curr->num_untouched(); if (!_curr->next()) return -1; for(trav = _curr->next(); trav; trav = trav->next()){ if ((tr = trav->find(delim)) < 0){ nr += trav->num_untouched(); } else{ nr += tr; if (!(_tmp = new char[nr+1])) return -1; get(_tmp, nr+1); ptr = _tmp; return nr+1; } } return -1; } int ChainBuf::peek( char &c ) { if (_tmp) { delete [] _tmp; _tmp = (char *)0; } if (!_curr) return FALSE; if (!_curr->peek(c)){ if (!(_curr = _curr->next())) return FALSE; return _curr->peek(c); } return TRUE; } <|endoftext|>
<commit_before>/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkRasterClip.h" SkRasterClip::SkRasterClip() { fIsBW = true; } SkRasterClip::SkRasterClip(const SkIRect& bounds) : fBW(bounds) { fIsBW = true; } SkRasterClip::~SkRasterClip() {} bool SkRasterClip::isEmpty() const { return fIsBW ? fBW.isEmpty() : fAA.isEmpty(); } bool SkRasterClip::isRect() const { return fIsBW ? fBW.isRect() : false; } bool SkRasterClip::isComplex() const { return fIsBW ? fBW.isComplex() : !fAA.isEmpty(); } const SkIRect& SkRasterClip::getBounds() const { return fIsBW ? fBW.getBounds() : fAA.getBounds(); } bool SkRasterClip::setEmpty() { fIsBW = true; fBW.setEmpty(); fAA.setEmpty(); return false; } bool SkRasterClip::setRect(const SkIRect& rect) { fIsBW = true; fAA.setEmpty(); return fBW.setRect(rect); } bool SkRasterClip::setPath(const SkPath& path, const SkRegion& clip, bool doAA) { if (this->isBW() && !doAA) { return fBW.setPath(path, clip); } else { if (this->isBW()) { this->convertToAA(); } return fAA.setPath(path, &clip, doAA); } } bool SkRasterClip::setPath(const SkPath& path, const SkIRect& clip, bool doAA) { SkRegion tmp; tmp.setRect(clip); return this->setPath(path, tmp, doAA); } bool SkRasterClip::setPath(const SkPath& path, const SkRasterClip& clip, bool doAA) { if (clip.isBW()) { return this->setPath(path, clip.bwRgn(), doAA); } else { SkRegion tmp; tmp.setRect(clip.getBounds()); if (!this->setPath(path, clip, doAA)) { return false; } return this->op(clip, SkRegion::kIntersect_Op); } } bool SkRasterClip::op(const SkIRect& rect, SkRegion::Op op) { return fIsBW ? fBW.op(rect, op) : fAA.op(rect, op); } bool SkRasterClip::op(const SkRegion& rgn, SkRegion::Op op) { if (fIsBW) { return fBW.op(rgn, op); } else { SkAAClip tmp; tmp.setRegion(rgn); return fAA.op(tmp, op); } } bool SkRasterClip::op(const SkRasterClip& clip, SkRegion::Op op) { if (this->isBW() && clip.isBW()) { return fBW.op(clip.fBW, op); } else { SkAAClip tmp; const SkAAClip* other; if (this->isBW()) { this->convertToAA(); } if (clip.isBW()) { tmp.setRegion(clip.bwRgn()); other = &tmp; } else { other = &clip.aaRgn(); } return fAA.op(*other, op); } } // return true if x is nearly integral (within 1/256) since that is the highest // precision our aa code can have. static bool is_integral(SkScalar x) { int ix = SkScalarRoundToInt(x); SkScalar sx = SkIntToScalar(ix); return SkScalarAbs(sx - x) < (SK_Scalar1 / 256); } bool SkRasterClip::op(const SkRect& r, SkRegion::Op op, bool doAA) { if (doAA) { // check that the rect really needs aa if (is_integral(r.fLeft) && is_integral(r.fTop) && is_integral(r.fRight) && is_integral(r.fBottom)) { doAA = false; } } if (fIsBW && !doAA) { SkIRect ir; r.round(&ir); fBW.op(ir, op); } else { if (fIsBW) { this->convertToAA(); } fAA.op(r, op, doAA); } } const SkRegion& SkRasterClip::forceGetBW() { if (!fIsBW) { fBW.setRect(fAA.getBounds()); } return fBW; } void SkRasterClip::convertToAA() { SkASSERT(fIsBW); fAA.setRegion(fBW); fIsBW = false; } <commit_msg>forgot explicit return statements<commit_after>/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkRasterClip.h" SkRasterClip::SkRasterClip() { fIsBW = true; } SkRasterClip::SkRasterClip(const SkIRect& bounds) : fBW(bounds) { fIsBW = true; } SkRasterClip::~SkRasterClip() {} bool SkRasterClip::isEmpty() const { return fIsBW ? fBW.isEmpty() : fAA.isEmpty(); } bool SkRasterClip::isRect() const { return fIsBW ? fBW.isRect() : false; } bool SkRasterClip::isComplex() const { return fIsBW ? fBW.isComplex() : !fAA.isEmpty(); } const SkIRect& SkRasterClip::getBounds() const { return fIsBW ? fBW.getBounds() : fAA.getBounds(); } bool SkRasterClip::setEmpty() { fIsBW = true; fBW.setEmpty(); fAA.setEmpty(); return false; } bool SkRasterClip::setRect(const SkIRect& rect) { fIsBW = true; fAA.setEmpty(); return fBW.setRect(rect); } bool SkRasterClip::setPath(const SkPath& path, const SkRegion& clip, bool doAA) { if (this->isBW() && !doAA) { return fBW.setPath(path, clip); } else { if (this->isBW()) { this->convertToAA(); } return fAA.setPath(path, &clip, doAA); } } bool SkRasterClip::setPath(const SkPath& path, const SkIRect& clip, bool doAA) { SkRegion tmp; tmp.setRect(clip); return this->setPath(path, tmp, doAA); } bool SkRasterClip::setPath(const SkPath& path, const SkRasterClip& clip, bool doAA) { if (clip.isBW()) { return this->setPath(path, clip.bwRgn(), doAA); } else { SkRegion tmp; tmp.setRect(clip.getBounds()); if (!this->setPath(path, clip, doAA)) { return false; } return this->op(clip, SkRegion::kIntersect_Op); } } bool SkRasterClip::op(const SkIRect& rect, SkRegion::Op op) { return fIsBW ? fBW.op(rect, op) : fAA.op(rect, op); } bool SkRasterClip::op(const SkRegion& rgn, SkRegion::Op op) { if (fIsBW) { return fBW.op(rgn, op); } else { SkAAClip tmp; tmp.setRegion(rgn); return fAA.op(tmp, op); } } bool SkRasterClip::op(const SkRasterClip& clip, SkRegion::Op op) { if (this->isBW() && clip.isBW()) { return fBW.op(clip.fBW, op); } else { SkAAClip tmp; const SkAAClip* other; if (this->isBW()) { this->convertToAA(); } if (clip.isBW()) { tmp.setRegion(clip.bwRgn()); other = &tmp; } else { other = &clip.aaRgn(); } return fAA.op(*other, op); } } // return true if x is nearly integral (within 1/256) since that is the highest // precision our aa code can have. static bool is_integral(SkScalar x) { int ix = SkScalarRoundToInt(x); SkScalar sx = SkIntToScalar(ix); return SkScalarAbs(sx - x) < (SK_Scalar1 / 256); } bool SkRasterClip::op(const SkRect& r, SkRegion::Op op, bool doAA) { if (doAA) { // check that the rect really needs aa if (is_integral(r.fLeft) && is_integral(r.fTop) && is_integral(r.fRight) && is_integral(r.fBottom)) { doAA = false; } } if (fIsBW && !doAA) { SkIRect ir; r.round(&ir); return fBW.op(ir, op); } else { if (fIsBW) { this->convertToAA(); } return fAA.op(r, op, doAA); } } const SkRegion& SkRasterClip::forceGetBW() { if (!fIsBW) { fBW.setRect(fAA.getBounds()); } return fBW; } void SkRasterClip::convertToAA() { SkASSERT(fIsBW); fAA.setRegion(fBW); fIsBW = false; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth 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. * * VapourSynth 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 Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vscore.h" VSThread::VSThread(VSThreadPool *owner) : owner(owner), stop(false) { } void VSThread::stopThread() { stop = true; } void VSThread::run() { owner->lock.lock(); owner->activeThreads++; while (true) { bool ranTask = false; for (int i = 0; i < owner->tasks.count(); i++) { PFrameContext rCtx = owner->tasks[i]; if (rCtx->frameDone && rCtx->returnedFrame) { owner->tasks.removeAt(i--); owner->returnFrame(rCtx, rCtx->returnedFrame); ranTask = true; break; } else { PFrameContext pCtx = rCtx; if (rCtx->returnedFrame || rCtx->hasError()) rCtx = rCtx->upstreamContext; Q_ASSERT(rCtx); Q_ASSERT(pCtx); // if an error has already been flagged upstream simply drop this task so a filter won't get multiple arError calls for the same frame if (rCtx->hasError()) { owner->tasks.removeAt(i--); continue; } bool isSingleInstance = rCtx->clip->filterMode == fmSerial || rCtx->clip->filterMode == fmParallelRequests; // this check is common for both filter modes, it makes sure that multiple calls won't be made in parallel to a single filter to produce the same frame // special casing so serial unordered doesn't need yet another list if (owner->runningTasks.contains(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n))) continue; if (isSingleInstance) { // this is the complicated case, a new frame may not be started until all calls are completed for the current one if (owner->framesInProgress.contains(rCtx->clip) && owner->framesInProgress[rCtx->clip] != rCtx->n) continue; } // mark task as active owner->tasks.removeAt(i--); owner->runningTasks.insert(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n), rCtx); if ((rCtx->clip->filterMode == fmParallelRequests && pCtx->returnedFrame) || (rCtx->clip->filterMode == fmSerial)) owner->framesInProgress.insert(rCtx->clip, rCtx->n); owner->lock.unlock(); // run task ActivationReason ar = arInitial; if (pCtx->hasError()) { ar = arError; rCtx->setError(pCtx->getErrorMessage()); } else if (pCtx != rCtx && pCtx->returnedFrame) { if (rCtx->numFrameRequests.deref()) ar = arFrameReady; else ar = arAllFramesReady; Q_ASSERT(rCtx->numFrameRequests >= 0); rCtx->availableFrames.insert(FrameKey(pCtx->clip, pCtx->n), pCtx->returnedFrame); rCtx->lastCompletedN = pCtx->n; rCtx->lastCompletedNode = pCtx->node; } PVideoFrame f = rCtx->clip->getFrameInternal(rCtx->n, ar, rCtx); ranTask = true; owner->lock.lock(); if (f && rCtx->numFrameRequests > 0) qFatal("Frame returned but there are still pending frame requests, filter: " + rCtx->clip->name); PFrameContext a = pCtx; char b[100]; if (a->returnedFrame) a = a->upstreamContext; if (rCtx->clip->name == "FFVideoSource") { sprintf(b, "src:\t%d\n", a->n); OutputDebugStringA(b); } else if (f) { //sprintf(b, "%s:\t%d\t%d\t%d\n", rCtx->clip->name.constData(), ((int)a->clip) & 0xff, a->n, (int)((bool)f)); //OutputDebugStringA(b); } owner->runningTasks.remove(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n)); if (f || ar == arError || rCtx->hasError()) { // free all input frames quickly since the frame processing is done rCtx->availableFrames.clear(); if (isSingleInstance) { if (owner->framesInProgress[rCtx->clip] != rCtx->n && !rCtx->hasError()) qWarning("Releasing unobtained frame lock"); owner->framesInProgress.remove(rCtx->clip); } owner->allContexts.remove(FrameKey(rCtx->clip, rCtx->n)); } if (rCtx->hasError()) { PFrameContext n; do { n = rCtx->notificationChain; if (n) { rCtx->notificationChain.clear(); n->setError(rCtx->getErrorMessage()); } if (rCtx->upstreamContext) { owner->startInternal(rCtx); } if (rCtx->frameDone) { owner->lock.unlock(); QMutexLocker callbackLock(&owner->callbackLock); rCtx->frameDone(rCtx->userData, NULL, rCtx->n, rCtx->node, rCtx->getErrorMessage().constData()); callbackLock.unlock(); owner->lock.lock(); } } while ((rCtx = n)); } else if (f) { Q_ASSERT(rCtx->numFrameRequests == 0); PFrameContext n; do { n = rCtx->notificationChain; if (n) rCtx->notificationChain.clear(); if (rCtx->upstreamContext) { rCtx->returnedFrame = f; owner->startInternal(rCtx); } if (rCtx->frameDone) owner->returnFrame(rCtx, f); } while ((rCtx = n)); } else if (rCtx->numFrameRequests > 0 || rCtx->n < 0) { // already scheduled or in the case of negative n it is simply a cache notify message } else { qFatal("No frame returned at the end of processing by " + rCtx->clip->name); } break; } } if (!ranTask && !stop) { owner->activeThreads--; owner->newWork.wait(&owner->lock); owner->activeThreads++; } else if (stop) { owner->activeThreads--; owner->lock.unlock(); return; } } } VSThreadPool::VSThreadPool(VSCore *core, int threadCount) : core(core), activeThreads(0) { setMaxThreadCount(threadCount); } int VSThreadPool::activeThreadCount() const { return activeThreads; } int VSThreadPool::threadCount() const { return allThreads.count(); } void VSThreadPool::setMaxThreadCount(int threadCount) { QMutexLocker m(&lock); while (threadCount > allThreads.count()) { VSThread *vst = new VSThread(this); allThreads.insert(vst); vst->start(); } while (threadCount < allThreads.count()) { VSThread *t = *allThreads.begin(); t->stopThread(); newWork.wakeAll(); m.unlock(); t->wait(); m.relock(); allThreads.remove(t); delete t; newWork.wakeAll(); } } void VSThreadPool::wakeThread() { if (activeThreads < threadCount()) newWork.wakeOne(); } void VSThreadPool::releaseThread() { setMaxThreadCount(allThreads.count() + 1); } void VSThreadPool::reserveThread() { setMaxThreadCount(allThreads.count() - 1); } void VSThreadPool::notifyCaches(CacheActivation reason) { for (int i = 0; i < core->caches.count(); i++) tasks.append(PFrameContext(new FrameContext(reason, core->caches[i], PFrameContext()))); } void VSThreadPool::start(const PFrameContext &context) { Q_ASSERT(context); QMutexLocker m(&lock); startInternal(context); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const PVideoFrame &f) { Q_ASSERT(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); VSFrameRef *ref = new VSFrameRef(f); QMutexLocker m(&callbackLock); rCtx->frameDone(rCtx->userData, ref, rCtx->n, rCtx->node, NULL); m.unlock(); lock.lock(); } void VSThreadPool::startInternal(const PFrameContext &context) { //technically this could be done by walking up the context chain and add a new notification to the correct one //unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it if (context->n < 0) qFatal("Negative frame request by: " + context->clip->name); // check to see if it's time to reevaluate cache sizes if (!context->upstreamContext && ticks.fetchAndAddAcquire(1) == 99) { ticks = 0; notifyCaches(cCacheTick); } // add it immediately if the task is to return a completed frame if (context->returnedFrame) { tasks.append(context); wakeThread(); return; } else { if (context->upstreamContext) context->upstreamContext->numFrameRequests.ref(); //////////////////////// // see if the task is a duplicate foreach(const PFrameContext & ctx, tasks) { if (context->clip == ctx->clip && context->n == ctx->n) { if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { PFrameContext rCtx = ctx; if (rCtx->returnedFrame) rCtx = rCtx->upstreamContext; if (context->clip == rCtx->clip && context->n == rCtx->n) { PFrameContext t = rCtx; while (t && t->notificationChain) t = t->notificationChain; t->notificationChain = context; return; } } } } FrameKey p(context->clip, context->n); if (runningTasks.contains(p)) { PFrameContext ctx = runningTasks[p]; Q_ASSERT(ctx); if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { PFrameContext rCtx = ctx; if (rCtx->returnedFrame) rCtx = rCtx->upstreamContext; if (context->clip == rCtx->clip && context->n == rCtx->n) { PFrameContext t = rCtx; while (t && t->notificationChain) t = t->notificationChain; t->notificationChain = context; return; } } } if (allContexts.contains(p)) { PFrameContext ctx = allContexts[p]; Q_ASSERT(ctx); Q_ASSERT(context->clip == ctx->clip && context->n == ctx->n); if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { while (ctx->notificationChain) ctx = ctx->notificationChain; ctx->notificationChain = context; return; } } else { allContexts[p] = context; } tasks.append(context); wakeThread(); return; } } void VSThreadPool::waitForDone() { } VSThreadPool::~VSThreadPool() { setMaxThreadCount(0); }; <commit_msg>remove debug code that keeps sneaking in<commit_after>/* * Copyright (c) 2012 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth 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. * * VapourSynth 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 Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vscore.h" VSThread::VSThread(VSThreadPool *owner) : owner(owner), stop(false) { } void VSThread::stopThread() { stop = true; } void VSThread::run() { owner->lock.lock(); owner->activeThreads++; while (true) { bool ranTask = false; for (int i = 0; i < owner->tasks.count(); i++) { PFrameContext rCtx = owner->tasks[i]; if (rCtx->frameDone && rCtx->returnedFrame) { owner->tasks.removeAt(i--); owner->returnFrame(rCtx, rCtx->returnedFrame); ranTask = true; break; } else { PFrameContext pCtx = rCtx; if (rCtx->returnedFrame || rCtx->hasError()) rCtx = rCtx->upstreamContext; Q_ASSERT(rCtx); Q_ASSERT(pCtx); // if an error has already been flagged upstream simply drop this task so a filter won't get multiple arError calls for the same frame if (rCtx->hasError()) { owner->tasks.removeAt(i--); continue; } bool isSingleInstance = rCtx->clip->filterMode == fmSerial || rCtx->clip->filterMode == fmParallelRequests; // this check is common for both filter modes, it makes sure that multiple calls won't be made in parallel to a single filter to produce the same frame // special casing so serial unordered doesn't need yet another list if (owner->runningTasks.contains(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n))) continue; if (isSingleInstance) { // this is the complicated case, a new frame may not be started until all calls are completed for the current one if (owner->framesInProgress.contains(rCtx->clip) && owner->framesInProgress[rCtx->clip] != rCtx->n) continue; } // mark task as active owner->tasks.removeAt(i--); owner->runningTasks.insert(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n), rCtx); if ((rCtx->clip->filterMode == fmParallelRequests && pCtx->returnedFrame) || (rCtx->clip->filterMode == fmSerial)) owner->framesInProgress.insert(rCtx->clip, rCtx->n); owner->lock.unlock(); // run task ActivationReason ar = arInitial; if (pCtx->hasError()) { ar = arError; rCtx->setError(pCtx->getErrorMessage()); } else if (pCtx != rCtx && pCtx->returnedFrame) { if (rCtx->numFrameRequests.deref()) ar = arFrameReady; else ar = arAllFramesReady; Q_ASSERT(rCtx->numFrameRequests >= 0); rCtx->availableFrames.insert(FrameKey(pCtx->clip, pCtx->n), pCtx->returnedFrame); rCtx->lastCompletedN = pCtx->n; rCtx->lastCompletedNode = pCtx->node; } PVideoFrame f = rCtx->clip->getFrameInternal(rCtx->n, ar, rCtx); ranTask = true; owner->lock.lock(); if (f && rCtx->numFrameRequests > 0) qFatal("Frame returned but there are still pending frame requests, filter: " + rCtx->clip->name); owner->runningTasks.remove(FrameKey(rCtx->clip, rCtx->clip->filterMode == fmUnordered ? -1 : rCtx->n)); if (f || ar == arError || rCtx->hasError()) { // free all input frames quickly since the frame processing is done rCtx->availableFrames.clear(); if (isSingleInstance) { if (owner->framesInProgress[rCtx->clip] != rCtx->n && !rCtx->hasError()) qWarning("Releasing unobtained frame lock"); owner->framesInProgress.remove(rCtx->clip); } owner->allContexts.remove(FrameKey(rCtx->clip, rCtx->n)); } if (rCtx->hasError()) { PFrameContext n; do { n = rCtx->notificationChain; if (n) { rCtx->notificationChain.clear(); n->setError(rCtx->getErrorMessage()); } if (rCtx->upstreamContext) { owner->startInternal(rCtx); } if (rCtx->frameDone) { owner->lock.unlock(); QMutexLocker callbackLock(&owner->callbackLock); rCtx->frameDone(rCtx->userData, NULL, rCtx->n, rCtx->node, rCtx->getErrorMessage().constData()); callbackLock.unlock(); owner->lock.lock(); } } while ((rCtx = n)); } else if (f) { Q_ASSERT(rCtx->numFrameRequests == 0); PFrameContext n; do { n = rCtx->notificationChain; if (n) rCtx->notificationChain.clear(); if (rCtx->upstreamContext) { rCtx->returnedFrame = f; owner->startInternal(rCtx); } if (rCtx->frameDone) owner->returnFrame(rCtx, f); } while ((rCtx = n)); } else if (rCtx->numFrameRequests > 0 || rCtx->n < 0) { // already scheduled or in the case of negative n it is simply a cache notify message } else { qFatal("No frame returned at the end of processing by " + rCtx->clip->name); } break; } } if (!ranTask && !stop) { owner->activeThreads--; owner->newWork.wait(&owner->lock); owner->activeThreads++; } else if (stop) { owner->activeThreads--; owner->lock.unlock(); return; } } } VSThreadPool::VSThreadPool(VSCore *core, int threadCount) : core(core), activeThreads(0) { setMaxThreadCount(threadCount); } int VSThreadPool::activeThreadCount() const { return activeThreads; } int VSThreadPool::threadCount() const { return allThreads.count(); } void VSThreadPool::setMaxThreadCount(int threadCount) { QMutexLocker m(&lock); while (threadCount > allThreads.count()) { VSThread *vst = new VSThread(this); allThreads.insert(vst); vst->start(); } while (threadCount < allThreads.count()) { VSThread *t = *allThreads.begin(); t->stopThread(); newWork.wakeAll(); m.unlock(); t->wait(); m.relock(); allThreads.remove(t); delete t; newWork.wakeAll(); } } void VSThreadPool::wakeThread() { if (activeThreads < threadCount()) newWork.wakeOne(); } void VSThreadPool::releaseThread() { setMaxThreadCount(allThreads.count() + 1); } void VSThreadPool::reserveThread() { setMaxThreadCount(allThreads.count() - 1); } void VSThreadPool::notifyCaches(CacheActivation reason) { for (int i = 0; i < core->caches.count(); i++) tasks.append(PFrameContext(new FrameContext(reason, core->caches[i], PFrameContext()))); } void VSThreadPool::start(const PFrameContext &context) { Q_ASSERT(context); QMutexLocker m(&lock); startInternal(context); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const PVideoFrame &f) { Q_ASSERT(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); VSFrameRef *ref = new VSFrameRef(f); QMutexLocker m(&callbackLock); rCtx->frameDone(rCtx->userData, ref, rCtx->n, rCtx->node, NULL); m.unlock(); lock.lock(); } void VSThreadPool::startInternal(const PFrameContext &context) { //technically this could be done by walking up the context chain and add a new notification to the correct one //unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it if (context->n < 0) qFatal("Negative frame request by: " + context->clip->name); // check to see if it's time to reevaluate cache sizes if (!context->upstreamContext && ticks.fetchAndAddAcquire(1) == 99) { ticks = 0; notifyCaches(cCacheTick); } // add it immediately if the task is to return a completed frame if (context->returnedFrame) { tasks.append(context); wakeThread(); return; } else { if (context->upstreamContext) context->upstreamContext->numFrameRequests.ref(); //////////////////////// // see if the task is a duplicate foreach(const PFrameContext & ctx, tasks) { if (context->clip == ctx->clip && context->n == ctx->n) { if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { PFrameContext rCtx = ctx; if (rCtx->returnedFrame) rCtx = rCtx->upstreamContext; if (context->clip == rCtx->clip && context->n == rCtx->n) { PFrameContext t = rCtx; while (t && t->notificationChain) t = t->notificationChain; t->notificationChain = context; return; } } } } FrameKey p(context->clip, context->n); if (runningTasks.contains(p)) { PFrameContext ctx = runningTasks[p]; Q_ASSERT(ctx); if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { PFrameContext rCtx = ctx; if (rCtx->returnedFrame) rCtx = rCtx->upstreamContext; if (context->clip == rCtx->clip && context->n == rCtx->n) { PFrameContext t = rCtx; while (t && t->notificationChain) t = t->notificationChain; t->notificationChain = context; return; } } } if (allContexts.contains(p)) { PFrameContext ctx = allContexts[p]; Q_ASSERT(ctx); Q_ASSERT(context->clip == ctx->clip && context->n == ctx->n); if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.append(context); wakeThread(); return; } else { while (ctx->notificationChain) ctx = ctx->notificationChain; ctx->notificationChain = context; return; } } else { allContexts[p] = context; } tasks.append(context); wakeThread(); return; } } void VSThreadPool::waitForDone() { } VSThreadPool::~VSThreadPool() { setMaxThreadCount(0); }; <|endoftext|>
<commit_before>/*********************************************************************** filename: TabControlDemo.cpp created: 27/6/2006 author: Andrew Zabolotny *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGuiSample.h" #include "CEGUI/CEGUI.h" using namespace CEGUI; #define SKIN "TaharezLook" // for this to work you'll have to change the .layout files //#define SKIN "WindowsLook" static const char *PageText [] = { "This is page three", "And this is page four, it's not too different from page three, isn't it?", "Yep, you guessed, this is page five", "And this is page six", "Seven", "Eight", "Nine. Quite boring, isn't it?", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "And, finally, sixteen. Congrats, you found the last page!", }; // Sample sub-class for ListboxTextItem that auto-sets the selection brush // image. This saves doing it manually every time in the code. class MyListItem : public ListboxTextItem { public: MyListItem (const String& text) : ListboxTextItem(text) { setSelectionBrushImage(SKIN "/MultiListSelectionBrush"); } }; // Sample class class TabControlDemo : public CEGuiSample { public: // method to initialse the samples windows and events. bool initialiseSample () { // we will use of the WindowManager. WindowManager& winMgr = WindowManager::getSingleton (); // load scheme and set up defaults SchemeManager::getSingleton().createFromFile(SKIN ".scheme"); System::getSingleton().getDefaultGUIRoot().getMouseCursor().setDefaultImage (SKIN "/MouseArrow"); // Ensure font is loaded // First font gets set as the default font automatically FontManager::getSingleton().createFromFile("DejaVuSans-10.font"); // load an image to use as a background ImageManager::getSingleton().addFromImageFile("BackgroundImage", "GPN-2000-001437.png"); // here we will use a StaticImage as the root, then we can use it to place a background image Window* background = winMgr.createWindow (SKIN "/StaticImage"); // set area rectangle background->setArea (URect (cegui_reldim (0), cegui_reldim (0), cegui_reldim (1), cegui_reldim (1))); // disable frame and standard background background->setProperty ("FrameEnabled", "false"); background->setProperty ("BackgroundEnabled", "false"); // set the background image background->setProperty ("Image", "BackgroundImage"); // install this as the root GUI sheet System::getSingleton ().setGUISheet (background); // set tooltip styles (by default there is none) System::getSingleton ().setDefaultTooltip (SKIN "/Tooltip"); // load some demo windows and attach to the background 'root' background->addChild(winMgr.loadLayoutFromFile("TabControlDemo.layout")); TabControl *tc = static_cast<TabControl *>(background->getChild("Frame/TabControl")); // Add some pages to tab control tc->addTab(winMgr.loadLayoutFromFile("TabPage1.layout")); tc->addTab(winMgr.loadLayoutFromFile("TabPage2.layout")); WindowManager::getSingleton().DEBUG_dumpWindowNames("asd"); static_cast<PushButton *> ( background->getChild("Frame/TabControl/Page1/AddTab"))->subscribeEvent ( PushButton::EventClicked, Event::Subscriber (&TabControlDemo::handleAddTab, this)); // Click to visit this tab static_cast<PushButton *> ( background->getChild("Frame/TabControl/Page1/Go"))->subscribeEvent ( PushButton::EventClicked, Event::Subscriber (&TabControlDemo::handleGoto, this)); // Click to make this tab button visible (when scrolling is required) static_cast<PushButton *> ( background->getChild("Frame/TabControl/Page1/Show"))->subscribeEvent ( PushButton::EventClicked, Event::Subscriber (&TabControlDemo::handleShow, this)); static_cast<PushButton *> ( background->getChild("Frame/TabControl/Page1/Del"))->subscribeEvent ( PushButton::EventClicked, Event::Subscriber (&TabControlDemo::handleDel, this)); RadioButton *rb = static_cast<RadioButton *> ( background->getChild("Frame/TabControl/Page1/TabPaneTop")); rb->setSelected (tc->getTabPanePosition () == TabControl::Top); rb->subscribeEvent ( RadioButton::EventSelectStateChanged, Event::Subscriber (&TabControlDemo::handleTabPanePos, this)); rb = static_cast<RadioButton *> ( background->getChild("Frame/TabControl/Page1/TabPaneBottom")); rb->setSelected (tc->getTabPanePosition () == TabControl::Bottom); rb->subscribeEvent ( RadioButton::EventSelectStateChanged, Event::Subscriber (&TabControlDemo::handleTabPanePos, this)); Scrollbar *sb = static_cast<Scrollbar *> ( background->getChild("Frame/TabControl/Page1/TabHeight")); sb->setScrollPosition (tc->getTabHeight ().d_offset); sb->subscribeEvent ( Scrollbar::EventScrollPositionChanged, Event::Subscriber (&TabControlDemo::handleTabHeight, this)); sb = static_cast<Scrollbar *> ( background->getChild("Frame/TabControl/Page1/TabPadding")); sb->setScrollPosition (tc->getTabTextPadding ().d_offset); sb->subscribeEvent ( Scrollbar::EventScrollPositionChanged, Event::Subscriber (&TabControlDemo::handleTabPadding, this)); refreshPageList (); // From now on, we don't rely on the exceptions anymore, but perform nice (and recommended) checks // ourselves. return true; } // method to perform any required cleanup operations. void cleanupSample () { // me? cleanup? what? } void refreshPageList () { Window* root = System::getSingleton().getGUISheet(); // Check if the windows exists Listbox *lbox = NULL; TabControl *tc = NULL; if (root->isChild("Frame/TabControl/Page1/PageList")) { lbox = static_cast<Listbox *> (root->getChild( "Frame/TabControl/Page1/PageList")); } if (root->isChild("Frame/TabControl")) { tc = static_cast<TabControl *>(root->getChild( "Frame/TabControl")); } if (lbox && tc) { lbox->resetList (); for (size_t i = 0; i < tc->getTabCount (); i++) { lbox->addItem (new MyListItem ( tc->getTabContentsAtIndex (i)->getName ())); } } } bool handleTabPanePos (const EventArgs& e) { TabControl::TabPanePosition tpp; switch (static_cast<const WindowEventArgs&> (e).window->getID ()) { case 0: tpp = TabControl::Top; break; case 1: tpp = TabControl::Bottom; break; default: return false; } // Check if the window exists Window* root = System::getSingleton().getGUISheet(); if (root->isChild("Frame/TabControl")) { static_cast<TabControl *>(root->getChild( "Frame/TabControl"))->setTabPanePosition (tpp); } return true; } bool handleTabHeight (const EventArgs& e) { Scrollbar *sb = static_cast<Scrollbar *> ( static_cast<const WindowEventArgs&> (e).window); // Check if the window exists Window* root = System::getSingleton().getGUISheet(); if (root->isChild("Frame/TabControl")) { static_cast<TabControl *> (root->getChild( "Frame/TabControl"))->setTabHeight ( UDim (0, sb->getScrollPosition ())); } // The return value mainly sais that we handled it, not if something failed. return true; } bool handleTabPadding (const EventArgs& e) { Scrollbar *sb = static_cast<Scrollbar *> ( static_cast<const WindowEventArgs&> (e).window); // Check if the window exists Window* root = System::getSingleton().getGUISheet(); if (root->isChild("Frame/TabControl")) { static_cast<TabControl *> (root->getChild( "Frame/TabControl"))->setTabTextPadding ( UDim (0, sb->getScrollPosition ())); } return true; } bool handleAddTab (const EventArgs&) { Window* root = System::getSingleton().getGUISheet(); // Check if the window exists if (root->isChild("Frame/TabControl")) { TabControl *tc = static_cast<TabControl *>(root->getChild( "Frame/TabControl")); // Add some tab buttons once for (int num = 3; num <= 16; num++) { std::stringstream pgname; pgname << "Page" << num; if (root->isChild("Frame/TabControl/" + pgname.str())) // Next continue; Window *pg = NULL; CEGUI_TRY { pg = WindowManager::getSingleton().loadLayoutFromFile("TabPage.layout"); pg->setName(String(pgname.str())); } CEGUI_CATCH (CEGUI::Exception&) { outputExceptionMessage("Some error occured while adding a tabpage. Please see the logfile." ); break; } // This window has just been created while loading the layout if (pg->isChild("Text")) { Window* txt = pg->getChild("Text"); txt->setText(PageText [num - 3]); pg->setText(pgname.str()); tc->addTab(pg); refreshPageList (); break; } } } return true; } bool handleGoto (const EventArgs&) { Window* root = System::getSingleton().getGUISheet(); // Check if the windows exists Listbox *lbox = NULL; TabControl *tc = NULL; if (root->isChild("Frame/TabControl/Page1/PageList")) { lbox = static_cast<Listbox *> (root->getChild( "Frame/TabControl/Page1/PageList")); } if (root->isChild("Frame/TabControl")) { tc = static_cast<TabControl *>(root->getChild( "Frame/TabControl")); } if (lbox && tc) { ListboxItem *lbi = lbox->getFirstSelectedItem (); if (lbi) { tc->setSelectedTab (lbi->getText ()); } } return true; } bool handleShow (const EventArgs&) { Window* root = System::getSingleton().getGUISheet(); // Check if the windows exists Listbox *lbox = NULL; TabControl *tc = NULL; if (root->isChild("Frame/TabControl/Page1/PageList")) { lbox = static_cast<Listbox *> (root->getChild( "Frame/TabControl/Page1/PageList")); } if (root->isChild("Frame/TabControl")) { tc = static_cast<TabControl *>(root->getChild( "Frame/TabControl")); } if (lbox && tc) { ListboxItem *lbi = lbox->getFirstSelectedItem (); if (lbi) { tc->makeTabVisible (lbi->getText ()); } } return true; } bool handleDel (const EventArgs&) { Window* root = System::getSingleton().getGUISheet(); // Check if the windows exists Listbox *lbox = NULL; TabControl *tc = NULL; if (root->isChild("Frame/TabControl/Page1/PageList")) { lbox = static_cast<Listbox *> (root->getChild( "Frame/TabControl/Page1/PageList")); } if (root->isChild("Frame/TabControl")) { tc = static_cast<TabControl *>(root->getChild( "Frame/TabControl")); } if (lbox && tc) { ListboxItem* lbi = lbox->getFirstSelectedItem(); if (lbi) { Window* content = tc->getTabContents(lbi->getText()); tc->removeTab(lbi->getText()); // Remove the actual window from Cegui WindowManager::getSingleton().destroyWindow(content); refreshPageList(); } } return true; } }; int main(int /*argc*/, char* /*argv*/[]) { // This is a basic start-up for the sample application which is // object orientated in nature, so we just need an instance of // the CEGuiSample based object and then tell that sample application // to run. All of the samples will use code similar to this in the // main/WinMain function. TabControlDemo app; return app.run (); } <commit_msg>Again! Freak!<commit_after>/*********************************************************************** filename: TabControlDemo.cpp created: 27/6/2006 author: Andrew Zabolotny *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGuiSample.h" #include "CEGUI/CEGUI.h" using namespace CEGUI; #define SKIN "TaharezLook" // for this to work you'll have to change the .layout files //#define SKIN "WindowsLook" static const char* PageText [] = { "This is page three", "And this is page four, it's not too different from page three, isn't it?", "Yep, you guessed, this is page five", "And this is page six", "Seven", "Eight", "Nine. Quite boring, isn't it?", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "And, finally, sixteen. Congrats, you found the last page!", }; // Sample sub-class for ListboxTextItem that auto-sets the selection brush // image. This saves doing it manually every time in the code. class MyListItem : public ListboxTextItem { public: MyListItem(const String& text) : ListboxTextItem(text) { setSelectionBrushImage(SKIN "/MultiListSelectionBrush"); } }; // Sample class class TabControlDemo : public CEGuiSample { public: // method to initialse the samples windows and events. bool initialiseSample() { // we will use of the WindowManager. WindowManager& winMgr = WindowManager::getSingleton(); // load scheme and set up defaults SchemeManager::getSingleton().createFromFile(SKIN ".scheme"); System::getSingleton().getDefaultGUIRoot().getMouseCursor().setDefaultImage(SKIN "/MouseArrow"); // Ensure font is loaded // First font gets set as the default font automatically FontManager::getSingleton().createFromFile("DejaVuSans-10.font"); // load an image to use as a background ImageManager::getSingleton().addFromImageFile("BackgroundImage", "GPN-2000-001437.png"); // here we will use a StaticImage as the root, then we can use it to place a background image Window* background = winMgr.createWindow(SKIN "/StaticImage"); // set area rectangle background->setArea(URect(cegui_reldim(0), cegui_reldim(0), cegui_reldim(1), cegui_reldim(1))); // disable frame and standard background background->setProperty("FrameEnabled", "false"); background->setProperty("BackgroundEnabled", "false"); // set the background image background->setProperty("Image", "BackgroundImage"); // install this as the root GUI sheet System::getSingleton().setGUISheet(background); // set tooltip styles (by default there is none) System::getSingleton().setDefaultTooltip(SKIN "/Tooltip"); // load some demo windows and attach to the background 'root' background->addChild(winMgr.loadLayoutFromFile("TabControlDemo.layout")); TabControl* tc = static_cast<TabControl*>(background->getChild("Frame/TabControl")); // Add some pages to tab control tc->addTab(winMgr.loadLayoutFromFile("TabPage1.layout")); tc->addTab(winMgr.loadLayoutFromFile("TabPage2.layout")); WindowManager::getSingleton().DEBUG_dumpWindowNames("asd"); static_cast<PushButton*>( background->getChild("Frame/TabControl/Page1/AddTab"))->subscribeEvent( PushButton::EventClicked, Event::Subscriber(&TabControlDemo::handleAddTab, this)); // Click to visit this tab static_cast<PushButton*>( background->getChild("Frame/TabControl/Page1/Go"))->subscribeEvent( PushButton::EventClicked, Event::Subscriber(&TabControlDemo::handleGoto, this)); // Click to make this tab button visible (when scrolling is required) static_cast<PushButton*>( background->getChild("Frame/TabControl/Page1/Show"))->subscribeEvent( PushButton::EventClicked, Event::Subscriber(&TabControlDemo::handleShow, this)); static_cast<PushButton*>( background->getChild("Frame/TabControl/Page1/Del"))->subscribeEvent( PushButton::EventClicked, Event::Subscriber(&TabControlDemo::handleDel, this)); RadioButton* rb = static_cast<RadioButton*>( background->getChild("Frame/TabControl/Page1/TabPaneTop")); rb->setSelected(tc->getTabPanePosition() == TabControl::Top); rb->subscribeEvent( RadioButton::EventSelectStateChanged, Event::Subscriber(&TabControlDemo::handleTabPanePos, this)); rb = static_cast<RadioButton*>( background->getChild("Frame/TabControl/Page1/TabPaneBottom")); rb->setSelected(tc->getTabPanePosition() == TabControl::Bottom); rb->subscribeEvent( RadioButton::EventSelectStateChanged, Event::Subscriber(&TabControlDemo::handleTabPanePos, this)); Scrollbar* sb = static_cast<Scrollbar*>( background->getChild("Frame/TabControl/Page1/TabHeight")); sb->setScrollPosition(tc->getTabHeight().d_offset); sb->subscribeEvent( Scrollbar::EventScrollPositionChanged, Event::Subscriber(&TabControlDemo::handleTabHeight, this)); sb = static_cast<Scrollbar*>( background->getChild("Frame/TabControl/Page1/TabPadding")); sb->setScrollPosition(tc->getTabTextPadding().d_offset); sb->subscribeEvent( Scrollbar::EventScrollPositionChanged, Event::Subscriber(&TabControlDemo::handleTabPadding, this)); refreshPageList(); // From now on, we don't rely on the exceptions anymore, but perform nice (and recommended) checks // ourselves. return true; } // method to perform any required cleanup operations. void cleanupSample() { // me? cleanup? what? } void refreshPageList() { Window* root = System::getSingleton().getGUISheet(); // Check if the windows exists Listbox* lbox = NULL; TabControl* tc = NULL; if (root->isChild("Frame/TabControl/Page1/PageList")) { lbox = static_cast<Listbox*>(root->getChild( "Frame/TabControl/Page1/PageList")); } if (root->isChild("Frame/TabControl")) { tc = static_cast<TabControl*>(root->getChild( "Frame/TabControl")); } if (lbox && tc) { lbox->resetList(); for (size_t i = 0; i < tc->getTabCount(); i++) { lbox->addItem(new MyListItem( tc->getTabContentsAtIndex(i)->getName())); } } } bool handleTabPanePos(const EventArgs& e) { TabControl::TabPanePosition tpp; switch (static_cast<const WindowEventArgs&>(e).window->getID()) { case 0: tpp = TabControl::Top; break; case 1: tpp = TabControl::Bottom; break; default: return false; } // Check if the window exists Window* root = System::getSingleton().getGUISheet(); if (root->isChild("Frame/TabControl")) { static_cast<TabControl*>(root->getChild( "Frame/TabControl"))->setTabPanePosition(tpp); } return true; } bool handleTabHeight(const EventArgs& e) { Scrollbar* sb = static_cast<Scrollbar*>( static_cast<const WindowEventArgs&>(e).window); // Check if the window exists Window* root = System::getSingleton().getGUISheet(); if (root->isChild("Frame/TabControl")) { static_cast<TabControl*>(root->getChild( "Frame/TabControl"))->setTabHeight( UDim(0, sb->getScrollPosition())); } // The return value mainly sais that we handled it, not if something failed. return true; } bool handleTabPadding(const EventArgs& e) { Scrollbar* sb = static_cast<Scrollbar*>( static_cast<const WindowEventArgs&>(e).window); // Check if the window exists Window* root = System::getSingleton().getGUISheet(); if (root->isChild("Frame/TabControl")) { static_cast<TabControl*>(root->getChild( "Frame/TabControl"))->setTabTextPadding( UDim(0, sb->getScrollPosition())); } return true; } bool handleAddTab(const EventArgs&) { Window* root = System::getSingleton().getGUISheet(); // Check if the window exists if (root->isChild("Frame/TabControl")) { TabControl* tc = static_cast<TabControl*>(root->getChild( "Frame/TabControl")); // Add some tab buttons once for (int num = 3; num <= 16; num++) { std::stringstream pgname; pgname << "Page" << num; if (root->isChild("Frame/TabControl/" + pgname.str())) // Next continue; Window* pg = NULL; CEGUI_TRY { pg = WindowManager::getSingleton().loadLayoutFromFile("TabPage.layout"); pg->setName(String(pgname.str())); } CEGUI_CATCH(CEGUI::Exception&) { outputExceptionMessage("Some error occured while adding a tabpage. Please see the logfile."); break; } // This window has just been created while loading the layout if (pg->isChild("Text")) { Window* txt = pg->getChild("Text"); txt->setText(PageText [num - 3]); pg->setText(pgname.str()); tc->addTab(pg); refreshPageList(); break; } } } return true; } bool handleGoto(const EventArgs&) { Window* root = System::getSingleton().getGUISheet(); // Check if the windows exists Listbox* lbox = NULL; TabControl* tc = NULL; if (root->isChild("Frame/TabControl/Page1/PageList")) { lbox = static_cast<Listbox*>(root->getChild( "Frame/TabControl/Page1/PageList")); } if (root->isChild("Frame/TabControl")) { tc = static_cast<TabControl*>(root->getChild( "Frame/TabControl")); } if (lbox && tc) { ListboxItem* lbi = lbox->getFirstSelectedItem(); if (lbi) { tc->setSelectedTab(lbi->getText()); } } return true; } bool handleShow(const EventArgs&) { Window* root = System::getSingleton().getGUISheet(); // Check if the windows exists Listbox* lbox = NULL; TabControl* tc = NULL; if (root->isChild("Frame/TabControl/Page1/PageList")) { lbox = static_cast<Listbox*>(root->getChild( "Frame/TabControl/Page1/PageList")); } if (root->isChild("Frame/TabControl")) { tc = static_cast<TabControl*>(root->getChild( "Frame/TabControl")); } if (lbox && tc) { ListboxItem* lbi = lbox->getFirstSelectedItem(); if (lbi) { tc->makeTabVisible(lbi->getText()); } } return true; } bool handleDel(const EventArgs&) { Window* root = System::getSingleton().getGUISheet(); // Check if the windows exists Listbox* lbox = NULL; TabControl* tc = NULL; if (root->isChild("Frame/TabControl/Page1/PageList")) { lbox = static_cast<Listbox*>(root->getChild( "Frame/TabControl/Page1/PageList")); } if (root->isChild("Frame/TabControl")) { tc = static_cast<TabControl*>(root->getChild( "Frame/TabControl")); } if (lbox && tc) { ListboxItem* lbi = lbox->getFirstSelectedItem(); if (lbi) { Window* content = tc->getTabContents(lbi->getText()); tc->removeTab(lbi->getText()); // Remove the actual window from Cegui WindowManager::getSingleton().destroyWindow(content); refreshPageList(); } } return true; } }; int main(int /*argc*/, char* /*argv*/[]) { // This is a basic start-up for the sample application which is // object orientated in nature, so we just need an instance of // the CEGuiSample based object and then tell that sample application // to run. All of the samples will use code similar to this in the // main/WinMain function. TabControlDemo app; return app.run(); } <|endoftext|>
<commit_before> #include "axis.h" #include <stdlib.h> #include "legacy_commands.h" //TODO: goal of refactor is to kick this out completely extern "C" { #include "low_level.h" } // C interface extern "C" { void axis_thread_entry(void const* temp_motor_ptr) { Motor_t* motor = (Motor_t*)temp_motor_ptr; //TODO: explicit axis number assignment //for now we search for it uint8_t ax_number = 0; while (&motors[ax_number] != motor) ++ax_number; static const AxisConfig default_config; Axis axis(default_config, ax_number, motor); axis.StateMachineLoop(); } } // extern "C" void Axis::SetupLegacyMappings() { // Legacy reachability from C legacy_motor_ref_->axis_legacy.enable_control = &enable_control_; // override for compatibility with legacy comms paradigm // TODO next gen comms exposed_bools[4 * axis_number_ + 1] = &enable_control_; exposed_bools[4 * axis_number_ + 2] = &do_calibration_; } Axis::Axis(const AxisConfig& config, uint8_t axis_number, Motor_t* legacy_motor_ref) : axis_number_(axis_number), enable_control_(config.enable_control_at_start), do_calibration_(config.do_calibration_at_start), legacy_motor_ref_(legacy_motor_ref) { SetupLegacyMappings(); } void Axis::StateMachineLoop() { //TODO: Move this somewhere else // Allocate the map for anti-cogging algorithm and initialize all values to 0.0f int encoder_cpr = legacy_motor_ref_->encoder.encoder_cpr; legacy_motor_ref_->anticogging.cogging_map = (float*)malloc(encoder_cpr * sizeof(float)); if (legacy_motor_ref_->anticogging.cogging_map != NULL) { for (int i = 0; i < encoder_cpr; i++) { legacy_motor_ref_->anticogging.cogging_map[i] = 0.0f; } } legacy_motor_ref_->motor_thread = osThreadGetId(); legacy_motor_ref_->thread_ready = true; bool calibration_ok = false; for (;;) { if (do_calibration_) { do_calibration_ = false; __HAL_TIM_MOE_ENABLE(legacy_motor_ref_->motor_timer); // enable pwm outputs calibration_ok = motor_calibration(legacy_motor_ref_); __HAL_TIM_MOE_DISABLE_UNCONDITIONALLY(legacy_motor_ref_->motor_timer); // disables pwm outputs } if (calibration_ok && enable_control_) { legacy_motor_ref_->enable_step_dir = true; __HAL_TIM_MOE_ENABLE(legacy_motor_ref_->motor_timer); bool spin_up_ok = true; if (legacy_motor_ref_->rotor_mode == ROTOR_MODE_SENSORLESS) spin_up_ok = spin_up_sensorless(legacy_motor_ref_); if (spin_up_ok) control_motor_loop(legacy_motor_ref_); __HAL_TIM_MOE_DISABLE_UNCONDITIONALLY(legacy_motor_ref_->motor_timer); legacy_motor_ref_->enable_step_dir = false; if (enable_control_) { // if control is still enabled, we exited because of error calibration_ok = false; enable_control_ = false; } } // give some time to lower priority threads osDelay(2); } legacy_motor_ref_->thread_ready = false; }<commit_msg>Keep rotor estimation up to date while idling<commit_after> #include "axis.h" #include <stdlib.h> #include "legacy_commands.h" //TODO: goal of refactor is to kick this out completely extern "C" { #include "low_level.h" } // C interface extern "C" { void axis_thread_entry(void const* temp_motor_ptr) { Motor_t* motor = (Motor_t*)temp_motor_ptr; //TODO: explicit axis number assignment //for now we search for it uint8_t ax_number = 0; while (&motors[ax_number] != motor) ++ax_number; static const AxisConfig default_config; Axis axis(default_config, ax_number, motor); axis.StateMachineLoop(); } } // extern "C" void Axis::SetupLegacyMappings() { // Legacy reachability from C legacy_motor_ref_->axis_legacy.enable_control = &enable_control_; // override for compatibility with legacy comms paradigm // TODO next gen comms exposed_bools[4 * axis_number_ + 1] = &enable_control_; exposed_bools[4 * axis_number_ + 2] = &do_calibration_; } Axis::Axis(const AxisConfig& config, uint8_t axis_number, Motor_t* legacy_motor_ref) : axis_number_(axis_number), enable_control_(config.enable_control_at_start), do_calibration_(config.do_calibration_at_start), legacy_motor_ref_(legacy_motor_ref) { SetupLegacyMappings(); } void Axis::StateMachineLoop() { //TODO: Move this somewhere else // Allocate the map for anti-cogging algorithm and initialize all values to 0.0f int encoder_cpr = legacy_motor_ref_->encoder.encoder_cpr; legacy_motor_ref_->anticogging.cogging_map = (float*)malloc(encoder_cpr * sizeof(float)); if (legacy_motor_ref_->anticogging.cogging_map != NULL) { for (int i = 0; i < encoder_cpr; i++) { legacy_motor_ref_->anticogging.cogging_map[i] = 0.0f; } } legacy_motor_ref_->motor_thread = osThreadGetId(); legacy_motor_ref_->thread_ready = true; bool calibration_ok = false; for (;;) { // Keep rotor estimation up to date while idling osSignalWait(M_SIGNAL_PH_CURRENT_MEAS, osWaitForever); update_rotor(legacy_motor_ref_); if (do_calibration_) { do_calibration_ = false; __HAL_TIM_MOE_ENABLE(legacy_motor_ref_->motor_timer); // enable pwm outputs calibration_ok = motor_calibration(legacy_motor_ref_); __HAL_TIM_MOE_DISABLE_UNCONDITIONALLY(legacy_motor_ref_->motor_timer); // disables pwm outputs } if (calibration_ok && enable_control_) { legacy_motor_ref_->enable_step_dir = true; __HAL_TIM_MOE_ENABLE(legacy_motor_ref_->motor_timer); bool spin_up_ok = true; if (legacy_motor_ref_->rotor_mode == ROTOR_MODE_SENSORLESS) spin_up_ok = spin_up_sensorless(legacy_motor_ref_); if (spin_up_ok) control_motor_loop(legacy_motor_ref_); __HAL_TIM_MOE_DISABLE_UNCONDITIONALLY(legacy_motor_ref_->motor_timer); legacy_motor_ref_->enable_step_dir = false; if (enable_control_) { // if control is still enabled, we exited because of error calibration_ok = false; enable_control_ = false; } } } legacy_motor_ref_->thread_ready = false; }<|endoftext|>
<commit_before>// GridMatch.cpp : Defines the entry point for the console application. //#define USE_GPU #include "Header.h" #include "GMS.h" #include "VideoMatch.h" #include "ORBextractor.h" void GridMatch(Mat &img1, Mat &img2); void runImagePair(){ Mat img1 = imread("./data/nn_left.jpg"); Mat img2 = imread("./data/nn_right.jpg"); imresize(img1, 480); imresize(img2, 480); GridMatch(img1, img2); } void runVideo(){ string filename = "./data/chair.mp4"; testVideo(filename); } int _tmain(int argc, _TCHAR* argv[]) { #ifdef USE_GPU int flag = cuda::getCudaEnabledDeviceCount(); if (flag != 0){ cuda::setDevice(0); } #endif // USE_GPU runImagePair(); // runVideo(); return 0; } void GridMatch(Mat &img1, Mat &img2){ vector<KeyPoint> kp1, kp2; Mat d1, d2; vector<DMatch> matches_all, matches_grid; Ptr<ORB> orb = ORB::create(100000); orb->setFastThreshold(0); orb->detectAndCompute(img1, Mat(), kp1, d1); orb->detectAndCompute(img2, Mat(), kp2, d2); //ORB_SLAM2::ORBextractor *pOrb = new ORB_SLAM2::ORBextractor(100000, 1.2, 8, 20, 0); //(*pOrb)(img1, Mat(), kp1, d1); //(*pOrb)(img2, Mat(), kp2, d2); #ifdef USE_GPU GpuMat gd1(d1), gd2(d2); Ptr<cuda::DescriptorMatcher> matcher = cv::cuda::DescriptorMatcher::createBFMatcher(NORM_HAMMING); matcher->match(gd1, gd2, matches_all); #else BFMatcher matcher(NORM_HAMMING); matcher.match(d1, d2, matches_all); #endif // GMS filter GMS gms; gms.init(img1.size(), img2.size(), kp1, kp2, matches_all); gms.setParameter(20, 20); matches_grid = gms.getInlier(0); cout << "Get total " << matches_grid.size() << " matches." << endl; Mat show = DrawInlier(img1, img2, kp1, kp2, matches_grid, 1); imshow("show", show); waitKey(); } <commit_msg>Update demo.cpp<commit_after>// GridMatch.cpp : Defines the entry point for the console application. //#define USE_GPU #include "Header.h" #include "GMS.h" #include "VideoMatch.h" #include "ORBextractor.h" void GridMatch(Mat &img1, Mat &img2); void runImagePair(){ Mat img1 = imread("./data/nn_left.jpg"); Mat img2 = imread("./data/nn_right.jpg"); imresize(img1, 480); imresize(img2, 480); GridMatch(img1, img2); } void runVideo(){ string filename = "./data/chair.mp4"; testVideo(filename); } int _tmain(int argc, _TCHAR* argv[]) { #ifdef USE_GPU int flag = cuda::getCudaEnabledDeviceCount(); if (flag != 0){ cuda::setDevice(0); } #endif // USE_GPU runImagePair(); // runVideo(); return 0; } void GridMatch(Mat &img1, Mat &img2){ vector<KeyPoint> kp1, kp2; Mat d1, d2; vector<DMatch> matches_all, matches_grid; Ptr<ORB> orb = ORB::create(10000); orb->setFastThreshold(0); orb->detectAndCompute(img1, Mat(), kp1, d1); orb->detectAndCompute(img2, Mat(), kp2, d2); //ORB_SLAM2::ORBextractor *pOrb = new ORB_SLAM2::ORBextractor(100000, 1.2, 8, 20, 0); //(*pOrb)(img1, Mat(), kp1, d1); //(*pOrb)(img2, Mat(), kp2, d2); #ifdef USE_GPU GpuMat gd1(d1), gd2(d2); Ptr<cuda::DescriptorMatcher> matcher = cv::cuda::DescriptorMatcher::createBFMatcher(NORM_HAMMING); matcher->match(gd1, gd2, matches_all); #else BFMatcher matcher(NORM_HAMMING); matcher.match(d1, d2, matches_all); #endif // GMS filter GMS gms; gms.init(img1.size(), img2.size(), kp1, kp2, matches_all); gms.setParameter(20, 20); matches_grid = gms.getInlier(0); cout << "Get total " << matches_grid.size() << " matches." << endl; Mat show = DrawInlier(img1, img2, kp1, kp2, matches_grid, 1); imshow("show", show); waitKey(); } <|endoftext|>
<commit_before>/// HEADER #include <csapex.h> /// PROJECT #include <csapex/core/csapex_core.h> #include <csapex/core/settings/settings_local.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex/param/parameter_factory.h> #include <csapex/utility/error_handling.h> #include <csapex/utility/exceptions.h> #include <csapex/utility/thread.h> #include <csapex/view/csapex_view_core_local.h> #include <csapex/view/csapex_view_core_remote.h> #include <csapex/view/csapex_window.h> #include <csapex/view/gui_exception_handler.h> #include <csapex/io/server.h> #include <csapex/model/graph_facade.h> /// SYSTEM #include <iostream> #include <QtGui> #include <QStatusBar> #include <QMessageBox> #include <boost/program_options.hpp> #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> #undef BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/version.hpp> #if (BOOST_VERSION / 100000) >= 1 && (BOOST_VERSION / 100 % 1000) >= 54 namespace bf3 = boost::filesystem; #else namespace bf3 = boost::filesystem3; #endif namespace po = boost::program_options; using namespace csapex; CsApexGuiApp::CsApexGuiApp(int& argc, char** argv, ExceptionHandler &handler) : QApplication(argc, argv), handler(handler) {} CsApexCoreApp::CsApexCoreApp(int& argc, char** argv, ExceptionHandler &handler) : QCoreApplication(argc, argv), handler(handler) {} bool CsApexCoreApp::notify(QObject* receiver, QEvent* event) { try { return QCoreApplication::notify(receiver, event); } catch(...) { std::exception_ptr eptr = std::current_exception(); handler.handleException(eptr); return true; } } bool CsApexGuiApp::notify(QObject* receiver, QEvent* event) { try { return QApplication::notify(receiver, event); } catch(...) { std::exception_ptr eptr = std::current_exception(); handler.handleException(eptr); return true; } } Main::Main(std::unique_ptr<QCoreApplication> &&a, Settings& settings, ExceptionHandler& handler) : app(std::move(a)), settings(settings), handler(handler), splash(nullptr), recover_needed(false) { csapex::thread::set_name("cs::APEX main"); } Main::~Main() { delete splash; } int Main::runImpl() { csapex::error_handling::init(); int result = app->exec(); return result; } int Main::runWithGui() { app->processEvents(); // CsApexViewCoreLocal view_core(core); CsApexViewCoreRemote view_core("localhost", 12345, core); CsApexWindow w(view_core); QObject::connect(&w, SIGNAL(statusChanged(QString)), this, SLOT(showMessage(QString))); app->connect(&w, &CsApexWindow::closed, app.get(), &QCoreApplication::quit); app->connect(app.get(), SIGNAL(lastWindowClosed()), app.get(), SLOT(quit())); csapex::error_handling::stop_request().connect([this](){ static int request = 0; if(request == 0) { core->shutdown(); std::cout << "shutdown request" << std::endl; } else if(request >= 3) { raise(SIGTERM); } ++request; }); core->shutdown_requested.connect([this](){ QCoreApplication::postEvent(app.get(), new QCloseEvent); }); checkRecoveryFile(view_core, w); w.start(); core->startup(); w.show(); splash->finish(&w); int res = runImpl(); deleteRecoveryConfig(); return res; } int Main::runHeadless() { GraphFacadePtr root = core->getRoot(); csapex::error_handling::stop_request().connect([this, root](){ core->shutdown(); app->quit(); }); core->startup(); return runImpl(); } int Main::run() { bool headless = settings.get<bool>("headless"); std::string config_to_load = settings.get<std::string>("config"); if(!headless) { splash = new CsApexSplashScreen; splash->show(); settings.set("config_recovery", false); askForRecoveryConfig(config_to_load); showMessage("loading libraries"); } core = std::make_shared<CsApexCore>(settings, handler); try { server = std::make_shared<Server>(core); server->start(); } catch (const boost::system::system_error& ex) { std::cerr << "Could not start command server: [" << ex.code() << "] " << ex.what() << std::endl; } if(headless) { return runHeadless(); } else { return runWithGui(); } } void Main::checkRecoveryFile(CsApexViewCore &view_core, CsApexWindow &w) { QTimer *timer = new QTimer(this); QObject::connect(timer, &QTimer::timeout, [&](){ if(recover_needed) { recover_needed = false; std::string temp_file_name = settings.get("config")->as<std::string>() + ".recover"; core->saveAs(temp_file_name, true); w.statusBar()->showMessage(tr("Recovery file saved.")); } }); timer->start(settings.getPersistent("config_recovery_save_interval", 1000)); observe(view_core.undo_state_changed, [&](){ recover_needed = true; }); } void Main::askForRecoveryConfig(const std::string& config_to_load) { bf3::path temp_file = config_to_load + ".recover"; if(bf3::exists(temp_file)) { showMessage("handling recovery file"); std::time_t mod_time_t = bf3::last_write_time(temp_file); char mod_time[20]; strftime(mod_time, 20, "%Y-%m-%d %H:%M:%S", localtime(&mod_time_t)); std::string question = "The application did not exit correctly. " "Do you want to recover<br /><b>" + temp_file.filename().string() + "</b>?<br />(last modified: " + mod_time + ")"; QMessageBox::StandardButton reply = QMessageBox::question(splash, "Configuration Recovery", QString::fromStdString(question), QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { settings.set("config_recovery", true); settings.set("config_recovery_file", temp_file.string()); settings.set("config_recovery_original", config_to_load); } } } void Main::deleteRecoveryConfig() { bool recovery = settings.getTemporary("config_recovery", false); if(!recovery) { bf3::path temp_file = settings.get("config")->as<std::string>() + ".recover"; if(bf3::exists(temp_file)) { bf3::remove(temp_file); } } } void Main::showMessage(const QString& msg) { if(splash->isVisible()) { splash->showMessage(msg); } app->processEvents(); } int main(int argc, char** argv) { SettingsLocal settings; int effective_argc = argc; std::string path_to_bin(argv[0]); po::options_description desc("Allowed options"); desc.add_options() ("help", "show help message") ("debug", "enable debug output") ("dump", "show variables") ("paused", "start paused") ("headless", "run without gui") ("threadless", "run without threading") ("fatal_exceptions", "abort execution on exception") ("disable_thread_grouping", "by default create one thread per node") ("input", "config file to load") ; po::positional_options_description p; p.add("input", 1); // first check for --headless or --fatal_exceptions parameter // this has to be done before the qapp can be created, which // has to be done before parameters can be read. bool headless = false; bool fatal_exceptions = false; for(int i = 1; i < effective_argc; ++i) { std::string arg(argv[i]); if(arg == "--headless") { headless = true; } else if(arg == "--fatal_exceptions") { fatal_exceptions = true; } } if(!headless) { // if headless not requested, check if there is a display // if not, we enforce headless mode #if WIN32 if (false) { #else if (!getenv("DISPLAY")) { #endif headless = true; std::cout << "warning: enforcing headless mode because there is no display detected" << std::endl; } } std::shared_ptr<ExceptionHandler> handler; // filters all qt parameters from argv std::unique_ptr<QCoreApplication> app; if(headless) { handler.reset(new ExceptionHandler(fatal_exceptions)); app.reset(new CsApexCoreApp(effective_argc, argv, *handler)); } else { std::shared_ptr<GuiExceptionHandler> h(new GuiExceptionHandler(fatal_exceptions)); handler = h; app.reset(new CsApexGuiApp(effective_argc, argv, *handler)); h->moveToThread(app->thread()); } // filters ros remappings std::vector<std::string> remapping_args; std::vector<std::string> rest_args; for(int i = 1; i < effective_argc; ++i) { std::string arg(argv[i]); if(arg.find(":=") != std::string::npos) { remapping_args.push_back(arg); } else { rest_args.push_back(arg); } } // now check for remaining parameters po::variables_map vm; std::vector<std::string> additional_args; try { po::parsed_options parsed = po::command_line_parser(rest_args).options(desc).positional(p).run(); po::store(parsed, vm); po::notify(vm); additional_args = po::collect_unrecognized(parsed.options, po::include_positional); } catch(const std::exception& e) { std::cerr << "cannot parse parameters: " << e.what() << std::endl; return 4; } // add ros remappings additional_args.insert(additional_args.end(), remapping_args.begin(), remapping_args.end()); // display help? if(vm.count("help")) { std::cerr << desc << std::endl; return 1; } if(vm.count("dump")) { std::cout << "to be passed on:\n"; for(std::size_t i = 0; i < additional_args.size(); ++i) { std::cout << additional_args[i] << '\n'; } std::cout << std::flush; return 0; } // which file to use? if (vm.count("input")) { settings.set("config",vm["input"].as<std::string>()); } else { settings.set("config",Settings::default_config); } if(!settings.knows("path_to_bin")) { settings.addTemporary(csapex::param::ParameterFactory::declareFileInputPath("path_to_bin", path_to_bin)); } else { settings.set("path_to_bin", path_to_bin); } settings.set("debug", vm.count("debug") > 0); settings.set("headless", headless); settings.set("threadless", vm.count("threadless") > 0); settings.set("thread_grouping", vm.count("disable_thread_grouping") == 0); settings.set("additional_args", additional_args); settings.set("initially_paused", vm.count("paused") > 0); settings.set("access-test", std::string("access granted.")); // start the app Main m(std::move(app), settings, *handler); try { return m.run(); } catch(const csapex::Failure& af) { std::cerr << af.what() << std::endl; return 42; } } /// MOC #include "moc_csapex.cpp" <commit_msg>switched remote to local view<commit_after>/// HEADER #include <csapex.h> /// PROJECT #include <csapex/core/csapex_core.h> #include <csapex/core/settings/settings_local.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex/param/parameter_factory.h> #include <csapex/utility/error_handling.h> #include <csapex/utility/exceptions.h> #include <csapex/utility/thread.h> #include <csapex/view/csapex_view_core_local.h> #include <csapex/view/csapex_view_core_remote.h> #include <csapex/view/csapex_window.h> #include <csapex/view/gui_exception_handler.h> #include <csapex/io/server.h> #include <csapex/model/graph_facade.h> /// SYSTEM #include <iostream> #include <QtGui> #include <QStatusBar> #include <QMessageBox> #include <boost/program_options.hpp> #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> #undef BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/version.hpp> #if (BOOST_VERSION / 100000) >= 1 && (BOOST_VERSION / 100 % 1000) >= 54 namespace bf3 = boost::filesystem; #else namespace bf3 = boost::filesystem3; #endif namespace po = boost::program_options; using namespace csapex; CsApexGuiApp::CsApexGuiApp(int& argc, char** argv, ExceptionHandler &handler) : QApplication(argc, argv), handler(handler) {} CsApexCoreApp::CsApexCoreApp(int& argc, char** argv, ExceptionHandler &handler) : QCoreApplication(argc, argv), handler(handler) {} bool CsApexCoreApp::notify(QObject* receiver, QEvent* event) { try { return QCoreApplication::notify(receiver, event); } catch(...) { std::exception_ptr eptr = std::current_exception(); handler.handleException(eptr); return true; } } bool CsApexGuiApp::notify(QObject* receiver, QEvent* event) { try { return QApplication::notify(receiver, event); } catch(...) { std::exception_ptr eptr = std::current_exception(); handler.handleException(eptr); return true; } } Main::Main(std::unique_ptr<QCoreApplication> &&a, Settings& settings, ExceptionHandler& handler) : app(std::move(a)), settings(settings), handler(handler), splash(nullptr), recover_needed(false) { csapex::thread::set_name("cs::APEX main"); } Main::~Main() { delete splash; } int Main::runImpl() { csapex::error_handling::init(); int result = app->exec(); return result; } int Main::runWithGui() { app->processEvents(); CsApexViewCoreLocal view_core(core); // CsApexViewCoreRemote view_core("localhost", 12345, core); CsApexWindow w(view_core); QObject::connect(&w, SIGNAL(statusChanged(QString)), this, SLOT(showMessage(QString))); app->connect(&w, &CsApexWindow::closed, app.get(), &QCoreApplication::quit); app->connect(app.get(), SIGNAL(lastWindowClosed()), app.get(), SLOT(quit())); csapex::error_handling::stop_request().connect([this](){ static int request = 0; if(request == 0) { core->shutdown(); std::cout << "shutdown request" << std::endl; } else if(request >= 3) { raise(SIGTERM); } ++request; }); core->shutdown_requested.connect([this](){ QCoreApplication::postEvent(app.get(), new QCloseEvent); }); checkRecoveryFile(view_core, w); w.start(); core->startup(); w.show(); splash->finish(&w); int res = runImpl(); deleteRecoveryConfig(); return res; } int Main::runHeadless() { GraphFacadePtr root = core->getRoot(); csapex::error_handling::stop_request().connect([this, root](){ core->shutdown(); app->quit(); }); core->startup(); return runImpl(); } int Main::run() { bool headless = settings.get<bool>("headless"); std::string config_to_load = settings.get<std::string>("config"); if(!headless) { splash = new CsApexSplashScreen; splash->show(); settings.set("config_recovery", false); askForRecoveryConfig(config_to_load); showMessage("loading libraries"); } core = std::make_shared<CsApexCore>(settings, handler); try { server = std::make_shared<Server>(core); server->start(); } catch (const boost::system::system_error& ex) { std::cerr << "Could not start command server: [" << ex.code() << "] " << ex.what() << std::endl; } if(headless) { return runHeadless(); } else { return runWithGui(); } } void Main::checkRecoveryFile(CsApexViewCore &view_core, CsApexWindow &w) { QTimer *timer = new QTimer(this); QObject::connect(timer, &QTimer::timeout, [&](){ if(recover_needed) { recover_needed = false; std::string temp_file_name = settings.get("config")->as<std::string>() + ".recover"; core->saveAs(temp_file_name, true); w.statusBar()->showMessage(tr("Recovery file saved.")); } }); timer->start(settings.getPersistent("config_recovery_save_interval", 1000)); observe(view_core.undo_state_changed, [&](){ recover_needed = true; }); } void Main::askForRecoveryConfig(const std::string& config_to_load) { bf3::path temp_file = config_to_load + ".recover"; if(bf3::exists(temp_file)) { showMessage("handling recovery file"); std::time_t mod_time_t = bf3::last_write_time(temp_file); char mod_time[20]; strftime(mod_time, 20, "%Y-%m-%d %H:%M:%S", localtime(&mod_time_t)); std::string question = "The application did not exit correctly. " "Do you want to recover<br /><b>" + temp_file.filename().string() + "</b>?<br />(last modified: " + mod_time + ")"; QMessageBox::StandardButton reply = QMessageBox::question(splash, "Configuration Recovery", QString::fromStdString(question), QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { settings.set("config_recovery", true); settings.set("config_recovery_file", temp_file.string()); settings.set("config_recovery_original", config_to_load); } } } void Main::deleteRecoveryConfig() { bool recovery = settings.getTemporary("config_recovery", false); if(!recovery) { bf3::path temp_file = settings.get("config")->as<std::string>() + ".recover"; if(bf3::exists(temp_file)) { bf3::remove(temp_file); } } } void Main::showMessage(const QString& msg) { if(splash->isVisible()) { splash->showMessage(msg); } app->processEvents(); } int main(int argc, char** argv) { SettingsLocal settings; int effective_argc = argc; std::string path_to_bin(argv[0]); po::options_description desc("Allowed options"); desc.add_options() ("help", "show help message") ("debug", "enable debug output") ("dump", "show variables") ("paused", "start paused") ("headless", "run without gui") ("threadless", "run without threading") ("fatal_exceptions", "abort execution on exception") ("disable_thread_grouping", "by default create one thread per node") ("input", "config file to load") ; po::positional_options_description p; p.add("input", 1); // first check for --headless or --fatal_exceptions parameter // this has to be done before the qapp can be created, which // has to be done before parameters can be read. bool headless = false; bool fatal_exceptions = false; for(int i = 1; i < effective_argc; ++i) { std::string arg(argv[i]); if(arg == "--headless") { headless = true; } else if(arg == "--fatal_exceptions") { fatal_exceptions = true; } } if(!headless) { // if headless not requested, check if there is a display // if not, we enforce headless mode #if WIN32 if (false) { #else if (!getenv("DISPLAY")) { #endif headless = true; std::cout << "warning: enforcing headless mode because there is no display detected" << std::endl; } } std::shared_ptr<ExceptionHandler> handler; // filters all qt parameters from argv std::unique_ptr<QCoreApplication> app; if(headless) { handler.reset(new ExceptionHandler(fatal_exceptions)); app.reset(new CsApexCoreApp(effective_argc, argv, *handler)); } else { std::shared_ptr<GuiExceptionHandler> h(new GuiExceptionHandler(fatal_exceptions)); handler = h; app.reset(new CsApexGuiApp(effective_argc, argv, *handler)); h->moveToThread(app->thread()); } // filters ros remappings std::vector<std::string> remapping_args; std::vector<std::string> rest_args; for(int i = 1; i < effective_argc; ++i) { std::string arg(argv[i]); if(arg.find(":=") != std::string::npos) { remapping_args.push_back(arg); } else { rest_args.push_back(arg); } } // now check for remaining parameters po::variables_map vm; std::vector<std::string> additional_args; try { po::parsed_options parsed = po::command_line_parser(rest_args).options(desc).positional(p).run(); po::store(parsed, vm); po::notify(vm); additional_args = po::collect_unrecognized(parsed.options, po::include_positional); } catch(const std::exception& e) { std::cerr << "cannot parse parameters: " << e.what() << std::endl; return 4; } // add ros remappings additional_args.insert(additional_args.end(), remapping_args.begin(), remapping_args.end()); // display help? if(vm.count("help")) { std::cerr << desc << std::endl; return 1; } if(vm.count("dump")) { std::cout << "to be passed on:\n"; for(std::size_t i = 0; i < additional_args.size(); ++i) { std::cout << additional_args[i] << '\n'; } std::cout << std::flush; return 0; } // which file to use? if (vm.count("input")) { settings.set("config",vm["input"].as<std::string>()); } else { settings.set("config",Settings::default_config); } if(!settings.knows("path_to_bin")) { settings.addTemporary(csapex::param::ParameterFactory::declareFileInputPath("path_to_bin", path_to_bin)); } else { settings.set("path_to_bin", path_to_bin); } settings.set("debug", vm.count("debug") > 0); settings.set("headless", headless); settings.set("threadless", vm.count("threadless") > 0); settings.set("thread_grouping", vm.count("disable_thread_grouping") == 0); settings.set("additional_args", additional_args); settings.set("initially_paused", vm.count("paused") > 0); settings.set("access-test", std::string("access granted.")); // start the app Main m(std::move(app), settings, *handler); try { return m.run(); } catch(const csapex::Failure& af) { std::cerr << af.what() << std::endl; return 42; } } /// MOC #include "moc_csapex.cpp" <|endoftext|>
<commit_before>#include <string> #include <functional> #include <fstream> #include <set> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/optional.hpp> #include <boost/filesystem.hpp> #include <json/json.h> #include <json_help.hpp> #include "raftrpc.hpp" #include "raftstate.hpp" #include "raftrequest.hpp" #include "raftclient.hpp" raft::Client::Handlers::Handlers(const send_request_type& send_request, const append_to_log_type& append_to_log, const leader_type& leader) :send_request_(send_request), append_to_log_(append_to_log), leader_(leader) { } void raft::Client::Handlers::send_request(const std::string& to, const Json::Value& request) const { send_request_(to, request); } void raft::Client::Handlers::append_to_log(const Json::Value& request) const { append_to_log_(request); } boost::optional<std::string> raft::Client::Handlers::leader() const { return leader_(); } raft::Client::Client(const std::string& id, raft::Client::Handlers& handlers) :id_(id), handlers_(handlers) { } void raft::Client::commit_handler(const Json::Value& root) { const std::string type = json_help::checked_from_json<std::string>(root, "type", "Bad commit RPC:"); if(type == "update") { raft::request::Update entry(root); BOOST_LOG_TRIVIAL(info) << "Committing update on key: " << entry.key() << " version: " << entry.old_version() << " -> " << entry.new_version(); commit_if_valid(entry); } else if(type == "delete") { raft::request::Delete entry(root); BOOST_LOG_TRIVIAL(info) << "Committing delete on key: " << entry.key() << " version: " << entry.version(); commit_if_valid(entry); } else if(type == "rename") { raft::request::Rename entry(root); BOOST_LOG_TRIVIAL(info) << "Committing rename on key: " << entry.key() << " -> " << entry.new_key() << " version: " << entry.version(); commit_if_valid(entry); } else if(type == "add") { raft::request::Add entry(root); BOOST_LOG_TRIVIAL(info) << "Committing add on key: " << entry.key() << " version: " << entry.version(); commit_if_valid(entry); } else throw std::runtime_error("Bad commit RPC: unknown type " + type); } bool raft::Client::exists(const std::string& key) const noexcept { exists_map(key, version_map_); } std::tuple<std::string, std::string> raft::Client::operator [](const std::string& key) noexcept(false) { return *version_map_.at(key); } void raft::Client::commit_notify(const request::Update& rpc) { commit_update_(rpc); } void raft::Client::commit_notify(const request::Rename& rpc) { commit_rename_(rpc); } void raft::Client::commit_notify(const request::Delete& rpc) { commit_delete_(rpc); } void raft::Client::commit_notify(const request::Add& rpc) { commit_add_(rpc); } raft::Client::version_map_type& raft::Client::fetch_map(apply_target target) { if(target == apply_main) return version_map_; else return pending_version_map_; } bool raft::Client::exists_map(const std::string& key, const version_map_type& map) noexcept { return map.count(key) == 1 && map.at(key); } void raft::Client::apply_to(const raft::request::Update& update, apply_target target) { fetch_map(target)[update.key()] = std::make_tuple(update.new_version(), update.from()); } void raft::Client::apply_to(const raft::request::Delete& update, apply_target target) { fetch_map(target).erase(update.key()); } void raft::Client::apply_to(const raft::request::Rename& update, apply_target target) { //fetch the if(target == apply_pending) { //if the from isn't in pending, it needs to be in main std::string version; if(exists_map(update.key(), pending_version_map_)) { version = std::get<0>(*pending_version_map_.at(update.key())); //erase it pending_version_map_.erase(update.key()); } else //let it be bounds checked version = std::get<0>(*version_map_.at(update.key())); //Add the rename pending_version_map_[update.new_key()] = std::make_tuple(version, update.from()); } else { //only read the main version_map_[update.new_key()] = std::make_tuple(std::get<0>(*version_map_[update.key()]), update.from()); version_map_.erase(update.key()); } } void raft::Client::apply_to(const raft::request::Add& update, apply_target target) { fetch_map(target)[update.key()] = std::make_tuple(update.version(), update.from()); } raft::Client::validity raft::Client::request_traits<raft::request::Update>::valid( const rpc_type& rpc, const version_map_type& version_map, const version_map_type& pending_map) { if(!exists_map(rpc.key(), pending_map)) return valid_impl(rpc, version_map); else return valid_impl(rpc, pending_map); } raft::Client::validity raft::Client::request_traits<raft::request::Update>::valid( const rpc_type& rpc, const version_map_type& version_map) { return valid_impl(rpc, version_map); } raft::Client::validity raft::Client::request_traits<raft::request::Update> ::valid_impl(const rpc_type& rpc, const version_map_type& version_map) { if(exists_map(rpc.key(), version_map)) { if(std::get<0>(*version_map.at(rpc.key())) == rpc.new_version()) return request_done; else return std::get<0>(*version_map.at(rpc.key())) == rpc.old_version() ? request_valid : request_invalid; } else return request_invalid; } raft::Client::validity raft::Client::request_traits<raft::request::Delete>::valid( const rpc_type& rpc, const version_map_type& version_map, const version_map_type& pending_map) { if(!exists_map(rpc.key(), pending_map)) return valid_impl(rpc, version_map); else return valid_impl(rpc, pending_map); } raft::Client::validity raft::Client::request_traits<raft::request::Delete>::valid( const rpc_type& rpc, const version_map_type& version_map) { return valid_impl(rpc, version_map); } raft::Client::validity raft::Client::request_traits<raft::request::Delete> ::valid_impl(const rpc_type& rpc, const version_map_type& version_map) { if(exists_map(rpc.key(), version_map)) return std::get<0>(*version_map.at(rpc.key())) == rpc.version() ? request_valid : request_invalid; else return request_done; } raft::Client::validity raft::Client::request_traits<raft::request::Rename>::valid( const rpc_type& rpc, const version_map_type& version_map, const version_map_type& pending_map) { auto from_version = most_recent(rpc.key(), version_map, pending_map); auto to_version = most_recent(rpc.new_key(), version_map, pending_map); if(!from_version && to_version && *to_version == rpc.version()) return request_done; if(from_version && !to_version && *from_version == rpc.version()) return request_valid; return request_invalid; } raft::Client::validity raft::Client::request_traits<raft::request::Rename>::valid( const rpc_type& rpc, const version_map_type& version_map) { if(exists_map(rpc.key(), version_map) && std::get<0>(*version_map.at(rpc.key())) == rpc.version()) return request_valid; else if(exists_map(rpc.new_key(), version_map) && std::get<0>(*version_map.at(rpc.new_key())) == rpc.version()) return request_done; else return request_invalid; } boost::optional<std::string> raft::Client ::request_traits<raft::request::Rename>::most_recent( const std::string& key, const version_map_type& version_map, const version_map_type& pending_map) { if(exists_map(key, pending_map)) return std::get<0>(*pending_map.at(key)); else { if(exists_map(key, version_map)) return std::get<0>(*version_map.at(key)); else return boost::none; } } raft::Client::validity raft::Client::request_traits<raft::request::Add>::valid( const rpc_type& rpc, const version_map_type& version_map, const version_map_type& pending_map) { if(!exists_map(rpc.key(), pending_map)) { if(exists_map(rpc.key(), version_map)) { return std::get<0>(*version_map.at(rpc.key())) == rpc.version() ? request_done : request_invalid; } else return request_valid; } else { return std::get<0>(*pending_map.at(rpc.key())) == rpc.version() ? request_done : request_invalid; } } raft::Client::validity raft::Client::request_traits<raft::request::Add>::valid( const rpc_type& rpc, const version_map_type& version_map) { if(!exists_map(rpc.key(), version_map)) return request_valid; else if(std::get<0>(*version_map.at(rpc.key())) == rpc.version()) return request_done; else return request_invalid; } <commit_msg>Delete tombstones now added and checked for.<commit_after>#include <string> #include <functional> #include <fstream> #include <set> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/optional.hpp> #include <boost/filesystem.hpp> #include <json/json.h> #include <json_help.hpp> #include "raftrpc.hpp" #include "raftstate.hpp" #include "raftrequest.hpp" #include "raftclient.hpp" raft::Client::Handlers::Handlers(const send_request_type& send_request, const append_to_log_type& append_to_log, const leader_type& leader) :send_request_(send_request), append_to_log_(append_to_log), leader_(leader) { } void raft::Client::Handlers::send_request(const std::string& to, const Json::Value& request) const { send_request_(to, request); } void raft::Client::Handlers::append_to_log(const Json::Value& request) const { append_to_log_(request); } boost::optional<std::string> raft::Client::Handlers::leader() const { return leader_(); } raft::Client::Client(const std::string& id, raft::Client::Handlers& handlers) :id_(id), handlers_(handlers) { } void raft::Client::commit_handler(const Json::Value& root) { const std::string type = json_help::checked_from_json<std::string>(root, "type", "Bad commit RPC:"); if(type == "update") { raft::request::Update entry(root); BOOST_LOG_TRIVIAL(info) << "Committing update on key: " << entry.key() << " version: " << entry.old_version() << " -> " << entry.new_version(); commit_if_valid(entry); } else if(type == "delete") { raft::request::Delete entry(root); BOOST_LOG_TRIVIAL(info) << "Committing delete on key: " << entry.key() << " version: " << entry.version(); commit_if_valid(entry); } else if(type == "rename") { raft::request::Rename entry(root); BOOST_LOG_TRIVIAL(info) << "Committing rename on key: " << entry.key() << " -> " << entry.new_key() << " version: " << entry.version(); commit_if_valid(entry); } else if(type == "add") { raft::request::Add entry(root); BOOST_LOG_TRIVIAL(info) << "Committing add on key: " << entry.key() << " version: " << entry.version(); commit_if_valid(entry); } else throw std::runtime_error("Bad commit RPC: unknown type " + type); } bool raft::Client::exists(const std::string& key) const noexcept { exists_map(key, version_map_); } std::tuple<std::string, std::string> raft::Client::operator [](const std::string& key) noexcept(false) { return *version_map_.at(key); } void raft::Client::commit_notify(const request::Update& rpc) { commit_update_(rpc); } void raft::Client::commit_notify(const request::Rename& rpc) { commit_rename_(rpc); } void raft::Client::commit_notify(const request::Delete& rpc) { commit_delete_(rpc); } void raft::Client::commit_notify(const request::Add& rpc) { commit_add_(rpc); } raft::Client::version_map_type& raft::Client::fetch_map(apply_target target) { if(target == apply_main) return version_map_; else return pending_version_map_; } bool raft::Client::exists_map(const std::string& key, const version_map_type& map) noexcept { return map.count(key) == 1 && map.at(key); } void raft::Client::apply_to(const raft::request::Update& update, apply_target target) { fetch_map(target)[update.key()] = std::make_tuple(update.new_version(), update.from()); } void raft::Client::apply_to(const raft::request::Delete& update, apply_target target) { if(apply_pending == target) pending_version_map_[update.key()] = boost::none; else { //if there's a tombstone in pending, clean it up if(pending_version_map_.count(update.key()) && pending_version_map_[update.key()]) pending_version_map_.erase(update.key()); fetch_map(target).erase(update.key()); } } void raft::Client::apply_to(const raft::request::Rename& update, apply_target target) { //fetch the if(target == apply_pending) { //if the from isn't in pending, it needs to be in main std::string version; if(exists_map(update.key(), pending_version_map_)) { version = std::get<0>(*pending_version_map_.at(update.key())); //erase it pending_version_map_[update.key()] = boost::none; } else //let it be bounds checked version = std::get<0>(*version_map_.at(update.key())); //Add the rename pending_version_map_[update.new_key()] = std::make_tuple(version, update.from()); } else { //only read the main version_map_[update.new_key()] = std::make_tuple(std::get<0>(*version_map_[update.key()]), update.from()); version_map_.erase(update.key()); } } void raft::Client::apply_to(const raft::request::Add& update, apply_target target) { fetch_map(target)[update.key()] = std::make_tuple(update.version(), update.from()); } raft::Client::validity raft::Client::request_traits<raft::request::Update>::valid( const rpc_type& rpc, const version_map_type& version_map, const version_map_type& pending_map) { if(!exists_map(rpc.key(), pending_map)) return valid_impl(rpc, version_map); else return valid_impl(rpc, pending_map); } raft::Client::validity raft::Client::request_traits<raft::request::Update>::valid( const rpc_type& rpc, const version_map_type& version_map) { return valid_impl(rpc, version_map); } raft::Client::validity raft::Client::request_traits<raft::request::Update> ::valid_impl(const rpc_type& rpc, const version_map_type& version_map) { if(exists_map(rpc.key(), version_map)) { if(std::get<0>(*version_map.at(rpc.key())) == rpc.new_version()) return request_done; else return std::get<0>(*version_map.at(rpc.key())) == rpc.old_version() ? request_valid : request_invalid; } else return request_invalid; } raft::Client::validity raft::Client::request_traits<raft::request::Delete>::valid( const rpc_type& rpc, const version_map_type& version_map, const version_map_type& pending_map) { //not using exists_map because if there're tombstones in pending we don't want //to mark valid. if(pending_map.count(rpc.key()) == 0) return valid_impl(rpc, version_map); else return valid_impl(rpc, pending_map); } raft::Client::validity raft::Client::request_traits<raft::request::Delete>::valid( const rpc_type& rpc, const version_map_type& version_map) { return valid_impl(rpc, version_map); } raft::Client::validity raft::Client::request_traits<raft::request::Delete> ::valid_impl(const rpc_type& rpc, const version_map_type& version_map) { if(version_map.count(rpc.key()) == 1 && version_map.at(rpc.key())) return std::get<0>(*version_map.at(rpc.key())) == rpc.version() ? request_valid : request_invalid; else return version_map.count(rpc.key()) == 1 ? request_invalid : request_done; } raft::Client::validity raft::Client::request_traits<raft::request::Rename>::valid( const rpc_type& rpc, const version_map_type& version_map, const version_map_type& pending_map) { auto from_version = most_recent(rpc.key(), version_map, pending_map); auto to_version = most_recent(rpc.new_key(), version_map, pending_map); if(!from_version && to_version && *to_version == rpc.version()) return request_done; if(from_version && !to_version && *from_version == rpc.version()) return request_valid; return request_invalid; } raft::Client::validity raft::Client::request_traits<raft::request::Rename>::valid( const rpc_type& rpc, const version_map_type& version_map) { if(exists_map(rpc.key(), version_map) && std::get<0>(*version_map.at(rpc.key())) == rpc.version()) return request_valid; else if(exists_map(rpc.new_key(), version_map) && std::get<0>(*version_map.at(rpc.new_key())) == rpc.version()) return request_done; else return request_invalid; } boost::optional<std::string> raft::Client ::request_traits<raft::request::Rename>::most_recent( const std::string& key, const version_map_type& version_map, const version_map_type& pending_map) { if(exists_map(key, pending_map)) return std::get<0>(*pending_map.at(key)); else { if(exists_map(key, version_map)) return std::get<0>(*version_map.at(key)); else return boost::none; } } raft::Client::validity raft::Client::request_traits<raft::request::Add>::valid( const rpc_type& rpc, const version_map_type& version_map, const version_map_type& pending_map) { if(!exists_map(rpc.key(), pending_map)) { if(exists_map(rpc.key(), version_map)) { return std::get<0>(*version_map.at(rpc.key())) == rpc.version() ? request_done : request_invalid; } else return request_valid; } else { return std::get<0>(*pending_map.at(rpc.key())) == rpc.version() ? request_done : request_invalid; } } raft::Client::validity raft::Client::request_traits<raft::request::Add>::valid( const rpc_type& rpc, const version_map_type& version_map) { if(!exists_map(rpc.key(), version_map)) return request_valid; else if(std::get<0>(*version_map.at(rpc.key())) == rpc.version()) return request_done; else return request_invalid; } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "SoundStream.h" // Debug prints only #include "OpenALAudioModule.h" #include <QFile> namespace OpenALAudio { SoundStream::SoundStream(std::string stream_name, uint frequency, int sample_width, bool stereo) : name_(stream_name), frequency_(frequency), sample_width_(sample_width), stereo_(stereo), current_buffer_(0) { switch (sample_width_) { case 8: if (stereo) format_ = AL_FORMAT_STEREO8; else format_ = AL_FORMAT_MONO8; break; case 16: if (stereo) format_ = AL_FORMAT_STEREO16; else format_ = AL_FORMAT_MONO16; break; } alGenSources(1, &source_); alSourcef(source_, AL_GAIN, 1.0f); alSourcef(source_, AL_ROLLOFF_FACTOR, 0.0); // TODO: Check this for spatial playback alSourcef(source_, AL_REFERENCE_DISTANCE, 10.0); alGenBuffers(MAX_BUFFER_COUNT, buffers_); for (int i = 0; i < MAX_BUFFER_COUNT; i++) { const int empty_buffer_fill_size = 100; ALuint buffer_handle = buffers_[i]; playback_buffers_[buffer_handle] = new u8[empty_buffer_fill_size]; memset(playback_buffers_[buffer_handle], 0, empty_buffer_fill_size); alBufferData(buffer_handle, format_, playback_buffers_[buffer_handle], empty_buffer_fill_size, frequency_); alSourceQueueBuffers(source_, 1, &buffer_handle); } Play(); } SoundStream::~SoundStream() { Release(); } void SoundStream::Release() { alSourceStop(source_); alDeleteSources(1, &source_); alDeleteBuffers(MAX_BUFFER_COUNT, buffers_); for (int i = 0; i < MAX_BUFFER_COUNT; i++) { delete [] playback_buffers_[i]; playback_buffers_[i] = 0; } for (std::vector<u8*>::iterator i = data_queue_.begin(); i != data_queue_.end(); ++i) { u8* data = *i; delete [] data; data = 0; } data_queue_.clear(); data_queue_packet_sizes_.clear(); } void SoundStream::Play() { alSourcePlay(source_); OpenALAudioModule::LogDebug(">> Stream playback started"); } int SoundStream::GetReceivedAudioDataLengthMs() { u32 byte_count = 0; for (std::vector<u32>::iterator i = data_queue_packet_sizes_.begin(); i != data_queue_packet_sizes_.end(); ++i) { u32 size = *i; byte_count += size; } return byte_count*1000*8/sample_width_/frequency_; } void SoundStream::StoreToQueue(u8* data, int size) { u8* local_copy = new u8[size]; // RESERVE MEMORY memcpy(local_copy, data, size); data_queue_.push_back(local_copy); data_queue_packet_sizes_.push_back(size); assert(data_queue_.size() == data_queue_packet_sizes_.size()); } ALint SoundStream::FillBufferFromQueue(ALint buffer_handle) { // Copy audio data from queue to playback buffers int total_queue_size = 0; for (std::vector<u32>::iterator i = data_queue_packet_sizes_.begin(); i != data_queue_packet_sizes_.end(); ++i) { u32 size = *i; total_queue_size += size; } u8* local_copy = new u8[total_queue_size]; // RESERVE MEMORY u32 offset = 0; for (int i = 0; i < data_queue_.size(); i++) { u32 size = data_queue_packet_sizes_[i]; memcpy(local_copy + offset, data_queue_[i], size); delete [] data_queue_[i]; // FREE MEMORY offset += size; } data_queue_.clear(); data_queue_packet_sizes_.clear(); // clear previously playback buffer if (playback_buffers_[buffer_handle]) delete [] playback_buffers_[buffer_handle]; // FREE MEMORY playback_buffers_[buffer_handle] = local_copy; alBufferData(buffer_handle, format_, playback_buffers_[buffer_handle], total_queue_size, frequency_); if (alGetError() == AL_OUT_OF_MEMORY) { OpenALAudioModule::LogError("Cannot fill audio buffer: OpenAl out of memory"); return 0; } if (alGetError() != AL_NONE) { OpenALAudioModule::LogError("Cannot fill audio buffer: Reason unknown"); return 0; } return buffer_handle; } void SoundStream::AddData(u8 *data, uint size) { if (!add_data_mutex_.tryLock()) return; int max_buffer_length_ms = 200; ALint empty_buffer_count = 0; alGetSourcei(source_, AL_BUFFERS_PROCESSED, &empty_buffer_count); if (empty_buffer_count == 0 && GetReceivedAudioDataLengthMs() > max_buffer_length_ms) { // OpenALAudioModule::LogDebug("Drop audio packet, no buffers for playback."); // All the buffers are full, we'll ignore this audio sample packet add_data_mutex_.unlock(); return; } StoreToQueue(data, size); if (empty_buffer_count == 0 || GetReceivedAudioDataLengthMs() < max_buffer_length_ms / 2) { // we do not want to fill OpenAL buffer even if we have one available but we have stored the data to queue add_data_mutex_.unlock(); return; } // Now we have a ampty OpenAl buffer to fill and at enough data on queue ALuint buffer_handle; alSourceUnqueueBuffers(source_, 1, &buffer_handle); if (alGetError() != AL_NONE) { OpenALAudioModule::LogDebug("Could not pull empty buffer from source!"); add_data_mutex_.unlock(); return; } if (!FillBufferFromQueue(buffer_handle)) { add_data_mutex_.unlock(); return; } // Queue buffer back to sources playlist alSourceQueueBuffers(source_, 1, &buffer_handle); if (!IsPlaying()) Play(); add_data_mutex_.unlock(); } bool SoundStream::IsPlaying() { ALenum state; alGetSourcei(source_, AL_SOURCE_STATE, &state); return (state == AL_PLAYING); } void SoundStream::SetPosition(const Vector3df &position) { if (source_) { //alSourcei(source_, AL_SOURCE_RELATIVE, AL_FALSE); alSourcei(source_, AL_SOURCE_RELATIVE, AL_TRUE); ALfloat sound_pos[] = { position.x, position.y, position.z }; alSourcefv(source_, AL_POSITION, sound_pos); } } } <commit_msg>Changed streamed media positional voice attributes.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "SoundStream.h" // Debug prints only #include "OpenALAudioModule.h" #include <QFile> namespace OpenALAudio { SoundStream::SoundStream(std::string stream_name, uint frequency, int sample_width, bool stereo) : name_(stream_name), frequency_(frequency), sample_width_(sample_width), stereo_(stereo), current_buffer_(0) { switch (sample_width_) { case 8: if (stereo) format_ = AL_FORMAT_STEREO8; else format_ = AL_FORMAT_MONO8; break; case 16: if (stereo) format_ = AL_FORMAT_STEREO16; else format_ = AL_FORMAT_MONO16; break; } alGenSources(1, &source_); alSourcef(source_, AL_GAIN, 1.0f); alSourcef(source_, AL_ROLLOFF_FACTOR, 0.0); // TODO: Check this for spatial playback alSourcef(source_, AL_REFERENCE_DISTANCE, 10.0); alGenBuffers(MAX_BUFFER_COUNT, buffers_); for (int i = 0; i < MAX_BUFFER_COUNT; i++) { const int empty_buffer_fill_size = 100; ALuint buffer_handle = buffers_[i]; playback_buffers_[buffer_handle] = new u8[empty_buffer_fill_size]; memset(playback_buffers_[buffer_handle], 0, empty_buffer_fill_size); alBufferData(buffer_handle, format_, playback_buffers_[buffer_handle], empty_buffer_fill_size, frequency_); alSourceQueueBuffers(source_, 1, &buffer_handle); } Play(); } SoundStream::~SoundStream() { Release(); } void SoundStream::Release() { alSourceStop(source_); alDeleteSources(1, &source_); alDeleteBuffers(MAX_BUFFER_COUNT, buffers_); for (int i = 0; i < MAX_BUFFER_COUNT; i++) { delete [] playback_buffers_[i]; playback_buffers_[i] = 0; } for (std::vector<u8*>::iterator i = data_queue_.begin(); i != data_queue_.end(); ++i) { u8* data = *i; delete [] data; data = 0; } data_queue_.clear(); data_queue_packet_sizes_.clear(); } void SoundStream::Play() { alSourcePlay(source_); OpenALAudioModule::LogDebug(">> Stream playback started"); } int SoundStream::GetReceivedAudioDataLengthMs() { u32 byte_count = 0; for (std::vector<u32>::iterator i = data_queue_packet_sizes_.begin(); i != data_queue_packet_sizes_.end(); ++i) { u32 size = *i; byte_count += size; } return byte_count*1000*8/sample_width_/frequency_; } void SoundStream::StoreToQueue(u8* data, int size) { u8* local_copy = new u8[size]; // RESERVE MEMORY memcpy(local_copy, data, size); data_queue_.push_back(local_copy); data_queue_packet_sizes_.push_back(size); assert(data_queue_.size() == data_queue_packet_sizes_.size()); } ALint SoundStream::FillBufferFromQueue(ALint buffer_handle) { // Copy audio data from queue to playback buffers int total_queue_size = 0; for (std::vector<u32>::iterator i = data_queue_packet_sizes_.begin(); i != data_queue_packet_sizes_.end(); ++i) { u32 size = *i; total_queue_size += size; } u8* local_copy = new u8[total_queue_size]; // RESERVE MEMORY u32 offset = 0; for (int i = 0; i < data_queue_.size(); i++) { u32 size = data_queue_packet_sizes_[i]; memcpy(local_copy + offset, data_queue_[i], size); delete [] data_queue_[i]; // FREE MEMORY offset += size; } data_queue_.clear(); data_queue_packet_sizes_.clear(); // clear previously playback buffer if (playback_buffers_[buffer_handle]) delete [] playback_buffers_[buffer_handle]; // FREE MEMORY playback_buffers_[buffer_handle] = local_copy; alBufferData(buffer_handle, format_, playback_buffers_[buffer_handle], total_queue_size, frequency_); if (alGetError() == AL_OUT_OF_MEMORY) { OpenALAudioModule::LogError("Cannot fill audio buffer: OpenAl out of memory"); return 0; } if (alGetError() != AL_NONE) { OpenALAudioModule::LogError("Cannot fill audio buffer: Reason unknown"); return 0; } return buffer_handle; } void SoundStream::AddData(u8 *data, uint size) { if (!add_data_mutex_.tryLock()) return; int max_buffer_length_ms = 200; ALint empty_buffer_count = 0; alGetSourcei(source_, AL_BUFFERS_PROCESSED, &empty_buffer_count); if (empty_buffer_count == 0 && GetReceivedAudioDataLengthMs() > max_buffer_length_ms) { // OpenALAudioModule::LogDebug("Drop audio packet, no buffers for playback."); // All the buffers are full, we'll ignore this audio sample packet add_data_mutex_.unlock(); return; } StoreToQueue(data, size); if (empty_buffer_count == 0 || GetReceivedAudioDataLengthMs() < max_buffer_length_ms / 2) { // we do not want to fill OpenAL buffer even if we have one available but we have stored the data to queue add_data_mutex_.unlock(); return; } // Now we have a ampty OpenAl buffer to fill and at enough data on queue ALuint buffer_handle; alSourceUnqueueBuffers(source_, 1, &buffer_handle); if (alGetError() != AL_NONE) { OpenALAudioModule::LogDebug("Could not pull empty buffer from source!"); add_data_mutex_.unlock(); return; } if (!FillBufferFromQueue(buffer_handle)) { add_data_mutex_.unlock(); return; } // Queue buffer back to sources playlist alSourceQueueBuffers(source_, 1, &buffer_handle); if (!IsPlaying()) Play(); add_data_mutex_.unlock(); } bool SoundStream::IsPlaying() { ALenum state; alGetSourcei(source_, AL_SOURCE_STATE, &state); return (state == AL_PLAYING); } void SoundStream::SetPosition(const Vector3df &position) { if (source_) { alSourcei(source_, AL_SOURCE_RELATIVE, AL_FALSE); //alSourcei(source_, AL_SOURCE_RELATIVE, AL_TRUE); ALfloat sound_pos[] = { position.x, position.y, position.z }; alSourcefv(source_, AL_POSITION, sound_pos); } } } <|endoftext|>
<commit_before>#include "C3DFileAdapter.h" #include "btkAcquisitionFileReader.h" #include "btkAcquisition.h" #include "btkForcePlatformsExtractor.h" #include "btkGroundReactionWrenchFilter.h" namespace { // Function to convert Eigen matrix to SimTK matrix. This can become a lambda // funciton inside extendRead in future. template<typename _Scalar, int _Rows, int _Cols> SimTK::Matrix_<double> convertToSimtkMatrix(const Eigen::Matrix<_Scalar, _Rows, _Cols>& eigenMat) { SimTK::Matrix_<double> simtkMat{static_cast<int>(eigenMat.rows()), static_cast<int>(eigenMat.cols())}; for(int r = 0; r < eigenMat.rows(); ++r) for(int c = 0; c < eigenMat.cols(); ++c) simtkMat(r, c) = eigenMat(r, c); return simtkMat; } } // anonymous namespace namespace OpenSim { const std::string C3DFileAdapter::_markers{"markers"}; const std::string C3DFileAdapter::_forces{"forces"}; const std::unordered_map<std::string, size_t> C3DFileAdapter::_unit_index{{"marker", 0}, {"angle" , 1}, {"force" , 2}, {"moment", 3}, {"power" , 4}, {"scalar", 5}}; C3DFileAdapter* C3DFileAdapter::clone() const { return new C3DFileAdapter{*this}; } C3DFileAdapter::Tables C3DFileAdapter::read(const std::string& fileName) { auto abstables = C3DFileAdapter{}.extendRead(fileName); auto marker_table = std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_markers)); auto force_table = std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_forces)); Tables tables{}; tables.emplace(_markers, marker_table); tables.emplace( _forces, force_table); return tables; } void C3DFileAdapter::write(const C3DFileAdapter::Tables& tables, const std::string& fileName) { throw Exception{"Writing C3D not supported yet."}; } C3DFileAdapter::OutputTables C3DFileAdapter::extendRead(const std::string& fileName) const { auto reader = btk::AcquisitionFileReader::New(); reader->SetFilename(fileName); reader->Update(); auto acquisition = reader->GetOutput(); EventTable event_table{}; auto events = acquisition->GetEvents(); for (auto it = events->Begin(); it != events->End(); ++it) { auto et = *it; event_table.push_back({ et->GetLabel(), et->GetTime(), et->GetFrame(), et->GetDescription() }); } OutputTables tables{}; auto marker_pts = btk::PointCollection::New(); for(auto it = acquisition->BeginPoint(); it != acquisition->EndPoint(); ++it) { auto pt = *it; if(pt->GetType() == btk::Point::Marker) marker_pts->InsertItem(pt); } if(marker_pts->GetItemNumber() != 0) { int marker_nrow = marker_pts->GetFrontItem()->GetFrameNumber(); int marker_ncol = marker_pts->GetItemNumber(); std::vector<double> marker_times(marker_nrow); SimTK::Matrix_<SimTK::Vec3> marker_matrix(marker_nrow, marker_ncol); std::vector<std::string> marker_labels{}; for (auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) { marker_labels.push_back(SimTK::Value<std::string>((*it)->GetLabel())); } double time_step{1.0 / acquisition->GetPointFrequency()}; for(int f = 0; f < marker_nrow; ++f) { SimTK::RowVector_<SimTK::Vec3> row{marker_pts->GetItemNumber()}; int m{0}; for(auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) { auto pt = *it; row[m++] = SimTK::Vec3{pt->GetValues().coeff(f, 0), pt->GetValues().coeff(f, 1), pt->GetValues().coeff(f, 2)}; } marker_matrix.updRow(f) = row; marker_times[f] = 0 + f * time_step; //TODO: 0 should be start_time } // Create the data auto& marker_table = *new TimeSeriesTableVec3(marker_times, marker_matrix, marker_labels); marker_table. updTableMetaData(). setValueForKey("DataRate", std::to_string(acquisition->GetPointFrequency())); marker_table. updTableMetaData(). setValueForKey("Units", acquisition->GetPointUnit()); marker_table.updTableMetaData().setValueForKey("events", event_table); tables.emplace(_markers, std::shared_ptr<TimeSeriesTableVec3>(&marker_table)); } // This is probably the right way to get the raw forces data from force // platforms. Extract the collection of force platforms. auto force_platforms_extractor = btk::ForcePlatformsExtractor::New(); force_platforms_extractor->SetInput(acquisition); auto force_platform_collection = force_platforms_extractor->GetOutput(); force_platforms_extractor->Update(); std::vector<SimTK::Matrix_<double>> fpCalMatrices{}; std::vector<SimTK::Matrix_<double>> fpCorners{}; std::vector<SimTK::Matrix_<double>> fpOrigins{}; std::vector<unsigned> fpTypes{}; auto fp_force_pts = btk::PointCollection::New(); auto fp_moment_pts = btk::PointCollection::New(); auto fp_position_pts = btk::PointCollection::New(); for(auto platform = force_platform_collection->Begin(); platform != force_platform_collection->End(); ++platform) { const auto& calMatrix = (*platform)->GetCalMatrix(); const auto& corners = (*platform)->GetCorners(); const auto& origins = (*platform)->GetOrigin(); fpCalMatrices.push_back(convertToSimtkMatrix(calMatrix)); fpCorners.push_back(convertToSimtkMatrix(corners)); fpOrigins.push_back(convertToSimtkMatrix(origins)); fpTypes.push_back(static_cast<unsigned>((*platform)->GetType())); // Get ground reaction wrenches for the force platform. auto ground_reaction_wrench_filter = btk::GroundReactionWrenchFilter::New(); ground_reaction_wrench_filter->SetInput(*platform); auto wrench_collection = ground_reaction_wrench_filter->GetOutput(); ground_reaction_wrench_filter->Update(); for(auto wrench = wrench_collection->Begin(); wrench != wrench_collection->End(); ++wrench) { // Forces time series. fp_force_pts->InsertItem((*wrench)->GetForce()); // Moment time series. fp_moment_pts->InsertItem((*wrench)->GetMoment()); // Position time series. fp_position_pts->InsertItem((*wrench)->GetPosition()); } } if(fp_force_pts->GetItemNumber() != 0) { std::vector<std::string> labels{}; ValueArray<std::string> units{}; for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) { auto fp_str = std::to_string(fp); labels.push_back(SimTK::Value<std::string>("f" + fp_str)); auto force_unit = acquisition->GetPointUnits(). at(_unit_index.at("force")); units.upd().push_back(SimTK::Value<std::string>(force_unit)); labels.push_back(SimTK::Value<std::string>("p" + fp_str)); auto position_unit = acquisition->GetPointUnits(). at(_unit_index.at("marker")); units.upd().push_back(SimTK::Value<std::string>(position_unit)); labels.push_back(SimTK::Value<std::string>("m" + fp_str)); auto moment_unit = acquisition->GetPointUnits(). at(_unit_index.at("moment")); units.upd().push_back(SimTK::Value<std::string>(moment_unit)); } const int nf = fp_force_pts->GetFrontItem()->GetFrameNumber(); std::vector<double> force_times(nf); SimTK::Matrix_<SimTK::Vec3> force_matrix(nf, labels.size()); double time_step{1.0 / acquisition->GetAnalogFrequency()}; for(int f = 0; f < nf; ++f) { SimTK::RowVector_<SimTK::Vec3> row{fp_force_pts->GetItemNumber() * 3}; int col{0}; for(auto fit = fp_force_pts->Begin(), mit = fp_moment_pts->Begin(), pit = fp_position_pts->Begin(); fit != fp_force_pts->End(); ++fit, ++mit, ++pit) { row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0), (*fit)->GetValues().coeff(f, 1), (*fit)->GetValues().coeff(f, 2)}; ++col; row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0), (*pit)->GetValues().coeff(f, 1), (*pit)->GetValues().coeff(f, 2)}; ++col; row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0), (*mit)->GetValues().coeff(f, 1), (*mit)->GetValues().coeff(f, 2)}; ++col; } force_matrix.updRow(f) = row; force_times[f] = 0 + f * time_step; //TODO: 0 should be start_time } auto& force_table = *(new TimeSeriesTableVec3(force_times, force_matrix, labels)); TimeSeriesTableVec3::DependentsMetaData force_dep_metadata = force_table.getDependentsMetaData(); // add units to the dependent meta data force_dep_metadata.setValueArrayForKey("units", units); force_table.setDependentsMetaData(force_dep_metadata); force_table. updTableMetaData(). setValueForKey("CalibrationMatrices", std::move(fpCalMatrices)); force_table. updTableMetaData(). setValueForKey("Corners", std::move(fpCorners)); force_table. updTableMetaData(). setValueForKey("Origins", std::move(fpOrigins)); force_table. updTableMetaData(). setValueForKey("Types", std::move(fpTypes)); force_table. updTableMetaData(). setValueForKey("DataRate", std::to_string(acquisition->GetAnalogFrequency())); tables.emplace(_forces, std::shared_ptr<TimeSeriesTableVec3>(&force_table)); force_table.updTableMetaData().setValueForKey("events", event_table); } return tables; } void C3DFileAdapter::extendWrite(const InputTables& absTables, const std::string& fileName) const { throw Exception{"Writing to C3D not supported yet."}; } } // namespace OpenSim <commit_msg>Avoid warning in C3DFileAdapter.cpp.<commit_after>#include "C3DFileAdapter.h" #include "btkAcquisitionFileReader.h" #include "btkAcquisition.h" #include "btkForcePlatformsExtractor.h" #include "btkGroundReactionWrenchFilter.h" namespace { // Function to convert Eigen matrix to SimTK matrix. This can become a lambda // funciton inside extendRead in future. template<typename _Scalar, int _Rows, int _Cols> SimTK::Matrix_<double> convertToSimtkMatrix(const Eigen::Matrix<_Scalar, _Rows, _Cols>& eigenMat) { SimTK::Matrix_<double> simtkMat{static_cast<int>(eigenMat.rows()), static_cast<int>(eigenMat.cols())}; for(int r = 0; r < eigenMat.rows(); ++r) for(int c = 0; c < eigenMat.cols(); ++c) simtkMat(r, c) = eigenMat(r, c); return simtkMat; } } // anonymous namespace namespace OpenSim { const std::string C3DFileAdapter::_markers{"markers"}; const std::string C3DFileAdapter::_forces{"forces"}; const std::unordered_map<std::string, size_t> C3DFileAdapter::_unit_index{{"marker", 0}, {"angle" , 1}, {"force" , 2}, {"moment", 3}, {"power" , 4}, {"scalar", 5}}; C3DFileAdapter* C3DFileAdapter::clone() const { return new C3DFileAdapter{*this}; } C3DFileAdapter::Tables C3DFileAdapter::read(const std::string& fileName) { auto abstables = C3DFileAdapter{}.extendRead(fileName); auto marker_table = std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_markers)); auto force_table = std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_forces)); Tables tables{}; tables.emplace(_markers, marker_table); tables.emplace( _forces, force_table); return tables; } void C3DFileAdapter::write(const C3DFileAdapter::Tables& tables, const std::string& fileName) { throw Exception{"Writing C3D not supported yet."}; } C3DFileAdapter::OutputTables C3DFileAdapter::extendRead(const std::string& fileName) const { auto reader = btk::AcquisitionFileReader::New(); reader->SetFilename(fileName); reader->Update(); auto acquisition = reader->GetOutput(); EventTable event_table{}; auto events = acquisition->GetEvents(); for (auto it = events->Begin(); it != events->End(); ++it) { auto et = *it; event_table.push_back({ et->GetLabel(), et->GetTime(), et->GetFrame(), et->GetDescription() }); } OutputTables tables{}; auto marker_pts = btk::PointCollection::New(); for(auto it = acquisition->BeginPoint(); it != acquisition->EndPoint(); ++it) { auto pt = *it; if(pt->GetType() == btk::Point::Marker) marker_pts->InsertItem(pt); } if(marker_pts->GetItemNumber() != 0) { int marker_nrow = marker_pts->GetFrontItem()->GetFrameNumber(); int marker_ncol = marker_pts->GetItemNumber(); std::vector<double> marker_times(marker_nrow); SimTK::Matrix_<SimTK::Vec3> marker_matrix(marker_nrow, marker_ncol); std::vector<std::string> marker_labels{}; for (auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) { marker_labels.push_back(SimTK::Value<std::string>((*it)->GetLabel())); } double time_step{1.0 / acquisition->GetPointFrequency()}; for(int f = 0; f < marker_nrow; ++f) { SimTK::RowVector_<SimTK::Vec3> row{marker_pts->GetItemNumber()}; int m{0}; for(auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) { auto pt = *it; row[m++] = SimTK::Vec3{pt->GetValues().coeff(f, 0), pt->GetValues().coeff(f, 1), pt->GetValues().coeff(f, 2)}; } marker_matrix.updRow(f) = row; marker_times[f] = 0 + f * time_step; //TODO: 0 should be start_time } // Create the data auto& marker_table = *new TimeSeriesTableVec3(marker_times, marker_matrix, marker_labels); marker_table. updTableMetaData(). setValueForKey("DataRate", std::to_string(acquisition->GetPointFrequency())); marker_table. updTableMetaData(). setValueForKey("Units", acquisition->GetPointUnit()); marker_table.updTableMetaData().setValueForKey("events", event_table); tables.emplace(_markers, std::shared_ptr<TimeSeriesTableVec3>(&marker_table)); } // This is probably the right way to get the raw forces data from force // platforms. Extract the collection of force platforms. auto force_platforms_extractor = btk::ForcePlatformsExtractor::New(); force_platforms_extractor->SetInput(acquisition); auto force_platform_collection = force_platforms_extractor->GetOutput(); force_platforms_extractor->Update(); std::vector<SimTK::Matrix_<double>> fpCalMatrices{}; std::vector<SimTK::Matrix_<double>> fpCorners{}; std::vector<SimTK::Matrix_<double>> fpOrigins{}; std::vector<unsigned> fpTypes{}; auto fp_force_pts = btk::PointCollection::New(); auto fp_moment_pts = btk::PointCollection::New(); auto fp_position_pts = btk::PointCollection::New(); for(auto platform = force_platform_collection->Begin(); platform != force_platform_collection->End(); ++platform) { const auto& calMatrix = (*platform)->GetCalMatrix(); const auto& corners = (*platform)->GetCorners(); const auto& origins = (*platform)->GetOrigin(); fpCalMatrices.push_back(convertToSimtkMatrix(calMatrix)); fpCorners.push_back(convertToSimtkMatrix(corners)); fpOrigins.push_back(convertToSimtkMatrix(origins)); fpTypes.push_back(static_cast<unsigned>((*platform)->GetType())); // Get ground reaction wrenches for the force platform. auto ground_reaction_wrench_filter = btk::GroundReactionWrenchFilter::New(); ground_reaction_wrench_filter->SetInput(*platform); auto wrench_collection = ground_reaction_wrench_filter->GetOutput(); ground_reaction_wrench_filter->Update(); for(auto wrench = wrench_collection->Begin(); wrench != wrench_collection->End(); ++wrench) { // Forces time series. fp_force_pts->InsertItem((*wrench)->GetForce()); // Moment time series. fp_moment_pts->InsertItem((*wrench)->GetMoment()); // Position time series. fp_position_pts->InsertItem((*wrench)->GetPosition()); } } if(fp_force_pts->GetItemNumber() != 0) { std::vector<std::string> labels{}; ValueArray<std::string> units{}; for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) { auto fp_str = std::to_string(fp); labels.push_back(SimTK::Value<std::string>("f" + fp_str)); auto force_unit = acquisition->GetPointUnits(). at(_unit_index.at("force")); units.upd().push_back(SimTK::Value<std::string>(force_unit)); labels.push_back(SimTK::Value<std::string>("p" + fp_str)); auto position_unit = acquisition->GetPointUnits(). at(_unit_index.at("marker")); units.upd().push_back(SimTK::Value<std::string>(position_unit)); labels.push_back(SimTK::Value<std::string>("m" + fp_str)); auto moment_unit = acquisition->GetPointUnits(). at(_unit_index.at("moment")); units.upd().push_back(SimTK::Value<std::string>(moment_unit)); } const int nf = fp_force_pts->GetFrontItem()->GetFrameNumber(); std::vector<double> force_times(nf); SimTK::Matrix_<SimTK::Vec3> force_matrix(nf, (int)labels.size()); double time_step{1.0 / acquisition->GetAnalogFrequency()}; for(int f = 0; f < nf; ++f) { SimTK::RowVector_<SimTK::Vec3> row{fp_force_pts->GetItemNumber() * 3}; int col{0}; for(auto fit = fp_force_pts->Begin(), mit = fp_moment_pts->Begin(), pit = fp_position_pts->Begin(); fit != fp_force_pts->End(); ++fit, ++mit, ++pit) { row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0), (*fit)->GetValues().coeff(f, 1), (*fit)->GetValues().coeff(f, 2)}; ++col; row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0), (*pit)->GetValues().coeff(f, 1), (*pit)->GetValues().coeff(f, 2)}; ++col; row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0), (*mit)->GetValues().coeff(f, 1), (*mit)->GetValues().coeff(f, 2)}; ++col; } force_matrix.updRow(f) = row; force_times[f] = 0 + f * time_step; //TODO: 0 should be start_time } auto& force_table = *(new TimeSeriesTableVec3(force_times, force_matrix, labels)); TimeSeriesTableVec3::DependentsMetaData force_dep_metadata = force_table.getDependentsMetaData(); // add units to the dependent meta data force_dep_metadata.setValueArrayForKey("units", units); force_table.setDependentsMetaData(force_dep_metadata); force_table. updTableMetaData(). setValueForKey("CalibrationMatrices", std::move(fpCalMatrices)); force_table. updTableMetaData(). setValueForKey("Corners", std::move(fpCorners)); force_table. updTableMetaData(). setValueForKey("Origins", std::move(fpOrigins)); force_table. updTableMetaData(). setValueForKey("Types", std::move(fpTypes)); force_table. updTableMetaData(). setValueForKey("DataRate", std::to_string(acquisition->GetAnalogFrequency())); tables.emplace(_forces, std::shared_ptr<TimeSeriesTableVec3>(&force_table)); force_table.updTableMetaData().setValueForKey("events", event_table); } return tables; } void C3DFileAdapter::extendWrite(const InputTables& absTables, const std::string& fileName) const { throw Exception{"Writing to C3D not supported yet."}; } } // namespace OpenSim <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, 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 "logger.h" #include "ep_engine.h" #include "objectregistry.h" #include "utility.h" #include <cstdarg> #include <mutex> Logger::Logger(const std::string& prefix_) : prefix(prefix_), min_log_level(EXTENSION_LOG_DETAIL) { } void Logger::log(EXTENSION_LOG_LEVEL severity, const char* fmt, ...) const { va_list va; va_start(va, fmt); vlog(severity, fmt, va); va_end(va); } void Logger::vlog(EXTENSION_LOG_LEVEL severity, const char* fmt, va_list va) const { if (severity < min_log_level) { // Message isn't high enough priority for this logger. return; } if (severity < Logger::global_log_level) { // Message isn't high enough for global priority. return; } if (Logger::logger_api.load(std::memory_order_relaxed) == nullptr) { // Cannot log it without a valid logger api. return; } static EXTENSION_LOGGER_DESCRIPTOR* logger; if (logger == nullptr) { // This locking isn't really needed because get_logger will // always return the same address, but it'll keep thread sanitizer // and other tools from complaining ;-) static std::mutex mutex; std::lock_guard<std::mutex> guard(mutex); logger = Logger::logger_api.load(std::memory_order_relaxed)->get_logger(); global_log_level.store(Logger::logger_api.load(std::memory_order_relaxed)->get_level(), std::memory_order_relaxed); } EventuallyPersistentEngine *engine = ObjectRegistry::onSwitchThread(NULL, true); // Format the message into a buffer. char buffer[2048]; int pos = 0; if (prefix.size() > 0) { pos = snprintf(buffer, sizeof(buffer), "%s ", prefix.c_str()); } vsnprintf(buffer + pos, sizeof(buffer) - pos, fmt, va); // Log it. if (engine) { logger->log(severity, NULL, "(%s) %s", engine->getName().c_str(), buffer); } else { logger->log(severity, NULL, "(No Engine) %s", buffer); } ObjectRegistry::onSwitchThread(engine); }; void Logger::setLoggerAPI(SERVER_LOG_API* api) { Logger::logger_api.store(api, std::memory_order_relaxed); } void Logger::setGlobalLogLevel(EXTENSION_LOG_LEVEL level) { Logger::global_log_level.store(level, std::memory_order_relaxed); } std::atomic<SERVER_LOG_API*> Logger::logger_api; std::atomic<EXTENSION_LOG_LEVEL> Logger::global_log_level; <commit_msg>Remove extraneous semi-colon at end of function<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, 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 "logger.h" #include "ep_engine.h" #include "objectregistry.h" #include "utility.h" #include <cstdarg> #include <mutex> Logger::Logger(const std::string& prefix_) : prefix(prefix_), min_log_level(EXTENSION_LOG_DETAIL) { } void Logger::log(EXTENSION_LOG_LEVEL severity, const char* fmt, ...) const { va_list va; va_start(va, fmt); vlog(severity, fmt, va); va_end(va); } void Logger::vlog(EXTENSION_LOG_LEVEL severity, const char* fmt, va_list va) const { if (severity < min_log_level) { // Message isn't high enough priority for this logger. return; } if (severity < Logger::global_log_level) { // Message isn't high enough for global priority. return; } if (Logger::logger_api.load(std::memory_order_relaxed) == nullptr) { // Cannot log it without a valid logger api. return; } static EXTENSION_LOGGER_DESCRIPTOR* logger; if (logger == nullptr) { // This locking isn't really needed because get_logger will // always return the same address, but it'll keep thread sanitizer // and other tools from complaining ;-) static std::mutex mutex; std::lock_guard<std::mutex> guard(mutex); logger = Logger::logger_api.load(std::memory_order_relaxed)->get_logger(); global_log_level.store(Logger::logger_api.load(std::memory_order_relaxed)->get_level(), std::memory_order_relaxed); } EventuallyPersistentEngine *engine = ObjectRegistry::onSwitchThread(NULL, true); // Format the message into a buffer. char buffer[2048]; int pos = 0; if (prefix.size() > 0) { pos = snprintf(buffer, sizeof(buffer), "%s ", prefix.c_str()); } vsnprintf(buffer + pos, sizeof(buffer) - pos, fmt, va); // Log it. if (engine) { logger->log(severity, NULL, "(%s) %s", engine->getName().c_str(), buffer); } else { logger->log(severity, NULL, "(No Engine) %s", buffer); } ObjectRegistry::onSwitchThread(engine); } void Logger::setLoggerAPI(SERVER_LOG_API* api) { Logger::logger_api.store(api, std::memory_order_relaxed); } void Logger::setGlobalLogLevel(EXTENSION_LOG_LEVEL level) { Logger::global_log_level.store(level, std::memory_order_relaxed); } std::atomic<SERVER_LOG_API*> Logger::logger_api; std::atomic<EXTENSION_LOG_LEVEL> Logger::global_log_level; <|endoftext|>
<commit_before>// // Macro to run performance QA train // locally. The TPC performance task is attached. // // //13.10.2009 - J.Otwinowski@gsi.de // // /* Quick Start: 1. Start train macro (real data from GSI::SE). Source your own Alien environment. source /u/jacek/alien/set_alien_env.sh aliroot -b -q 'RunPerformanceTrainTPC.C("AliESDs.root",2,kFALSE,kTRUE,kTRUE)' 3. Start train macro (real data from lustre) aliroot -b -q 'RunPerformanceTrainTPC.C("AliESDs.root",2,kFALSE,kTRUE,kFALSE)' */ //_____________________________________________________________________________ void RunPerformanceTrainTPC(Char_t *file="esd.root", Int_t magField = 2, Bool_t bUseMCInfo=kFALSE, Bool_t bUseESDfriend=kTRUE, Bool_t bGrid=kTRUE) { // // Grid settings // use GSI::SE if(bGrid) { gSystem->Setenv("alien_CLOSE_SE","ALICE::GSI::SE"); TGrid * alien = TGrid::Connect("alien://",0,0,"t"); gSystem->Setenv("alien_CLOSE_SE","ALICE::GSI::SE"); } // // Train Configuration // Int_t iPWG1perfTPC = 1; // Test TPC performance Int_t iPWG1perfTRD = 0; // Test TRD performance Int_t iPWG1perfITS = 0; // Test ITS performance Int_t iPWG1perfCalo = 0; // Test Calo performance Int_t iPWG1perfMuonTrig = 0; // Test Muon Trigger performance Int_t iPWG1perfMuonEff = 0; // Test Muon Efficiency performance Int_t iPWG1perfTOF = 0; // Test TOF-TPC matching performance Int_t iPWG1perfPrimVertex = 0; // Test Primary Vertex performance Int_t iPWG1v0QA = 0; // V0 algorithm QA task // // Load Libraries // gSystem->Load("libANALYSIS"); gSystem->Load("libANALYSISalice"); gSystem->Load("libTENDER"); gSystem->Load("libCORRFW"); gSystem->Load("libTPCcalib.so"); gSystem->Load("libPWG1"); gSystem->Load("libPHOSUtils"); gSystem->Load("libEMCALUtils"); gSystem->Load("libPWG4PartCorrBase"); gSystem->Load("libPWG4PartCorrDep"); gSystem->Load("libPWG3muon.so"); // The class is here // // OCDB Configuration // AliCDBManager *cdbManager = AliCDBManager::Instance(); cdbManager->SetDefaultStorage("local://$ALICE_ROOT/OCDB"); cdbManager->SetSpecificStorage("GRP/GRP/Data", Form("local://%s",gSystem->pwd())); cdbManager->SetRun(0); //cdbManager->SetCacheFlag(kFALSE); // initialize magnetic field from the GRP manager. if(magField==0) TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 0., 0., AliMagF::k2kG)); if(magField==1) TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k2kG)); if(magField==2) TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k5kG)); //AliGRPManager grpMan; //grpMan.ReadGRPEntry(); //grpMan.SetMagField(); //AliRunInfo *runInfo = grpMan.GetRunInfo(); // // Load geometry // AliGeomManager::LoadGeometry(); // // Swtich off all AliInfo (too much output!) // AliLog::SetGlobalLogLevel(AliLog::kError); // // Create input ESD chain // /* gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C"); TChain* chain = CreateESDChain(list,nFiles,fistFile); if(!chain) { Error("RunPerformanceTrain","ESD chain not created!"); return; } */ TChain *chain = new TChain("esdTree"); if(!chain) { Error("RunPerformanceTrain","ESD chain not created!"); return; } chain->Add(file); chain->Lookup(); // // Create analysis manager // AliAnalysisManager *mgr = new AliAnalysisManager; if(!mgr) { Error("RunPerformanceTrain","AliAnalysisManager not set!"); return; } // // Set ESD input handler // AliESDInputHandler* esdH = new AliESDInputHandler; if(!esdH) { Error("RunPerformanceTrain","AliESDInputHandler not created!"); return; } if(bUseESDfriend) esdH->SetActiveBranches("ESDfriend"); mgr->SetInputEventHandler(esdH); /* // // Set RecPoints and ESD input handler // AliESDInputHandlerRP* rpH = new AliESDInputHandlerRP; if(!rpH) { Error("RunPerformanceTrain","AliESDInputHandlerRP not created!"); return; } if(bUseESDfriend) rpH->SetActiveBranches("ESDfriend"); mgr->SetInputEventHandler(rpH); */ // // Set MC input handler // if(bUseMCInfo) { AliMCEventHandler* mcH = new AliMCEventHandler; if(!mcH) { Error("RunPerformanceTrain","AliMCEventHandler not created!"); return; } mcH->SetReadTR(kTRUE); mgr->SetMCtruthEventHandler(mcH); } // // Add task to AliAnalysisManager // // // TPC performance // if(iPWG1perfTPC) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskPerformanceTPC.C"); AliPerformanceTask *tpcQA = AddTaskPerformanceTPC(bUseMCInfo,bUseESDfriend); if(!tpcQA) { Error("RunPerformanceTrain","AliPerformanceTask not created!"); return; } } else { Printf("RunPerformanceTrain: TPC Performance - EXCLUDED!"); } // // TRD perormance // if(iPWG1perfTRD) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTrainPerformanceTRD.C"); if(!AddTrainPerformanceTRD(bUseMCInfo,bUseESDfriend)) { Error("RunPerformanceTrain","TrainPerformanceTRD not created!"); return; } } else { Printf("RunPerformanceTrain: TRD TrainPerformanceTRD - EXCLUDED!"); } // // ITS performance // if(iPWG1perfITS) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskPerformanceITS.C"); AliAnalysisTaskITSTrackingCheck *itsQA = AddTaskPerformanceITS(bUseMCInfo); if(!itsQA) { Error("RunPerformanceTrain","AliAnalysisTaskITSTrackingCheck not created!"); return; } } else { Printf("RunPerformanceTrain: AliAnalysisTaskITSTrackingCheck - EXCLUDED!"); } // // Calorimeter Performance // if(iPWG1perfCalo) { gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCalorimeterQA.C"); AliAnalysisTaskParticleCorrelation *taskCaloQA = AddTaskCalorimeterQA("ESD",bUseMCInfo,kFALSE); if(!taskCaloQA) { Error("RunPerformanceTrain","AliAnalysisTaskParticleCorrelation not created!"); return; } mgr->AddTask(taskCaloQA); } else { Printf("RunPerformanceTrain: AliAnalysisTaskParticleCorrelation - EXCLUDED!"); } // // Muon Trigger // if(iPWG1perfMuonTrig) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskMTRchamberEfficiency.C"); AliAnalysisTaskTrigChEff *taskMuonTrig = AddTaskMTRchamberEfficiency(); if(!taskMuonTrig) { Error("RunPerformanceTrain","AliAnalysisTaskTrigChEff not created!"); return; } mgr->AddTask(taskMuonTrig); } else { Printf("RunPerformanceTrain: AliAnalysisTaskTrigChEff - EXCLUDED!"); } // // Muon Efficiency // if(iPWG1perfMuonEff) { // } else { Printf("RunPerformanceTrain: Muon Efficiency - EXCLUDED!"); } // // TOF performance // if(iPWG1perfTOF) { // } else { Printf("RunPerformanceTrain: TOF - EXCLUDED!"); } // // PWG1 Primary Vertex // if(iPWG1perfPrimVertex) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskVertexESD.C"); AliAnalysisTaskVertexESD *taskPrimVertex = AddTaskVertexESD(); if(!taskPrimVertex) { Error("RunPerformanceTrain","AliAnalysisTaskVertexESD not created!"); return; } } else { Printf("RunPerformanceTrain: AliAnalysisTaskVertexESD - EXCLUDED!"); } // // PWG1 V0 QA // if (iPWG1v0QA) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskV0QA.C"); AliAnalysisTaskV0QA *taskv0QA = AddTaskV0QA(bUseMCInfo); if(!taskv0QA) { Error("RunPerformanceTrain","AliAnalysisTaskV0QA not created!"); return; } } else { Printf("RunPerformanceTrain: AliAnalysisTaskV0QA - EXCLUDED!"); } // // Disable debug printouts // mgr->SetDebugLevel(0); if (!mgr->InitAnalysis()) return; mgr->PrintStatus(); //mgr->StartAnalysis("local",chain, nEvents, firstEvent); mgr->StartAnalysis("local",chain); } <commit_msg>change description and name of the function<commit_after>// // Macro to run performance QA train // locally. The TPC performance task is attached. // // //13.10.2009 - J.Otwinowski@gsi.de // // /* Quick Start: 1. Start train macro (real data from GSI::SE). Source your own Alien environment. source /u/jacek/alien/set_alien_env.sh aliroot -b -q 'RunPerformanceTrain.C("AliESDs.root",2,kFALSE,kTRUE,kTRUE)' 3. Start train macro (real data from lustre) aliroot -b -q 'RunPerformanceTrain.C("AliESDs.root",2,kFALSE,kTRUE,kFALSE)' */ //_____________________________________________________________________________ void RunPerformanceTrain(Char_t *file="esd.root", Int_t magField = 2, Bool_t bUseMCInfo=kFALSE, Bool_t bUseESDfriend=kTRUE, Bool_t bGrid=kTRUE) { // // Grid settings // use GSI::SE if(bGrid) { gSystem->Setenv("alien_CLOSE_SE","ALICE::GSI::SE"); TGrid * alien = TGrid::Connect("alien://",0,0,"t"); gSystem->Setenv("alien_CLOSE_SE","ALICE::GSI::SE"); } // // Train Configuration // Int_t iPWG1perfTPC = 1; // Test TPC performance Int_t iPWG1perfTRD = 0; // Test TRD performance Int_t iPWG1perfITS = 0; // Test ITS performance Int_t iPWG1perfCalo = 0; // Test Calo performance Int_t iPWG1perfMuonTrig = 0; // Test Muon Trigger performance Int_t iPWG1perfMuonEff = 0; // Test Muon Efficiency performance Int_t iPWG1perfTOF = 0; // Test TOF-TPC matching performance Int_t iPWG1perfPrimVertex = 0; // Test Primary Vertex performance Int_t iPWG1v0QA = 0; // V0 algorithm QA task // // Load Libraries // gSystem->Load("libANALYSIS"); gSystem->Load("libANALYSISalice"); gSystem->Load("libTENDER"); gSystem->Load("libCORRFW"); gSystem->Load("libTPCcalib.so"); gSystem->Load("libPWG1"); gSystem->Load("libPHOSUtils"); gSystem->Load("libEMCALUtils"); gSystem->Load("libPWG4PartCorrBase"); gSystem->Load("libPWG4PartCorrDep"); gSystem->Load("libPWG3muon.so"); // The class is here // // OCDB Configuration // AliCDBManager *cdbManager = AliCDBManager::Instance(); cdbManager->SetDefaultStorage("local://$ALICE_ROOT/OCDB"); cdbManager->SetSpecificStorage("GRP/GRP/Data", Form("local://%s",gSystem->pwd())); cdbManager->SetRun(0); //cdbManager->SetCacheFlag(kFALSE); // initialize magnetic field from the GRP manager. if(magField==0) TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 0., 0., AliMagF::k2kG)); if(magField==1) TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k2kG)); if(magField==2) TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k5kG)); //AliGRPManager grpMan; //grpMan.ReadGRPEntry(); //grpMan.SetMagField(); //AliRunInfo *runInfo = grpMan.GetRunInfo(); // // Load geometry // AliGeomManager::LoadGeometry(); // // Swtich off all AliInfo (too much output!) // AliLog::SetGlobalLogLevel(AliLog::kError); // // Create input ESD chain // /* gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C"); TChain* chain = CreateESDChain(list,nFiles,fistFile); if(!chain) { Error("RunPerformanceTrain","ESD chain not created!"); return; } */ TChain *chain = new TChain("esdTree"); if(!chain) { Error("RunPerformanceTrain","ESD chain not created!"); return; } chain->Add(file); chain->Lookup(); // // Create analysis manager // AliAnalysisManager *mgr = new AliAnalysisManager; if(!mgr) { Error("RunPerformanceTrain","AliAnalysisManager not set!"); return; } // // Set ESD input handler // AliESDInputHandler* esdH = new AliESDInputHandler; if(!esdH) { Error("RunPerformanceTrain","AliESDInputHandler not created!"); return; } if(bUseESDfriend) esdH->SetActiveBranches("ESDfriend"); mgr->SetInputEventHandler(esdH); /* // // Set RecPoints and ESD input handler // AliESDInputHandlerRP* rpH = new AliESDInputHandlerRP; if(!rpH) { Error("RunPerformanceTrain","AliESDInputHandlerRP not created!"); return; } if(bUseESDfriend) rpH->SetActiveBranches("ESDfriend"); mgr->SetInputEventHandler(rpH); */ // // Set MC input handler // if(bUseMCInfo) { AliMCEventHandler* mcH = new AliMCEventHandler; if(!mcH) { Error("RunPerformanceTrain","AliMCEventHandler not created!"); return; } mcH->SetReadTR(kTRUE); mgr->SetMCtruthEventHandler(mcH); } // // Add task to AliAnalysisManager // // // TPC performance // if(iPWG1perfTPC) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskPerformanceTPC.C"); AliPerformanceTask *tpcQA = AddTaskPerformanceTPC(bUseMCInfo,bUseESDfriend); if(!tpcQA) { Error("RunPerformanceTrain","AliPerformanceTask not created!"); return; } } else { Printf("RunPerformanceTrain: TPC Performance - EXCLUDED!"); } // // TRD perormance // if(iPWG1perfTRD) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTrainPerformanceTRD.C"); if(!AddTrainPerformanceTRD(bUseMCInfo,bUseESDfriend)) { Error("RunPerformanceTrain","TrainPerformanceTRD not created!"); return; } } else { Printf("RunPerformanceTrain: TRD TrainPerformanceTRD - EXCLUDED!"); } // // ITS performance // if(iPWG1perfITS) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskPerformanceITS.C"); AliAnalysisTaskITSTrackingCheck *itsQA = AddTaskPerformanceITS(bUseMCInfo); if(!itsQA) { Error("RunPerformanceTrain","AliAnalysisTaskITSTrackingCheck not created!"); return; } } else { Printf("RunPerformanceTrain: AliAnalysisTaskITSTrackingCheck - EXCLUDED!"); } // // Calorimeter Performance // if(iPWG1perfCalo) { gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCalorimeterQA.C"); AliAnalysisTaskParticleCorrelation *taskCaloQA = AddTaskCalorimeterQA("ESD",bUseMCInfo,kFALSE); if(!taskCaloQA) { Error("RunPerformanceTrain","AliAnalysisTaskParticleCorrelation not created!"); return; } mgr->AddTask(taskCaloQA); } else { Printf("RunPerformanceTrain: AliAnalysisTaskParticleCorrelation - EXCLUDED!"); } // // Muon Trigger // if(iPWG1perfMuonTrig) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskMTRchamberEfficiency.C"); AliAnalysisTaskTrigChEff *taskMuonTrig = AddTaskMTRchamberEfficiency(); if(!taskMuonTrig) { Error("RunPerformanceTrain","AliAnalysisTaskTrigChEff not created!"); return; } mgr->AddTask(taskMuonTrig); } else { Printf("RunPerformanceTrain: AliAnalysisTaskTrigChEff - EXCLUDED!"); } // // Muon Efficiency // if(iPWG1perfMuonEff) { // } else { Printf("RunPerformanceTrain: Muon Efficiency - EXCLUDED!"); } // // TOF performance // if(iPWG1perfTOF) { // } else { Printf("RunPerformanceTrain: TOF - EXCLUDED!"); } // // PWG1 Primary Vertex // if(iPWG1perfPrimVertex) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskVertexESD.C"); AliAnalysisTaskVertexESD *taskPrimVertex = AddTaskVertexESD(); if(!taskPrimVertex) { Error("RunPerformanceTrain","AliAnalysisTaskVertexESD not created!"); return; } } else { Printf("RunPerformanceTrain: AliAnalysisTaskVertexESD - EXCLUDED!"); } // // PWG1 V0 QA // if (iPWG1v0QA) { gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskV0QA.C"); AliAnalysisTaskV0QA *taskv0QA = AddTaskV0QA(bUseMCInfo); if(!taskv0QA) { Error("RunPerformanceTrain","AliAnalysisTaskV0QA not created!"); return; } } else { Printf("RunPerformanceTrain: AliAnalysisTaskV0QA - EXCLUDED!"); } // // Disable debug printouts // mgr->SetDebugLevel(0); if (!mgr->InitAnalysis()) return; mgr->PrintStatus(); //mgr->StartAnalysis("local",chain, nEvents, firstEvent); mgr->StartAnalysis("local",chain); } <|endoftext|>
<commit_before>// // PROJECT CHRONO - http://projectchrono.org // // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // test the drive chain system. // // Author: Justin Madsen, 2015 /////////////////////////////////////////////////// #include "physics/ChSystem.h" // #include "particlefactory/ChParticleEmitter.h" #include "core/ChFileutils.h" #include "core/ChStream.h" #include "core/ChRealtimeStep.h" #include "physics/ChSystem.h" #include "physics/ChLinkDistance.h" #include "physics/ChBodyEasy.h" #include "utils/ChUtilsInputOutput.h" #include "utils/ChUtilsData.h" #include "assets/ChTexture.h" #include "assets/ChColorAsset.h" /* #if IRRLICHT_ENABLED */ #include "unit_IRRLICHT/ChIrrApp.h" #include "subsys/driver/ChIrrGuiTrack.h" // Use the main namespaces of Irrlicht using namespace irr; using namespace core; /* # define USE_IRRLICHT #endif */ #include "subsys/trackVehicle/DriveChain.h" #include "ModelDefs.h" // Use the main namespace of Chrono using namespace chrono; // ============================================================================= // User Settings // ============================================================================= // display the 1) system heirarchy, 2) a set of subsystem hardpoints, 3) constraint violations #define DEBUG_LOG // Initial vehicle position and heading. Defines the REF frame for the hull body ChVector<> initLoc(0, 1.0, 0); //ChQuaternion<> initRot = Q_from_AngAxis(CH_C_PI_4, VECT_Y); ChQuaternion<> initRot(QUNIT); // Simulation step size double step_size = 0.001; // Time interval between two render frames int FPS = 40; double render_step_size = 1.0 / FPS; // FPS = 50 // Time interval between two output frames double output_step_size = 1.0 / 1; // once a second // #ifdef USE_IRRLICHT // Point on chassis tracked by the camera double chaseDist = 3.0; double chaseHeight = 0.0; ChVector<> trackPoint(0, 0, 0); /* #else double tend = 20.0; const std::string out_dir = "../test_driveChain"; const std::string pov_dir = out_dir + "/POVRAY"; #endif */ int main(int argc, char* argv[]) { // NOTE: utils library built with this sets this statically // SetChronoDataPath(CHRONO_DATA_DIR); // -------------------------- // Create the Chain system (drive gear, idler, chain) // The drive chain inherits ChSystem. DriveChain chainSystem("Justins driveChain system", VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES); // set the chassis REF at the specified initial config. chainSystem.Initialize(ChCoordsys<>(initLoc, initRot)); /* #ifdef USE_IRRLICHT */ // -------------------------- // Setup the Irrlicht GUI // Create the Irrlicht visualization applicaiton bool do_shadows = false; // shadow map is experimental ChIrrApp application(chainSystem.GetSystem(), L"test driveChain demo", dimension2d<u32>(1000, 800), false, do_shadows); // assumes Y-up application.AddTypicalSky(); irr::scene::ILightSceneNode* mlight = 0; if (do_shadows) { mlight = application.AddLightWithShadow( irr::core::vector3df(10.f, 60.f, 30.f), irr::core::vector3df(0.f, 0.f, 0.f), 150, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false); } else { application.AddTypicalLights( irr::core::vector3df(30.f, 100.f, 30.f), irr::core::vector3df(30.f, 100.f, 50.f), 250, 130); } application.SetTimestep(step_size); // the GUI driver ChIrrGuiTrack driver(application, chainSystem, trackPoint, chaseDist, chaseHeight); // Set the time response for steering and throttle keyboard inputs. // NOTE: this is not exact, since we do not render quite at the specified FPS. double throttle_time = 1.0; // time to go from 0 to +1 double braking_time = 0.3; // time to go from 0 to +1 // driver.SetSteeringDelta(render_step_size / 1); driver.SetThrottleDelta(render_step_size / throttle_time); driver.SetBrakingDelta(render_step_size / braking_time); // Set up the assets for rendering application.AssetBindAll(); application.AssetUpdateAll(); if (do_shadows) { application.AddShadowAll(); } /* #else Track_FuncDriver driver; #endif */ // --------------------- // GUI and render settings // GUI driver inputs std::vector<double> throttle_input; std::vector<double> braking_input; // Number of simulation steps between two 3D view render frames int render_steps = (int)std::ceil(render_step_size / step_size); // Number of simulation steps between two output frames int output_steps = (int)std::ceil(output_step_size / step_size); // --------------------- // Simulation loop #ifdef DEBUG_LOG GetLog() << "\n\n============ System Configuration ============\n"; chainSystem.GetSystem()->ShowHierarchy(GetLog() ); #endif // Initialize simulation frame counter and simulation time int step_number = 0; double time = 0; /* #ifdef USE_IRRLICHT */ ChRealtimeStepTimer realtime_timer; while (application.GetDevice()->run()) { // keep track of the time spent calculating each sim step ChTimer<double> step_time; step_time.start(); // Render scene if (step_number % render_steps == 0) { application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192)); driver.DrawAll(); application.GetVideoDriver()->endScene(); } // Collect output data from modules (for inter-module communication) throttle_input = driver.GetThrottle(); braking_input = driver.GetBraking(); // Update time = chainSystem.GetSystem()->GetChTime(); driver.Update(time); chainSystem.Update(time, throttle_input[0], braking_input[0]); // Advance simulation for one timestep for all modules // double step = realtime_timer.SuggestSimulationStep(step_size); driver.Advance(step_size); // SETTLING FOLLOWED BY NORMAL OPERATION STEP SIZES HARDCODED // 1e-5 and 1e-4, respectively chainSystem.Advance(step_size); step_number++; } application.GetDevice()->drop(); /* #else int render_frame = 0; if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) { std::cout << "Error creating directory " << pov_dir << std::endl; return 1; } chainSystem.ExportMeshPovray(out_dir); char filename[100]; while (time < tend) { if (step_number % render_steps == 0) { // Output render data sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1); utils::WriteShapesPovray(chainSystem.GetSystem(), filename); std::cout << "Output frame: " << render_frame << std::endl; std::cout << "Sim frame: " << step_number << std::endl; std::cout << "Time: " << time << std::endl; std::cout << " throttle: " << driver.GetThrottle() << " braking: " << driver.GetBraking() << std::endl; std::cout << std::endl; render_frame++; } // Collect output data from modules (for inter-module communication) throttle_input = driver.GetThrottle(); braking_input = driver.GetBraking(); // Update modules (process inputs from other modules) time = chainSystem.GetSystem()->GetChTime(); driver.Update(time); chainSystem.Update(time, throttle_input, braking_input); // Advance simulation for one timestep for all modules driver.Advance(step_size); chainSystem.Advance(step_size); // Increment frame number step_number++; } #endif */ return 0; } <commit_msg>use the manual camera position update, to keep a side-view of the chain.<commit_after>// // PROJECT CHRONO - http://projectchrono.org // // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // test the drive chain system. // // Author: Justin Madsen, 2015 /////////////////////////////////////////////////// #include "physics/ChSystem.h" // #include "particlefactory/ChParticleEmitter.h" #include "core/ChFileutils.h" #include "core/ChStream.h" #include "core/ChRealtimeStep.h" #include "physics/ChSystem.h" #include "physics/ChLinkDistance.h" #include "physics/ChBodyEasy.h" #include "utils/ChUtilsInputOutput.h" #include "utils/ChUtilsData.h" #include "assets/ChTexture.h" #include "assets/ChColorAsset.h" /* #if IRRLICHT_ENABLED */ #include "unit_IRRLICHT/ChIrrApp.h" #include "subsys/driver/ChIrrGuiTrack.h" // Use the main namespaces of Irrlicht using namespace irr; using namespace core; /* # define USE_IRRLICHT #endif */ #include "subsys/trackVehicle/DriveChain.h" #include "ModelDefs.h" // Use the main namespace of Chrono using namespace chrono; // ============================================================================= // User Settings // ============================================================================= // display the 1) system heirarchy, 2) a set of subsystem hardpoints, 3) constraint violations #define DEBUG_LOG // Initial vehicle position and heading. Defines the REF frame for the hull body ChVector<> initLoc(0, 1.0, 0); //ChQuaternion<> initRot = Q_from_AngAxis(CH_C_PI_4, VECT_Y); ChQuaternion<> initRot(QUNIT); // Simulation step size double step_size = 0.001; // Time interval between two render frames int FPS = 40; double render_step_size = 1.0 / FPS; // FPS = 50 // Time interval between two output frames double output_step_size = 1.0 / 1; // once a second // #ifdef USE_IRRLICHT // Point on chassis tracked by the camera ChVector<> trackPoint(-0.5, 0, 0); // if chase cam enabled: double chaseDist = 3.0; double chaseHeight = 0.0; // set a static camera position ChVector<> cameraPos(-0.5, 1.25, 2); /* #else double tend = 20.0; const std::string out_dir = "../test_driveChain"; const std::string pov_dir = out_dir + "/POVRAY"; #endif */ int main(int argc, char* argv[]) { // NOTE: utils library built with this sets this statically // SetChronoDataPath(CHRONO_DATA_DIR); // -------------------------- // Create the Chain system (drive gear, idler, chain) // The drive chain inherits ChSystem. DriveChain chainSystem("Justins driveChain system", VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES); // set the chassis REF at the specified initial config. chainSystem.Initialize(ChCoordsys<>(initLoc, initRot)); /* #ifdef USE_IRRLICHT */ // -------------------------- // Setup the Irrlicht GUI // Create the Irrlicht visualization applicaiton bool do_shadows = false; // shadow map is experimental ChIrrApp application(chainSystem.GetSystem(), L"test driveChain demo", dimension2d<u32>(1000, 800), false, do_shadows); // assumes Y-up application.AddTypicalSky(); irr::scene::ILightSceneNode* mlight = 0; if (do_shadows) { mlight = application.AddLightWithShadow( irr::core::vector3df(10.f, 60.f, 30.f), irr::core::vector3df(0.f, 0.f, 0.f), 150, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false); } else { application.AddTypicalLights( irr::core::vector3df(30.f, 100.f, 30.f), irr::core::vector3df(30.f, 100.f, 50.f), 250, 130); } application.SetTimestep(step_size); // the GUI driver ChIrrGuiTrack driver(application, chainSystem, trackPoint, chaseDist, chaseHeight); // even though using a chase camera, set the initial camera position laterally driver.SetCameraPos(cameraPos); // Set the time response for steering and throttle keyboard inputs. // NOTE: this is not exact, since we do not render quite at the specified FPS. double throttle_time = 1.0; // time to go from 0 to +1 double braking_time = 0.3; // time to go from 0 to +1 // driver.SetSteeringDelta(render_step_size / 1); driver.SetThrottleDelta(render_step_size / throttle_time); driver.SetBrakingDelta(render_step_size / braking_time); // Set up the assets for rendering application.AssetBindAll(); application.AssetUpdateAll(); if (do_shadows) { application.AddShadowAll(); } /* #else Track_FuncDriver driver; #endif */ // --------------------- // GUI and render settings // GUI driver inputs std::vector<double> throttle_input; std::vector<double> braking_input; // Number of simulation steps between two 3D view render frames int render_steps = (int)std::ceil(render_step_size / step_size); // Number of simulation steps between two output frames int output_steps = (int)std::ceil(output_step_size / step_size); // --------------------- // Simulation loop #ifdef DEBUG_LOG GetLog() << "\n\n============ System Configuration ============\n"; chainSystem.GetSystem()->ShowHierarchy(GetLog() ); #endif // Initialize simulation frame counter and simulation time int step_number = 0; double time = 0; /* #ifdef USE_IRRLICHT */ ChRealtimeStepTimer realtime_timer; while (application.GetDevice()->run()) { // keep track of the time spent calculating each sim step ChTimer<double> step_time; step_time.start(); // Render scene if (step_number % render_steps == 0) { application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192)); driver.DrawAll(); application.GetVideoDriver()->endScene(); } // Collect output data from modules (for inter-module communication) throttle_input = driver.GetThrottle(); braking_input = driver.GetBraking(); // Update time = chainSystem.GetSystem()->GetChTime(); driver.Update(time); chainSystem.Update(time, throttle_input[0], braking_input[0]); // Advance simulation for one timestep for all modules // double step = realtime_timer.SuggestSimulationStep(step_size); driver.Advance(step_size, cameraPos); // SETTLING FOLLOWED BY NORMAL OPERATION STEP SIZES HARDCODED // 1e-5 and 1e-4, respectively // application.SetPaused(true); if( !application.GetPaused() ) chainSystem.Advance(step_size); step_number++; } application.GetDevice()->drop(); /* #else int render_frame = 0; if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) { std::cout << "Error creating directory " << pov_dir << std::endl; return 1; } chainSystem.ExportMeshPovray(out_dir); char filename[100]; while (time < tend) { if (step_number % render_steps == 0) { // Output render data sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1); utils::WriteShapesPovray(chainSystem.GetSystem(), filename); std::cout << "Output frame: " << render_frame << std::endl; std::cout << "Sim frame: " << step_number << std::endl; std::cout << "Time: " << time << std::endl; std::cout << " throttle: " << driver.GetThrottle() << " braking: " << driver.GetBraking() << std::endl; std::cout << std::endl; render_frame++; } // Collect output data from modules (for inter-module communication) throttle_input = driver.GetThrottle(); braking_input = driver.GetBraking(); // Update modules (process inputs from other modules) time = chainSystem.GetSystem()->GetChTime(); driver.Update(time); chainSystem.Update(time, throttle_input, braking_input); // Advance simulation for one timestep for all modules driver.Advance(step_size); chainSystem.Advance(step_size); // Increment frame number step_number++; } #endif */ return 0; } <|endoftext|>
<commit_before>#include "lua_tile.h" extern "C" { # include <lua/src/lua.h> # include <lua/src/lauxlib.h> # include <lua/src/lualib.h> } #include <lua/lua_state.h> using namespace am::lua; #include <game/tile.h> #include <game/tile_type.h> #include <game/engine.h> using namespace am::game; #include <util/json_value.h> using namespace am::util; #include "lua_tile_type.h" #include "lua_tile_set.h" namespace am { namespace lua { namespace game { /** * @class * The Tile class represents a single tile and all the properties of that tile. * Tiles are added to maps via the TileInstance class. Each tile stores their graphic * tile type list, name, description and the tile set which this tile is apart of. */ /** * Creates a new tile object with the given name, the name need only be unique within its tile set. * Until a full name is specified, the tile full name is "No full name" * * @param stringname The name of the tile. */ /** * Creates a new tile object with the given name and full name, * the name need only be unique within its tile set. * Full name differs in that it is the name that is presented to the user. * * @param string name The name of the tile. * @param string description The description of the tile. */ int Tile_ctor(lua_State *lua) { int args = lua_gettop(lua); if (args == 1 && lua_isstring(lua, -1)) { Tile *tile = new Tile(lua_tostring(lua, -1)); wrapRefObject<Tile>(lua, tile); return 1; } else if (args == 2 && lua_isstring(lua, -2) && lua_isstring(lua, -1)) { Tile *tile = new Tile(lua_tostring(lua, -2), lua_tostring(lua, -1)); wrapRefObject<Tile>(lua, tile); return 1; } lua_pushnil(lua); return 1; } /** * Release the reference count on this tile. */ int Tile_dtor(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { tile->release(); } return 0; } /** * Compares this tile against another tile object. * * @param Tile rhs The other tile to compare with. * @returns boolean True if they are the same tile object. */ int Tile_eq(lua_State *lua) { Tile *lhs = castUData<Tile>(lua, 1); Tile *rhs = castUData<Tile>(lua, 2); lua_pushboolean(lua, lhs == rhs); return 1; } int Tile_register(lua_State *lua) { luaL_Reg regs[] = { { "new", Tile_ctor }, { "__gc", Tile_dtor }, { "__eq", Tile_eq }, { "name", Tile_name }, { "full_name", Tile_full_name }, { "description", Tile_description }, { "tile_set", Tile_tile_set }, { "add_tile_type", Tile_add_tile_type }, { "remove_tile_type", Tile_remove_tile_type }, { "remove_all_tile_types", Tile_remove_all_tile_types }, { "has_tile_type", Tile_has_tile_type }, { "tile_types", Tile_tile_types }, { "load_def", Tile_load_def }, { NULL, NULL } }; luaL_newmetatable(lua, Tile::LUA_TABLENAME); luaL_setfuncs(lua, regs, 0); lua_pushvalue(lua, -1); lua_setfield(lua, -1, "__index"); return 1; } /** * Returns the tile name. * * @returns string The name of the tile. */ /** * Sets the name of the tile. * If there already exists a tile with the same name, it will be overridden * by this tile if the 'checkForExisting' argument is not true. * * @param string name The new name for this tile. * @param boolean [false] checkForExisting When true the name will be not changed if there * is already a tile with the same name in the tile's tile set. * @returns boolean True if the tile's name was changed. */ int Tile_name(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { int args = lua_gettop(lua); if (args == 1) { lua_pushstring(lua, tile->getName().c_str()); return 1; } else if (lua_isstring(lua, 2)) { bool checkForExisting = false; if (args >= 3) { checkForExisting = lua_tobool(lua, 3); } if (checkForExisting) { lua_pushboolean(lua, tile->setNameWithCheck(lua_tostring(lua, -1))); return 1; } tile->setName(lua_tostring(lua, -1)); lua_pushboolean(lua, 1); return 1; } } lua_pushnil(lua); return 1; } /** * Returns the full name of this tile, this is used to display the tile's name to the user. * * @returns string The tiles full name. */ /** * Sets the tile's full name, this is used to display the tile's name to the user. * * @param string fullName The tile's new full name. * @returns Tile This */ int Tile_full_name(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { if (lua_gettop(lua) == 1) { lua_pushstring(lua, tile->getFullName().c_str()); return 1; } else if (lua_isstring(lua, -1)) { tile->setFullName(lua_tostring(lua, -1)); lua_first(lua); } } lua_pushnil(lua); return 1; } /** * Returns the description for this tile. * * @returns string The tiles description. */ /** * Sets the tile's description. * * @param string description The tile's description. * @returns Tile This */ int Tile_description(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { if (lua_gettop(lua) == 1) { lua_pushstring(lua, tile->getDescription().c_str()); return 1; } else if (lua_isstring(lua, -1)) { tile->setDescription(lua_tostring(lua, -1)); lua_first(lua); } } lua_pushnil(lua); return 1; } /** * Returns the tile set that this tile is apart of, nil will be return if it is not part of a tile set. * * @returns TileSet The tile's tile set, or nil if it does not have one. */ /** * Sets and adds the tile to the given tile set. * Any tile with the same name in the tile set will be overridden by this tile. * Unless the 'checkForExisting' argument is set to true, then if the tileset already has * a tile with the same name then tile set is not changed. * * @param TileSet set The tile set to add to, can be nil. * @param boolean [false] checkForExisting When true the tile set will not be changed if it * already has a tile with the same name. * @returns boolean True if the tile set was changed. */ int Tile_tile_set(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { int args = lua_gettop(lua); if (args == 1) { if (tile->getTileSet()) { wrapRefObject<TileSet>(lua, tile->getTileSet()); return 1; } } else { TileSet *set = castUData<TileSet>(lua, 2); // If a non-nil tile set has been passed in. if (set) { bool withCheck = false; if (args == 3) { withCheck = lua_tobool(lua, 3); } // Checking for existing tiles with the same name. if (withCheck) { if (set->addTileWithCheck(tile)) { tile->setTileSet(set); lua_pushboolean(lua, 1); return 1; } lua_pushboolean(lua, 0); return 1; } // Just replace any tile with the same name. else { tile->setTileSet(set); set->addTile(tile); lua_pushboolean(lua, 1); return 1; } } // The given tile set was nil, so there's nothing to check. else { tile->setTileSet(set); lua_pushboolean(lua, 1); return 1; } } } lua_pushnil(lua); return 1; } /** * Adds a tile type to the list of tile types. * If a type is already in the list, it will be ignored. * * @param TileType tileType The tile type to add to the list. * @returns Tile This */ /** * Adds a tile type to the list of tile types. * If a type is already in the list, it will be ignored. * * @param string tileTypeName The name of the tile type to add to the list. * @returns Tile This */ int Tile_add_tile_type(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { TileType *tileType = getTileType(lua, -1); if (tileType) { tile->addTileType(tileType); } lua_first(lua); } lua_pushnil(lua); return 1; } /** * Removes a tile type from the list of tile types. * If a type is not in the list, it will be ignored. * * @param TileType tileType The tile type to remove from the list. * @returns Tile This */ /** * Removes a tile type from the list of tile types. * If a type is not in the list, it will be ignored. * * @param string tileTypeName The name of the tile type to remove from the list. * @returns Tile This */ int Tile_remove_tile_type(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { TileType *tileType = getTileType(lua, -1); if (tileType) { tile->removeTileType(tileType); } lua_first(lua); } lua_pushnil(lua); return 1; } /** * Removes all tile types from this tiles list of tile types. * * @returns Tile This */ int Tile_remove_all_tile_types(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { tile->removeAllTileTypes(); lua_first(lua); } lua_pushnil(lua); return 1; } /** * Returns true if the given tile type is in the list of tile types. * * @param TileType tileType The tile type to check for. * @returns boolean True if the given tile type is in the list. */ /** * Returns true if the given tile type is in the list of tile types. * * @param string tileTypeName The name of tile type to check for. * @returns boolean True if the given tile type is in the list. */ int Tile_has_tile_type(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { TileType *tileType = getTileType(lua, -1); if (tileType) { lua_pushboolean(lua, tile->hasTileType(tileType)); return 1; } } lua_pushnil(lua); return 1; } /** * Returns an array of all the tile types in this tiles list of tile tpyes. * * <pre> * Tile, TileType = import("Tile", "TileType") * tile = Tile.new("swamp") * land = TileType.new("land") * water = TileType.new("water") * tile:add_tile_type(land) * tile:add_tile_type(water) * * types = tile:tile_types() * am_log("Type 1: " .. types[1]:name()") -- Outputs "Type 1: land" * am_log("Type 2: " .. types[2]:name()") -- Outputs "Type 2: wayer" * </pre> * * @returns Array The array of all the tile types on this tile. */ int Tile_tile_types(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { LuaState L(lua); L.newTable(); auto types = tile->getTileTypes(); int i = 1; for (auto iter = types.begin(); iter != types.end(); ++iter) { //L.setTableValue("name", (*iter)->getName()); wrapObject<TileType>(lua, *iter); lua_rawseti(lua, -2, i++); } return 1; } lua_pushnil(lua); return 1; } /** * @private * TODO */ int Tile_load_def(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile && lua_istable(lua, -1)) { LuaState wrap(lua); tile->loadDef(wrap); } return 0; } TileType *getTileType(lua_State *lua, int n) { TileType *tileType = NULL; if (lua_isstring(lua, n)) { tileType = Engine::getEngine()->getTileType(lua_tostring(lua, n)); } else { tileType = castUData<TileType>(lua, n); } return tileType; } } } } <commit_msg>- Added error checking for Tile Lua wrapper.<commit_after>#include "lua_tile.h" extern "C" { # include <lua/src/lua.h> # include <lua/src/lauxlib.h> # include <lua/src/lualib.h> } #include <lua/lua_state.h> using namespace am::lua; #include <game/tile.h> #include <game/tile_type.h> #include <game/engine.h> using namespace am::game; #include <util/json_value.h> using namespace am::util; #include "lua_tile_type.h" #include "lua_tile_set.h" namespace am { namespace lua { namespace game { /** * @class * The Tile class represents a single tile and all the properties of that tile. * Tiles are added to maps via the TileInstance class. Each tile stores their graphic * tile type list, name, description and the tile set which this tile is apart of. */ /** * Creates a new tile object with the given name, the name need only be unique within its tile set. * Until a full name is specified, the tile full name is "No full name" * * @param stringname The name of the tile. */ /** * Creates a new tile object with the given name and full name, * the name need only be unique within its tile set. * Full name differs in that it is the name that is presented to the user. * * @param string name The name of the tile. * @param string fullName The full name of the tile. */ int Tile_ctor(lua_State *lua) { int args = lua_gettop(lua); if (args == 1 && lua_isstr(lua, 1)) { Tile *tile = new Tile(lua_tostring(lua, 1)); wrapRefObject<Tile>(lua, tile); return 1; } else if (args == 2 && lua_isstr(lua, 1) && lua_isstr(lua, 2)) { Tile *tile = new Tile(lua_tostring(lua, 1), lua_tostring(lua, 2)); wrapRefObject<Tile>(lua, tile); return 1; } return LuaState::expectedArgs(lua, "@new", 2, "string name", "string name, string fullName"); } /** * Release the reference count on this tile. */ int Tile_dtor(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { tile->release(); return 0; } return LuaState::expectedContext(lua, "__gc", "Tile"); } /** * Compares this tile against another tile object. * * @param Tile rhs The other tile to compare with. * @returns boolean True if they are the same tile object. */ int Tile_eq(lua_State *lua) { Tile *lhs = castUData<Tile>(lua, 1); Tile *rhs = castUData<Tile>(lua, 2); lua_pushboolean(lua, lhs == rhs); return 1; } int Tile_register(lua_State *lua) { luaL_Reg regs[] = { { "new", Tile_ctor }, { "__gc", Tile_dtor }, { "__eq", Tile_eq }, { "name", Tile_name }, { "full_name", Tile_full_name }, { "description", Tile_description }, { "tile_set", Tile_tile_set }, { "add_tile_type", Tile_add_tile_type }, { "remove_tile_type", Tile_remove_tile_type }, { "remove_all_tile_types", Tile_remove_all_tile_types }, { "has_tile_type", Tile_has_tile_type }, { "tile_types", Tile_tile_types }, { "load_def", Tile_load_def }, { NULL, NULL } }; luaL_newmetatable(lua, Tile::LUA_TABLENAME); luaL_setfuncs(lua, regs, 0); lua_pushvalue(lua, -1); lua_setfield(lua, -1, "__index"); return 1; } /** * Returns the tile name. * * @returns string The name of the tile. */ /** * Sets the name of the tile. * If there already exists a tile with the same name, it will be overridden * by this tile if the 'checkForExisting' argument is not true. * * @param string name The new name for this tile. * @param boolean [false] checkForExisting When true the name will be not changed if there * is already a tile with the same name in the tile's tile set. * @returns boolean True if the tile's name was changed. */ int Tile_name(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { int args = lua_gettop(lua); if (args == 1) { lua_pushstring(lua, tile->getName().c_str()); return 1; } else if (lua_isstr(lua, 2)) { bool checkForExisting = false; bool valid = true; if (args >= 3) { if (lua_isbool(lua, 3)) { checkForExisting = lua_tobool(lua, 3); } else { valid = false; } } if (checkForExisting) { lua_pushboolean(lua, tile->setNameWithCheck(lua_tostring(lua, 2))); return 1; } if (valid) { tile->setName(lua_tostring(lua, 2)); lua_pushboolean(lua, 1); return 1; } } return LuaState::expectedArgs(lua, "name", "string name, boolean [false] checkForExisting"); } return LuaState::expectedContext(lua, "name", "Tile"); } /** * Returns the full name of this tile, this is used to display the tile's name to the user. * * @returns string The tiles full name. */ /** * Sets the tile's full name, this is used to display the tile's name to the user. * * @param string fullName The tile's new full name. * @returns Tile This */ int Tile_full_name(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { if (lua_gettop(lua) == 1) { lua_pushstring(lua, tile->getFullName().c_str()); return 1; } else if (lua_isstr(lua, 2)) { tile->setFullName(lua_tostring(lua, 2)); lua_first(lua); } return LuaState::expectedArgs(lua, "full_name", "string fullName"); } return LuaState::expectedContext(lua, "full_name", "Tile"); } /** * Returns the description for this tile. * * @returns string The tiles description. */ /** * Sets the tile's description. * * @param string description The tile's description. * @returns Tile This */ int Tile_description(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { if (lua_gettop(lua) == 1) { lua_pushstring(lua, tile->getDescription().c_str()); return 1; } else if (lua_isstr(lua, 2)) { tile->setDescription(lua_tostring(lua, 2)); lua_first(lua); } return LuaState::expectedArgs(lua, "description", "string description"); } return LuaState::expectedContext(lua, "description", "Tile"); } /** * Returns the tile set that this tile is apart of, nil will be return if it is not part of a tile set. * * @returns TileSet The tile's tile set, or nil if it does not have one. */ /** * Sets and adds the tile to the given tile set. * Any tile with the same name in the tile set will be overridden by this tile. * Unless the 'checkForExisting' argument is set to true, then if the tileset already has * a tile with the same name then tile set is not changed. * * @param TileSet set The tile set to add to, can be nil. * @param boolean [false] checkForExisting When true the tile set will not be changed if it * already has a tile with the same name. * @returns boolean True if the tile set was changed. */ int Tile_tile_set(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { int args = lua_gettop(lua); if (args == 1) { if (tile->getTileSet()) { wrapRefObject<TileSet>(lua, tile->getTileSet()); return 1; } lua_pushnil(lua); return 1; } else { TileSet *set = castUData<TileSet>(lua, 2); // If a non-nil tile set has been passed in. if (set) { bool withCheck = false; if (args == 3) { withCheck = lua_tobool(lua, 3); } // Checking for existing tiles with the same name. if (withCheck) { if (set->addTileWithCheck(tile)) { tile->setTileSet(set); lua_pushboolean(lua, 1); return 1; } lua_pushboolean(lua, 0); return 1; } // Just replace any tile with the same name. else { tile->setTileSet(set); set->addTile(tile); lua_pushboolean(lua, 1); return 1; } } // The given tile set was nil, so there's nothing to check. else { tile->setTileSet(set); lua_pushboolean(lua, 1); return 1; } } return LuaState::expectedArgs(lua, "tile_set", "TileSet tileSet, boolean [false] checkForExisting"); } return LuaState::expectedContext(lua, "tile_set", "Tile"); } /** * Adds a tile type to the list of tile types. * If a type is already in the list, it will be ignored. * * @param TileType tileType The tile type to add to the list. * @returns Tile This */ /** * Adds a tile type to the list of tile types. * If a type is already in the list, it will be ignored. * * @param string tileTypeName The name of the tile type to add to the list. * @returns Tile This */ int Tile_add_tile_type(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { TileType *tileType = getTileType(lua, 2); if (tileType) { tile->addTileType(tileType); lua_first(lua); } return LuaState::expectedArgs(lua, "add_tile_type", 2, "TileType tileType", "string tileTypeName"); } return LuaState::expectedContext(lua, "add_tile_type", "Tile"); } /** * Removes a tile type from the list of tile types. * If a type is not in the list, it will be ignored. * * @param TileType tileType The tile type to remove from the list. * @returns Tile This */ /** * Removes a tile type from the list of tile types. * If a type is not in the list, it will be ignored. * * @param string tileTypeName The name of the tile type to remove from the list. * @returns Tile This */ int Tile_remove_tile_type(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { TileType *tileType = getTileType(lua, 2); if (tileType) { tile->removeTileType(tileType); lua_first(lua); } return LuaState::expectedArgs(lua, "remove_tile_type", 2, "TileType tileType", "string tileTypeName"); } return LuaState::expectedContext(lua, "remove_tile_type", "Tile"); } /** * Removes all tile types from this tiles list of tile types. * * @returns Tile This */ int Tile_remove_all_tile_types(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { tile->removeAllTileTypes(); lua_first(lua); } return LuaState::expectedContext(lua, "remove_all_tile_types", "Tile"); } /** * Returns true if the given tile type is in the list of tile types. * * @param TileType tileType The tile type to check for. * @returns boolean True if the given tile type is in the list. */ /** * Returns true if the given tile type is in the list of tile types. * * @param string tileTypeName The name of tile type to check for. * @returns boolean True if the given tile type is in the list. */ int Tile_has_tile_type(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { TileType *tileType = getTileType(lua, 2); if (tileType) { lua_pushboolean(lua, tile->hasTileType(tileType)); return 1; } return LuaState::expectedArgs(lua, "has_tile_type", 2, "TileType tileType", "string tileTypeName"); } return LuaState::expectedContext(lua, "has_tile_type", "Tile"); } /** * Returns an array of all the tile types in this tiles list of tile tpyes. * * <pre> * Tile, TileType = import("Tile", "TileType") * tile = Tile.new("swamp") * land = TileType.new("land") * water = TileType.new("water") * tile:add_tile_type(land) * tile:add_tile_type(water) * * types = tile:tile_types() * am_log("Type 1: " .. types[1]:name()") -- Outputs "Type 1: land" * am_log("Type 2: " .. types[2]:name()") -- Outputs "Type 2: wayer" * </pre> * * @returns Array The array of all the tile types on this tile. */ int Tile_tile_types(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile) { LuaState L(lua); L.newTable(); auto types = tile->getTileTypes(); int i = 1; for (auto iter = types.begin(); iter != types.end(); ++iter) { wrapObject<TileType>(lua, *iter); lua_rawseti(lua, -2, i++); } return 1; } return LuaState::expectedContext(lua, "tile_types", "Tile"); } /** * @private * TODO */ int Tile_load_def(lua_State *lua) { Tile *tile = castUData<Tile>(lua, 1); if (tile && lua_istable(lua, -1)) { LuaState wrap(lua); tile->loadDef(wrap); } return 0; } TileType *getTileType(lua_State *lua, int n) { TileType *tileType = NULL; if (lua_isstring(lua, n)) { tileType = Engine::getEngine()->getTileType(lua_tostring(lua, n)); } else { tileType = castUData<TileType>(lua, n); } return tileType; } } } } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2012-2013, SimQuest Solutions 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. /// \file /// Tests for the Group class. #include "SurgSim/Graphics/UnitTests/MockObjects.h" #include "SurgSim/Graphics/UnitTests/MockOsgObjects.h" #include "SurgSim/Graphics/OsgGroup.h" #include "gtest/gtest.h" using SurgSim::Graphics::Actor; using SurgSim::Graphics::Group; using SurgSim::Graphics::OsgActor; using SurgSim::Graphics::OsgGroup; TEST(OsgGroupTests, InitTest) { ASSERT_NO_THROW({std::shared_ptr<Group> group = std::make_shared<OsgGroup>("test name");}); } TEST(OsgGroupTests, OsgNodesTest) { std::shared_ptr<OsgGroup> osgGroup = std::make_shared<OsgGroup>("test group"); osg::ref_ptr<osg::Switch> osgSwitch = dynamic_cast<osg::Switch*>(osgGroup->getOsgGroup().get()); ASSERT_TRUE(osgSwitch.valid()) << "Group's OSG node should be a switch!"; } TEST(OsgGroupTests, VisibilityTest) { std::shared_ptr<OsgGroup> osgGroup = std::make_shared<OsgGroup>("test group"); std::shared_ptr<Group> group = osgGroup; EXPECT_TRUE(group->isVisible()); group->setVisible(true); EXPECT_TRUE(group->isVisible()); } TEST(OsgGroupTests, AddRemoveTest) { std::shared_ptr<OsgGroup> osgGroup = std::make_shared<OsgGroup>("test group"); std::shared_ptr<Group> group = osgGroup; EXPECT_EQ(0u, group->getActors().size()); EXPECT_EQ(0u, group->getGroups().size()); osg::ref_ptr<osg::Switch> osgSwitch = dynamic_cast<osg::Switch*>(osgGroup->getOsgGroup().get()); ASSERT_TRUE(osgSwitch.valid()) << "Group's OSG node should be a switch!"; EXPECT_EQ(0u, osgSwitch->getNumChildren()); /// Add an actor and make sure the osg::Switch value for it is set correctly (should be true) std::shared_ptr<OsgActor> actor1 = std::make_shared<MockOsgActor>("test actor 1"); group->addActor(actor1); EXPECT_EQ(1u, group->getActors().size()); EXPECT_EQ(1u, osgSwitch->getNumChildren()); EXPECT_EQ(0u, osgSwitch->getChildIndex(actor1->getOsgNode())); EXPECT_TRUE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should be visible!"; /// Set group to not visible and check the osg::Switch values group->setVisible(false); EXPECT_FALSE(group->isVisible()); EXPECT_FALSE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should not be visible!"; /// Add another actor and make sure the osg::Switch value for it is set correctly (should be false) std::shared_ptr<OsgActor> actor2 = std::make_shared<MockOsgActor>("test actor 2"); group->addActor(actor2); EXPECT_EQ(2u, group->getActors().size()); EXPECT_EQ(2u, osgSwitch->getNumChildren()); EXPECT_EQ(1u, osgSwitch->getChildIndex(actor2->getOsgNode())); EXPECT_FALSE(osgSwitch->getChildValue(actor2->getOsgNode())) << "Actor 2 should not be visible!"; /// Set group to visible and check the osg::Switch values group->setVisible(true); EXPECT_TRUE(group->isVisible()); EXPECT_TRUE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should be visible!"; EXPECT_TRUE(osgSwitch->getChildValue(actor2->getOsgNode())) << "Actor 2 should be visible!"; /// Add a group and make sure the osg::Switch value for it is set correctly (should be true) std::shared_ptr<OsgGroup> subGroup1 = std::make_shared<OsgGroup>("test sub-group 1"); group->addGroup(subGroup1); EXPECT_EQ(1u, group->getGroups().size()); EXPECT_EQ(3u, osgSwitch->getNumChildren()); EXPECT_EQ(2u, osgSwitch->getChildIndex(subGroup1->getOsgGroup())); EXPECT_TRUE(osgSwitch->getChildValue(subGroup1->getOsgGroup())) << "Group 1 should be visible!"; /// Set group to not visible and check the osg::Switch values group->setVisible(false); EXPECT_FALSE(group->isVisible()); EXPECT_FALSE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should not be visible!"; EXPECT_FALSE(osgSwitch->getChildValue(actor2->getOsgNode())) << "Actor 1 should not be visible!"; EXPECT_FALSE(osgSwitch->getChildValue(subGroup1->getOsgGroup())) << "Group 1 should not be visible!"; /// Add another group and make sure the osg::Switch value for it is set correctly (should be false) std::shared_ptr<OsgGroup> subGroup2 = std::make_shared<OsgGroup>("test sub-group 1"); group->addGroup(subGroup2); EXPECT_EQ(2u, group->getGroups().size()); EXPECT_EQ(4u, osgSwitch->getNumChildren()); EXPECT_EQ(3u, osgSwitch->getChildIndex(subGroup2->getOsgGroup())); EXPECT_FALSE(osgSwitch->getChildValue(subGroup2->getOsgGroup())) << "Group 2 should not be visible!"; /// Set group to visible and check the osg::Switch values group->setVisible(true); EXPECT_TRUE(group->isVisible()); EXPECT_TRUE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should be visible!"; EXPECT_TRUE(osgSwitch->getChildValue(actor2->getOsgNode())) << "Actor 2 should be visible!"; EXPECT_TRUE(osgSwitch->getChildValue(subGroup1->getOsgGroup())) << "Group 1 should be visible!"; EXPECT_TRUE(osgSwitch->getChildValue(subGroup2->getOsgGroup())) << "Group 2 should be visible!"; /// Try to add a duplicate actor EXPECT_FALSE(group->addActor(actor1)); EXPECT_EQ(2u, group->getActors().size()); EXPECT_EQ(4u, osgSwitch->getNumChildren()); /// Try to add a duplicate group EXPECT_FALSE(group->addGroup(subGroup2)); EXPECT_EQ(2u, group->getGroups().size()); EXPECT_EQ(4u, osgSwitch->getNumChildren()); /// Remove a group EXPECT_TRUE(group->removeGroup(subGroup2)); EXPECT_EQ(3u, osgSwitch->getNumChildren()); EXPECT_EQ(3u, osgSwitch->getChildIndex(subGroup2->getOsgGroup())); /// Remove an actor EXPECT_TRUE(group->removeActor(actor1)); EXPECT_EQ(2u, osgSwitch->getNumChildren()); EXPECT_EQ(2u, osgSwitch->getChildIndex(actor1->getOsgNode())); /// Try to remove a group that is not in the group EXPECT_FALSE(group->removeGroup(subGroup2)); EXPECT_EQ(2u, osgSwitch->getChildIndex(subGroup2->getOsgGroup())); /// Try to remove an actor that is not in the group EXPECT_FALSE(group->removeActor(actor1)); EXPECT_EQ(2u, osgSwitch->getChildIndex(actor1->getOsgNode())); /// Try to add a non-OSG actor std::shared_ptr<MockActor> nonOsgActor = std::make_shared<MockActor>("non-osg actor"); EXPECT_FALSE(group->addActor(nonOsgActor)) << "OsgGroup should only succeed on actors that derive from OsgActor!"; EXPECT_EQ(1u, group->getActors().size()); EXPECT_EQ(group->getActors().end(), std::find(group->getActors().begin(), group->getActors().end(), nonOsgActor)); EXPECT_EQ(2u, osgSwitch->getNumChildren()); /// Try to add a non-OSG group std::shared_ptr<MockGroup> nonOsgSubgroup = std::make_shared<MockGroup>("non-osg group"); EXPECT_FALSE(group->addGroup(nonOsgSubgroup)) << "OsgGroup should only succeed on groups that derive from OsgGroup!"; EXPECT_EQ(1u, group->getGroups().size()); EXPECT_EQ(group->getGroups().end(), std::find(group->getGroups().begin(),group->getGroups().end(), nonOsgSubgroup)); EXPECT_EQ(2u, osgSwitch->getNumChildren()); } <commit_msg>Add clear tests for OsgGroup<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2012-2013, SimQuest Solutions 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. /// \file /// Tests for the Group class. #include "SurgSim/Graphics/UnitTests/MockObjects.h" #include "SurgSim/Graphics/UnitTests/MockOsgObjects.h" #include "SurgSim/Graphics/OsgGroup.h" #include "gtest/gtest.h" using SurgSim::Graphics::Actor; using SurgSim::Graphics::Group; using SurgSim::Graphics::OsgActor; using SurgSim::Graphics::OsgGroup; TEST(OsgGroupTests, InitTest) { ASSERT_NO_THROW({std::shared_ptr<Group> group = std::make_shared<OsgGroup>("test name");}); } TEST(OsgGroupTests, OsgNodesTest) { std::shared_ptr<OsgGroup> osgGroup = std::make_shared<OsgGroup>("test group"); osg::ref_ptr<osg::Switch> osgSwitch = dynamic_cast<osg::Switch*>(osgGroup->getOsgGroup().get()); ASSERT_TRUE(osgSwitch.valid()) << "Group's OSG node should be a switch!"; } TEST(OsgGroupTests, VisibilityTest) { std::shared_ptr<OsgGroup> osgGroup = std::make_shared<OsgGroup>("test group"); std::shared_ptr<Group> group = osgGroup; EXPECT_TRUE(group->isVisible()); group->setVisible(true); EXPECT_TRUE(group->isVisible()); } TEST(OsgGroupTests, AddRemoveTest) { std::shared_ptr<OsgGroup> osgGroup = std::make_shared<OsgGroup>("test group"); std::shared_ptr<Group> group = osgGroup; EXPECT_EQ(0u, group->getActors().size()); EXPECT_EQ(0u, group->getGroups().size()); osg::ref_ptr<osg::Switch> osgSwitch = dynamic_cast<osg::Switch*>(osgGroup->getOsgGroup().get()); ASSERT_TRUE(osgSwitch.valid()) << "Group's OSG node should be a switch!"; EXPECT_EQ(0u, osgSwitch->getNumChildren()); /// Add an actor and make sure the osg::Switch value for it is set correctly (should be true) std::shared_ptr<OsgActor> actor1 = std::make_shared<MockOsgActor>("test actor 1"); group->addActor(actor1); EXPECT_EQ(1u, group->getActors().size()); EXPECT_EQ(1u, osgSwitch->getNumChildren()); EXPECT_EQ(0u, osgSwitch->getChildIndex(actor1->getOsgNode())); EXPECT_TRUE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should be visible!"; /// Set group to not visible and check the osg::Switch values group->setVisible(false); EXPECT_FALSE(group->isVisible()); EXPECT_FALSE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should not be visible!"; /// Add another actor and make sure the osg::Switch value for it is set correctly (should be false) std::shared_ptr<OsgActor> actor2 = std::make_shared<MockOsgActor>("test actor 2"); group->addActor(actor2); EXPECT_EQ(2u, group->getActors().size()); EXPECT_EQ(2u, osgSwitch->getNumChildren()); EXPECT_EQ(1u, osgSwitch->getChildIndex(actor2->getOsgNode())); EXPECT_FALSE(osgSwitch->getChildValue(actor2->getOsgNode())) << "Actor 2 should not be visible!"; /// Set group to visible and check the osg::Switch values group->setVisible(true); EXPECT_TRUE(group->isVisible()); EXPECT_TRUE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should be visible!"; EXPECT_TRUE(osgSwitch->getChildValue(actor2->getOsgNode())) << "Actor 2 should be visible!"; /// Add a group and make sure the osg::Switch value for it is set correctly (should be true) std::shared_ptr<OsgGroup> subGroup1 = std::make_shared<OsgGroup>("test sub-group 1"); group->addGroup(subGroup1); EXPECT_EQ(1u, group->getGroups().size()); EXPECT_EQ(3u, osgSwitch->getNumChildren()); EXPECT_EQ(2u, osgSwitch->getChildIndex(subGroup1->getOsgGroup())); EXPECT_TRUE(osgSwitch->getChildValue(subGroup1->getOsgGroup())) << "Group 1 should be visible!"; /// Set group to not visible and check the osg::Switch values group->setVisible(false); EXPECT_FALSE(group->isVisible()); EXPECT_FALSE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should not be visible!"; EXPECT_FALSE(osgSwitch->getChildValue(actor2->getOsgNode())) << "Actor 1 should not be visible!"; EXPECT_FALSE(osgSwitch->getChildValue(subGroup1->getOsgGroup())) << "Group 1 should not be visible!"; /// Add another group and make sure the osg::Switch value for it is set correctly (should be false) std::shared_ptr<OsgGroup> subGroup2 = std::make_shared<OsgGroup>("test sub-group 1"); group->addGroup(subGroup2); EXPECT_EQ(2u, group->getGroups().size()); EXPECT_EQ(4u, osgSwitch->getNumChildren()); EXPECT_EQ(3u, osgSwitch->getChildIndex(subGroup2->getOsgGroup())); EXPECT_FALSE(osgSwitch->getChildValue(subGroup2->getOsgGroup())) << "Group 2 should not be visible!"; /// Set group to visible and check the osg::Switch values group->setVisible(true); EXPECT_TRUE(group->isVisible()); EXPECT_TRUE(osgSwitch->getChildValue(actor1->getOsgNode())) << "Actor 1 should be visible!"; EXPECT_TRUE(osgSwitch->getChildValue(actor2->getOsgNode())) << "Actor 2 should be visible!"; EXPECT_TRUE(osgSwitch->getChildValue(subGroup1->getOsgGroup())) << "Group 1 should be visible!"; EXPECT_TRUE(osgSwitch->getChildValue(subGroup2->getOsgGroup())) << "Group 2 should be visible!"; /// Try to add a duplicate actor EXPECT_FALSE(group->addActor(actor1)); EXPECT_EQ(2u, group->getActors().size()); EXPECT_EQ(4u, osgSwitch->getNumChildren()); /// Try to add a duplicate group EXPECT_FALSE(group->addGroup(subGroup2)); EXPECT_EQ(2u, group->getGroups().size()); EXPECT_EQ(4u, osgSwitch->getNumChildren()); /// Remove a group EXPECT_TRUE(group->removeGroup(subGroup2)); EXPECT_EQ(3u, osgSwitch->getNumChildren()); EXPECT_EQ(3u, osgSwitch->getChildIndex(subGroup2->getOsgGroup())); /// Remove an actor EXPECT_TRUE(group->removeActor(actor1)); EXPECT_EQ(2u, osgSwitch->getNumChildren()); EXPECT_EQ(2u, osgSwitch->getChildIndex(actor1->getOsgNode())); /// Try to remove a group that is not in the group EXPECT_FALSE(group->removeGroup(subGroup2)); EXPECT_EQ(2u, osgSwitch->getChildIndex(subGroup2->getOsgGroup())); /// Try to remove an actor that is not in the group EXPECT_FALSE(group->removeActor(actor1)); EXPECT_EQ(2u, osgSwitch->getChildIndex(actor1->getOsgNode())); /// Try to add a non-OSG actor std::shared_ptr<MockActor> nonOsgActor = std::make_shared<MockActor>("non-osg actor"); EXPECT_FALSE(group->addActor(nonOsgActor)) << "OsgGroup should only succeed on actors that derive from OsgActor!"; EXPECT_EQ(1u, group->getActors().size()); EXPECT_EQ(group->getActors().end(), std::find(group->getActors().begin(), group->getActors().end(), nonOsgActor)); EXPECT_EQ(2u, osgSwitch->getNumChildren()); /// Try to add a non-OSG group std::shared_ptr<MockGroup> nonOsgSubgroup = std::make_shared<MockGroup>("non-osg group"); EXPECT_FALSE(group->addGroup(nonOsgSubgroup)) << "OsgGroup should only succeed on groups that derive from OsgGroup!"; EXPECT_EQ(1u, group->getGroups().size()); EXPECT_EQ(group->getGroups().end(), std::find(group->getGroups().begin(),group->getGroups().end(), nonOsgSubgroup)); EXPECT_EQ(2u, osgSwitch->getNumChildren()); } TEST(OsgGroupTests, ClearTests) { std::shared_ptr<OsgGroup> osgGroup = std::make_shared<OsgGroup>("test name"); std::shared_ptr<Group> group = osgGroup; std::shared_ptr<Actor> actor1 = std::make_shared<MockOsgActor>("test actor 1"); std::shared_ptr<Actor> actor2 = std::make_shared<MockOsgActor>("test actor 2"); std::shared_ptr<Group> group1 = std::make_shared<OsgGroup>("test group 1"); std::shared_ptr<Group> group2 = std::make_shared<OsgGroup>("test group 2"); osg::ref_ptr<osg::Switch> osgSwitch = dynamic_cast<osg::Switch*>(osgGroup->getOsgGroup().get()); ASSERT_TRUE(osgSwitch.valid()) << "Group's OSG node should be a switch!"; EXPECT_EQ(0u, group->getActors().size()); EXPECT_EQ(0u, group->getGroups().size()); EXPECT_EQ(0u, osgSwitch->getNumChildren()); // Add actors and groups group->addActor(actor1); group->addActor(actor2); group->addGroup(group1); group->addGroup(group2); EXPECT_EQ(2u, group->getActors().size()); EXPECT_EQ(2u, group->getGroups().size()); EXPECT_EQ(4u, osgSwitch->getNumChildren()); // Remove all actors group->clearActors(); EXPECT_EQ(0u, group->getActors().size()); EXPECT_EQ(2u, group->getGroups().size()); EXPECT_EQ(2u, osgSwitch->getNumChildren()); // Add actors again group->addActor(actor1); group->addActor(actor2); EXPECT_EQ(2u, group->getActors().size()); EXPECT_EQ(2u, group->getGroups().size()); EXPECT_EQ(4u, osgSwitch->getNumChildren()); // Remove all groups group->clearGroups(); EXPECT_EQ(2u, group->getActors().size()); EXPECT_EQ(0u, group->getGroups().size()); EXPECT_EQ(2u, osgSwitch->getNumChildren()); // Add groups again group->addGroup(group1); group->addGroup(group2); EXPECT_EQ(2u, group->getActors().size()); EXPECT_EQ(2u, group->getGroups().size()); EXPECT_EQ(4u, osgSwitch->getNumChildren()); // Remove everything group->clear(); EXPECT_EQ(0u, group->getActors().size()); EXPECT_EQ(0u, group->getGroups().size()); EXPECT_EQ(0u, osgSwitch->getNumChildren()); }<|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "otbImageFileReader.h" #include "otbImage.h" #include "itkRGBPixel.h" #include "itkExceptionObject.h" #include <iostream> int otbPNGIndexedNbBandsTest(int argc, char* argv[]) { // Verify the number of parameters in the command line const char * inputFilename = argv[1]; const unsigned int nbBands = atoi(argv[2]); typedef itk::RGBPixel<unsigned char> InputPixelType; const unsigned int Dimension = 2; typedef otb::Image< InputPixelType, Dimension > InputImageType; typedef otb::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( inputFilename ); reader->UpdateOutputInformation(); if ( reader->GetOutput()->GetNumberOfComponentsPerPixel() == nbBands ) { return EXIT_SUCCESS; } else { return EXIT_FAILURE; } } <commit_msg>TEST:ioTvCheckNbBandsPNGIndexee with comments<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "otbImageFileReader.h" #include "otbImage.h" #include "itkRGBPixel.h" #include "itkExceptionObject.h" #include <iostream> int otbPNGIndexedNbBandsTest(int argc, char* argv[]) { // Verify the number of parameters in the command line const char * inputFilename = argv[1]; const unsigned int nbBands = atoi(argv[2]); typedef itk::RGBPixel<unsigned char> InputPixelType; const unsigned int Dimension = 2; typedef otb::Image< InputPixelType, Dimension > InputImageType; typedef otb::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( inputFilename ); reader->UpdateOutputInformation(); if ( reader->GetOutput()->GetNumberOfComponentsPerPixel() == nbBands ) { return EXIT_SUCCESS; } else { std::cout << "Read " << reader->GetOutput()->GetNumberOfComponentsPerPixel() << " but the real number of bands is " << nbBands <<std::endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before><commit_msg>Prediction: implement main procedures in pedestrian interaction<commit_after><|endoftext|>
<commit_before>/** * \file postprocessing.hh * \brief postprocessing.hh **/ #ifndef POSTPROCESSING_HH #define POSTPROCESSING_HH #include <dune/fem/operator/projection/l2projection.hh> #include <dune/fem/io/file/vtkio.hh> #include <dune/fem/io/file/datawriter.hh> #include "logging.hh" #include "misc.hh" #include "parametercontainer.hh" #include <dune/fem/misc/l2norm.hh> #include <cmath> #include <sstream> template < class StokesPassImp, class ProblemImp > class PostProcessor { public: typedef ProblemImp ProblemType; typedef StokesPassImp StokesPassType; typedef typename StokesPassType::DiscreteStokesFunctionSpaceWrapperType DiscreteStokesFunctionSpaceWrapperType; typedef typename StokesPassType::DiscreteStokesFunctionWrapperType DiscreteStokesFunctionWrapperType; typedef typename ProblemType::VelocityType ContinuousVelocityType; typedef typename ProblemType::PressureType ContinuousPressureType; typedef typename ProblemType::ForceType ForceType; typedef typename ProblemType::DirichletDataType DirichletDataType; typedef typename StokesPassType::GridPartType GridPartType; typedef typename GridPartType::GridType GridType; typedef Dune::VTKIO<GridPartType> VTKWriterType; typedef typename StokesPassType::DiscreteVelocityFunctionType DiscreteVelocityFunctionType; typedef typename StokesPassType::DiscreteVelocityFunctionSpaceType DiscreteVelocityFunctionSpaceType; typedef typename StokesPassType::DiscretePressureFunctionType DiscretePressureFunctionType; typedef typename StokesPassType::DiscretePressureFunctionSpaceType DiscretePressureFunctionSpaceType; PostProcessor( const DiscreteStokesFunctionSpaceWrapperType& wrapper, const ProblemType& prob ) : //pass_( pass ), problem_( prob ), spaceWrapper_( wrapper ), gridPart_( wrapper.gridPart() ), velocitySpace_ ( wrapper.discreteVelocitySpace() ), discreteExactVelocity_( "u_exact", wrapper.discreteVelocitySpace() ), discreteExactForce_( "f_exact", wrapper.discreteVelocitySpace() ), discreteExactDirichlet_( "gd_exact", wrapper.discreteVelocitySpace() ), discreteExactPressure_( "p_exact", wrapper.discretePressureSpace() ), errorFunc_velocity_( "err_velocity", wrapper.discreteVelocitySpace() ), errorFunc_pressure_( "err_pressure", wrapper.discretePressureSpace() ), solutionAssembled_( false ), current_refine_level_( std::numeric_limits<int>::min() ), l2_error_pressure_( - std::numeric_limits<double>::max() ), l2_error_velocity_( - std::numeric_limits<double>::max() ), vtkWriter_( wrapper.gridPart() ), datadir_( Parameters().getParam( "fem.io.datadir", std::string("data") )) { Stuff::testCreateDirectory( datadir_ ); } ~PostProcessor() { } void assembleExactSolution() { typedef Dune::L2Projection< double, double, ContinuousVelocityType, DiscreteVelocityFunctionType > ProjectionV; ProjectionV projectionV; projectionV( problem_.velocity(), discreteExactVelocity_ ); typedef Dune::L2Projection< double, double, DirichletDataType, DiscreteVelocityFunctionType > ProjectionD; ProjectionD projectionD; projectionD( problem_.dirichletData(), discreteExactDirichlet_ ); typedef Dune::L2Projection< double, double, ForceType, DiscreteVelocityFunctionType > ProjectionF; ProjectionF projectionF; projectionF( problem_.force(), discreteExactForce_ ); typedef Dune::L2Projection< double, double, ContinuousPressureType, DiscretePressureFunctionType > ProjectionP; ProjectionP projectionP; projectionP( problem_.pressure(), discreteExactPressure_ ); } template <class Function> void vtk_write( const Function& f ) { vtkWriter_.addVertexData(f); std::stringstream path; if ( Parameters().getParam( "per-run-output", false ) ) path << datadir_ << "/ref" << current_refine_level_ << "_" << f.name(); else path << datadir_ << "/" << f.name(); vtkWriter_.write( path.str().c_str() ); vtkWriter_.clear(); } void save( const GridType& grid, const DiscreteStokesFunctionWrapperType& wrapper, int refine_level ) { if ( !solutionAssembled_ || current_refine_level_ != refine_level ) //re-assemble solution if refine level has changed assembleExactSolution(); current_refine_level_ = refine_level; vtk_write( wrapper.discretePressure() ); vtk_write( wrapper.discreteVelocity() ); if ( ProblemType:: hasMeaningfulAnalyticalSolution ) { calcError( wrapper.discretePressure() , wrapper.discreteVelocity() ); vtk_write( discreteExactVelocity_ ); vtk_write( discreteExactPressure_ ); vtk_write( discreteExactForce_ ); vtk_write( discreteExactDirichlet_ ); vtk_write( errorFunc_pressure_ ); vtk_write( errorFunc_velocity_ ); } typedef Dune::Tuple<DiscreteVelocityFunctionType*> IOTupleType; IOTupleType dataTup ( &discreteExactVelocity_ ); typedef Dune::DataWriter< GridType, IOTupleType > DataWriterType; DataWriterType datawriter ( grid, dataTup, 0,0,0 ); #ifndef NLOG entityColoration(); #endif } void calcError( const DiscretePressureFunctionType& pressure, const DiscreteVelocityFunctionType& velocity ) { if ( !solutionAssembled_ ) assembleExactSolution(); errorFunc_pressure_.assign( discreteExactPressure_ ); errorFunc_pressure_ -= pressure; errorFunc_velocity_.assign( discreteExactVelocity_ ); errorFunc_velocity_ -= velocity; Dune::L2Norm< GridPartType > l2_Error( gridPart_ ); l2_error_pressure_ = l2_Error.norm( errorFunc_pressure_ ); l2_error_velocity_ = l2_Error.norm( errorFunc_velocity_ ); Logger().Info().Resume(); Logger().Info() << "L2-Error Pressure: " << std::setw(8) << l2_error_pressure_ << "\n" << "L2-Error Velocity: " << std::setw(8) << l2_error_velocity_ << std::endl; } std::vector<double> getError() { std::vector<double> ret; ret.push_back( l2_error_velocity_ ); ret.push_back( l2_error_pressure_ ); return ret; } void entityColoration() { DiscretePressureFunctionType cl ( "entitiy-num", spaceWrapper_.discretePressureSpace() ); unsigned long numberOfEntities = 0; typedef typename GridPartType::GridType::template Codim< 0 >::Entity EntityType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::IntersectionIteratorType IntersectionIteratorType; EntityIteratorType entityItEndLog = velocitySpace_.end(); for ( EntityIteratorType entityItLog = velocitySpace_.begin(); entityItLog != entityItEndLog; ++entityItLog, ++numberOfEntities ) { const EntityType& entity = *entityItLog; const typename EntityType::Geometry& geo = entity .geometry(); // dbg << "entity: " << numberOfEntities <<"\n"; for ( int i = 0; i < geo.corners(); ++i ){ // Stuff::printFieldVector( geo[i], " corner", dbg ); } // dbg << std::endl; typename DiscretePressureFunctionType::LocalFunctionType lf = cl.localFunction( entity ); for ( int i = 0; i < lf.numDofs(); ++i ){ lf[i] = numberOfEntities; } unsigned long numberOfIntersections =0; IntersectionIteratorType intItEnd = gridPart_.iend( entity ); for ( IntersectionIteratorType intIt = gridPart_.ibegin( entity ); intIt != intItEnd; ++intIt,++numberOfIntersections ) { // if we are inside the grid if ( intIt.neighbor() && !intIt.boundary() ) { // count inner intersections } // if we are on the boundary of the grid if ( !intIt.neighbor() && intIt.boundary() ) { // count boundary intersections } } } vtk_write( cl ); } private: const ProblemType& problem_; const DiscreteStokesFunctionSpaceWrapperType& spaceWrapper_; const GridPartType& gridPart_; const DiscreteVelocityFunctionSpaceType& velocitySpace_; DiscreteVelocityFunctionType discreteExactVelocity_; DiscreteVelocityFunctionType discreteExactForce_; DiscreteVelocityFunctionType discreteExactDirichlet_; DiscretePressureFunctionType discreteExactPressure_; DiscreteVelocityFunctionType errorFunc_velocity_; DiscretePressureFunctionType errorFunc_pressure_; bool solutionAssembled_; int current_refine_level_; double l2_error_pressure_; double l2_error_velocity_; VTKWriterType vtkWriter_; std::string datadir_; }; #undef vtk_write #endif // end of postprocessing.hh <commit_msg>output calculated velo/pressure in grape output<commit_after>/** * \file postprocessing.hh * \brief postprocessing.hh **/ #ifndef POSTPROCESSING_HH #define POSTPROCESSING_HH #include <dune/fem/operator/projection/l2projection.hh> #include <dune/fem/io/file/vtkio.hh> #include <dune/fem/io/file/datawriter.hh> #include "logging.hh" #include "misc.hh" #include "parametercontainer.hh" #include <dune/fem/misc/l2norm.hh> #include <cmath> #include <sstream> template < class StokesPassImp, class ProblemImp > class PostProcessor { public: typedef ProblemImp ProblemType; typedef StokesPassImp StokesPassType; typedef typename StokesPassType::DiscreteStokesFunctionSpaceWrapperType DiscreteStokesFunctionSpaceWrapperType; typedef typename StokesPassType::DiscreteStokesFunctionWrapperType DiscreteStokesFunctionWrapperType; typedef typename ProblemType::VelocityType ContinuousVelocityType; typedef typename ProblemType::PressureType ContinuousPressureType; typedef typename ProblemType::ForceType ForceType; typedef typename ProblemType::DirichletDataType DirichletDataType; typedef typename StokesPassType::GridPartType GridPartType; typedef typename GridPartType::GridType GridType; typedef Dune::VTKIO<GridPartType> VTKWriterType; typedef typename StokesPassType::DiscreteVelocityFunctionType DiscreteVelocityFunctionType; typedef typename StokesPassType::DiscreteVelocityFunctionSpaceType DiscreteVelocityFunctionSpaceType; typedef typename StokesPassType::DiscretePressureFunctionType DiscretePressureFunctionType; typedef typename StokesPassType::DiscretePressureFunctionSpaceType DiscretePressureFunctionSpaceType; PostProcessor( const DiscreteStokesFunctionSpaceWrapperType& wrapper, const ProblemType& prob ) : //pass_( pass ), problem_( prob ), spaceWrapper_( wrapper ), gridPart_( wrapper.gridPart() ), velocitySpace_ ( wrapper.discreteVelocitySpace() ), discreteExactVelocity_( "u_exact", wrapper.discreteVelocitySpace() ), discreteExactForce_( "f_exact", wrapper.discreteVelocitySpace() ), discreteExactDirichlet_( "gd_exact", wrapper.discreteVelocitySpace() ), discreteExactPressure_( "p_exact", wrapper.discretePressureSpace() ), errorFunc_velocity_( "err_velocity", wrapper.discreteVelocitySpace() ), errorFunc_pressure_( "err_pressure", wrapper.discretePressureSpace() ), solutionAssembled_( false ), current_refine_level_( std::numeric_limits<int>::min() ), l2_error_pressure_( - std::numeric_limits<double>::max() ), l2_error_velocity_( - std::numeric_limits<double>::max() ), vtkWriter_( wrapper.gridPart() ), datadir_( Parameters().getParam( "fem.io.datadir", std::string("data") )) { Stuff::testCreateDirectory( datadir_ ); } ~PostProcessor() { } void assembleExactSolution() { typedef Dune::L2Projection< double, double, ContinuousVelocityType, DiscreteVelocityFunctionType > ProjectionV; ProjectionV projectionV; projectionV( problem_.velocity(), discreteExactVelocity_ ); typedef Dune::L2Projection< double, double, DirichletDataType, DiscreteVelocityFunctionType > ProjectionD; ProjectionD projectionD; projectionD( problem_.dirichletData(), discreteExactDirichlet_ ); typedef Dune::L2Projection< double, double, ForceType, DiscreteVelocityFunctionType > ProjectionF; ProjectionF projectionF; projectionF( problem_.force(), discreteExactForce_ ); typedef Dune::L2Projection< double, double, ContinuousPressureType, DiscretePressureFunctionType > ProjectionP; ProjectionP projectionP; projectionP( problem_.pressure(), discreteExactPressure_ ); } template <class Function> void vtk_write( const Function& f ) { vtkWriter_.addVertexData(f); std::stringstream path; if ( Parameters().getParam( "per-run-output", false ) ) path << datadir_ << "/ref" << current_refine_level_ << "_" << f.name(); else path << datadir_ << "/" << f.name(); vtkWriter_.write( path.str().c_str() ); vtkWriter_.clear(); } void save( const GridType& grid, const DiscreteStokesFunctionWrapperType& wrapper, int refine_level ) { if ( !solutionAssembled_ || current_refine_level_ != refine_level ) //re-assemble solution if refine level has changed assembleExactSolution(); current_refine_level_ = refine_level; vtk_write( wrapper.discretePressure() ); vtk_write( wrapper.discreteVelocity() ); if ( ProblemType:: hasMeaningfulAnalyticalSolution ) { calcError( wrapper.discretePressure() , wrapper.discreteVelocity() ); vtk_write( discreteExactVelocity_ ); vtk_write( discreteExactPressure_ ); vtk_write( discreteExactForce_ ); vtk_write( discreteExactDirichlet_ ); vtk_write( errorFunc_pressure_ ); vtk_write( errorFunc_velocity_ ); } typedef Dune::Tuple< const DiscreteVelocityFunctionType*, const DiscretePressureFunctionType* > IOTupleType; IOTupleType dataTup ( &wrapper.discreteVelocity(), &wrapper.discretePressure() ); typedef Dune::DataWriter< GridType, IOTupleType > DataWriterType; DataWriterType datawriter ( grid, dataTup, 0,0,0 ); datawriter.write( 0, 0 ); #ifndef NLOG entityColoration(); #endif } void calcError( const DiscretePressureFunctionType& pressure, const DiscreteVelocityFunctionType& velocity ) { if ( !solutionAssembled_ ) assembleExactSolution(); errorFunc_pressure_.assign( discreteExactPressure_ ); errorFunc_pressure_ -= pressure; errorFunc_velocity_.assign( discreteExactVelocity_ ); errorFunc_velocity_ -= velocity; Dune::L2Norm< GridPartType > l2_Error( gridPart_ ); l2_error_pressure_ = l2_Error.norm( errorFunc_pressure_ ); l2_error_velocity_ = l2_Error.norm( errorFunc_velocity_ ); Logger().Info().Resume(); Logger().Info() << "L2-Error Pressure: " << std::setw(8) << l2_error_pressure_ << "\n" << "L2-Error Velocity: " << std::setw(8) << l2_error_velocity_ << std::endl; } std::vector<double> getError() { std::vector<double> ret; ret.push_back( l2_error_velocity_ ); ret.push_back( l2_error_pressure_ ); return ret; } void entityColoration() { DiscretePressureFunctionType cl ( "entitiy-num", spaceWrapper_.discretePressureSpace() ); unsigned long numberOfEntities = 0; typedef typename GridPartType::GridType::template Codim< 0 >::Entity EntityType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::IntersectionIteratorType IntersectionIteratorType; EntityIteratorType entityItEndLog = velocitySpace_.end(); for ( EntityIteratorType entityItLog = velocitySpace_.begin(); entityItLog != entityItEndLog; ++entityItLog, ++numberOfEntities ) { const EntityType& entity = *entityItLog; const typename EntityType::Geometry& geo = entity .geometry(); // dbg << "entity: " << numberOfEntities <<"\n"; for ( int i = 0; i < geo.corners(); ++i ){ // Stuff::printFieldVector( geo[i], " corner", dbg ); } // dbg << std::endl; typename DiscretePressureFunctionType::LocalFunctionType lf = cl.localFunction( entity ); for ( int i = 0; i < lf.numDofs(); ++i ){ lf[i] = numberOfEntities; } unsigned long numberOfIntersections =0; IntersectionIteratorType intItEnd = gridPart_.iend( entity ); for ( IntersectionIteratorType intIt = gridPart_.ibegin( entity ); intIt != intItEnd; ++intIt,++numberOfIntersections ) { // if we are inside the grid if ( intIt.neighbor() && !intIt.boundary() ) { // count inner intersections } // if we are on the boundary of the grid if ( !intIt.neighbor() && intIt.boundary() ) { // count boundary intersections } } } vtk_write( cl ); } private: const ProblemType& problem_; const DiscreteStokesFunctionSpaceWrapperType& spaceWrapper_; const GridPartType& gridPart_; const DiscreteVelocityFunctionSpaceType& velocitySpace_; DiscreteVelocityFunctionType discreteExactVelocity_; DiscreteVelocityFunctionType discreteExactForce_; DiscreteVelocityFunctionType discreteExactDirichlet_; DiscretePressureFunctionType discreteExactPressure_; DiscreteVelocityFunctionType errorFunc_velocity_; DiscretePressureFunctionType errorFunc_pressure_; bool solutionAssembled_; int current_refine_level_; double l2_error_pressure_; double l2_error_velocity_; VTKWriterType vtkWriter_; std::string datadir_; }; #undef vtk_write #endif // end of postprocessing.hh <|endoftext|>
<commit_before>#if defined(_WIN32) || defined(__APPLE__) #include "generic_fsnotifier.h" /** * Attaches JNI to the current thread. */ extern JNIEnv* attach_jni(JavaVM* jvm, const char* name, bool daemon); /** * Detaches JNI from the current thread. */ extern int detach_jni(JavaVM* jvm); AbstractServer::AbstractServer(JNIEnv* env, jobject watcherCallback) { JavaVM* jvm; int jvmStatus = env->GetJavaVM(&jvm); if (jvmStatus < 0) { throw FileWatcherException("Could not store jvm instance"); } this->jvm = jvm; jclass callbackClass = env->GetObjectClass(watcherCallback); this->watcherCallbackMethod = env->GetMethodID(callbackClass, "pathChanged", "(ILjava/lang/String;)V"); jobject globalWatcherCallback = env->NewGlobalRef(watcherCallback); if (globalWatcherCallback == NULL) { throw FileWatcherException("Could not get global ref for watcher callback"); } this->watcherCallback = globalWatcherCallback; } AbstractServer::~AbstractServer() { JNIEnv* env = getThreadEnv(); if (env != NULL) { env->DeleteGlobalRef(watcherCallback); } } void AbstractServer::startThread() { unique_lock<mutex> lock(watcherThreadMutex); this->watcherThread = thread(&AbstractServer::run, this); this->watcherThreadStarted.wait(lock); if (initException) { if (watcherThread.joinable()) { watcherThread.join(); } rethrow_exception(initException); } } void AbstractServer::run() { JNIEnv* env = attach_jni(jvm, "File watcher server", true); log_fine(env, "Starting thread", NULL); runLoop(env, [this](exception_ptr initException) { unique_lock<mutex> lock(watcherThreadMutex); this->initException = initException; watcherThreadStarted.notify_all(); log_fine(getThreadEnv(), "Started thread", NULL); }); log_fine(env, "Stopping thread", NULL); detach_jni(jvm); } JNIEnv* AbstractServer::getThreadEnv() { JNIEnv* env; jint ret = jvm->GetEnv((void**) &(env), JNI_VERSION_1_6); if (ret != JNI_OK) { fprintf(stderr, "Failed to get JNI env for current thread: %d\n", ret); throw FileWatcherException("Failed to get JNI env for current thread"); } return env; } void AbstractServer::reportChange(JNIEnv* env, int type, const u16string& path) { jstring javaPath = env->NewString((jchar*) path.c_str(), path.length()); env->CallVoidMethod(watcherCallback, watcherCallbackMethod, type, javaPath); env->DeleteLocalRef(javaPath); } JNIEnv* attach_jni(JavaVM* jvm, const char* name, bool daemon) { JNIEnv* env; // Work around const char* issue char* nameCopy = strdup(name); JavaVMAttachArgs args = { JNI_VERSION_1_6, // version nameCopy, // thread name NULL // thread group }; free(nameCopy); jint ret = daemon ? jvm->AttachCurrentThreadAsDaemon((void**) &(env), (void*) &args) : jvm->AttachCurrentThread((void**) &(env), (void*) &args); if (ret != JNI_OK) { fprintf(stderr, "Failed to attach JNI to current thread: %d\n", ret); return NULL; } return env; } int detach_jni(JavaVM* jvm) { jint ret = jvm->DetachCurrentThread(); if (ret != JNI_OK) { fprintf(stderr, "Failed to detach JNI from current thread: %d\n", ret); } return ret; } #endif <commit_msg>Use RAII for JNI attachment<commit_after>#if defined(_WIN32) || defined(__APPLE__) #include "generic_fsnotifier.h" class JNIThread { public: JNIThread(JavaVM* jvm, const char* name, bool daemon) { this->jvm = jvm; JNIEnv* env; // Work around const char* issue char* nameCopy = strdup(name); JavaVMAttachArgs args = { JNI_VERSION_1_6, // version nameCopy, // thread name NULL // thread group }; free(nameCopy); jint ret = daemon ? jvm->AttachCurrentThreadAsDaemon((void**) &env, (void*) &args) : jvm->AttachCurrentThread((void**) &env, (void*) &args); if (ret != JNI_OK) { fprintf(stderr, "Failed to attach JNI to current thread: %d\n", ret); throw new FileWatcherException("Failed to attach JNI to current thread"); } } ~JNIThread() { jint ret = jvm->DetachCurrentThread(); if (ret != JNI_OK) { fprintf(stderr, "Failed to detach JNI from current thread: %d\n", ret); } } private: JavaVM* jvm; }; AbstractServer::AbstractServer(JNIEnv* env, jobject watcherCallback) { JavaVM* jvm; int jvmStatus = env->GetJavaVM(&jvm); if (jvmStatus < 0) { throw FileWatcherException("Could not store jvm instance"); } this->jvm = jvm; jclass callbackClass = env->GetObjectClass(watcherCallback); this->watcherCallbackMethod = env->GetMethodID(callbackClass, "pathChanged", "(ILjava/lang/String;)V"); jobject globalWatcherCallback = env->NewGlobalRef(watcherCallback); if (globalWatcherCallback == NULL) { throw FileWatcherException("Could not get global ref for watcher callback"); } this->watcherCallback = globalWatcherCallback; } AbstractServer::~AbstractServer() { JNIEnv* env = getThreadEnv(); if (env != NULL) { env->DeleteGlobalRef(watcherCallback); } } void AbstractServer::startThread() { unique_lock<mutex> lock(watcherThreadMutex); this->watcherThread = thread(&AbstractServer::run, this); this->watcherThreadStarted.wait(lock); if (initException) { if (watcherThread.joinable()) { watcherThread.join(); } rethrow_exception(initException); } } void AbstractServer::run() { JNIThread jniThread(jvm, "File watcher server", true); JNIEnv* env = getThreadEnv(); log_fine(env, "Starting thread", NULL); runLoop(env, [this](exception_ptr initException) { unique_lock<mutex> lock(watcherThreadMutex); this->initException = initException; watcherThreadStarted.notify_all(); log_fine(getThreadEnv(), "Started thread", NULL); }); log_fine(env, "Stopping thread", NULL); } JNIEnv* AbstractServer::getThreadEnv() { JNIEnv* env; jint ret = jvm->GetEnv((void**) &(env), JNI_VERSION_1_6); if (ret != JNI_OK) { fprintf(stderr, "Failed to get JNI env for current thread: %d\n", ret); throw FileWatcherException("Failed to get JNI env for current thread"); } return env; } void AbstractServer::reportChange(JNIEnv* env, int type, const u16string& path) { jstring javaPath = env->NewString((jchar*) path.c_str(), path.length()); env->CallVoidMethod(watcherCallback, watcherCallbackMethod, type, javaPath); env->DeleteLocalRef(javaPath); } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestConeLayoutStrategy.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. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkCellData.h" #include "vtkConeLayoutStrategy.h" #include "vtkCommand.h" #include "vtkDataRepresentation.h" #include "vtkGraphLayoutView.h" #include "vtkIdTypeArray.h" #include "vtkInteractorEventRecorder.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkStringArray.h" #include "vtkStringToNumeric.h" #include "vtkTestUtilities.h" #include "vtkXMLTreeReader.h" using vtkstd::string; #include "vtkSmartPointer.h" #define VTK_CREATE(type, name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() int TestConeLayoutStrategy(int argc, char* argv[]) { VTK_CREATE(vtkTesting, testHelper); testHelper->AddArguments(argc,const_cast<const char **>(argv)); string dataRoot = testHelper->GetDataRoot(); // string file = dataRoot + "/Data/treetest.xml"; string file = dataRoot + "/Data/Infovis/XML/vtkclasses.xml"; VTK_CREATE(vtkXMLTreeReader, reader); reader->SetFileName(file.c_str()); reader->SetMaskArrays(true); reader->Update(); vtkTree* t = reader->GetOutput(); VTK_CREATE(vtkStringArray, label); label->SetName("edge label"); VTK_CREATE(vtkIdTypeArray, dist); dist->SetName("distance"); for (vtkIdType i = 0; i < t->GetNumberOfEdges(); i++) { dist->InsertNextValue(i); switch (i % 3) { case 0: label->InsertNextValue("a"); break; case 1: label->InsertNextValue("b"); break; case 2: label->InsertNextValue("c"); break; } } t->GetEdgeData()->AddArray(dist); t->GetEdgeData()->AddArray(label); VTK_CREATE(vtkStringToNumeric, numeric); numeric->SetInput(t); // Graph layout view VTK_CREATE(vtkGraphLayoutView, view); VTK_CREATE(vtkConeLayoutStrategy, strategy); strategy->SetSpacing(0.3); view->SetLayoutStrategy(strategy); view->SetVertexLabelArrayName("id"); // view->SetVertexLabelArrayName("name"); view->VertexLabelVisibilityOn(); view->SetVertexColorArrayName("id"); // view->SetVertexColorArrayName("size"); view->ColorVerticesOn(); view->SetEdgeColorArrayName("distance"); view->ColorEdgesOn(); view->SetEdgeLabelArrayName("edge label"); view->EdgeLabelVisibilityOn(); view->SetRepresentationFromInputConnection(numeric->GetOutputPort()); view->GetRenderer()->ResetCamera(); VTK_CREATE(vtkRenderWindow, win); win->SetSize( 600, 600 ); win->SetMultiSamples(0); // ensure to have the same test image everywhere view->SetupRenderWindow(win); view->Update(); int retVal = vtkRegressionTestImage(win); if( retVal == vtkRegressionTester::DO_INTERACTOR ) { win->GetInteractor()->Initialize(); win->GetInteractor()->Start(); retVal = vtkRegressionTester::PASSED; } return !retVal; } <commit_msg>BUG: Updating cone layout to not try to color by a string array.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestConeLayoutStrategy.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. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkCellData.h" #include "vtkConeLayoutStrategy.h" #include "vtkCommand.h" #include "vtkDataRepresentation.h" #include "vtkGraphLayoutView.h" #include "vtkIdTypeArray.h" #include "vtkInteractorEventRecorder.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkStringArray.h" #include "vtkStringToNumeric.h" #include "vtkTestUtilities.h" #include "vtkXMLTreeReader.h" using vtkstd::string; #include "vtkSmartPointer.h" #define VTK_CREATE(type, name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() int TestConeLayoutStrategy(int argc, char* argv[]) { VTK_CREATE(vtkTesting, testHelper); testHelper->AddArguments(argc,const_cast<const char **>(argv)); string dataRoot = testHelper->GetDataRoot(); // string file = dataRoot + "/Data/treetest.xml"; string file = dataRoot + "/Data/Infovis/XML/vtkclasses.xml"; VTK_CREATE(vtkXMLTreeReader, reader); reader->SetFileName(file.c_str()); reader->SetMaskArrays(true); reader->Update(); vtkTree* t = reader->GetOutput(); VTK_CREATE(vtkStringArray, label); label->SetName("edge label"); VTK_CREATE(vtkIdTypeArray, dist); dist->SetName("distance"); for (vtkIdType i = 0; i < t->GetNumberOfEdges(); i++) { dist->InsertNextValue(i); switch (i % 3) { case 0: label->InsertNextValue("a"); break; case 1: label->InsertNextValue("b"); break; case 2: label->InsertNextValue("c"); break; } } t->GetEdgeData()->AddArray(dist); t->GetEdgeData()->AddArray(label); VTK_CREATE(vtkStringToNumeric, numeric); numeric->SetInput(t); // Graph layout view VTK_CREATE(vtkGraphLayoutView, view); VTK_CREATE(vtkConeLayoutStrategy, strategy); strategy->SetSpacing(0.3); view->SetLayoutStrategy(strategy); view->SetVertexLabelArrayName("id"); view->VertexLabelVisibilityOn(); view->SetEdgeColorArrayName("distance"); view->ColorEdgesOn(); view->SetEdgeLabelArrayName("edge label"); view->EdgeLabelVisibilityOn(); view->SetRepresentationFromInputConnection(numeric->GetOutputPort()); view->GetRenderer()->ResetCamera(); VTK_CREATE(vtkRenderWindow, win); win->SetSize( 600, 600 ); win->SetMultiSamples(0); // ensure to have the same test image everywhere view->SetupRenderWindow(win); view->SetInteractionModeTo3D(); view->SetLabelPlacementModeToLabelPlacer(); view->Update(); int retVal = vtkRegressionTestImage(win); if( retVal == vtkRegressionTester::DO_INTERACTOR ) { win->GetInteractor()->Initialize(); win->GetInteractor()->Start(); retVal = vtkRegressionTester::PASSED; } return !retVal; } <|endoftext|>
<commit_before>#include "EagleLib/Logging.h" #include "MetaObject/Logging/Log.hpp" #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks.hpp> #include <boost/log/attributes.hpp> #include <boost/log/common.hpp> #include <boost/log/exceptions.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/expressions/attr.hpp> #include <boost/log/attributes/time_traits.hpp> #include <boost/log/expressions/formatters.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/attributes/named_scope.hpp> #include <boost/log/expressions/formatters/named_scope.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/sinks/async_frontend.hpp> #include <boost/log/sinks/basic_sink_backend.hpp> #include <boost/filesystem.hpp> #include <EagleLib/logger.hpp> #include <opencv2/core.hpp> int static_errorHandler(int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata) { std::stringstream ss; LOG(debug) << "Exception at" << mo::print_callstack(0, true, ss) << "[" << file_name << ":" << line << " " << func_name << "] " << err_msg; throw mo::ExceptionWithCallStack<cv::Exception>(cv::Exception(status, err_msg, func_name, file_name, line), ss.str()); return 0; } boost::shared_ptr< boost::log::sinks::asynchronous_sink<EagleLib::ui_collector>> log_sink; void EagleLib::SetupLogging() { cv::redirectError(&static_errorHandler); BOOST_LOG_TRIVIAL(info) << "File logging to " << boost::filesystem::absolute(boost::filesystem::path("")).string() << "/logs"; boost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::debug); boost::log::add_common_attributes(); if (!boost::filesystem::exists("./logs") || !boost::filesystem::is_directory("./logs")) { boost::filesystem::create_directory("./logs"); } boost::log::core::get()->add_global_attribute("Scope", boost::log::attributes::named_scope()); // https://gist.github.com/xiongjia/e23b9572d3fc3d677e3d auto consoleFmtTimeStamp = boost::log::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%M:%S.%f"); auto fmtThreadId = boost::log::expressions::attr<boost::log::attributes::current_thread_id::value_type>("ThreadID"); auto fmtSeverity = boost::log::expressions::attr<boost::log::trivial::severity_level>("Severity"); auto fmtScope = boost::log::expressions::format_named_scope("Scope", boost::log::keywords::format = "%n(%f:%l)", boost::log::keywords::iteration = boost::log::expressions::reverse, boost::log::keywords::depth = 2); boost::log::formatter consoleFmt = boost::log::expressions::format("%1%<%2%,%3%> %4%") % consoleFmtTimeStamp // 1 % fmtThreadId // 2 % fmtSeverity // 3 % boost::log::expressions::smessage; // 4 auto consoleSink = boost::log::add_console_log(std::clog); consoleSink->set_formatter(consoleFmt); auto fmtTimeStamp = boost::log::expressions:: format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S.%f"); // File sink boost::log::formatter logFmt = boost::log::expressions::format("[%1%] (%2%) [%3%] [%4%] %5%") % fmtTimeStamp % fmtThreadId % fmtSeverity % fmtScope % boost::log::expressions::smessage; auto fsSink = boost::log::add_file_log( boost::log::keywords::file_name = "./logs/%Y-%m-%d_%H-%M-%S.%N.log", boost::log::keywords::rotation_size = 10 * 1024 * 1024, boost::log::keywords::min_free_space = 30 * 1024 * 1024, boost::log::keywords::open_mode = std::ios_base::app); //fsSink->set_formatter(logFmt); fsSink->locked_backend()->auto_flush(true); log_sink.reset(new boost::log::sinks::asynchronous_sink<EagleLib::ui_collector>()); boost::log::core::get()->add_sink(log_sink); } void EagleLib::ShutdownLogging() { log_sink->flush(); log_sink->stop(); log_sink.reset(); } <commit_msg>Skip levels of the callstack which are constant<commit_after>#include "EagleLib/Logging.h" #include "MetaObject/Logging/Log.hpp" #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks.hpp> #include <boost/log/attributes.hpp> #include <boost/log/common.hpp> #include <boost/log/exceptions.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/expressions/attr.hpp> #include <boost/log/attributes/time_traits.hpp> #include <boost/log/expressions/formatters.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/attributes/named_scope.hpp> #include <boost/log/expressions/formatters/named_scope.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/sinks/async_frontend.hpp> #include <boost/log/sinks/basic_sink_backend.hpp> #include <boost/filesystem.hpp> #include <EagleLib/logger.hpp> #include <opencv2/core.hpp> int static_errorHandler(int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata) { std::stringstream ss; LOG(debug) << "Exception at" << mo::print_callstack(5, true, ss) << "[" << file_name << ":" << line << " " << func_name << "] " << err_msg; throw mo::ExceptionWithCallStack<cv::Exception>(cv::Exception(status, err_msg, func_name, file_name, line), ss.str()); return 0; } boost::shared_ptr< boost::log::sinks::asynchronous_sink<EagleLib::ui_collector>> log_sink; void EagleLib::SetupLogging() { cv::redirectError(&static_errorHandler); BOOST_LOG_TRIVIAL(info) << "File logging to " << boost::filesystem::absolute(boost::filesystem::path("")).string() << "/logs"; boost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::debug); boost::log::add_common_attributes(); if (!boost::filesystem::exists("./logs") || !boost::filesystem::is_directory("./logs")) { boost::filesystem::create_directory("./logs"); } boost::log::core::get()->add_global_attribute("Scope", boost::log::attributes::named_scope()); // https://gist.github.com/xiongjia/e23b9572d3fc3d677e3d auto consoleFmtTimeStamp = boost::log::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%M:%S.%f"); auto fmtThreadId = boost::log::expressions::attr<boost::log::attributes::current_thread_id::value_type>("ThreadID"); auto fmtSeverity = boost::log::expressions::attr<boost::log::trivial::severity_level>("Severity"); auto fmtScope = boost::log::expressions::format_named_scope("Scope", boost::log::keywords::format = "%n(%f:%l)", boost::log::keywords::iteration = boost::log::expressions::reverse, boost::log::keywords::depth = 2); boost::log::formatter consoleFmt = boost::log::expressions::format("%1%<%2%,%3%> %4%") % consoleFmtTimeStamp // 1 % fmtThreadId // 2 % fmtSeverity // 3 % boost::log::expressions::smessage; // 4 auto consoleSink = boost::log::add_console_log(std::clog); consoleSink->set_formatter(consoleFmt); auto fmtTimeStamp = boost::log::expressions:: format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S.%f"); // File sink boost::log::formatter logFmt = boost::log::expressions::format("[%1%] (%2%) [%3%] [%4%] %5%") % fmtTimeStamp % fmtThreadId % fmtSeverity % fmtScope % boost::log::expressions::smessage; auto fsSink = boost::log::add_file_log( boost::log::keywords::file_name = "./logs/%Y-%m-%d_%H-%M-%S.%N.log", boost::log::keywords::rotation_size = 10 * 1024 * 1024, boost::log::keywords::min_free_space = 30 * 1024 * 1024, boost::log::keywords::open_mode = std::ios_base::app); //fsSink->set_formatter(logFmt); fsSink->locked_backend()->auto_flush(true); log_sink.reset(new boost::log::sinks::asynchronous_sink<EagleLib::ui_collector>()); boost::log::core::get()->add_sink(log_sink); } void EagleLib::ShutdownLogging() { log_sink->flush(); log_sink->stop(); log_sink.reset(); } <|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 "webkit/glue/plugins/webplugin_delegate_impl.h" #include <string> #include <vector> #include "base/file_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/scoped_ptr.h" #include "base/stats_counters.h" #include "base/string_util.h" #include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_instance.h" #include "webkit/glue/plugins/plugin_lib.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/plugins/plugin_stream_url.h" #include "webkit/glue/webkit_glue.h" using webkit_glue::WebPlugin; using webkit_glue::WebPluginDelegate; using webkit_glue::WebPluginResourceClient; using WebKit::WebCursorInfo; using WebKit::WebKeyboardEvent; using WebKit::WebInputEvent; using WebKit::WebMouseEvent; WebPluginDelegateImpl* WebPluginDelegateImpl::Create( const FilePath& filename, const std::string& mime_type, gfx::PluginWindowHandle containing_view) { scoped_refptr<NPAPI::PluginLib> plugin_lib = NPAPI::PluginLib::CreatePluginLib(filename); if (plugin_lib.get() == NULL) return NULL; NPError err = plugin_lib->NP_Initialize(); if (err != NPERR_NO_ERROR) return NULL; scoped_refptr<NPAPI::PluginInstance> instance = plugin_lib->CreateInstance(mime_type); return new WebPluginDelegateImpl(containing_view, instance.get()); } void WebPluginDelegateImpl::PluginDestroyed() { if (handle_event_depth_) { MessageLoop::current()->DeleteSoon(FROM_HERE, this); } else { delete this; } } bool WebPluginDelegateImpl::Initialize( const GURL& url, const std::vector<std::string>& arg_names, const std::vector<std::string>& arg_values, WebPlugin* plugin, bool load_manually) { plugin_ = plugin; instance_->set_web_plugin(plugin_); if (quirks_ & PLUGIN_QUIRK_DONT_ALLOW_MULTIPLE_INSTANCES) { NPAPI::PluginLib* plugin_lib = instance()->plugin_lib(); if (plugin_lib->instance_count() > 1) { return false; } } if (quirks_ & PLUGIN_QUIRK_DIE_AFTER_UNLOAD) webkit_glue::SetForcefullyTerminatePluginProcess(true); int argc = 0; scoped_array<char*> argn(new char*[arg_names.size()]); scoped_array<char*> argv(new char*[arg_names.size()]); for (size_t i = 0; i < arg_names.size(); ++i) { if (quirks_ & PLUGIN_QUIRK_NO_WINDOWLESS && LowerCaseEqualsASCII(arg_names[i], "windowlessvideo")) { continue; } argn[argc] = const_cast<char*>(arg_names[i].c_str()); argv[argc] = const_cast<char*>(arg_values[i].c_str()); argc++; } bool start_result = instance_->Start( url, argn.get(), argv.get(), argc, load_manually); if (!start_result) return false; windowless_ = instance_->windowless(); if (!windowless_) { if (!WindowedCreatePlugin()) return false; } else { // For windowless plugins we should set the containing window handle // as the instance window handle. This is what Safari does. Not having // a valid window handle causes subtle bugs with plugins which retrieve // the window handle and validate the same. The window handle can be // retrieved via NPN_GetValue of NPNVnetscapeWindow. instance_->set_window_handle(parent_); } bool should_load = PlatformInitialize(); plugin_url_ = url.spec(); return should_load; } void WebPluginDelegateImpl::DestroyInstance() { if (instance_ && (instance_->npp()->ndata != NULL)) { // Shutdown all streams before destroying so that // no streams are left "in progress". Need to do // this before calling set_web_plugin(NULL) because the // instance uses the helper to do the download. instance_->CloseStreams(); window_.window = NULL; if (!(quirks_ & PLUGIN_QUIRK_DONT_SET_NULL_WINDOW_HANDLE_ON_DESTROY)) { instance_->NPP_SetWindow(&window_); } instance_->NPP_Destroy(); instance_->set_web_plugin(NULL); PlatformDestroyInstance(); instance_ = 0; } } void WebPluginDelegateImpl::UpdateGeometry( const gfx::Rect& window_rect, const gfx::Rect& clip_rect) { if (first_set_window_call_) { first_set_window_call_ = false; // Plugins like media player on Windows have a bug where in they handle the // first geometry update and ignore the rest resulting in painting issues. // This quirk basically ignores the first set window call sequence for // these plugins and has been tested for Windows plugins only. if (quirks_ & PLUGIN_QUIRK_IGNORE_FIRST_SETWINDOW_CALL) return; } if (windowless_) { WindowlessUpdateGeometry(window_rect, clip_rect); } else { WindowedUpdateGeometry(window_rect, clip_rect); } } void WebPluginDelegateImpl::SetFocus(bool focused) { DCHECK(windowless_); // This is called when internal WebKit focus (the focused element on the page) // changes, but plugins need to know about OS-level focus, so we have an extra // layer of focus tracking. has_webkit_focus_ = focused; if (containing_view_has_focus_) SetPluginHasFocus(focused); } void WebPluginDelegateImpl::SetPluginHasFocus(bool focused) { if (focused == plugin_has_focus_) return; if (PlatformSetPluginHasFocus(focused)) plugin_has_focus_ = focused; } void WebPluginDelegateImpl::SetContentAreaHasFocus(bool has_focus) { containing_view_has_focus_ = has_focus; if (!windowless_) return; SetPluginHasFocus(containing_view_has_focus_ && has_webkit_focus_); } NPObject* WebPluginDelegateImpl::GetPluginScriptableObject() { return instance_->GetPluginScriptableObject(); } void WebPluginDelegateImpl::DidFinishLoadWithReason(const GURL& url, NPReason reason, int notify_id) { if (quirks_ & PLUGIN_QUIRK_ALWAYS_NOTIFY_SUCCESS && reason == NPRES_NETWORK_ERR) { // Flash needs this or otherwise it unloads the launching swf object. reason = NPRES_DONE; } instance()->DidFinishLoadWithReason(url, reason, notify_id); } int WebPluginDelegateImpl::GetProcessId() { // We are in process, so the plugin pid is this current process pid. return base::GetCurrentProcId(); } void WebPluginDelegateImpl::SendJavaScriptStream(const GURL& url, const std::string& result, bool success, int notify_id) { instance()->SendJavaScriptStream(url, result, success, notify_id); } void WebPluginDelegateImpl::DidReceiveManualResponse( const GURL& url, const std::string& mime_type, const std::string& headers, uint32 expected_length, uint32 last_modified) { if (!windowless_) { // Calling NPP_WriteReady before NPP_SetWindow causes movies to not load in // Flash. See http://b/issue?id=892174. DCHECK(windowed_did_set_window_); } instance()->DidReceiveManualResponse(url, mime_type, headers, expected_length, last_modified); } void WebPluginDelegateImpl::DidReceiveManualData(const char* buffer, int length) { instance()->DidReceiveManualData(buffer, length); } void WebPluginDelegateImpl::DidFinishManualLoading() { instance()->DidFinishManualLoading(); } void WebPluginDelegateImpl::DidManualLoadFail() { instance()->DidManualLoadFail(); } FilePath WebPluginDelegateImpl::GetPluginPath() { return instance()->plugin_lib()->plugin_info().path; } void WebPluginDelegateImpl::WindowedUpdateGeometry( const gfx::Rect& window_rect, const gfx::Rect& clip_rect) { if (WindowedReposition(window_rect, clip_rect) || !windowed_did_set_window_) { // Let the plugin know that it has been moved WindowedSetWindow(); } } bool WebPluginDelegateImpl::HandleInputEvent(const WebInputEvent& event, WebCursorInfo* cursor_info) { DCHECK(windowless_) << "events should only be received in windowless mode"; bool pop_user_gesture = false; if (IsUserGesture(event)) { pop_user_gesture = true; instance()->PushPopupsEnabledState(true); } bool handled = PlatformHandleInputEvent(event, cursor_info); if (pop_user_gesture) { instance()->PopPopupsEnabledState(); } return handled; } bool WebPluginDelegateImpl::IsUserGesture(const WebInputEvent& event) { switch (event.type) { case WebInputEvent::MouseDown: case WebInputEvent::MouseUp: case WebInputEvent::KeyDown: case WebInputEvent::KeyUp: return true; default: return false; } return false; } WebPluginResourceClient* WebPluginDelegateImpl::CreateResourceClient( unsigned long resource_id, const GURL& url, int notify_id) { return instance()->CreateStream( resource_id, url, std::string(), notify_id); } WebPluginResourceClient* WebPluginDelegateImpl::CreateSeekableResourceClient( unsigned long resource_id, int range_request_id) { return instance()->GetRangeRequest(range_request_id); } <commit_msg>Fix full screen mode for windowless flash plugins. Flash doesn't expect a "kill focus" message to be sent when the window is deactivated.<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 "webkit/glue/plugins/webplugin_delegate_impl.h" #include <string> #include <vector> #include "base/file_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/scoped_ptr.h" #include "base/stats_counters.h" #include "base/string_util.h" #include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_instance.h" #include "webkit/glue/plugins/plugin_lib.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/plugins/plugin_stream_url.h" #include "webkit/glue/webkit_glue.h" using webkit_glue::WebPlugin; using webkit_glue::WebPluginDelegate; using webkit_glue::WebPluginResourceClient; using WebKit::WebCursorInfo; using WebKit::WebKeyboardEvent; using WebKit::WebInputEvent; using WebKit::WebMouseEvent; WebPluginDelegateImpl* WebPluginDelegateImpl::Create( const FilePath& filename, const std::string& mime_type, gfx::PluginWindowHandle containing_view) { scoped_refptr<NPAPI::PluginLib> plugin_lib = NPAPI::PluginLib::CreatePluginLib(filename); if (plugin_lib.get() == NULL) return NULL; NPError err = plugin_lib->NP_Initialize(); if (err != NPERR_NO_ERROR) return NULL; scoped_refptr<NPAPI::PluginInstance> instance = plugin_lib->CreateInstance(mime_type); return new WebPluginDelegateImpl(containing_view, instance.get()); } void WebPluginDelegateImpl::PluginDestroyed() { if (handle_event_depth_) { MessageLoop::current()->DeleteSoon(FROM_HERE, this); } else { delete this; } } bool WebPluginDelegateImpl::Initialize( const GURL& url, const std::vector<std::string>& arg_names, const std::vector<std::string>& arg_values, WebPlugin* plugin, bool load_manually) { plugin_ = plugin; instance_->set_web_plugin(plugin_); if (quirks_ & PLUGIN_QUIRK_DONT_ALLOW_MULTIPLE_INSTANCES) { NPAPI::PluginLib* plugin_lib = instance()->plugin_lib(); if (plugin_lib->instance_count() > 1) { return false; } } if (quirks_ & PLUGIN_QUIRK_DIE_AFTER_UNLOAD) webkit_glue::SetForcefullyTerminatePluginProcess(true); int argc = 0; scoped_array<char*> argn(new char*[arg_names.size()]); scoped_array<char*> argv(new char*[arg_names.size()]); for (size_t i = 0; i < arg_names.size(); ++i) { if (quirks_ & PLUGIN_QUIRK_NO_WINDOWLESS && LowerCaseEqualsASCII(arg_names[i], "windowlessvideo")) { continue; } argn[argc] = const_cast<char*>(arg_names[i].c_str()); argv[argc] = const_cast<char*>(arg_values[i].c_str()); argc++; } bool start_result = instance_->Start( url, argn.get(), argv.get(), argc, load_manually); if (!start_result) return false; windowless_ = instance_->windowless(); if (!windowless_) { if (!WindowedCreatePlugin()) return false; } else { // For windowless plugins we should set the containing window handle // as the instance window handle. This is what Safari does. Not having // a valid window handle causes subtle bugs with plugins which retrieve // the window handle and validate the same. The window handle can be // retrieved via NPN_GetValue of NPNVnetscapeWindow. instance_->set_window_handle(parent_); } bool should_load = PlatformInitialize(); plugin_url_ = url.spec(); return should_load; } void WebPluginDelegateImpl::DestroyInstance() { if (instance_ && (instance_->npp()->ndata != NULL)) { // Shutdown all streams before destroying so that // no streams are left "in progress". Need to do // this before calling set_web_plugin(NULL) because the // instance uses the helper to do the download. instance_->CloseStreams(); window_.window = NULL; if (!(quirks_ & PLUGIN_QUIRK_DONT_SET_NULL_WINDOW_HANDLE_ON_DESTROY)) { instance_->NPP_SetWindow(&window_); } instance_->NPP_Destroy(); instance_->set_web_plugin(NULL); PlatformDestroyInstance(); instance_ = 0; } } void WebPluginDelegateImpl::UpdateGeometry( const gfx::Rect& window_rect, const gfx::Rect& clip_rect) { if (first_set_window_call_) { first_set_window_call_ = false; // Plugins like media player on Windows have a bug where in they handle the // first geometry update and ignore the rest resulting in painting issues. // This quirk basically ignores the first set window call sequence for // these plugins and has been tested for Windows plugins only. if (quirks_ & PLUGIN_QUIRK_IGNORE_FIRST_SETWINDOW_CALL) return; } if (windowless_) { WindowlessUpdateGeometry(window_rect, clip_rect); } else { WindowedUpdateGeometry(window_rect, clip_rect); } } void WebPluginDelegateImpl::SetFocus(bool focused) { DCHECK(windowless_); // This is called when internal WebKit focus (the focused element on the page) // changes, but plugins need to know about OS-level focus, so we have an extra // layer of focus tracking. // // On Windows, historically browsers did not set focus events to windowless // plugins when the toplevel window focus changes. Sending such focus events // breaks full screen mode in Flash because it will come out of full screen // mode when it loses focus, and its full screen window causes the browser to // lose focus. has_webkit_focus_ = focused; #ifndef OS_WIN if (containing_view_has_focus_) SetPluginHasFocus(focused); #else SetPluginHasFocus(focused); #endif } void WebPluginDelegateImpl::SetPluginHasFocus(bool focused) { if (focused == plugin_has_focus_) return; if (PlatformSetPluginHasFocus(focused)) plugin_has_focus_ = focused; } void WebPluginDelegateImpl::SetContentAreaHasFocus(bool has_focus) { containing_view_has_focus_ = has_focus; if (!windowless_) return; #ifndef OS_WIN // See SetFocus above. SetPluginHasFocus(containing_view_has_focus_ && has_webkit_focus_); #endif } NPObject* WebPluginDelegateImpl::GetPluginScriptableObject() { return instance_->GetPluginScriptableObject(); } void WebPluginDelegateImpl::DidFinishLoadWithReason(const GURL& url, NPReason reason, int notify_id) { if (quirks_ & PLUGIN_QUIRK_ALWAYS_NOTIFY_SUCCESS && reason == NPRES_NETWORK_ERR) { // Flash needs this or otherwise it unloads the launching swf object. reason = NPRES_DONE; } instance()->DidFinishLoadWithReason(url, reason, notify_id); } int WebPluginDelegateImpl::GetProcessId() { // We are in process, so the plugin pid is this current process pid. return base::GetCurrentProcId(); } void WebPluginDelegateImpl::SendJavaScriptStream(const GURL& url, const std::string& result, bool success, int notify_id) { instance()->SendJavaScriptStream(url, result, success, notify_id); } void WebPluginDelegateImpl::DidReceiveManualResponse( const GURL& url, const std::string& mime_type, const std::string& headers, uint32 expected_length, uint32 last_modified) { if (!windowless_) { // Calling NPP_WriteReady before NPP_SetWindow causes movies to not load in // Flash. See http://b/issue?id=892174. DCHECK(windowed_did_set_window_); } instance()->DidReceiveManualResponse(url, mime_type, headers, expected_length, last_modified); } void WebPluginDelegateImpl::DidReceiveManualData(const char* buffer, int length) { instance()->DidReceiveManualData(buffer, length); } void WebPluginDelegateImpl::DidFinishManualLoading() { instance()->DidFinishManualLoading(); } void WebPluginDelegateImpl::DidManualLoadFail() { instance()->DidManualLoadFail(); } FilePath WebPluginDelegateImpl::GetPluginPath() { return instance()->plugin_lib()->plugin_info().path; } void WebPluginDelegateImpl::WindowedUpdateGeometry( const gfx::Rect& window_rect, const gfx::Rect& clip_rect) { if (WindowedReposition(window_rect, clip_rect) || !windowed_did_set_window_) { // Let the plugin know that it has been moved WindowedSetWindow(); } } bool WebPluginDelegateImpl::HandleInputEvent(const WebInputEvent& event, WebCursorInfo* cursor_info) { DCHECK(windowless_) << "events should only be received in windowless mode"; bool pop_user_gesture = false; if (IsUserGesture(event)) { pop_user_gesture = true; instance()->PushPopupsEnabledState(true); } bool handled = PlatformHandleInputEvent(event, cursor_info); if (pop_user_gesture) { instance()->PopPopupsEnabledState(); } return handled; } bool WebPluginDelegateImpl::IsUserGesture(const WebInputEvent& event) { switch (event.type) { case WebInputEvent::MouseDown: case WebInputEvent::MouseUp: case WebInputEvent::KeyDown: case WebInputEvent::KeyUp: return true; default: return false; } return false; } WebPluginResourceClient* WebPluginDelegateImpl::CreateResourceClient( unsigned long resource_id, const GURL& url, int notify_id) { return instance()->CreateStream( resource_id, url, std::string(), notify_id); } WebPluginResourceClient* WebPluginDelegateImpl::CreateSeekableResourceClient( unsigned long resource_id, int range_request_id) { return instance()->GetRangeRequest(range_request_id); } <|endoftext|>
<commit_before> #include "RMinimizer.h" #include "Math/IFunction.h" #include <TVectorD.h> #include "Math/BasicMinimizer.h" #include "Math/MultiNumGradFunction.h" const ROOT::Math::IMultiGenFunction *gFunction; double minfunction(TVectorD x){ return (*gFunction)(x.GetMatrixArray()); } RMinimizer::RMinimizer(Option_t *method){ fMethod=method; if (fMethod.empty() ) fMethod="BFGS"; } void RMinimizer::SetFunction(& gFunction) { // set the function to minimizer // need to calculate numerically the derivatives: do via class MultiNumGradFunction // no need to clone the passed function ROOT::Math::MultiNumGradFunction gradFunc(gFunction); // function is cloned inside so can be delete afterwards // called base class method setfunction // (note: write explicitly otherwise it will call back itself) BasicMinimizer::SetFunction(gradFunc); } //SetFunctions bool RMinimizer::Minimize() { (gFunction)= ObjFunction(); /* *"Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent" (Brent only for 1D minimization) */ //std::cout<<"Number of dimension ="<< NDim() << std::endl; //pass function to R ROOT::R::TRInterface &r=gR->Instance(); r["minfunction"] = ROOT::R::TRFunction((minfunction)); r["method"] = fMethod.c_str(); std::vector<double> stepSizes(StepSizes(), StepSizes()+NDim()); std::vector<double> values(X(), X()+NDim()); r["stepsizes"] = stepSizes; r["initialparams"] = values; //find minimum in R TString cmd = TString::Format("result <- optim( initialparams, minfunction,method='%s',control = list(ndeps=stepsizes,maxit=%d,trace=%d,abstol=%e))",fMethod.c_str(),MaxIterations(),PrintLevel(),Tolerance()); //std::cout << "Calling R with command " << cmd << std::endl; r.Parse(cmd.Data()); //get result from R TVectorD vector=r.ParseEval("result$par").ToVector<Double_t>(); const double *min=vector.GetMatrixArray(); //std::cout.precision(8); //print results //std::cout<<"-----------------------------------------"<<std::endl; //std::cout<<"Minimum x="<<min[0]<<" y="<<min[1]<<std::endl; SetFinalValues(min); SetMinValue((*gFunction)(min)); //std::cout<<"Value at minimum ="<<MinValue()<<std::endl; r.Parse("optimHess(result$par, minfunction, gradFunc)"); TString cmd2 = TString::Format("hresult <- optim( initialparams, minfunction,NULL, method='%s',hessian = TRUE, control = list(ndeps=stepsizes,maxit=%d,trace=%d,abstol=%e))",fMethod.c_str(),MaxIterations(),PrintLevel(),Tolerance()); r.Parse(cmd2.Data()); //getting the min calculated with the gradient TVectorD hmin=r.ParseEval("hresult$par").ToVector<Double_t>(); return kTRUE; } <commit_msg>fixed include header location<commit_after> #include "Math/RMinimizer.h" #include "Math/IFunction.h" #include <TVectorD.h> #include "Math/BasicMinimizer.h" #include "Math/MultiNumGradFunction.h" const ROOT::Math::IMultiGenFunction *gFunction; double minfunction(TVectorD x){ return (*gFunction)(x.GetMatrixArray()); } RMinimizer::RMinimizer(Option_t *method){ fMethod=method; if (fMethod.empty() ) fMethod="BFGS"; } void RMinimizer::SetFunction(& gFunction) { // set the function to minimizer // need to calculate numerically the derivatives: do via class MultiNumGradFunction // no need to clone the passed function ROOT::Math::MultiNumGradFunction gradFunc(gFunction); // function is cloned inside so can be delete afterwards // called base class method setfunction // (note: write explicitly otherwise it will call back itself) BasicMinimizer::SetFunction(gradFunc); } //SetFunctions bool RMinimizer::Minimize() { (gFunction)= ObjFunction(); /* *"Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent" (Brent only for 1D minimization) */ //std::cout<<"Number of dimension ="<< NDim() << std::endl; //pass function to R ROOT::R::TRInterface &r=gR->Instance(); r["minfunction"] = ROOT::R::TRFunction((minfunction)); r["method"] = fMethod.c_str(); std::vector<double> stepSizes(StepSizes(), StepSizes()+NDim()); std::vector<double> values(X(), X()+NDim()); r["stepsizes"] = stepSizes; r["initialparams"] = values; //find minimum in R TString cmd = TString::Format("result <- optim( initialparams, minfunction,method='%s',control = list(ndeps=stepsizes,maxit=%d,trace=%d,abstol=%e))",fMethod.c_str(),MaxIterations(),PrintLevel(),Tolerance()); //std::cout << "Calling R with command " << cmd << std::endl; r.Parse(cmd.Data()); //get result from R TVectorD vector=r.ParseEval("result$par").ToVector<Double_t>(); const double *min=vector.GetMatrixArray(); //std::cout.precision(8); //print results //std::cout<<"-----------------------------------------"<<std::endl; //std::cout<<"Minimum x="<<min[0]<<" y="<<min[1]<<std::endl; SetFinalValues(min); SetMinValue((*gFunction)(min)); //std::cout<<"Value at minimum ="<<MinValue()<<std::endl; r.Parse("optimHess(result$par, minfunction, gradFunc)"); TString cmd2 = TString::Format("hresult <- optim( initialparams, minfunction,NULL, method='%s',hessian = TRUE, control = list(ndeps=stepsizes,maxit=%d,trace=%d,abstol=%e))",fMethod.c_str(),MaxIterations(),PrintLevel(),Tolerance()); r.Parse(cmd2.Data()); //getting the min calculated with the gradient TVectorD hmin=r.ParseEval("hresult$par").ToVector<Double_t>(); return kTRUE; } <|endoftext|>
<commit_before>/* * DefaultForwardChainerCB.cc * * Copyright (C) 2015 Misgana Bayetta * * Author: Misgana Bayetta <misgana.bayetta@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atomutils/AtomUtils.h> #include <opencog/guile/SchemeSmob.h> #include <opencog/atoms/bind/BindLink.h> #include "DefaultForwardChainerCB.h" #include "PLNCommons.h" using namespace opencog; DefaultForwardChainerCB::DefaultForwardChainerCB( AtomSpace* as, source_selection_mode ts_mode /*=TV_FITNESS_BASED*/) : ForwardChainerCallBack(as) { as_ = as; fcim_ = new ForwardChainInputMatchCB(as); fcpm_ = new ForwardChainPatternMatchCB(as); ts_mode_ = ts_mode; } DefaultForwardChainerCB::~DefaultForwardChainerCB() { delete fcim_; delete fcpm_; } /** * choose rule based on premises of rule matching the source * uses temporary atomspace to limit the search space * * @param fcmem forward chainer's working memory * @return a vector of chosen rules */ vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem) { Handle source = fcmem.get_cur_source(); if (source == Handle::UNDEFINED or NodeCast(source)) throw InvalidParamException(TRACE_INFO, "Needs a source atom of type LINK"); HandleSeq chosen_bindlinks; if (LinkCast(source)) { AtomSpace rule_atomspace; Handle source_cpy = rule_atomspace.addAtom(source); // Copy rules to the temporary atomspace. vector<Rule*> rules = fcmem.get_rules(); for (Rule* r : rules) { rule_atomspace.addAtom(r->get_handle()); } // Create bindlink with source as an implicant. PLNCommons pc(&rule_atomspace); Handle copy = pc.replace_nodes_with_varnode(source_cpy, NODE); Handle bind_link = pc.create_bindLink(copy, false); // Pattern match. BindLinkPtr bl(BindLinkCast(bind_link)); DefaultImplicator imp(&rule_atomspace); imp.implicand = bl->get_implicand(); imp.set_type_restrictions(bl->get_typemap()); bl->imply(&imp); // Get matched bindLinks. HandleSeq matches = imp.result_list; if (matches.empty()) { logger().debug( "No matching BindLink was found.Returning empty vector"); return vector<Rule*> { }; } HandleSeq bindlinks; for (Handle hm : matches) { //get all BindLinks whose part of their premise matches with hm HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK); for (Handle hi : hs) { if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) { bindlinks.push_back(hi); } } } // Copy handles to main atomspace. for (Handle h : bindlinks) { chosen_bindlinks.push_back(as_->addAtom(h)); } } // Try to find specialized rules that contain the source node. if (NodeCast(source)) { chosen_bindlinks = get_rootlinks(source, as_, BIND_LINK); } // Find the rules containing the bindLink in copied_back. vector<Rule*> matched_rules; vector<Rule*> rules = fcmem.get_rules(); for (Rule* r : rules) { auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(), r->get_handle()); //xxx not matching if (it != chosen_bindlinks.end()) { matched_rules.push_back(r); } } return matched_rules; } /** * Gets all top level links of certain types and subclasses that contain @param hsource * * @param hsource handle whose top level links are to be searched * @param as the atomspace in which search is to be done * @param link_type the root link types to be searched * @param subclasses a flag that tells to look subclasses of @link_type */ HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle hsource, AtomSpace* as, Type link_type, bool subclasses) { auto outgoing = [as](Handle h) {return as->getOutgoing(h);}; PLNCommons pc(as); HandleSeq chosen_roots; HandleSeq candidates_roots; pc.get_root_links(hsource, candidates_roots); for (Handle hr : candidates_roots) { bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr) == chosen_roots.end(); auto type = as->getType(hr); bool subtype = (subclasses and classserver().isA(type, link_type)); if (((type == link_type) or subtype) and notexist) { //make sure matches are actually part of the premise list rather than the output of the bindLink Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..)))) if (pc.exists_in(hpremise, hsource)) { chosen_roots.push_back(hr); } } } return chosen_roots; } HandleSeq DefaultForwardChainerCB::choose_premises(FCMemory& fcmem) { HandleSeq inputs; PLNCommons pc(as_); Handle hsource = fcmem.get_cur_source(); // Get everything associated with the source handle. HandleSeq neighbors = getNeighbors(hsource, true, true, LINK, true); // Add all root links of atoms in @param neighbors. for (auto hn : neighbors) { if (hn->getType() != VARIABLE_NODE) { HandleSeq roots; pc.get_root_links(hn, roots); for (auto r : roots) { if (find(inputs.begin(), inputs.end(), r) == inputs.end() and r->getType() != BIND_LINK) inputs.push_back(r); } } } return inputs; } Handle DefaultForwardChainerCB::choose_next_source(FCMemory& fcmem) { HandleSeq tlist = fcmem.get_premise_list(); map<Handle, float> tournament_elem; PLNCommons pc(as_); Handle hchosen = Handle::UNDEFINED; for (Handle t : tlist) { switch (ts_mode_) { case TV_FITNESS_BASED: { float fitness = pc.tv_fitness(t); tournament_elem[t] = fitness; } break; case STI_BASED: tournament_elem[t] = t->getSTI(); break; default: throw RuntimeException(TRACE_INFO, "Unknown source selection mode."); break; } } //!Choose a new source that has never been chosen before. //!xxx FIXME since same handle might be chosen multiple times the following //!code doesn't guarantee all sources have been exhaustively looked. for (size_t i = 0; i < tournament_elem.size(); i++) { Handle hselected = pc.tournament_select(tournament_elem); if (fcmem.isin_source_list(hselected)) { continue; } else { hchosen = hselected; break; } } return hchosen; } //TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem) { Rule * cur_rule = fcmem.get_cur_rule(); fcpm_->set_fcmem(&fcmem); BindLinkPtr bl(BindLinkCast(cur_rule->get_handle())); bl->imply(fcpm_); HandleSeq product = fcpm_->get_products(); //! Make sure the inferences made are new. HandleSeq new_product; for (auto h : product) { if (not fcmem.isin_premise_list(h)) new_product.push_back(h); } return new_product; } <commit_msg>Replace getNeighbors by get_distant_neighbors<commit_after>/* * DefaultForwardChainerCB.cc * * Copyright (C) 2015 Misgana Bayetta * * Author: Misgana Bayetta <misgana.bayetta@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atomutils/AtomUtils.h> #include <opencog/guile/SchemeSmob.h> #include <opencog/atoms/bind/BindLink.h> #include "DefaultForwardChainerCB.h" #include "PLNCommons.h" using namespace opencog; DefaultForwardChainerCB::DefaultForwardChainerCB( AtomSpace* as, source_selection_mode ts_mode /*=TV_FITNESS_BASED*/) : ForwardChainerCallBack(as) { as_ = as; fcim_ = new ForwardChainInputMatchCB(as); fcpm_ = new ForwardChainPatternMatchCB(as); ts_mode_ = ts_mode; } DefaultForwardChainerCB::~DefaultForwardChainerCB() { delete fcim_; delete fcpm_; } /** * choose rule based on premises of rule matching the source * uses temporary atomspace to limit the search space * * @param fcmem forward chainer's working memory * @return a vector of chosen rules */ vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem) { Handle source = fcmem.get_cur_source(); if (source == Handle::UNDEFINED or NodeCast(source)) throw InvalidParamException(TRACE_INFO, "Needs a source atom of type LINK"); HandleSeq chosen_bindlinks; if (LinkCast(source)) { AtomSpace rule_atomspace; Handle source_cpy = rule_atomspace.addAtom(source); // Copy rules to the temporary atomspace. vector<Rule*> rules = fcmem.get_rules(); for (Rule* r : rules) { rule_atomspace.addAtom(r->get_handle()); } // Create bindlink with source as an implicant. PLNCommons pc(&rule_atomspace); Handle copy = pc.replace_nodes_with_varnode(source_cpy, NODE); Handle bind_link = pc.create_bindLink(copy, false); // Pattern match. BindLinkPtr bl(BindLinkCast(bind_link)); DefaultImplicator imp(&rule_atomspace); imp.implicand = bl->get_implicand(); imp.set_type_restrictions(bl->get_typemap()); bl->imply(&imp); // Get matched bindLinks. HandleSeq matches = imp.result_list; if (matches.empty()) { logger().debug( "No matching BindLink was found.Returning empty vector"); return vector<Rule*> { }; } HandleSeq bindlinks; for (Handle hm : matches) { //get all BindLinks whose part of their premise matches with hm HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK); for (Handle hi : hs) { if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) { bindlinks.push_back(hi); } } } // Copy handles to main atomspace. for (Handle h : bindlinks) { chosen_bindlinks.push_back(as_->addAtom(h)); } } // Try to find specialized rules that contain the source node. if (NodeCast(source)) { chosen_bindlinks = get_rootlinks(source, as_, BIND_LINK); } // Find the rules containing the bindLink in copied_back. vector<Rule*> matched_rules; vector<Rule*> rules = fcmem.get_rules(); for (Rule* r : rules) { auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(), r->get_handle()); //xxx not matching if (it != chosen_bindlinks.end()) { matched_rules.push_back(r); } } return matched_rules; } /** * Gets all top level links of certain types and subclasses that contain @param hsource * * @param hsource handle whose top level links are to be searched * @param as the atomspace in which search is to be done * @param link_type the root link types to be searched * @param subclasses a flag that tells to look subclasses of @link_type */ HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle hsource, AtomSpace* as, Type link_type, bool subclasses) { auto outgoing = [as](Handle h) {return as->getOutgoing(h);}; PLNCommons pc(as); HandleSeq chosen_roots; HandleSeq candidates_roots; pc.get_root_links(hsource, candidates_roots); for (Handle hr : candidates_roots) { bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr) == chosen_roots.end(); auto type = as->getType(hr); bool subtype = (subclasses and classserver().isA(type, link_type)); if (((type == link_type) or subtype) and notexist) { //make sure matches are actually part of the premise list rather than the output of the bindLink Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..)))) if (pc.exists_in(hpremise, hsource)) { chosen_roots.push_back(hr); } } } return chosen_roots; } HandleSeq DefaultForwardChainerCB::choose_premises(FCMemory& fcmem) { HandleSeq inputs; PLNCommons pc(as_); Handle hsource = fcmem.get_cur_source(); // Get everything associated with the source handle. UnorderedHandleSet neighbors = get_distant_neighbors(hsource, 2); // Add all root links of atoms in @param neighbors. for (auto hn : neighbors) { if (hn->getType() != VARIABLE_NODE) { HandleSeq roots; pc.get_root_links(hn, roots); for (auto r : roots) { if (find(inputs.begin(), inputs.end(), r) == inputs.end() and r->getType() != BIND_LINK) inputs.push_back(r); } } } return inputs; } Handle DefaultForwardChainerCB::choose_next_source(FCMemory& fcmem) { HandleSeq tlist = fcmem.get_premise_list(); map<Handle, float> tournament_elem; PLNCommons pc(as_); Handle hchosen = Handle::UNDEFINED; for (Handle t : tlist) { switch (ts_mode_) { case TV_FITNESS_BASED: { float fitness = pc.tv_fitness(t); tournament_elem[t] = fitness; } break; case STI_BASED: tournament_elem[t] = t->getSTI(); break; default: throw RuntimeException(TRACE_INFO, "Unknown source selection mode."); break; } } //!Choose a new source that has never been chosen before. //!xxx FIXME since same handle might be chosen multiple times the following //!code doesn't guarantee all sources have been exhaustively looked. for (size_t i = 0; i < tournament_elem.size(); i++) { Handle hselected = pc.tournament_select(tournament_elem); if (fcmem.isin_source_list(hselected)) { continue; } else { hchosen = hselected; break; } } return hchosen; } //TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem) { Rule * cur_rule = fcmem.get_cur_rule(); fcpm_->set_fcmem(&fcmem); BindLinkPtr bl(BindLinkCast(cur_rule->get_handle())); bl->imply(fcpm_); HandleSeq product = fcpm_->get_products(); //! Make sure the inferences made are new. HandleSeq new_product; for (auto h : product) { if (not fcmem.isin_premise_list(h)) new_product.push_back(h); } return new_product; } <|endoftext|>
<commit_before>/** * @file deBruijnGraphGen.hpp * @ingroup graphGen * @author Chirag Jain <cjain7@gatech.edu> * @brief Builds the edgelist for de bruijn graph using BLISS library. * * Copyright (c) 2015 Georgia Institute of Technology. All Rights Reserved. */ #ifndef DE_BRUIJN_GEN_HPP #define DE_BRUIJN_GEN_HPP //Includes #include <mpi.h> #include <iostream> #include <vector> //Own includes #include "graphGen/common/timer.hpp" //External includes #include "debruijn/de_bruijn_node_trait.hpp" #include "debruijn/de_bruijn_construct_engine.hpp" #include "debruijn/de_bruijn_nodes_distributed.hpp" namespace conn { namespace graphGen { /** * @class conn::graphGen::deBruijnGraph * @brief Builds the edgelist of de Bruijn graph * @details Sequences are expected in the FASTQ format * Restrict the alphabets of DNA to {A,C,G,T} */ class deBruijnGraph { public: //Kmer size set to 31, and alphabets set to 4 nucleotides using Alphabet = bliss::common::DNA; using KmerType = bliss::common::Kmer<31, Alphabet>; //BLISS internal data structure for storing de bruijn graph template <typename EdgeEnc> using NodeMapType = typename bliss::de_bruijn::de_bruijn_nodes_distributed< KmerType, bliss::de_bruijn::node::edge_exists<EdgeEnc>, int, bliss::kmer::transform::identity, bliss::kmer::hash::farm>; //Parser type, depends on the sequence file format //We restrict the usage to FASTQ format template <typename baseIter> using SeqParser = typename bliss::io::FASTQParser<baseIter>; /** * @brief populates the edge list vector * @param[in] fileName * @param[out] edgelist */ template <typename E> void populateEdgeList( std::vector< std::pair<E, E> > &edgeList, std::string &fileName, const mxx::comm &comm) { Timer timer; //Initialize the map bliss::de_bruijn::de_bruijn_engine<NodeMapType> idx(comm); //Build the de Bruijn graph as distributed map idx.template build<SeqParser>(fileName, comm); auto it = idx.cbegin(); //Deriving data type of de Bruijn graph storage container using mapPairType = typename std::iterator_traits<decltype(it)>::value_type; using constkmerType = typename std::tuple_element<0, mapPairType>::type; using kmerType = typename std::remove_const<constkmerType>::type; //Remove const from nodetype using edgeCountInfoType = typename std::tuple_element<1, mapPairType>::type; //Temporary storage for each kmer's neighbors in the graph std::vector<kmerType> tmpNeighborVector1; std::vector<kmerType> tmpNeighborVector2; bliss::kmer::transform::lex_less<KmerType> minKmer; static_assert(std::is_same<typename kmerType::KmerWordType, uint64_t>::value, "Kmer word type should be set to uint64_t"); //Read the index and populate the edges inside edgeList for(; it != idx.cend(); it++) { auto sourceKmer = it->first; //Get incoming neighbors bliss::de_bruijn::node::node_utils<kmerType, edgeCountInfoType>::get_in_neighbors(sourceKmer, it->second, tmpNeighborVector1); //Get outgoing neigbors bliss::de_bruijn::node::node_utils<kmerType, edgeCountInfoType>::get_out_neighbors(sourceKmer, it->second, tmpNeighborVector2); //typename kmerType::KmerWordType* sourceVertexData = minKmer(sourceKmer).getData(); size_t s = minKmer(sourceKmer).getData()[0]; //Push the edges to our edgeList for(auto &e : tmpNeighborVector1) { size_t d = minKmer(e).getData()[0]; edgeList.emplace_back(s, d); } //Same procedure for the outgoing edges for(auto &e : tmpNeighborVector2) { size_t d = minKmer(e).getData()[0]; edgeList.emplace_back(s, d); } } timer.end_section("graph generation completed"); } }; } } #endif <commit_msg>Potential bug fixed<commit_after>/** * @file deBruijnGraphGen.hpp * @ingroup graphGen * @author Chirag Jain <cjain7@gatech.edu> * @brief Builds the edgelist for de bruijn graph using BLISS library. * * Copyright (c) 2015 Georgia Institute of Technology. All Rights Reserved. */ #ifndef DE_BRUIJN_GEN_HPP #define DE_BRUIJN_GEN_HPP //Includes #include <mpi.h> #include <iostream> #include <vector> //Own includes #include "graphGen/common/timer.hpp" //External includes #include "debruijn/de_bruijn_node_trait.hpp" #include "debruijn/de_bruijn_construct_engine.hpp" #include "debruijn/de_bruijn_nodes_distributed.hpp" namespace conn { namespace graphGen { /** * @class conn::graphGen::deBruijnGraph * @brief Builds the edgelist of de Bruijn graph * @details Sequences are expected in the FASTQ format * Restrict the alphabets of DNA to {A,C,G,T} */ class deBruijnGraph { public: //Kmer size set to 31, and alphabets set to 4 nucleotides using Alphabet = bliss::common::DNA; using KmerType = bliss::common::Kmer<31, Alphabet>; //BLISS internal data structure for storing de bruijn graph template <typename EdgeEnc> using NodeMapType = typename bliss::de_bruijn::de_bruijn_nodes_distributed< KmerType, bliss::de_bruijn::node::edge_exists<EdgeEnc>, int, bliss::kmer::transform::identity, bliss::kmer::hash::farm>; //Parser type, depends on the sequence file format //We restrict the usage to FASTQ format template <typename baseIter> using SeqParser = typename bliss::io::FASTQParser<baseIter>; /** * @brief populates the edge list vector * @param[in] fileName * @param[out] edgelist */ template <typename E> void populateEdgeList( std::vector< std::pair<E, E> > &edgeList, std::string &fileName, const mxx::comm &comm) { Timer timer; //Initialize the map bliss::de_bruijn::de_bruijn_engine<NodeMapType> idx(comm); //Build the de Bruijn graph as distributed map idx.template build<SeqParser>(fileName, comm); auto it = idx.cbegin(); //Deriving data type of de Bruijn graph storage container using mapPairType = typename std::iterator_traits<decltype(it)>::value_type; using constkmerType = typename std::tuple_element<0, mapPairType>::type; using kmerType = typename std::remove_const<constkmerType>::type; //Remove const from nodetype using edgeCountInfoType = typename std::tuple_element<1, mapPairType>::type; //Temporary storage for each kmer's neighbors in the graph std::vector<kmerType> tmpNeighborVector1; std::vector<kmerType> tmpNeighborVector2; bliss::kmer::transform::lex_less<KmerType> minKmer; static_assert(std::is_same<typename kmerType::KmerWordType, uint64_t>::value, "Kmer word type should be set to uint64_t"); //Read the index and populate the edges inside edgeList for(; it != idx.cend(); it++) { auto sourceKmer = it->first; //Get incoming neighbors bliss::de_bruijn::node::node_utils<kmerType, edgeCountInfoType>::get_in_neighbors(sourceKmer, it->second, tmpNeighborVector1); //Get outgoing neigbors bliss::de_bruijn::node::node_utils<kmerType, edgeCountInfoType>::get_out_neighbors(sourceKmer, it->second, tmpNeighborVector2); //typename kmerType::KmerWordType* sourceVertexData = minKmer(sourceKmer).getData(); auto s = minKmer(sourceKmer).getData()[0]; //Push the edges to our edgeList for(auto &e : tmpNeighborVector1) { auto d = minKmer(e).getData()[0]; edgeList.emplace_back(s, d); } //Same procedure for the outgoing edges for(auto &e : tmpNeighborVector2) { auto d = minKmer(e).getData()[0]; edgeList.emplace_back(s, d); } } timer.end_section("graph generation completed"); } }; } } #endif <|endoftext|>
<commit_before> #include "relay.h" #ifdef RELAY bool relayEnabled = RELAY_ENABLED; uint8_t relayChannel = RELAY_CHANNEL; // Channel to switch between PXX and PPM control; Allowed only channels CH5..CH8; uint8_t gpsModeChannel = GPS_MODE_CHANNEL; // Set it to channel to enable GPS HOLD mode; Allowed only channels CH5..CH8; uint16_t gpsHoldValue = GPS_HOLD_VALUE; // Set it to enable GPS HOLD in GPS_MODE_CHANNEL on both relay and mission drone; // RELAY_CHANNEL signal boundaries to enable PXX or CPPM control; uint16_t activePXX_Min = ACTIVE_PXX_MIN; // Min. value for make PXX control active; uint16_t activePXX_Max = ACTIVE_PXX_MAX; // Max. value for make PXX control active; uint16_t activeCPPM_Min = ACTIVE_CPPM_MIN; // Min. value for make CPPM control active; uint16_t activeCPPM_Max = ACTIVE_CPPM_MAX; // Max. value for make CPPM control active; bool holdThrottleEnabled = HOLD_THROTTLE_ENABLED; // Enable setting mid throttle (normally, 1500) for armed inactive copter and min throttle for disarmed inactive copter; uint16_t midThrottle = MID_THROTTLE; // Mid throttle value; uint16_t minThrottle = MIN_THROTTLE; // Min throttle value; // ARM channel signal boundaries for PXX or CPPM control; only armed copter will receive mid throttle when inactive; not armed will receive min throtlle; uint8_t armCPPMChannel = ARM_CPPM_CHANNEL; // Set it to channel to arm CPPM controlled copter; Allowed only channels CH5..CH8; uint8_t armPXXChannel = ARM_PXX_CHANNEL; // Set it to channel to arm PXX controlled copter; Allowed only channels CH5..CH8; uint16_t armCPPM_Min = ARM_CPPM_MIN; // Min. value for make CPPM arm; uint16_t armCPPM_Max = ARM_CPPM_MAX; // Max. value for make CPPM arm; uint16_t armPXX_Min = ARM_PXX_MIN; // Min. value for make PXX arm; uint16_t armPXX_Max = ARM_PXX_MAX; // Max. value for make PXX arm; // CH5 = 1000 for ARM_CPPM = 0; // CH6 = 1000 for ARM_PXX = 0; int16_t channels_out_pxx [NUM_CHANNELS_PXX] = { 1500,1500,1000,1500,1000,1000,1000,1000, 1000,1000,1000,1000,1000,1000,1000,1000}; int16_t channels_out_cppm[NUM_CHANNELS_CPPM] = { 1500,1500,1000,1500,1000,1000,1000,1000 }; static int8_t active = RELAY_ACTIVE_NONE; static int8_t oldActive = RELAY_ACTIVE_NONE; static bool channelsInitialized = false; static bool pxx_armed = false; static bool cppm_armed = false; void relayInit() { pinMode(PIN_CAMERA_SEL, OUTPUT); digitalWrite(PIN_CAMERA_SEL, CAMERA_CPPM); } int8_t getRelayActive() { return active; } bool isRelayActiveChanged() { if (oldActive == active) return false; oldActive = active; return true; } void setRelayActive(int8_t aActive) { if (aActive == active) { return; } active = aActive; beeper1.play(active == RELAY_ACTIVE_PXX ? &SEQ_RELAY_ACTIVE_PXX : active == RELAY_ACTIVE_CPPM ? &SEQ_RELAY_ACTIVE_CPPM : &SEQ_RELAY_ACTIVE_NONE); } #ifdef DEBUG_RELAY void dumpChannels(int16_t channels[], int8_t size) { for (int8_t i=0; i<size; i++) { if (i > 0) Serial.print(","); Serial.print(channels[i], DEC); } Serial.println(); } #endif bool inRange(uint16_t x, uint16_t min, uint16_t max) { return x >= min && x <= max; } void centerControlsAndHold(int16_t channels[], bool thrOverride, uint16_t thrOverrideValue) { // Enter GPS Hold; channels[gpsModeChannel] = gpsHoldValue; // Reset Roll, Pitch, Yaw; // Throttle is in last position; channels[CH1] = 1500; channels[CH2] = 1500; if (thrOverride) { channels[CH3] = thrOverrideValue; } channels[CH4] = 1500; } class Debouncer<T> { public: Debouncer(int8_t maxCount) : maxCount(maxCount), counter(0), initialized(false); T debounce(T value) { if (!initialized) { initialized = true; stableValue = value; prevValue = value; } else if (prevValue == value) { if (counter < maxCount) { counter++; } else { stableValue = value; } } else { // value == stableValue || value != prevValue; prevValue = value; counter = 0; } return stableValue; } private: int8_t maxCount; bool initialized; int8_t counter; T stableValue; T prevValue; } static Debouncer<bool> pxx_debouncer(ARM_DEBOUNCE_FRAMES); static Debouncer<bool> cppm_debouncer(ARM_DEBOUNCE_FRAMES); void updateChannelsRelay(int16_t channels[]) { pxx_armed = channelsInitialized && pxx_debouncer.debounce(inRange(channels[armPXXChannel], armPXX_Min, armPXX_Max)); cppm_armed = channelsInitialized && cppm_debouncer.debounce(inRange(channels[armCPPMChannel], armCPPM_Min, armCPPM_Max)); uint16_t value = channels[relayChannel]; if (relayEnabled && inRange(value, activePXX_Min, activePXX_Max)) { setRelayActive(RELAY_ACTIVE_PXX); } else if (relayEnabled && inRange(value, activeCPPM_Min, activeCPPM_Max)) { setRelayActive(RELAY_ACTIVE_CPPM); } else { setRelayActive(RELAY_ACTIVE_NONE); } if (active == RELAY_ACTIVE_PXX || !channelsInitialized) { memcpy(channels_out_pxx, channels, NUM_CHANNELS_PXX*sizeof(channels[0])); } if (active == RELAY_ACTIVE_CPPM || !channelsInitialized) { memcpy(channels_out_cppm, channels, NUM_CHANNELS_CPPM*sizeof(channels[0])); } if (relayEnabled) { if (active != RELAY_ACTIVE_PXX) { centerControlsAndHold(channels_out_pxx, holdThrottleEnabled, pxx_armed ? midThrottle : minThrottle); } if (active != RELAY_ACTIVE_CPPM) { centerControlsAndHold(channels_out_cppm, holdThrottleEnabled, cppm_armed ? midThrottle : minThrottle); } if (active == RELAY_ACTIVE_PXX) { digitalWrite(PIN_CAMERA_SEL, CAMERA_PXX); } if (active == RELAY_ACTIVE_CPPM) { digitalWrite(PIN_CAMERA_SEL, CAMERA_CPPM); } else { // If both CPPM and PXX copters are inactive, keep last selected camera; } } channelsInitialized = true; #ifdef DEBUG_RELAY Serial.print("active="); Serial.println(active == RELAY_ACTIVE_PXX ? "PXX" : active == RELAY_ACTIVE_CPPM ? "CPPM" : "---"); Serial.print("PXX ="); dumpChannels(channels_out_pxx, NUM_CHANNELS_PXX); Serial.print("CPPM="); dumpChannels(channels_out_cppm, NUM_CHANNELS_CPPM); #endif } bool getCPPMArmed() { return cppm_armed; } bool getPXXArmed() { return pxx_armed; } #endif <commit_msg>Arm status debouncer fixed;<commit_after> #include "relay.h" #ifdef RELAY bool relayEnabled = RELAY_ENABLED; uint8_t relayChannel = RELAY_CHANNEL; // Channel to switch between PXX and PPM control; Allowed only channels CH5..CH8; uint8_t gpsModeChannel = GPS_MODE_CHANNEL; // Set it to channel to enable GPS HOLD mode; Allowed only channels CH5..CH8; uint16_t gpsHoldValue = GPS_HOLD_VALUE; // Set it to enable GPS HOLD in GPS_MODE_CHANNEL on both relay and mission drone; // RELAY_CHANNEL signal boundaries to enable PXX or CPPM control; uint16_t activePXX_Min = ACTIVE_PXX_MIN; // Min. value for make PXX control active; uint16_t activePXX_Max = ACTIVE_PXX_MAX; // Max. value for make PXX control active; uint16_t activeCPPM_Min = ACTIVE_CPPM_MIN; // Min. value for make CPPM control active; uint16_t activeCPPM_Max = ACTIVE_CPPM_MAX; // Max. value for make CPPM control active; bool holdThrottleEnabled = HOLD_THROTTLE_ENABLED; // Enable setting mid throttle (normally, 1500) for armed inactive copter and min throttle for disarmed inactive copter; uint16_t midThrottle = MID_THROTTLE; // Mid throttle value; uint16_t minThrottle = MIN_THROTTLE; // Min throttle value; // ARM channel signal boundaries for PXX or CPPM control; only armed copter will receive mid throttle when inactive; not armed will receive min throtlle; uint8_t armCPPMChannel = ARM_CPPM_CHANNEL; // Set it to channel to arm CPPM controlled copter; Allowed only channels CH5..CH8; uint8_t armPXXChannel = ARM_PXX_CHANNEL; // Set it to channel to arm PXX controlled copter; Allowed only channels CH5..CH8; uint16_t armCPPM_Min = ARM_CPPM_MIN; // Min. value for make CPPM arm; uint16_t armCPPM_Max = ARM_CPPM_MAX; // Max. value for make CPPM arm; uint16_t armPXX_Min = ARM_PXX_MIN; // Min. value for make PXX arm; uint16_t armPXX_Max = ARM_PXX_MAX; // Max. value for make PXX arm; // CH5 = 1000 for ARM_CPPM = 0; // CH6 = 1000 for ARM_PXX = 0; int16_t channels_out_pxx [NUM_CHANNELS_PXX] = { 1500,1500,1000,1500,1000,1000,1000,1000, 1000,1000,1000,1000,1000,1000,1000,1000}; int16_t channels_out_cppm[NUM_CHANNELS_CPPM] = { 1500,1500,1000,1500,1000,1000,1000,1000 }; static int8_t active = RELAY_ACTIVE_NONE; static int8_t oldActive = RELAY_ACTIVE_NONE; static bool channelsInitialized = false; static bool pxx_armed = false; static bool cppm_armed = false; void relayInit() { pinMode(PIN_CAMERA_SEL, OUTPUT); digitalWrite(PIN_CAMERA_SEL, CAMERA_CPPM); } int8_t getRelayActive() { return active; } bool isRelayActiveChanged() { if (oldActive == active) return false; oldActive = active; return true; } void setRelayActive(int8_t aActive) { if (aActive == active) { return; } active = aActive; beeper1.play(active == RELAY_ACTIVE_PXX ? &SEQ_RELAY_ACTIVE_PXX : active == RELAY_ACTIVE_CPPM ? &SEQ_RELAY_ACTIVE_CPPM : &SEQ_RELAY_ACTIVE_NONE); } #ifdef DEBUG_RELAY void dumpChannels(int16_t channels[], int8_t size) { for (int8_t i=0; i<size; i++) { if (i > 0) Serial.print(","); Serial.print(channels[i], DEC); } Serial.println(); } #endif bool inRange(uint16_t x, uint16_t min, uint16_t max) { return x >= min && x <= max; } void centerControlsAndHold(int16_t channels[], bool thrOverride, uint16_t thrOverrideValue) { // Enter GPS Hold; channels[gpsModeChannel] = gpsHoldValue; // Reset Roll, Pitch, Yaw; // Throttle is in last position; channels[CH1] = 1500; channels[CH2] = 1500; if (thrOverride) { channels[CH3] = thrOverrideValue; } channels[CH4] = 1500; } template <typename T> class Debouncer { public: Debouncer(int8_t maxCount) : maxCount(maxCount), counter(0), initialized(false) {}; T debounce(T value) { if (!initialized) { initialized = true; stableValue = value; prevValue = value; } else if (prevValue == value) { if (counter < maxCount) { counter++; } else { stableValue = value; } } else { // value == stableValue || value != prevValue; prevValue = value; counter = 0; } return stableValue; } private: int8_t maxCount; bool initialized; int8_t counter; T stableValue; T prevValue; }; static Debouncer<bool> pxx_debouncer (ARM_DEBOUNCE_FRAMES); static Debouncer<bool> cppm_debouncer(ARM_DEBOUNCE_FRAMES); void updateChannelsRelay(int16_t channels[]) { pxx_armed = channelsInitialized && pxx_debouncer.debounce(inRange(channels[armPXXChannel], armPXX_Min, armPXX_Max)); cppm_armed = channelsInitialized && cppm_debouncer.debounce(inRange(channels[armCPPMChannel], armCPPM_Min, armCPPM_Max)); uint16_t value = channels[relayChannel]; if (relayEnabled && inRange(value, activePXX_Min, activePXX_Max)) { setRelayActive(RELAY_ACTIVE_PXX); } else if (relayEnabled && inRange(value, activeCPPM_Min, activeCPPM_Max)) { setRelayActive(RELAY_ACTIVE_CPPM); } else { setRelayActive(RELAY_ACTIVE_NONE); } if (active == RELAY_ACTIVE_PXX || !channelsInitialized) { memcpy(channels_out_pxx, channels, NUM_CHANNELS_PXX*sizeof(channels[0])); } if (active == RELAY_ACTIVE_CPPM || !channelsInitialized) { memcpy(channels_out_cppm, channels, NUM_CHANNELS_CPPM*sizeof(channels[0])); } if (relayEnabled) { if (active != RELAY_ACTIVE_PXX) { centerControlsAndHold(channels_out_pxx, holdThrottleEnabled, pxx_armed ? midThrottle : minThrottle); } if (active != RELAY_ACTIVE_CPPM) { centerControlsAndHold(channels_out_cppm, holdThrottleEnabled, cppm_armed ? midThrottle : minThrottle); } if (active == RELAY_ACTIVE_PXX) { digitalWrite(PIN_CAMERA_SEL, CAMERA_PXX); } if (active == RELAY_ACTIVE_CPPM) { digitalWrite(PIN_CAMERA_SEL, CAMERA_CPPM); } else { // If both CPPM and PXX copters are inactive, keep last selected camera; } } channelsInitialized = true; #ifdef DEBUG_RELAY Serial.print("active="); Serial.println(active == RELAY_ACTIVE_PXX ? "PXX" : active == RELAY_ACTIVE_CPPM ? "CPPM" : "---"); Serial.print("PXX ="); dumpChannels(channels_out_pxx, NUM_CHANNELS_PXX); Serial.print("CPPM="); dumpChannels(channels_out_cppm, NUM_CHANNELS_CPPM); #endif } bool getCPPMArmed() { return cppm_armed; } bool getPXXArmed() { return pxx_armed; } #endif <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libdui. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "duithemedaemonserver.h" #include <QDebug> #include <QApplication> #include <signal.h> #ifdef CLOSE_ON_ENTER #include "keypresswaiter.h" #endif void sigclose(int) { // kill the daemon so that it can save it's current state (caches, refcounts, etc) qApp->quit(); } int main(int argc, char **argv) { signal(SIGTERM, sigclose); signal(SIGINT, sigclose); QApplication::setGraphicsSystem(QLatin1String("native")); QApplication app(argc, argv); DuiThemeDaemonServer server; #ifdef CLOSE_ON_ENTER KeyPressWaiter keyWaiter; QObject::connect(&keyWaiter, SIGNAL(finished()), qApp, SLOT(quit())); keyWaiter.start(); #endif return app.exec(); } <commit_msg>Changes: add parameter to terminate themedaemon immediately<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libdui. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "duithemedaemonserver.h" #include <QDebug> #include <QApplication> #include <signal.h> #ifdef CLOSE_ON_ENTER #include "keypresswaiter.h" #endif void sigclose(int) { // kill the daemon so that it can save it's current state (caches, refcounts, etc) qApp->quit(); } int main(int argc, char **argv) { signal(SIGTERM, sigclose); signal(SIGINT, sigclose); QApplication::setGraphicsSystem(QLatin1String("native")); QApplication app(argc, argv); DuiThemeDaemonServer server; #ifdef CLOSE_ON_ENTER KeyPressWaiter keyWaiter; QObject::connect(&keyWaiter, SIGNAL(finished()), qApp, SLOT(quit())); keyWaiter.start(); #endif if (app.arguments().indexOf("-quitimmediately") >= 0) { QTimer::singleShot(0, &app, SLOT(quit())); } return app.exec(); } <|endoftext|>
<commit_before><commit_msg>Bug 45563 - incorrect IMPORT of Zotero RTF, regression<commit_after><|endoftext|>
<commit_before><commit_msg>Related: fdo#43380 fix parsing of the \cf RTF token<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. * */ #include "FlipperConnectionManagerImpl.h" #include <folly/String.h> #include <folly/futures/Future.h> #include <folly/io/async/AsyncSocketException.h> #include <folly/io/async/SSLContext.h> #include <folly/json.h> #include <rsocket/Payload.h> #include <rsocket/RSocket.h> #include <rsocket/transports/tcp/TcpConnectionFactory.h> #include <stdexcept> #include <thread> #include "ConnectionContextStore.h" #include "FlipperStep.h" #include "Log.h" #define WRONG_THREAD_EXIT_MSG \ "ERROR: Aborting flipper initialization because it's not running in the flipper thread." static constexpr int reconnectIntervalSeconds = 2; static constexpr int connectionKeepaliveSeconds = 10; static constexpr int securePort = 8088; static constexpr int insecurePort = 8089; static constexpr int maxPayloadSize = 0xFFFFFF; namespace facebook { namespace flipper { class ConnectionEvents : public rsocket::RSocketConnectionEvents { private: FlipperConnectionManagerImpl* websocket_; public: ConnectionEvents(FlipperConnectionManagerImpl* websocket) : websocket_(websocket) {} void onConnected() { websocket_->isOpen_ = true; if (websocket_->connectionIsTrusted_) { websocket_->callbacks_->onConnected(); } } void onDisconnected(const folly::exception_wrapper&) { if (!websocket_->isOpen_) return; websocket_->isOpen_ = false; if (websocket_->connectionIsTrusted_) { websocket_->connectionIsTrusted_ = false; websocket_->callbacks_->onDisconnected(); } websocket_->reconnect(); } void onClosed(const folly::exception_wrapper& e) { onDisconnected(e); } }; class Responder : public rsocket::RSocketResponder { private: FlipperConnectionManagerImpl* websocket_; public: Responder(FlipperConnectionManagerImpl* websocket) : websocket_(websocket) {} void handleFireAndForget( rsocket::Payload request, rsocket::StreamId streamId) { const auto payload = request.moveDataToString(); websocket_->callbacks_->onMessageReceived(folly::parseJson(payload)); } }; FlipperConnectionManagerImpl::FlipperConnectionManagerImpl( FlipperInitConfig config, std::shared_ptr<FlipperState> state, std::shared_ptr<ConnectionContextStore> contextStore) : deviceData_(config.deviceData), flipperState_(state), flipperEventBase_(config.callbackWorker), connectionEventBase_(config.connectionWorker), contextStore_(contextStore) { CHECK_THROW(config.callbackWorker, std::invalid_argument); CHECK_THROW(config.connectionWorker, std::invalid_argument); } FlipperConnectionManagerImpl::~FlipperConnectionManagerImpl() { stop(); } void FlipperConnectionManagerImpl::start() { auto step = flipperState_->start("Start connection thread"); folly::makeFuture() .via(flipperEventBase_->getEventBase()) .delayed(std::chrono::milliseconds(0)) .thenValue([this, step](auto&&) { step->complete(); startSync(); }); } void FlipperConnectionManagerImpl::startSync() { if (!isRunningInOwnThread()) { log(WRONG_THREAD_EXIT_MSG); return; } if (isOpen()) { log("Already connected"); return; } auto connect = flipperState_->start("Connect to desktop"); try { if (isCertificateExchangeNeeded()) { doCertificateExchange(); return; } connectSecurely(); connect->complete(); } catch (const folly::AsyncSocketException& e) { if (e.getType() == folly::AsyncSocketException::NOT_OPEN) { // The expected code path when flipper desktop is not running. // Don't count as a failed attempt. connect->fail("Port not open"); } else { log(e.what()); failedConnectionAttempts_++; connect->fail(e.what()); } reconnect(); } catch (const std::exception& e) { log(e.what()); connect->fail(e.what()); failedConnectionAttempts_++; reconnect(); } } void FlipperConnectionManagerImpl::doCertificateExchange() { rsocket::SetupParameters parameters; folly::SocketAddress address; parameters.payload = rsocket::Payload( folly::toJson(folly::dynamic::object("os", deviceData_.os)( "device", deviceData_.device)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, insecurePort); auto connectingInsecurely = flipperState_->start("Connect insecurely"); connectionIsTrusted_ = false; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address)), std::move(parameters), nullptr, std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingInsecurely->complete(); requestSignedCertFromFlipper(); } void FlipperConnectionManagerImpl::connectSecurely() { rsocket::SetupParameters parameters; folly::SocketAddress address; auto loadingDeviceId = flipperState_->start("Load Device Id"); auto deviceId = contextStore_->getDeviceId(); if (deviceId.compare("unknown")) { loadingDeviceId->complete(); } parameters.payload = rsocket::Payload(folly::toJson(folly::dynamic::object( "os", deviceData_.os)("device", deviceData_.device)( "device_id", deviceId)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, securePort); std::shared_ptr<folly::SSLContext> sslContext = contextStore_->getSSLContext(); auto connectingSecurely = flipperState_->start("Connect securely"); connectionIsTrusted_ = true; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address), std::move(sslContext)), std::move(parameters), std::make_shared<Responder>(this), std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingSecurely->complete(); failedConnectionAttempts_ = 0; } void FlipperConnectionManagerImpl::reconnect() { folly::makeFuture() .via(flipperEventBase_->getEventBase()) .delayed(std::chrono::seconds(reconnectIntervalSeconds)) .thenValue([this](auto&&) { startSync(); }); } void FlipperConnectionManagerImpl::stop() { if (client_) { client_->disconnect(); } client_ = nullptr; } bool FlipperConnectionManagerImpl::isOpen() const { return isOpen_ && connectionIsTrusted_; } void FlipperConnectionManagerImpl::setCallbacks(Callbacks* callbacks) { callbacks_ = callbacks; } void FlipperConnectionManagerImpl::sendMessage(const folly::dynamic& message) { flipperEventBase_->add([this, message]() { std::string json = folly::toJson(message); rsocket::Payload payload = rsocket::Payload(json); auto payloadLength = payload.data->computeChainDataLength(); DCHECK_LE(payloadLength, maxPayloadSize); if (payloadLength > maxPayloadSize) { auto logMessage = std::string( "Error: Skipping sending message larger than max rsocket payload: ") + json; log(logMessage); return; } if (client_) { client_->getRequester() ->fireAndForget(std::move(payload)) ->subscribe([]() {}); } }); } bool FlipperConnectionManagerImpl::isCertificateExchangeNeeded() { if (failedConnectionAttempts_ >= 2) { return true; } auto step = flipperState_->start("Check required certificates are present"); bool hasRequiredFiles = contextStore_->hasRequiredFiles(); if (hasRequiredFiles) { step->complete(); } return !hasRequiredFiles; } void FlipperConnectionManagerImpl::requestSignedCertFromFlipper() { auto generatingCSR = flipperState_->start("Generate CSR"); std::string csr = contextStore_->createCertificateSigningRequest(); generatingCSR->complete(); folly::dynamic message = folly::dynamic::object("method", "signCertificate")("csr", csr.c_str())( "destination", contextStore_->getCertificateDirectoryPath().c_str()); auto gettingCert = flipperState_->start("Getting cert from desktop"); flipperEventBase_->add([this, message, gettingCert]() { client_->getRequester() ->requestResponse(rsocket::Payload(folly::toJson(message))) ->subscribe( [this, gettingCert](rsocket::Payload p) { auto response = p.moveDataToString(); if (!response.empty()) { folly::dynamic config = folly::parseJson(response); contextStore_->storeConnectionConfig(config); } gettingCert->complete(); log("Certificate exchange complete."); // Disconnect after message sending is complete. // This will trigger a reconnect which should use the secure // channel. // TODO: Connect immediately, without waiting for reconnect client_ = nullptr; }, [this, message](folly::exception_wrapper e) { e.handle( [&](rsocket::ErrorWithPayload& errorWithPayload) { std::string errorMessage = errorWithPayload.payload.moveDataToString(); if (errorMessage.compare("not implemented")) { log("Desktop failed to provide certificates. Error from flipper desktop:\n" + errorMessage); client_ = nullptr; } else { sendLegacyCertificateRequest(message); } }, [e](...) { log(("Error during certificate exchange:" + e.what()) .c_str()); }); }); }); failedConnectionAttempts_ = 0; } void FlipperConnectionManagerImpl::sendLegacyCertificateRequest( folly::dynamic message) { // Desktop is using an old version of Flipper. // Fall back to fireAndForget, instead of requestResponse. auto sendingRequest = flipperState_->start("Sending fallback certificate request"); client_->getRequester() ->fireAndForget(rsocket::Payload(folly::toJson(message))) ->subscribe([this, sendingRequest]() { sendingRequest->complete(); folly::dynamic config = folly::dynamic::object(); contextStore_->storeConnectionConfig(config); client_ = nullptr; }); } bool FlipperConnectionManagerImpl::isRunningInOwnThread() { return flipperEventBase_->isInEventBaseThread(); } } // namespace flipper } // namespace facebook <commit_msg>Improve "Connect to desktop" diagnostic step<commit_after>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #include "FlipperConnectionManagerImpl.h" #include <folly/String.h> #include <folly/futures/Future.h> #include <folly/io/async/AsyncSocketException.h> #include <folly/io/async/SSLContext.h> #include <folly/json.h> #include <rsocket/Payload.h> #include <rsocket/RSocket.h> #include <rsocket/transports/tcp/TcpConnectionFactory.h> #include <stdexcept> #include <thread> #include "ConnectionContextStore.h" #include "FlipperStep.h" #include "Log.h" #define WRONG_THREAD_EXIT_MSG \ "ERROR: Aborting flipper initialization because it's not running in the flipper thread." static constexpr int reconnectIntervalSeconds = 2; static constexpr int connectionKeepaliveSeconds = 10; static constexpr int securePort = 8088; static constexpr int insecurePort = 8089; static constexpr int maxPayloadSize = 0xFFFFFF; namespace facebook { namespace flipper { class ConnectionEvents : public rsocket::RSocketConnectionEvents { private: FlipperConnectionManagerImpl* websocket_; public: ConnectionEvents(FlipperConnectionManagerImpl* websocket) : websocket_(websocket) {} void onConnected() { websocket_->isOpen_ = true; if (websocket_->connectionIsTrusted_) { websocket_->callbacks_->onConnected(); } } void onDisconnected(const folly::exception_wrapper&) { if (!websocket_->isOpen_) return; websocket_->isOpen_ = false; if (websocket_->connectionIsTrusted_) { websocket_->connectionIsTrusted_ = false; websocket_->callbacks_->onDisconnected(); } websocket_->reconnect(); } void onClosed(const folly::exception_wrapper& e) { onDisconnected(e); } }; class Responder : public rsocket::RSocketResponder { private: FlipperConnectionManagerImpl* websocket_; public: Responder(FlipperConnectionManagerImpl* websocket) : websocket_(websocket) {} void handleFireAndForget( rsocket::Payload request, rsocket::StreamId streamId) { const auto payload = request.moveDataToString(); websocket_->callbacks_->onMessageReceived(folly::parseJson(payload)); } }; FlipperConnectionManagerImpl::FlipperConnectionManagerImpl( FlipperInitConfig config, std::shared_ptr<FlipperState> state, std::shared_ptr<ConnectionContextStore> contextStore) : deviceData_(config.deviceData), flipperState_(state), flipperEventBase_(config.callbackWorker), connectionEventBase_(config.connectionWorker), contextStore_(contextStore) { CHECK_THROW(config.callbackWorker, std::invalid_argument); CHECK_THROW(config.connectionWorker, std::invalid_argument); } FlipperConnectionManagerImpl::~FlipperConnectionManagerImpl() { stop(); } void FlipperConnectionManagerImpl::start() { auto step = flipperState_->start("Start connection thread"); folly::makeFuture() .via(flipperEventBase_->getEventBase()) .delayed(std::chrono::milliseconds(0)) .thenValue([this, step](auto&&) { step->complete(); startSync(); }); } void FlipperConnectionManagerImpl::startSync() { if (!isRunningInOwnThread()) { log(WRONG_THREAD_EXIT_MSG); return; } if (isOpen()) { log("Already connected"); return; } bool isClientSetupStep = isCertificateExchangeNeeded(); auto step = flipperState_->start( isClientSetupStep ? "Establish pre-setup connection" : "Establish main connection"); try { if (isClientSetupStep) { doCertificateExchange(); } else { connectSecurely(); } step->complete(); } catch (const folly::AsyncSocketException& e) { if (e.getType() == folly::AsyncSocketException::NOT_OPEN) { // The expected code path when flipper desktop is not running. // Don't count as a failed attempt. step->fail("Port not open"); } else { log(e.what()); failedConnectionAttempts_++; step->fail(e.what()); } reconnect(); } catch (const std::exception& e) { log(e.what()); step->fail(e.what()); failedConnectionAttempts_++; reconnect(); } } void FlipperConnectionManagerImpl::doCertificateExchange() { rsocket::SetupParameters parameters; folly::SocketAddress address; parameters.payload = rsocket::Payload( folly::toJson(folly::dynamic::object("os", deviceData_.os)( "device", deviceData_.device)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, insecurePort); auto connectingInsecurely = flipperState_->start("Connect insecurely"); connectionIsTrusted_ = false; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address)), std::move(parameters), nullptr, std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingInsecurely->complete(); requestSignedCertFromFlipper(); } void FlipperConnectionManagerImpl::connectSecurely() { rsocket::SetupParameters parameters; folly::SocketAddress address; auto loadingDeviceId = flipperState_->start("Load Device Id"); auto deviceId = contextStore_->getDeviceId(); if (deviceId.compare("unknown")) { loadingDeviceId->complete(); } parameters.payload = rsocket::Payload(folly::toJson(folly::dynamic::object( "os", deviceData_.os)("device", deviceData_.device)( "device_id", deviceId)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, securePort); std::shared_ptr<folly::SSLContext> sslContext = contextStore_->getSSLContext(); auto connectingSecurely = flipperState_->start("Connect securely"); connectionIsTrusted_ = true; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address), std::move(sslContext)), std::move(parameters), std::make_shared<Responder>(this), std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingSecurely->complete(); failedConnectionAttempts_ = 0; } void FlipperConnectionManagerImpl::reconnect() { folly::makeFuture() .via(flipperEventBase_->getEventBase()) .delayed(std::chrono::seconds(reconnectIntervalSeconds)) .thenValue([this](auto&&) { startSync(); }); } void FlipperConnectionManagerImpl::stop() { if (client_) { client_->disconnect(); } client_ = nullptr; } bool FlipperConnectionManagerImpl::isOpen() const { return isOpen_ && connectionIsTrusted_; } void FlipperConnectionManagerImpl::setCallbacks(Callbacks* callbacks) { callbacks_ = callbacks; } void FlipperConnectionManagerImpl::sendMessage(const folly::dynamic& message) { flipperEventBase_->add([this, message]() { std::string json = folly::toJson(message); rsocket::Payload payload = rsocket::Payload(json); auto payloadLength = payload.data->computeChainDataLength(); DCHECK_LE(payloadLength, maxPayloadSize); if (payloadLength > maxPayloadSize) { auto logMessage = std::string( "Error: Skipping sending message larger than max rsocket payload: ") + json; log(logMessage); return; } if (client_) { client_->getRequester() ->fireAndForget(std::move(payload)) ->subscribe([]() {}); } }); } bool FlipperConnectionManagerImpl::isCertificateExchangeNeeded() { if (failedConnectionAttempts_ >= 2) { return true; } auto step = flipperState_->start("Check required certificates are present"); bool hasRequiredFiles = contextStore_->hasRequiredFiles(); if (hasRequiredFiles) { step->complete(); } return !hasRequiredFiles; } void FlipperConnectionManagerImpl::requestSignedCertFromFlipper() { auto generatingCSR = flipperState_->start("Generate CSR"); std::string csr = contextStore_->createCertificateSigningRequest(); generatingCSR->complete(); folly::dynamic message = folly::dynamic::object("method", "signCertificate")("csr", csr.c_str())( "destination", contextStore_->getCertificateDirectoryPath().c_str()); auto gettingCert = flipperState_->start("Getting cert from desktop"); flipperEventBase_->add([this, message, gettingCert]() { client_->getRequester() ->requestResponse(rsocket::Payload(folly::toJson(message))) ->subscribe( [this, gettingCert](rsocket::Payload p) { auto response = p.moveDataToString(); if (!response.empty()) { folly::dynamic config = folly::parseJson(response); contextStore_->storeConnectionConfig(config); } gettingCert->complete(); log("Certificate exchange complete."); // Disconnect after message sending is complete. // This will trigger a reconnect which should use the secure // channel. // TODO: Connect immediately, without waiting for reconnect client_ = nullptr; }, [this, message](folly::exception_wrapper e) { e.handle( [&](rsocket::ErrorWithPayload& errorWithPayload) { std::string errorMessage = errorWithPayload.payload.moveDataToString(); if (errorMessage.compare("not implemented")) { log("Desktop failed to provide certificates. Error from flipper desktop:\n" + errorMessage); client_ = nullptr; } else { sendLegacyCertificateRequest(message); } }, [e](...) { log(("Error during certificate exchange:" + e.what()) .c_str()); }); }); }); failedConnectionAttempts_ = 0; } void FlipperConnectionManagerImpl::sendLegacyCertificateRequest( folly::dynamic message) { // Desktop is using an old version of Flipper. // Fall back to fireAndForget, instead of requestResponse. auto sendingRequest = flipperState_->start("Sending fallback certificate request"); client_->getRequester() ->fireAndForget(rsocket::Payload(folly::toJson(message))) ->subscribe([this, sendingRequest]() { sendingRequest->complete(); folly::dynamic config = folly::dynamic::object(); contextStore_->storeConnectionConfig(config); client_ = nullptr; }); } bool FlipperConnectionManagerImpl::isRunningInOwnThread() { return flipperEventBase_->isInEventBaseThread(); } } // namespace flipper } // namespace facebook <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DragSource.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2008-02-18 14:47:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dtrans.hxx" #ifndef _COM_SUN_STAR_DATATRANSFER_DND_DNDCONSTANTS_HPP_ #include <com/sun/star/datatransfer/dnd/DNDConstants.hpp> #endif #ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_ #include <com/sun/star/datatransfer/XTransferable.hpp> #endif #ifndef _COM_SUN_STAR_AWT_MOUSEBUTTON_HPP_ #include <com/sun/star/awt/MouseButton.hpp> #endif #ifndef _RTL_UNLOAD_H_ #include <rtl/unload.h> #endif #ifndef COMPHELPER_MAKESEQUENCE_HXX_INCLUDED #include "comphelper/makesequence.hxx" #endif #include "DragSource.hxx" #include "DragSourceContext.hxx" #include "aqua_clipboard.hxx" #include "DragActionConversion.hxx" #include <rtl/ustring.h> #include <memory> using namespace rtl; using namespace cppu; using namespace osl; using namespace com::sun::star::datatransfer; using namespace com::sun::star::datatransfer::clipboard; using namespace com::sun::star::datatransfer::dnd; using namespace com::sun::star::datatransfer::dnd::DNDConstants; using namespace com::sun::star::uno; using namespace com::sun::star::awt::MouseButton; using namespace com::sun::star::awt; using namespace com::sun::star::lang; using namespace comphelper; using namespace std; extern rtl_StandardModuleCount g_moduleCount; // For OOo internal D&D we provide the Transferable without NSDragPboard // interference as a shortcut Reference<XTransferable> g_XTransferable = Reference<XTransferable>(); NSView* g_DragSourceView = nil; OUString dragSource_getImplementationName() { return OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.datatransfer.dnd.OleDragSource_V1")); } Sequence<OUString> dragSource_getSupportedServiceNames() { return makeSequence(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.datatransfer.dnd.OleDragSource"))); } @implementation DragSourceHelper; -(DragSourceHelper*)initWithDragSource: (DragSource*) pds { self = [super init]; if (self) { mDragSource = pds; } return self; } -(void)mouseDown: (NSEvent*)theEvent { mDragSource->saveMouseEvent(theEvent); } -(void)mouseDragged: (NSEvent*)theEvent { mDragSource->saveMouseEvent(theEvent); } -(unsigned int)draggingSourceOperationMaskForLocal: (MacOSBOOL)isLocal { return mDragSource->getSupportedDragOperations(isLocal); } -(void)draggedImage:(NSImage*)anImage beganAt:(NSPoint)aPoint { DragSourceDragEvent dsde(static_cast<OWeakObject*>(mDragSource), new DragSourceContext(mDragSource), mDragSource, DNDConstants::ACTION_COPY, DNDConstants::ACTION_COPY); mDragSource->mXDragSrcListener->dragEnter(dsde); } -(void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation { DragSourceDropEvent dsde(static_cast<OWeakObject*>(mDragSource), new DragSourceContext(mDragSource), static_cast< XDragSource* >(mDragSource), SystemToOfficeDragActions(operation), operation != NSDragOperationNone); mDragSource->mXDragSrcListener->dragDropEnd(dsde); mDragSource->mXDragSrcListener = Reference<XDragSourceListener>(); } -(void)draggedImage:(NSImage *)draggedImage movedTo:(NSPoint)screenPoint { DragSourceDragEvent dsde(static_cast<OWeakObject*>(mDragSource), new DragSourceContext(mDragSource), mDragSource, DNDConstants::ACTION_COPY, DNDConstants::ACTION_COPY); mDragSource->mXDragSrcListener->dragOver(dsde); } @end DragSource::DragSource( const Reference<XComponentContext>& context): WeakComponentImplHelper3<XDragSource, XInitialization, XServiceInfo>(m_aMutex), mXComponentContext(context), mView(NULL), mLastMouseEventBeforeStartDrag(nil), m_MouseButton(0) { g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt); } DragSource::~DragSource() { [(id <MouseEventListener>)mView unregisterMouseEventListener: mDragSourceHelper]; [mDragSourceHelper release]; g_moduleCount.modCnt.release( &g_moduleCount.modCnt ); } void SAL_CALL DragSource::initialize(const Sequence< Any >& aArguments) throw(Exception) { if (aArguments.getLength() < 2) { throw Exception(OUString(RTL_CONSTASCII_USTRINGPARAM("DragSource::initialize: Not enough parameter.")), static_cast<OWeakObject*>(this)); } Any pNSView = aArguments[1]; sal_uInt64 tmp = 0; pNSView >>= tmp; mView = (NSView*)tmp; /* All SalFrameView the base class for all VCL system views inherits from NSView in order to get mouse and other events. This is the only way to get these events. In order to start a drag operation we need to provide the mouse event which was the trigger. SalFrameView therefor implements a hook mechanism so that we can get mouse events for our purpose. */ if (![mView respondsToSelector: @selector(registerMouseEventListener:)] || ![mView respondsToSelector: @selector(unregisterMouseEventListener:)]) { throw Exception(OUString(RTL_CONSTASCII_USTRINGPARAM("DragSource::initialize: Provided view doesn't support mouse listener")), static_cast<OWeakObject*>(this)); } mDragSourceHelper = [[DragSourceHelper alloc] initWithDragSource: this]; if (mDragSourceHelper == nil) { throw Exception(OUString(RTL_CONSTASCII_USTRINGPARAM("DragSource::initialize: Cannot initialize DragSource")), static_cast<OWeakObject*>(this)); } [(id <MouseEventListener>)mView registerMouseEventListener: mDragSourceHelper]; } //---------------------------------------------------- // XDragSource //---------------------------------------------------- sal_Bool SAL_CALL DragSource::isDragImageSupported( ) throw(RuntimeException) { return true; } sal_Int32 SAL_CALL DragSource::getDefaultCursor( sal_Int8 /*dragAction*/ ) throw( IllegalArgumentException, RuntimeException) { return 0; } void SAL_CALL DragSource::startDrag(const DragGestureEvent& trigger, sal_Int8 sourceActions, sal_Int32 cursor, sal_Int32 image, const Reference<XTransferable >& transferable, const Reference<XDragSourceListener >& listener ) throw( RuntimeException) { MutexGuard guard(m_aMutex); OSL_ASSERT(listener.is() && "DragSource::startDrag: No XDragSourceListener provided\n"); OSL_ASSERT(transferable.is() && "DragSource::startDrag: No transferable provided\n"); trigger.Event >>= mMouseEvent; m_MouseButton= mMouseEvent.Buttons; mXDragSrcListener = listener; mXCurrentContext = static_cast<XDragSourceContext*>(new DragSourceContext(this)); auto_ptr<AquaClipboard> clipb(new AquaClipboard(this->mXComponentContext, NULL, false)); g_XTransferable = transferable; clipb->setContents(g_XTransferable, Reference<XClipboardOwner>()); mDragSourceActions = sourceActions; g_DragSourceView = mView; NSSize sz; sz.width = 5; sz.height = 5; NSImage* dragImage; dragImage = [[NSImage alloc] initWithSize: sz]; NSRect bounds; bounds.origin = NSMakePoint(0,0); bounds.size = sz; [dragImage lockFocus]; [[NSColor blackColor] set]; [NSBezierPath fillRect: bounds]; [dragImage unlockFocus]; NSPoint pInWnd = [mLastMouseEventBeforeStartDrag locationInWindow]; NSPoint p; p = [mView convertPoint: pInWnd fromView: nil]; p.x = p.x - sz.width/2; p.y = p.y - sz.height/2; [mView dragImage: dragImage at: p offset: NSMakeSize(0,0) event: mLastMouseEventBeforeStartDrag pasteboard: clipb->getPasteboard() source: mDragSourceHelper slideBack: 1]; [dragImage release]; g_XTransferable = Reference<XTransferable>(); g_DragSourceView = nil; } // In order to initiate a D&D operation we need to // provide the triggering mouse event which we get // from the SalFrameView that is associated with // this DragSource void DragSource::saveMouseEvent(NSEvent* theEvent) { if (mLastMouseEventBeforeStartDrag != nil) { [mLastMouseEventBeforeStartDrag release]; } mLastMouseEventBeforeStartDrag = theEvent; } /* isLocal indicates whether or not the DnD operation is OOo internal. */ unsigned int DragSource::getSupportedDragOperations(bool isLocal) const { unsigned int srcActions = OfficeToSystemDragActions(mDragSourceActions); if (isLocal) { // Support NSDragOperation generic which means we can // decide which D&D operation to choose. We map // NSDragOperationGenric to DNDConstants::ACTION_DEFAULT // in SystemToOfficeDragActions to signal this and // use it in DropTarget::determineDropAction srcActions |= NSDragOperationGeneric; } else { // Mask out link and move operations on external DnD srcActions &= ~(NSDragOperationMove | NSDragOperationLink); } return srcActions; } //################################ // XServiceInfo //################################ OUString SAL_CALL DragSource::getImplementationName( ) throw (RuntimeException) { return dragSource_getImplementationName(); } sal_Bool SAL_CALL DragSource::supportsService( const OUString& ServiceName ) throw (RuntimeException) { return ServiceName.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.datatransfer.dnd.OleDragSource"))); } Sequence< OUString > SAL_CALL DragSource::getSupportedServiceNames() throw (RuntimeException) { return dragSource_getSupportedServiceNames(); } <commit_msg>INTEGRATION: CWS changefileheader (1.2.6); FILE MERGED 2008/04/01 23:12:57 thb 1.2.6.4: #i85898# Removed misspelled include 2008/04/01 15:13:28 thb 1.2.6.3: #i85898# Stripping all external header guards 2008/04/01 12:28:24 thb 1.2.6.2: #i85898# Stripping all external header guards 2008/03/31 13:08:52 rt 1.2.6.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: DragSource.cxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dtrans.hxx" #include <com/sun/star/datatransfer/dnd/DNDConstants.hpp> #include <com/sun/star/datatransfer/XTransferable.hpp> #include <com/sun/star/awt/MouseButton.hpp> #include <rtl/unload.h> #include "comphelper/makesequence.hxx" #include "DragSource.hxx" #include "DragSourceContext.hxx" #include "aqua_clipboard.hxx" #include "DragActionConversion.hxx" #include <rtl/ustring.h> #include <memory> using namespace rtl; using namespace cppu; using namespace osl; using namespace com::sun::star::datatransfer; using namespace com::sun::star::datatransfer::clipboard; using namespace com::sun::star::datatransfer::dnd; using namespace com::sun::star::datatransfer::dnd::DNDConstants; using namespace com::sun::star::uno; using namespace com::sun::star::awt::MouseButton; using namespace com::sun::star::awt; using namespace com::sun::star::lang; using namespace comphelper; using namespace std; extern rtl_StandardModuleCount g_moduleCount; // For OOo internal D&D we provide the Transferable without NSDragPboard // interference as a shortcut Reference<XTransferable> g_XTransferable = Reference<XTransferable>(); NSView* g_DragSourceView = nil; OUString dragSource_getImplementationName() { return OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.datatransfer.dnd.OleDragSource_V1")); } Sequence<OUString> dragSource_getSupportedServiceNames() { return makeSequence(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.datatransfer.dnd.OleDragSource"))); } @implementation DragSourceHelper; -(DragSourceHelper*)initWithDragSource: (DragSource*) pds { self = [super init]; if (self) { mDragSource = pds; } return self; } -(void)mouseDown: (NSEvent*)theEvent { mDragSource->saveMouseEvent(theEvent); } -(void)mouseDragged: (NSEvent*)theEvent { mDragSource->saveMouseEvent(theEvent); } -(unsigned int)draggingSourceOperationMaskForLocal: (MacOSBOOL)isLocal { return mDragSource->getSupportedDragOperations(isLocal); } -(void)draggedImage:(NSImage*)anImage beganAt:(NSPoint)aPoint { DragSourceDragEvent dsde(static_cast<OWeakObject*>(mDragSource), new DragSourceContext(mDragSource), mDragSource, DNDConstants::ACTION_COPY, DNDConstants::ACTION_COPY); mDragSource->mXDragSrcListener->dragEnter(dsde); } -(void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation { DragSourceDropEvent dsde(static_cast<OWeakObject*>(mDragSource), new DragSourceContext(mDragSource), static_cast< XDragSource* >(mDragSource), SystemToOfficeDragActions(operation), operation != NSDragOperationNone); mDragSource->mXDragSrcListener->dragDropEnd(dsde); mDragSource->mXDragSrcListener = Reference<XDragSourceListener>(); } -(void)draggedImage:(NSImage *)draggedImage movedTo:(NSPoint)screenPoint { DragSourceDragEvent dsde(static_cast<OWeakObject*>(mDragSource), new DragSourceContext(mDragSource), mDragSource, DNDConstants::ACTION_COPY, DNDConstants::ACTION_COPY); mDragSource->mXDragSrcListener->dragOver(dsde); } @end DragSource::DragSource( const Reference<XComponentContext>& context): WeakComponentImplHelper3<XDragSource, XInitialization, XServiceInfo>(m_aMutex), mXComponentContext(context), mView(NULL), mLastMouseEventBeforeStartDrag(nil), m_MouseButton(0) { g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt); } DragSource::~DragSource() { [(id <MouseEventListener>)mView unregisterMouseEventListener: mDragSourceHelper]; [mDragSourceHelper release]; g_moduleCount.modCnt.release( &g_moduleCount.modCnt ); } void SAL_CALL DragSource::initialize(const Sequence< Any >& aArguments) throw(Exception) { if (aArguments.getLength() < 2) { throw Exception(OUString(RTL_CONSTASCII_USTRINGPARAM("DragSource::initialize: Not enough parameter.")), static_cast<OWeakObject*>(this)); } Any pNSView = aArguments[1]; sal_uInt64 tmp = 0; pNSView >>= tmp; mView = (NSView*)tmp; /* All SalFrameView the base class for all VCL system views inherits from NSView in order to get mouse and other events. This is the only way to get these events. In order to start a drag operation we need to provide the mouse event which was the trigger. SalFrameView therefor implements a hook mechanism so that we can get mouse events for our purpose. */ if (![mView respondsToSelector: @selector(registerMouseEventListener:)] || ![mView respondsToSelector: @selector(unregisterMouseEventListener:)]) { throw Exception(OUString(RTL_CONSTASCII_USTRINGPARAM("DragSource::initialize: Provided view doesn't support mouse listener")), static_cast<OWeakObject*>(this)); } mDragSourceHelper = [[DragSourceHelper alloc] initWithDragSource: this]; if (mDragSourceHelper == nil) { throw Exception(OUString(RTL_CONSTASCII_USTRINGPARAM("DragSource::initialize: Cannot initialize DragSource")), static_cast<OWeakObject*>(this)); } [(id <MouseEventListener>)mView registerMouseEventListener: mDragSourceHelper]; } //---------------------------------------------------- // XDragSource //---------------------------------------------------- sal_Bool SAL_CALL DragSource::isDragImageSupported( ) throw(RuntimeException) { return true; } sal_Int32 SAL_CALL DragSource::getDefaultCursor( sal_Int8 /*dragAction*/ ) throw( IllegalArgumentException, RuntimeException) { return 0; } void SAL_CALL DragSource::startDrag(const DragGestureEvent& trigger, sal_Int8 sourceActions, sal_Int32 cursor, sal_Int32 image, const Reference<XTransferable >& transferable, const Reference<XDragSourceListener >& listener ) throw( RuntimeException) { MutexGuard guard(m_aMutex); OSL_ASSERT(listener.is() && "DragSource::startDrag: No XDragSourceListener provided\n"); OSL_ASSERT(transferable.is() && "DragSource::startDrag: No transferable provided\n"); trigger.Event >>= mMouseEvent; m_MouseButton= mMouseEvent.Buttons; mXDragSrcListener = listener; mXCurrentContext = static_cast<XDragSourceContext*>(new DragSourceContext(this)); auto_ptr<AquaClipboard> clipb(new AquaClipboard(this->mXComponentContext, NULL, false)); g_XTransferable = transferable; clipb->setContents(g_XTransferable, Reference<XClipboardOwner>()); mDragSourceActions = sourceActions; g_DragSourceView = mView; NSSize sz; sz.width = 5; sz.height = 5; NSImage* dragImage; dragImage = [[NSImage alloc] initWithSize: sz]; NSRect bounds; bounds.origin = NSMakePoint(0,0); bounds.size = sz; [dragImage lockFocus]; [[NSColor blackColor] set]; [NSBezierPath fillRect: bounds]; [dragImage unlockFocus]; NSPoint pInWnd = [mLastMouseEventBeforeStartDrag locationInWindow]; NSPoint p; p = [mView convertPoint: pInWnd fromView: nil]; p.x = p.x - sz.width/2; p.y = p.y - sz.height/2; [mView dragImage: dragImage at: p offset: NSMakeSize(0,0) event: mLastMouseEventBeforeStartDrag pasteboard: clipb->getPasteboard() source: mDragSourceHelper slideBack: 1]; [dragImage release]; g_XTransferable = Reference<XTransferable>(); g_DragSourceView = nil; } // In order to initiate a D&D operation we need to // provide the triggering mouse event which we get // from the SalFrameView that is associated with // this DragSource void DragSource::saveMouseEvent(NSEvent* theEvent) { if (mLastMouseEventBeforeStartDrag != nil) { [mLastMouseEventBeforeStartDrag release]; } mLastMouseEventBeforeStartDrag = theEvent; } /* isLocal indicates whether or not the DnD operation is OOo internal. */ unsigned int DragSource::getSupportedDragOperations(bool isLocal) const { unsigned int srcActions = OfficeToSystemDragActions(mDragSourceActions); if (isLocal) { // Support NSDragOperation generic which means we can // decide which D&D operation to choose. We map // NSDragOperationGenric to DNDConstants::ACTION_DEFAULT // in SystemToOfficeDragActions to signal this and // use it in DropTarget::determineDropAction srcActions |= NSDragOperationGeneric; } else { // Mask out link and move operations on external DnD srcActions &= ~(NSDragOperationMove | NSDragOperationLink); } return srcActions; } //################################ // XServiceInfo //################################ OUString SAL_CALL DragSource::getImplementationName( ) throw (RuntimeException) { return dragSource_getImplementationName(); } sal_Bool SAL_CALL DragSource::supportsService( const OUString& ServiceName ) throw (RuntimeException) { return ServiceName.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.datatransfer.dnd.OleDragSource"))); } Sequence< OUString > SAL_CALL DragSource::getSupportedServiceNames() throw (RuntimeException) { return dragSource_getSupportedServiceNames(); } <|endoftext|>
<commit_before>// Copyright 2016 Frog Chen // // 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. //============================================================================= // ■ mouse.cpp //----------------------------------------------------------------------------- // 鼠标驱动程序。参照:http://wiki.osdev.org/PS/2_Mouse //============================================================================= namespace Mouse { //------------------------------------------------------------------------- // ● 定义 //------------------------------------------------------------------------- const unsigned int queue_size = 256; static uint8_t queue_data[queue_size]; static FMQueue8 queue(queue_data, queue_size); struct info { char stage; uint8_t msg[3]; } info; //------------------------------------------------------------------------- // ● 初始化 //------------------------------------------------------------------------- void initialize() { info.stage = -1; } //------------------------------------------------------------------------- // ● 处理队列中的数据(一项) //------------------------------------------------------------------------- void process_data() { char buf[15]; uint8_t msg = queue.shift(); switch (info.stage) { case 0: case 1: info.msg[(unsigned int) info.stage] = msg; info.stage++; break; case 2: info.msg[2] = msg; info.stage = 0; Graphics::fill_rect(0, 32, Graphics::width, Graphics::default_font_height, Graphics::BLACK); FMString::long2charbuf(buf, info.msg[0]); Graphics::draw_text((struct pos) {0, 32}, buf, Graphics::WHITE); FMString::long2charbuf(buf, info.msg[1]); Graphics::draw_text((struct pos) {64, 32}, buf, Graphics::WHITE); FMString::long2charbuf(buf, info.msg[2]); Graphics::draw_text((struct pos) {128, 32}, buf, Graphics::WHITE); break; default: if (msg == 0xfa) info.stage = 0; } } } <commit_msg>又一个修理提交<commit_after>// Copyright 2016 Frog Chen // // 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. //============================================================================= // ■ mouse.cpp //----------------------------------------------------------------------------- // 鼠标驱动程序。参照:http://wiki.osdev.org/PS/2_Mouse //============================================================================= namespace Mouse { //------------------------------------------------------------------------- // ● 定义 //------------------------------------------------------------------------- const unsigned int queue_size = 256; static uint8_t queue_data[queue_size]; static FMQueue8 queue(queue_data, queue_size); struct info { char stage; uint8_t msg[3]; } info; //------------------------------------------------------------------------- // ● 初始化 //------------------------------------------------------------------------- void initialize() { info.stage = -1; } //------------------------------------------------------------------------- // ● 处理队列中的数据(一项) //------------------------------------------------------------------------- void process_data() { char buf[15]; uint8_t msg = queue.shift(); switch (info.stage) { case 0: if (msg & 1 << 3){ info.msg[0] = msg; info.stage = 1; } break; case 1: info.msg[1] = msg; info.stage = 2; break; case 2: info.msg[2] = msg; info.stage = 0; Graphics::fill_rect(0, 32, Graphics::width, Graphics::default_font_height, Graphics::BLACK); FMString::long2charbuf(buf, info.msg[0]); Graphics::draw_text((struct pos) {0, 32}, buf, Graphics::WHITE); FMString::long2charbuf(buf, info.msg[1]); Graphics::draw_text((struct pos) {64, 32}, buf, Graphics::WHITE); FMString::long2charbuf(buf, info.msg[2]); Graphics::draw_text((struct pos) {128, 32}, buf, Graphics::WHITE); break; default: if (msg == 0xfa) info.stage = 0; } } } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_FUNCTIONAL_INTERFACES_HH #define DUNE_GDT_FUNCTIONAL_INTERFACES_HH #include <dune/stuff/common/crtp.hh> namespace Dune { namespace GDT { template <class Traits> class FunctionalInterface : public Stuff::CRTPInterface<FunctionalInterface<Traits>, Traits> { typedef typename Traits::derived_type derived_type; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::ScalarType ScalarType; template <class SourceType> ScalarType apply(const SourceType& source) const { CHECK_CRTP(this->as_imp(*this).apply(source)); return this->as_imp(*this).apply(source); } // apply(...) }; // class FunctionalInterface template <class Traits> class AssemblableFunctionalInterface : protected Stuff::CRTPInterface<AssemblableFunctionalInterface<Traits>, Traits> { public: typedef typename Traits::derived_type derived_type; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SpaceType SpaceType; typedef typename Traits::VectorType VectorType; typedef typename Traits::ScalarType ScalarType; private: static_assert(std::is_base_of<SpaceInterface<typename SpaceType::Traits>, SpaceType>::value, "SpaceType has to be derived from SpaceInterface!"); static_assert(std::is_base_of<Stuff::LA::VectorInterface<typename VectorType::Traits>, VectorType>::value, "VectorType has to be derived from Stuff::LA::VectorInterface!"); public: const GridViewType& grid_view() const { CHECK_CRTP(this->as_imp(*this).grid_view()); return this->as_imp(*this).grid_view(); } const SpaceType& space() const { CHECK_CRTP(this->as_imp(*this).space()); return this->as_imp(*this).space(); } void assemble() { CHECK_AND_CALL_CRTP(this->as_imp(*this).assemble()); } VectorType& vector() { CHECK_CRTP(this->as_imp(*this).vector()); return this->as_imp(*this).vector(); } const VectorType& vector() const { CHECK_CRTP(this->as_imp(*this).vector()); return this->as_imp(*this).vector(); } template <class S> ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const { CHECK_CRTP(this->as_imp(*this).apply(source)); return this->as_imp(*this).apply(source); } template <class S> ScalarType apply(const ConstDiscreteFunction<SpaceType, S>& source) const { return apply(source.vector()); } }; // class AssemblableFunctionalInterface } // namespace GDT } // namespace Dune #endif // DUNE_GDT_FUNCTIONAL_INTERFACES_HH <commit_msg>[functional.interfaces] update AssemblableFunctionalInterface * add default implementation for apply()<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_FUNCTIONAL_INTERFACES_HH #define DUNE_GDT_FUNCTIONAL_INTERFACES_HH #include <dune/stuff/common/crtp.hh> namespace Dune { namespace GDT { template <class Traits> class FunctionalInterface : public Stuff::CRTPInterface<FunctionalInterface<Traits>, Traits> { typedef typename Traits::derived_type derived_type; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::ScalarType ScalarType; template <class SourceType> ScalarType apply(const SourceType& source) const { CHECK_CRTP(this->as_imp(*this).apply(source)); return this->as_imp(*this).apply(source); } // apply(...) }; // class FunctionalInterface template <class Traits> class AssemblableFunctionalInterface : protected Stuff::CRTPInterface<AssemblableFunctionalInterface<Traits>, Traits> { public: typedef typename Traits::derived_type derived_type; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SpaceType SpaceType; typedef typename Traits::VectorType VectorType; typedef typename Traits::ScalarType ScalarType; private: static_assert(std::is_base_of<SpaceInterface<typename SpaceType::Traits>, SpaceType>::value, "SpaceType has to be derived from SpaceInterface!"); static_assert(std::is_base_of<Stuff::LA::VectorInterface<typename VectorType::Traits>, VectorType>::value, "VectorType has to be derived from Stuff::LA::VectorInterface!"); public: const GridViewType& grid_view() const { CHECK_CRTP(this->as_imp(*this).grid_view()); return this->as_imp(*this).grid_view(); } const SpaceType& space() const { CHECK_CRTP(this->as_imp(*this).space()); return this->as_imp(*this).space(); } void assemble() { CHECK_AND_CALL_CRTP(this->as_imp(*this).assemble()); } VectorType& vector() { CHECK_CRTP(this->as_imp(*this).vector()); return this->as_imp(*this).vector(); } const VectorType& vector() const { CHECK_CRTP(this->as_imp(*this).vector()); return this->as_imp(*this).vector(); } template <class S> ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const { typedef typename S::derived_type SourceType; assemble(); return vector().dot(static_cast<SourceType&>(source)); } template <class S> ScalarType apply(const ConstDiscreteFunction<SpaceType, S>& source) const { assemble(); assert(source.vector().size() == vector().size()); return apply(source.vector()); } }; // class AssemblableFunctionalInterface } // namespace GDT } // namespace Dune #endif // DUNE_GDT_FUNCTIONAL_INTERFACES_HH <|endoftext|>
<commit_before>#include <cap/mp_values.h> #include <deal.II/base/types.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/dofs/dof_handler.h> #include <iostream> namespace cap { // reads database for finite element model and write database for equivalent // circuit model void compute_equivalent_circuit(std::shared_ptr<boost::property_tree::ptree const> input_database, std::shared_ptr<boost::property_tree::ptree > output_database) { // TODO: of course we could clear the database or just overwrite but for // now let's just throw an exception if it is not empty if (!output_database->empty()) throw std::runtime_error("output_database was not empty..."); double const sandwich_height = input_database->get<double>("geometry.sandwich_height"); double const cross_sectional_area = sandwich_height * 1.0; double const electrode_width = input_database->get<double>("geometry.anode_electrode_width"); double const separator_width = input_database->get<double>("geometry.separator_width"); double const collector_width = input_database->get<double>("geometry.anode_collector_width"); // getting the material parameters values std::shared_ptr<boost::property_tree::ptree> material_properties_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("material_properties")); cap::MPValuesParameters<2> mp_values_params(material_properties_database); std::shared_ptr<boost::property_tree::ptree> geometry_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("geometry")); mp_values_params.geometry = std::make_shared<cap::DummyGeometry<2>>(geometry_database); std::shared_ptr<cap::MPValues<2> > mp_values = std::shared_ptr<cap::MPValues<2> > (new cap::MPValues<2>(mp_values_params)); // build dummy cell itertor and set its material id dealii::Triangulation<2> triangulation; dealii::GridGenerator::hyper_cube (triangulation); dealii::DoFHandler<2> dof_handler(triangulation); dealii::DoFHandler<2>::active_cell_iterator cell = dof_handler.begin_active(); // electrode cell->set_material_id( input_database->get<dealii::types::material_id>("material_properties.anode_electrode_material_id")); std::vector<double> electrode_solid_electrical_conductivity_values(1); std::vector<double> electrode_liquid_electrical_conductivity_values(1); mp_values->get_values("solid_electrical_conductivity", cell, electrode_solid_electrical_conductivity_values); mp_values->get_values("liquid_electrical_conductivity", cell, electrode_liquid_electrical_conductivity_values); double const electrode_resistivity = ( 1.0 / electrode_solid_electrical_conductivity_values[0] + 1.0 / electrode_liquid_electrical_conductivity_values[0] + 1.0 / ( electrode_solid_electrical_conductivity_values[0] + electrode_liquid_electrical_conductivity_values[0] ) ) / 3.0 ; double const electrode_resistance = electrode_resistivity * electrode_width / cross_sectional_area; std::vector<double> electrode_specific_capacitance_values(1); mp_values->get_values("specific_capacitance", cell, electrode_specific_capacitance_values); double const electrode_capacitance = electrode_specific_capacitance_values[0] * electrode_width * cross_sectional_area; std::vector<double> electrode_exchange_current_density_values(1); mp_values->get_values("faradaic_reaction_coefficient", cell, electrode_exchange_current_density_values); double const electrode_leakage_resistance = 1.0 / (electrode_exchange_current_density_values[0] * electrode_width * cross_sectional_area); std::cout<<"ELECTRODE\n"; std::cout<<" specific_capacitance="<<electrode_specific_capacitance_values[0]<<"\n"; std::cout<<" solid_electrical_conductivity="<<electrode_solid_electrical_conductivity_values[0]<<"\n"; std::cout<<" liquid_electrical_conductivity="<<electrode_liquid_electrical_conductivity_values[0]<<"\n"; std::cout<<" exchange_current_density="<<electrode_exchange_current_density_values[0]<<"\n"; std::cout<<" width="<<electrode_width<<"\n"; std::cout<<" cross_sectional_area="<<cross_sectional_area<<"\n"; // separator cell->set_material_id( input_database->get<dealii::types::material_id>("material_properties.separator_material_id")); std::vector<double> separator_liquid_electrical_conductivity_values(1); mp_values->get_values("liquid_electrical_conductivity", cell, separator_liquid_electrical_conductivity_values); double const separator_resistivity = 1.0 / separator_liquid_electrical_conductivity_values[0]; double const separator_resistance = separator_resistivity * separator_width / cross_sectional_area; std::cout<<"SEPARATOR\n"; std::cout<<" liquid_electrical_conductivity="<<separator_liquid_electrical_conductivity_values[0]<<"\n"; std::cout<<" width="<<separator_width<<"\n"; std::cout<<" cross_sectional_area="<<cross_sectional_area<<"\n"; // collector cell->set_material_id( input_database->get<dealii::types::material_id>("material_properties.anode_collector_material_id")); std::vector<double> collector_solid_electrical_conductivity_values(1); mp_values->get_values("solid_electrical_conductivity", cell, collector_solid_electrical_conductivity_values); double const collector_resistivity = 1.0 / collector_solid_electrical_conductivity_values[0]; double const collector_resistance = collector_resistivity * collector_width / cross_sectional_area; std::cout<<"COLLECTOR\n"; std::cout<<" solid_electrical_conductivity="<<collector_solid_electrical_conductivity_values[0]<<"\n"; std::cout<<" width="<<collector_width<<"\n"; std::cout<<" cross_sectional_area="<<cross_sectional_area<<"\n"; std::cout<<"electrode_capacitance="<<electrode_capacitance<<"\n"; std::cout<<"electrode_resistance="<<electrode_resistance<<"\n"; std::cout<<"electrode_leakage_resistance="<<electrode_leakage_resistance<<"\n"; std::cout<<"separator_resistance="<<separator_resistance<<"\n"; std::cout<<"collector_resistance="<<collector_resistance<<"\n"; // compute the effective resistance and capacitance double const sandwich_capacitance = electrode_capacitance / 2.0; double const sandwich_resistance = 2.0 * electrode_resistance + separator_resistance + 2.0 * collector_resistance; double const sandwich_leakage_resistance = 2.0 * electrode_leakage_resistance; std::cout<<"sandwich_capacitance="<<sandwich_capacitance<<"\n"; std::cout<<"sandwich_resistance="<<sandwich_resistance<<"\n"; std::cout<<"sandwich_leakage_resistance="<<sandwich_leakage_resistance<<"\n"; output_database->put("capacitance" , sandwich_capacitance ); output_database->put("series_resistance" , sandwich_resistance ); output_database->put("parallel_resistance", sandwich_leakage_resistance); if (std::isfinite(sandwich_leakage_resistance)) output_database->put("type", "ParallelRC"); else output_database->put("type", "SeriesRC" ); } } // end namespace cap <commit_msg>get material ids from geometry in equivalent circuits (getting them from mp is deprecated)<commit_after>#include <cap/mp_values.h> #include <deal.II/base/types.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/dofs/dof_handler.h> #include <iostream> namespace cap { // reads database for finite element model and write database for equivalent // circuit model void compute_equivalent_circuit(std::shared_ptr<boost::property_tree::ptree const> input_database, std::shared_ptr<boost::property_tree::ptree > output_database) { // TODO: of course we could clear the database or just overwrite but for // now let's just throw an exception if it is not empty if (!output_database->empty()) throw std::runtime_error("output_database was not empty..."); double const sandwich_height = input_database->get<double>("geometry.sandwich_height"); double const cross_sectional_area = sandwich_height * 1.0; double const electrode_width = input_database->get<double>("geometry.anode_electrode_width"); double const separator_width = input_database->get<double>("geometry.separator_width"); double const collector_width = input_database->get<double>("geometry.anode_collector_width"); // getting the material parameters values std::shared_ptr<boost::property_tree::ptree> material_properties_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("material_properties")); cap::MPValuesParameters<2> mp_values_params(material_properties_database); std::shared_ptr<boost::property_tree::ptree> geometry_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("geometry")); mp_values_params.geometry = std::make_shared<cap::DummyGeometry<2>>(geometry_database); std::shared_ptr<cap::MPValues<2> > mp_values = std::shared_ptr<cap::MPValues<2> > (new cap::MPValues<2>(mp_values_params)); // build dummy cell itertor and set its material id dealii::Triangulation<2> triangulation; dealii::GridGenerator::hyper_cube (triangulation); dealii::DoFHandler<2> dof_handler(triangulation); dealii::DoFHandler<2>::active_cell_iterator cell = dof_handler.begin_active(); // electrode cell->set_material_id( input_database->get<dealii::types::material_id>("geometry.anode_electrode_material_id")); std::vector<double> electrode_solid_electrical_conductivity_values(1); std::vector<double> electrode_liquid_electrical_conductivity_values(1); mp_values->get_values("solid_electrical_conductivity", cell, electrode_solid_electrical_conductivity_values); mp_values->get_values("liquid_electrical_conductivity", cell, electrode_liquid_electrical_conductivity_values); double const electrode_resistivity = ( 1.0 / electrode_solid_electrical_conductivity_values[0] + 1.0 / electrode_liquid_electrical_conductivity_values[0] + 1.0 / ( electrode_solid_electrical_conductivity_values[0] + electrode_liquid_electrical_conductivity_values[0] ) ) / 3.0 ; double const electrode_resistance = electrode_resistivity * electrode_width / cross_sectional_area; std::vector<double> electrode_specific_capacitance_values(1); mp_values->get_values("specific_capacitance", cell, electrode_specific_capacitance_values); double const electrode_capacitance = electrode_specific_capacitance_values[0] * electrode_width * cross_sectional_area; std::vector<double> electrode_exchange_current_density_values(1); mp_values->get_values("faradaic_reaction_coefficient", cell, electrode_exchange_current_density_values); double const electrode_leakage_resistance = 1.0 / (electrode_exchange_current_density_values[0] * electrode_width * cross_sectional_area); std::cout<<"ELECTRODE\n"; std::cout<<" specific_capacitance="<<electrode_specific_capacitance_values[0]<<"\n"; std::cout<<" solid_electrical_conductivity="<<electrode_solid_electrical_conductivity_values[0]<<"\n"; std::cout<<" liquid_electrical_conductivity="<<electrode_liquid_electrical_conductivity_values[0]<<"\n"; std::cout<<" exchange_current_density="<<electrode_exchange_current_density_values[0]<<"\n"; std::cout<<" width="<<electrode_width<<"\n"; std::cout<<" cross_sectional_area="<<cross_sectional_area<<"\n"; // separator cell->set_material_id( input_database->get<dealii::types::material_id>("geometry.separator_material_id")); std::vector<double> separator_liquid_electrical_conductivity_values(1); mp_values->get_values("liquid_electrical_conductivity", cell, separator_liquid_electrical_conductivity_values); double const separator_resistivity = 1.0 / separator_liquid_electrical_conductivity_values[0]; double const separator_resistance = separator_resistivity * separator_width / cross_sectional_area; std::cout<<"SEPARATOR\n"; std::cout<<" liquid_electrical_conductivity="<<separator_liquid_electrical_conductivity_values[0]<<"\n"; std::cout<<" width="<<separator_width<<"\n"; std::cout<<" cross_sectional_area="<<cross_sectional_area<<"\n"; // collector cell->set_material_id( input_database->get<dealii::types::material_id>("geometry.anode_collector_material_id")); std::vector<double> collector_solid_electrical_conductivity_values(1); mp_values->get_values("solid_electrical_conductivity", cell, collector_solid_electrical_conductivity_values); double const collector_resistivity = 1.0 / collector_solid_electrical_conductivity_values[0]; double const collector_resistance = collector_resistivity * collector_width / cross_sectional_area; std::cout<<"COLLECTOR\n"; std::cout<<" solid_electrical_conductivity="<<collector_solid_electrical_conductivity_values[0]<<"\n"; std::cout<<" width="<<collector_width<<"\n"; std::cout<<" cross_sectional_area="<<cross_sectional_area<<"\n"; std::cout<<"electrode_capacitance="<<electrode_capacitance<<"\n"; std::cout<<"electrode_resistance="<<electrode_resistance<<"\n"; std::cout<<"electrode_leakage_resistance="<<electrode_leakage_resistance<<"\n"; std::cout<<"separator_resistance="<<separator_resistance<<"\n"; std::cout<<"collector_resistance="<<collector_resistance<<"\n"; // compute the effective resistance and capacitance double const sandwich_capacitance = electrode_capacitance / 2.0; double const sandwich_resistance = 2.0 * electrode_resistance + separator_resistance + 2.0 * collector_resistance; double const sandwich_leakage_resistance = 2.0 * electrode_leakage_resistance; std::cout<<"sandwich_capacitance="<<sandwich_capacitance<<"\n"; std::cout<<"sandwich_resistance="<<sandwich_resistance<<"\n"; std::cout<<"sandwich_leakage_resistance="<<sandwich_leakage_resistance<<"\n"; output_database->put("capacitance" , sandwich_capacitance ); output_database->put("series_resistance" , sandwich_resistance ); output_database->put("parallel_resistance", sandwich_leakage_resistance); if (std::isfinite(sandwich_leakage_resistance)) output_database->put("type", "ParallelRC"); else output_database->put("type", "SeriesRC" ); } } // end namespace cap <|endoftext|>
<commit_before>/* Copyright (C) 2002 by John Harger This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgeom/vector3.h" #include "csutil/databuf.h" #include "csutil/objreg.h" #include "csutil/ref.h" #include "csutil/scf.h" #include "iutil/document.h" #include "iutil/string.h" #include "ivaria/reporter.h" #include "ivideo/graph3d.h" #include "ivideo/shader/shader.h" #include "glshader_ps1.h" #include "ps1_emu_common.h" CS_PLUGIN_NAMESPACE_BEGIN(GLShaderPS1) { void csShaderGLPS1_Common::Report (int severity, const char* msg, ...) { va_list args; va_start (args, msg); csReportV (shaderPlug->object_reg, severity, "crystalspace.graphics3d.shader.glps1", msg, args); va_end (args); } bool csShaderGLPS1_Common::Load (iShaderDestinationResolver*, iDocumentNode* program) { if(!program) return false; csRef<iDocumentNode> variablesnode = program->GetNode("ps1fp"); if (variablesnode) { csRef<iDocumentNodeIterator> it = variablesnode->GetNodes (); while (it->HasNext()) { csRef<iDocumentNode> child = it->Next(); if(child->GetType() != CS_NODE_ELEMENT) continue; if (!ParseCommon (child)) return false; } } return true; } bool csShaderGLPS1_Common::Load (iShaderDestinationResolver*, const char* program, csArray<csShaderVarMapping> &mappings) { programBuffer.AttachNew (new csDataBuffer (csStrNew (program), strlen (program))); for (size_t i = 0; i < mappings.GetSize (); i++) { variablemap.Push (VariableMapEntry (mappings[i])); } return true; } bool csShaderGLPS1_Common::Compile (iHierarchicalCache*, csRef<iString>* tag) { for (size_t i = 0; i < variablemap.GetSize (); i++) { int dest; if ((sscanf (variablemap[i].destination, "register %d", &dest) != 1) && (sscanf (variablemap[i].destination, "c%d", &dest) != 1)) { Report (CS_REPORTER_SEVERITY_WARNING, "Unknown variable destination %s", variablemap[i].destination.GetData()); continue; } if ((dest < 0) || (dest >= MAX_CONST_REGS)) { Report (CS_REPORTER_SEVERITY_WARNING, "Invalid constant register number %d, must be in range [0..%d]", dest, MAX_CONST_REGS); continue; } constantRegs[dest] = variablemap[i].mappingParam; } variablemap.DeleteAll(); tag->AttachNew (new scfString ("default")); return LoadProgramStringToGL(); } void csShaderGLPS1_Common::GetUsedShaderVars (csBitArray& bits) const { for (size_t c = 0; c < MAX_CONST_REGS; c++) { TryAddUsedShaderVarProgramParam (constantRegs[c], bits); } } } CS_PLUGIN_NAMESPACE_END(GLShaderPS1) <commit_msg>The Compile() argument 'tag' is actually optional<commit_after>/* Copyright (C) 2002 by John Harger This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgeom/vector3.h" #include "csutil/databuf.h" #include "csutil/objreg.h" #include "csutil/ref.h" #include "csutil/scf.h" #include "iutil/document.h" #include "iutil/string.h" #include "ivaria/reporter.h" #include "ivideo/graph3d.h" #include "ivideo/shader/shader.h" #include "glshader_ps1.h" #include "ps1_emu_common.h" CS_PLUGIN_NAMESPACE_BEGIN(GLShaderPS1) { void csShaderGLPS1_Common::Report (int severity, const char* msg, ...) { va_list args; va_start (args, msg); csReportV (shaderPlug->object_reg, severity, "crystalspace.graphics3d.shader.glps1", msg, args); va_end (args); } bool csShaderGLPS1_Common::Load (iShaderDestinationResolver*, iDocumentNode* program) { if(!program) return false; csRef<iDocumentNode> variablesnode = program->GetNode("ps1fp"); if (variablesnode) { csRef<iDocumentNodeIterator> it = variablesnode->GetNodes (); while (it->HasNext()) { csRef<iDocumentNode> child = it->Next(); if(child->GetType() != CS_NODE_ELEMENT) continue; if (!ParseCommon (child)) return false; } } return true; } bool csShaderGLPS1_Common::Load (iShaderDestinationResolver*, const char* program, csArray<csShaderVarMapping> &mappings) { programBuffer.AttachNew (new csDataBuffer (csStrNew (program), strlen (program))); for (size_t i = 0; i < mappings.GetSize (); i++) { variablemap.Push (VariableMapEntry (mappings[i])); } return true; } bool csShaderGLPS1_Common::Compile (iHierarchicalCache*, csRef<iString>* tag) { for (size_t i = 0; i < variablemap.GetSize (); i++) { int dest; if ((sscanf (variablemap[i].destination, "register %d", &dest) != 1) && (sscanf (variablemap[i].destination, "c%d", &dest) != 1)) { Report (CS_REPORTER_SEVERITY_WARNING, "Unknown variable destination %s", variablemap[i].destination.GetData()); continue; } if ((dest < 0) || (dest >= MAX_CONST_REGS)) { Report (CS_REPORTER_SEVERITY_WARNING, "Invalid constant register number %d, must be in range [0..%d]", dest, MAX_CONST_REGS); continue; } constantRegs[dest] = variablemap[i].mappingParam; } variablemap.DeleteAll(); if (tag) tag->AttachNew (new scfString ("default")); return LoadProgramStringToGL(); } void csShaderGLPS1_Common::GetUsedShaderVars (csBitArray& bits) const { for (size_t c = 0; c < MAX_CONST_REGS; c++) { TryAddUsedShaderVarProgramParam (constantRegs[c], bits); } } } CS_PLUGIN_NAMESPACE_END(GLShaderPS1) <|endoftext|>