text
stringlengths
54
60.6k
<commit_before>// Maintainer: Jan Kristian Sto. Domingo [jstod001@ucr.edu] // exec.cpp for rshell #include <iostream> #include <cstring> #include <string> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> using namespace std; //Notes on function formats: //execvp(const char *file, char *const argv[]) // tokenCounter function used to determine size of dynamically // allocated array for use in the execvp function unsigned tokenCounter(char* a) { unsigned count = 0; char* token; token = strtok(a, " ;"); while(token != NULL) { token = strtok(NULL, " ;"); count++; } return count; } int main() { int PID = fork(); if(PID == 0) { //cout << "child process" << endl; // command prompt char* username = getlogin(); char hostname[20]; gethostname(hostname, 20); cout << username << "@" << hostname << "$ "; string str_input; getline(cin, str_input); // output message for test purposes // cout << "Original string: " << str_input << endl << endl; char* c_input = new char[str_input.length() + 1]; strcpy(c_input, str_input.c_str()); // output message for test purposes // cout << "Converted to cstring: " << c_input << endl << endl; // new cstring now has to be tokenized and placed into a char** // for the exec vp function char* tmp = new char[str_input.length() + 1]; strcpy(tmp, c_input); // tmp protects the original cstring input // tmp will be used for the tokenCounter function unsigned token_count = 0; token_count = tokenCounter(tmp); char** arg; arg = new char* [token_count]; // output message for test purposes // cout << "c_input after tokenCounter: " << c_input << endl; // the following chunk of code will take each token // and place it into arg which will then be used as // a parameter in execvp unsigned i = 0; char* ptr; ptr = strtok(c_input, " ;"); while(ptr != NULL) { arg[i] = ptr; // cout message for test purposes cout << "arg[" << i << "] = " << arg[i] << endl; ptr = strtok(NULL, " ;"); i++; } //cout << arg[0] << endl; if(string(arg[0]) == "exit") { cout << "executing exit(0)" << endl; exit(0); } else { cout << "in execvp" << endl; execvp(arg[0], arg); perror(arg[0]); } } else { if(PID == -1) { perror("fork"); } int w = wait(0); if(w == -1) { perror("wait"); } //cout << "parent process" << endl; } return 0; } <commit_msg>removed some test comments from exec.cpp<commit_after>// Maintainer: Jan Kristian Sto. Domingo [jstod001@ucr.edu] // exec.cpp for rshell #include <iostream> #include <cstring> #include <string> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> using namespace std; //Notes on function formats: //execvp(const char *file, char *const argv[]) // tokenCounter function used to determine size of dynamically // allocated array for use in the execvp function unsigned tokenCounter(char* a) { unsigned count = 0; char* token; token = strtok(a, " ;"); while(token != NULL) { token = strtok(NULL, " ;"); count++; } return count; } int main() { int PID = fork(); if(PID == 0) { //cout << "child process" << endl; // command prompt char* username = getlogin(); char hostname[20]; gethostname(hostname, 20); cout << username << "@" << hostname << "$ "; string str_input; getline(cin, str_input); // output message for test purposes // cout << "Original string: " << str_input << endl << endl; char* c_input = new char[str_input.length() + 1]; strcpy(c_input, str_input.c_str()); // output message for test purposes // cout << "Converted to cstring: " << c_input << endl << endl; // new cstring now has to be tokenized and placed into a char** // for the exec vp function char* tmp = new char[str_input.length() + 1]; strcpy(tmp, c_input); // tmp protects the original cstring input // tmp will be used for the tokenCounter function unsigned token_count = 0; token_count = tokenCounter(tmp); char** arg; arg = new char* [token_count]; // output message for test purposes // cout << "c_input after tokenCounter: " << c_input << endl; // the following chunk of code will take each token // and place it into arg which will then be used as // a parameter in execvp unsigned i = 0; char* ptr; ptr = strtok(c_input, " ;"); while(ptr != NULL) { arg[i] = ptr; // cout message for test purposes //cout << "arg[" << i << "] = " << arg[i] << endl; ptr = strtok(NULL, " ;"); i++; } //cout << arg[0] << endl; if(string(arg[0]) == "exit") { //cout message for test purposes //cout << "executing exit(0)" << endl; exit(0); } else { //cout message for test purposes //cout << "in execvp" << endl; execvp(arg[0], arg); perror(arg[0]); } } else { if(PID == -1) { perror("fork"); } int w = wait(0); if(w == -1) { perror("wait"); } //cout << "parent process" << endl; } return 0; } <|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 "libtorrent/pch.hpp" #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; assert(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { namespace fs = boost::filesystem; const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { assert(path.is_complete()); close(); #if defined(_WIN32) && defined(UNICODE) std::wstring wpath(safe_convert(path.native_file_string())); m_fd = ::_wopen( wpath.c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); #else #ifdef _WIN32 m_fd = ::_open( #else m_fd = ::open( #endif utf8_native(path.native_file_string()).c_str() , map_open_mode(mode) #ifdef _WIN32 , S_IREAD | S_IWRITE); #else , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #endif #endif if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { assert(m_open_mode & mode_in); assert(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "read failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { assert(m_open_mode & mode_out); assert(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "write failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } void set_size(size_type s) { size_type pos = tell(); // Only set size if current file size not equals s. // 2 as "m" argument is to be sure seek() sets SEEK_END on // all compilers. if(s != seek(0, 2)) { seek(s - 1); char dummy = 0; read(&dummy, 1); seek(s - 1); write(&dummy, 1); } seek(pos); } size_type seek(size_type offset, int m = 1) { assert(m_open_mode); assert(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } return ret; } size_type tell() { assert(m_open_mode); assert(m_fd != -1); #ifdef _WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(fs::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(fs::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } void file::set_size(size_type s) { m_impl->set_size(s); } size_type file::seek(size_type pos, file::seek_mode m) { return m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <commit_msg>changed to use ftruncate to allocate files<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 "libtorrent/pch.hpp" #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; assert(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { namespace fs = boost::filesystem; const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { assert(path.is_complete()); close(); #if defined(_WIN32) && defined(UNICODE) std::wstring wpath(safe_convert(path.native_file_string())); m_fd = ::_wopen( wpath.c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); #else #ifdef _WIN32 m_fd = ::_open( #else m_fd = ::open( #endif utf8_native(path.native_file_string()).c_str() , map_open_mode(mode) #ifdef _WIN32 , S_IREAD | S_IWRITE); #else , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #endif #endif if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { assert(m_open_mode & mode_in); assert(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "read failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { assert(m_open_mode & mode_out); assert(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "write failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } void set_size(size_type s) { #ifdef _WIN32 #error file.cpp is for posix systems only. use file_win.cpp on windows #else if (ftruncate(m_fd, s) < 0) { std::stringstream msg; msg << "ftruncate failed: '" << strerror(errno); throw file_error(msg.str()); } #endif } size_type seek(size_type offset, int m = 1) { assert(m_open_mode); assert(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } return ret; } size_type tell() { assert(m_open_mode); assert(m_fd != -1); #ifdef _WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(fs::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(fs::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } void file::set_size(size_type s) { m_impl->set_size(s); } size_type file::seek(size_type pos, file::seek_mode m) { return m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SERVER_ROUTE_HPP #define SERVER_ROUTE_HPP #include <regex> #include <string> #include <delegate> #include "request.hpp" #include "response.hpp" #include "../route/path_to_regex.hpp" namespace server { using End_point = delegate<void(Request_ptr, Response_ptr)>; using Route_expr = std::regex; struct Route { Route(const std::string& ex, End_point e) : path{ex} , end_point{e} { expr = route::Path_to_regex::path_to_regex(path, keys); } std::string path; Route_expr expr; End_point end_point; route::Keys keys; }; //< struct Route } //< namespace server #endif //< SERVER_ROUTE_HPP <commit_msg>route: Add attribute to bring most viewed route to front of queue<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SERVER_ROUTE_HPP #define SERVER_ROUTE_HPP #include <regex> #include <string> #include <delegate> #include "request.hpp" #include "response.hpp" #include "../route/path_to_regex.hpp" namespace server { using End_point = delegate<void(Request_ptr, Response_ptr)>; using Route_expr = std::regex; struct Route { Route(const std::string& ex, End_point e) : path{ex} , end_point{e} { expr = route::Path_to_regex::path_to_regex(path, keys); } std::string path; Route_expr expr; End_point end_point; route::Keys keys; unsigned hits; }; //< struct Route inline bool operator < (const Route& lhs, const Route& rhs) noexcept { return lhs.hits < rhs.hits; } } //< namespace server #endif //< SERVER_ROUTE_HPP <|endoftext|>
<commit_before> #include "game.hpp" #include "seoSplasher/splashState.hpp" #include "seoSplasher/splashMenu.hpp" // set packfile name/filepath if one is being used #define PACKFILE_NAME "seoSplasherResources.dat" // set to true if a packfile is being used #define IS_USING_PACKFILE true // if not using cmake to build and using the ResourcePacker lib, // define ResourcePacker_FOUND #if defined(ResourcePacker_FOUND) #else # define IS_USING_PACKFILE false #endif #if IS_USING_PACKFILE == true # define RESOURCE_MANAGER_MODE GameResources::PACKFILE #else # define RESOURCE_MANAGER_MODE GameResources::DEFAULT #endif Game::Game() : window(sf::VideoMode(720,480), "SFML App"), resourceManager(&stateStack, RESOURCE_MANAGER_MODE, PACKFILE_NAME), mPlayer(), sPlayer(), stateStack(Context(window, resourceManager, mPlayer, sPlayer, ecEngine, rGen, isQuitting, mode, scontext, sfxContext)), isQuitting(false), mode(0) { registerResources(); registerStates(); frameTime = sf::seconds(1.f / 60.f); } void Game::run() { sf::Clock clock; sf::Time lastUpdateTime = sf::Time::Zero; while (window.isOpen() && !isQuitting) { lastUpdateTime += clock.restart(); while (lastUpdateTime > frameTime) { lastUpdateTime -= frameTime; processEvents(); update(frameTime); } draw(); } if(window.isOpen()) window.close(); } void Game::processEvents() { sf::Event event; while (window.pollEvent(event)) { stateStack.handleEvent(event); if(event.type == sf::Event::Closed) window.close(); } } void Game::update(sf::Time deltaTime) { stateStack.update(deltaTime); } void Game::draw() { window.clear(); stateStack.draw(); window.display(); } // register resources via resourceManager // Resource IDs must be listed in resourceIdentifiers.hpp void Game::registerResources() { resourceManager.registerTexture(Textures::WALL, "wall.png"); resourceManager.registerTexture(Textures::BREAKABLE, "breakable.png"); resourceManager.registerTexture(Textures::BALLOON_0, "balloon00.png"); resourceManager.registerTexture(Textures::BALLOON_1, "balloon01.png"); resourceManager.registerTexture(Textures::BALLOON_2, "balloon02.png"); resourceManager.registerTexture(Textures::SUPER_BALLOON_0, "superBalloon00.png"); resourceManager.registerTexture(Textures::SUPER_BALLOON_1, "superBalloon01.png"); resourceManager.registerTexture(Textures::SUPER_BALLOON_2, "superBalloon02.png"); resourceManager.registerTexture(Textures::C_BALLOON_0, "controlledBalloon00.png"); resourceManager.registerTexture(Textures::C_BALLOON_1, "controlledBalloon01.png"); resourceManager.registerTexture(Textures::C_BALLOON_2, "controlledBalloon02.png"); resourceManager.registerTexture(Textures::C_SUPER_BALLOON_0, "controlledSuperBalloon00.png"); resourceManager.registerTexture(Textures::C_SUPER_BALLOON_1, "controlledSuperBalloon01.png"); resourceManager.registerTexture(Textures::C_SUPER_BALLOON_2, "controlledSuperBalloon02.png"); resourceManager.registerTexture(Textures::PLAYER_ONE, "player1.png"); resourceManager.registerTexture(Textures::PLAYER_TWO, "player2.png"); resourceManager.registerTexture(Textures::PLAYER_THREE, "player3.png"); resourceManager.registerTexture(Textures::PLAYER_FOUR, "player4.png"); resourceManager.registerTexture(Textures::C_PLAYER_ONE, "computer1.png"); resourceManager.registerTexture(Textures::C_PLAYER_TWO, "computer2.png"); resourceManager.registerTexture(Textures::C_PLAYER_THREE, "computer3.png"); resourceManager.registerTexture(Textures::C_PLAYER_FOUR, "computer4.png"); resourceManager.registerTexture(Textures::SPLOSION_PLUS, "splosionPLUS.png"); resourceManager.registerTexture(Textures::SPLOSION_VERT, "splosionVERT.png"); resourceManager.registerTexture(Textures::SPLOSION_HORIZ, "splosionHORIZ.png"); resourceManager.registerTexture(Textures::BALLOON_UP_0, "balloonUp00.png"); resourceManager.registerTexture(Textures::BALLOON_UP_1, "balloonUp01.png"); resourceManager.registerTexture(Textures::BALLOON_UP_2, "balloonUp02.png"); resourceManager.registerTexture(Textures::RANGE_UP_0, "rangeUp00.png"); resourceManager.registerTexture(Textures::RANGE_UP_1, "rangeUp01.png"); resourceManager.registerTexture(Textures::RANGE_UP_2, "rangeUp02.png"); resourceManager.registerTexture(Textures::SPEED_UP_0, "speedUp00.png"); resourceManager.registerTexture(Textures::SPEED_UP_1, "speedUp01.png"); resourceManager.registerTexture(Textures::SPEED_UP_2, "speedUp02.png"); resourceManager.registerTexture(Textures::KICK_UPGRADE_0, "kickUpgrade00.png"); resourceManager.registerTexture(Textures::KICK_UPGRADE_1, "kickUpgrade01.png"); resourceManager.registerTexture(Textures::KICK_UPGRADE_2, "kickUpgrade02.png"); resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_0, "rControl00.png"); resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_1, "rControl01.png"); resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_2, "rControl02.png"); resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_0, "superBalloonUp00.png"); resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_1, "superBalloonUp01.png"); resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_2, "superBalloonUp02.png"); resourceManager.registerTexture(Textures::PIERCE_UPGRADE_0, "pierceUp00.png"); resourceManager.registerTexture(Textures::PIERCE_UPGRADE_1, "pierceUp01.png"); resourceManager.registerTexture(Textures::PIERCE_UPGRADE_2, "pierceUp02.png"); resourceManager.registerTexture(Textures::SPREAD_UPGRADE_0, "spreadUp00.png"); resourceManager.registerTexture(Textures::SPREAD_UPGRADE_1, "spreadUp01.png"); resourceManager.registerTexture(Textures::SPREAD_UPGRADE_2, "spreadUp02.png"); resourceManager.registerTexture(Textures::GHOST_UPGRADE_0, "ghostUp00.png"); resourceManager.registerTexture(Textures::GHOST_UPGRADE_1, "ghostUp01.png"); resourceManager.registerTexture(Textures::GHOST_UPGRADE_2, "ghostUp02.png"); resourceManager.registerFont(Fonts::CLEAR_SANS, "ClearSans-Regular.ttf"); resourceManager.registerSoundBuffer(Sound::BREAKABLE, "breakable.ogg"); resourceManager.registerSoundBuffer(Sound::COUNTDOWN_0, "countdown0.ogg"); resourceManager.registerSoundBuffer(Sound::COUNTDOWN_1, "countdown1.ogg"); resourceManager.registerSoundBuffer(Sound::DEATH, "death.ogg"); resourceManager.registerSoundBuffer(Sound::KICK, "kick.ogg"); resourceManager.registerSoundBuffer(Sound::SPLOSION, "splosion.ogg"); resourceManager.registerSoundBuffer(Sound::POWERUP, "powerup.ogg"); resourceManager.registerSoundBuffer(Sound::TRY_AGAIN_TUNE, "tryagain.ogg"); resourceManager.registerSoundBuffer(Sound::VICTORY_TUNE, "victory.ogg"); } // register states via stateStack // State IDs must be listed in stateIdentifiers.hpp void Game::registerStates() { stateStack.registerState<SplashState>(States::SPLASH); stateStack.registerState<SplashMenu>(States::MENU); stateStack.pushState(States::MENU); } <commit_msg>Fixed name of program<commit_after> #include "game.hpp" #include "seoSplasher/splashState.hpp" #include "seoSplasher/splashMenu.hpp" // set packfile name/filepath if one is being used #define PACKFILE_NAME "seoSplasherResources.dat" // set to true if a packfile is being used #define IS_USING_PACKFILE true // if not using cmake to build and using the ResourcePacker lib, // define ResourcePacker_FOUND #if defined(ResourcePacker_FOUND) #else # define IS_USING_PACKFILE false #endif #if IS_USING_PACKFILE == true # define RESOURCE_MANAGER_MODE GameResources::PACKFILE #else # define RESOURCE_MANAGER_MODE GameResources::DEFAULT #endif Game::Game() : window(sf::VideoMode(720,480), "SeoSplasher"), resourceManager(&stateStack, RESOURCE_MANAGER_MODE, PACKFILE_NAME), mPlayer(), sPlayer(), stateStack(Context(window, resourceManager, mPlayer, sPlayer, ecEngine, rGen, isQuitting, mode, scontext, sfxContext)), isQuitting(false), mode(0) { registerResources(); registerStates(); frameTime = sf::seconds(1.f / 60.f); } void Game::run() { sf::Clock clock; sf::Time lastUpdateTime = sf::Time::Zero; while (window.isOpen() && !isQuitting) { lastUpdateTime += clock.restart(); while (lastUpdateTime > frameTime) { lastUpdateTime -= frameTime; processEvents(); update(frameTime); } draw(); } if(window.isOpen()) window.close(); } void Game::processEvents() { sf::Event event; while (window.pollEvent(event)) { stateStack.handleEvent(event); if(event.type == sf::Event::Closed) window.close(); } } void Game::update(sf::Time deltaTime) { stateStack.update(deltaTime); } void Game::draw() { window.clear(); stateStack.draw(); window.display(); } // register resources via resourceManager // Resource IDs must be listed in resourceIdentifiers.hpp void Game::registerResources() { resourceManager.registerTexture(Textures::WALL, "wall.png"); resourceManager.registerTexture(Textures::BREAKABLE, "breakable.png"); resourceManager.registerTexture(Textures::BALLOON_0, "balloon00.png"); resourceManager.registerTexture(Textures::BALLOON_1, "balloon01.png"); resourceManager.registerTexture(Textures::BALLOON_2, "balloon02.png"); resourceManager.registerTexture(Textures::SUPER_BALLOON_0, "superBalloon00.png"); resourceManager.registerTexture(Textures::SUPER_BALLOON_1, "superBalloon01.png"); resourceManager.registerTexture(Textures::SUPER_BALLOON_2, "superBalloon02.png"); resourceManager.registerTexture(Textures::C_BALLOON_0, "controlledBalloon00.png"); resourceManager.registerTexture(Textures::C_BALLOON_1, "controlledBalloon01.png"); resourceManager.registerTexture(Textures::C_BALLOON_2, "controlledBalloon02.png"); resourceManager.registerTexture(Textures::C_SUPER_BALLOON_0, "controlledSuperBalloon00.png"); resourceManager.registerTexture(Textures::C_SUPER_BALLOON_1, "controlledSuperBalloon01.png"); resourceManager.registerTexture(Textures::C_SUPER_BALLOON_2, "controlledSuperBalloon02.png"); resourceManager.registerTexture(Textures::PLAYER_ONE, "player1.png"); resourceManager.registerTexture(Textures::PLAYER_TWO, "player2.png"); resourceManager.registerTexture(Textures::PLAYER_THREE, "player3.png"); resourceManager.registerTexture(Textures::PLAYER_FOUR, "player4.png"); resourceManager.registerTexture(Textures::C_PLAYER_ONE, "computer1.png"); resourceManager.registerTexture(Textures::C_PLAYER_TWO, "computer2.png"); resourceManager.registerTexture(Textures::C_PLAYER_THREE, "computer3.png"); resourceManager.registerTexture(Textures::C_PLAYER_FOUR, "computer4.png"); resourceManager.registerTexture(Textures::SPLOSION_PLUS, "splosionPLUS.png"); resourceManager.registerTexture(Textures::SPLOSION_VERT, "splosionVERT.png"); resourceManager.registerTexture(Textures::SPLOSION_HORIZ, "splosionHORIZ.png"); resourceManager.registerTexture(Textures::BALLOON_UP_0, "balloonUp00.png"); resourceManager.registerTexture(Textures::BALLOON_UP_1, "balloonUp01.png"); resourceManager.registerTexture(Textures::BALLOON_UP_2, "balloonUp02.png"); resourceManager.registerTexture(Textures::RANGE_UP_0, "rangeUp00.png"); resourceManager.registerTexture(Textures::RANGE_UP_1, "rangeUp01.png"); resourceManager.registerTexture(Textures::RANGE_UP_2, "rangeUp02.png"); resourceManager.registerTexture(Textures::SPEED_UP_0, "speedUp00.png"); resourceManager.registerTexture(Textures::SPEED_UP_1, "speedUp01.png"); resourceManager.registerTexture(Textures::SPEED_UP_2, "speedUp02.png"); resourceManager.registerTexture(Textures::KICK_UPGRADE_0, "kickUpgrade00.png"); resourceManager.registerTexture(Textures::KICK_UPGRADE_1, "kickUpgrade01.png"); resourceManager.registerTexture(Textures::KICK_UPGRADE_2, "kickUpgrade02.png"); resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_0, "rControl00.png"); resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_1, "rControl01.png"); resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_2, "rControl02.png"); resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_0, "superBalloonUp00.png"); resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_1, "superBalloonUp01.png"); resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_2, "superBalloonUp02.png"); resourceManager.registerTexture(Textures::PIERCE_UPGRADE_0, "pierceUp00.png"); resourceManager.registerTexture(Textures::PIERCE_UPGRADE_1, "pierceUp01.png"); resourceManager.registerTexture(Textures::PIERCE_UPGRADE_2, "pierceUp02.png"); resourceManager.registerTexture(Textures::SPREAD_UPGRADE_0, "spreadUp00.png"); resourceManager.registerTexture(Textures::SPREAD_UPGRADE_1, "spreadUp01.png"); resourceManager.registerTexture(Textures::SPREAD_UPGRADE_2, "spreadUp02.png"); resourceManager.registerTexture(Textures::GHOST_UPGRADE_0, "ghostUp00.png"); resourceManager.registerTexture(Textures::GHOST_UPGRADE_1, "ghostUp01.png"); resourceManager.registerTexture(Textures::GHOST_UPGRADE_2, "ghostUp02.png"); resourceManager.registerFont(Fonts::CLEAR_SANS, "ClearSans-Regular.ttf"); resourceManager.registerSoundBuffer(Sound::BREAKABLE, "breakable.ogg"); resourceManager.registerSoundBuffer(Sound::COUNTDOWN_0, "countdown0.ogg"); resourceManager.registerSoundBuffer(Sound::COUNTDOWN_1, "countdown1.ogg"); resourceManager.registerSoundBuffer(Sound::DEATH, "death.ogg"); resourceManager.registerSoundBuffer(Sound::KICK, "kick.ogg"); resourceManager.registerSoundBuffer(Sound::SPLOSION, "splosion.ogg"); resourceManager.registerSoundBuffer(Sound::POWERUP, "powerup.ogg"); resourceManager.registerSoundBuffer(Sound::TRY_AGAIN_TUNE, "tryagain.ogg"); resourceManager.registerSoundBuffer(Sound::VICTORY_TUNE, "victory.ogg"); } // register states via stateStack // State IDs must be listed in stateIdentifiers.hpp void Game::registerStates() { stateStack.registerState<SplashState>(States::SPLASH); stateStack.registerState<SplashMenu>(States::MENU); stateStack.pushState(States::MENU); } <|endoftext|>
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "graph.h" #include <assert.h> #include <stdio.h> #include "build_log.h" #include "depfile_parser.h" #include "deps_log.h" #include "disk_interface.h" #include "explain.h" #include "manifest_parser.h" #include "metrics.h" #include "state.h" #include "util.h" bool Node::Stat(DiskInterface* disk_interface) { METRIC_RECORD("node stat"); mtime_ = disk_interface->Stat(path_); return mtime_ > 0; } void Rule::AddBinding(const string& key, const EvalString& val) { bindings_[key] = val; } const EvalString* Rule::GetBinding(const string& key) const { map<string, EvalString>::const_iterator i = bindings_.find(key); if (i == bindings_.end()) return NULL; return &i->second; } // static bool Rule::IsReservedBinding(const string& var) { return var == "command" || var == "depfile" || var == "description" || var == "deps" || var == "generator" || var == "pool" || var == "restat" || var == "rspfile" || var == "rspfile_content"; } bool DependencyScan::RecomputeDirty(Edge* edge, string* err) { bool dirty = false; edge->outputs_ready_ = true; edge->deps_missing_ = false; if (!dep_loader_.LoadDeps(edge, err)) { if (!err->empty()) return false; // Failed to load dependency info: rebuild to regenerate it. dirty = edge->deps_missing_ = true; } // Visit all inputs; we're dirty if any of the inputs are dirty. Node* most_recent_input = NULL; for (vector<Node*>::iterator i = edge->inputs_.begin(); i != edge->inputs_.end(); ++i) { if ((*i)->StatIfNecessary(disk_interface_)) { if (Edge* in_edge = (*i)->in_edge()) { if (!RecomputeDirty(in_edge, err)) return false; } else { // This input has no in-edge; it is dirty if it is missing. if (!(*i)->exists()) EXPLAIN("%s has no in-edge and is missing", (*i)->path().c_str()); (*i)->set_dirty(!(*i)->exists()); } } // If an input is not ready, neither are our outputs. if (Edge* in_edge = (*i)->in_edge()) { if (!in_edge->outputs_ready_) edge->outputs_ready_ = false; } if (!edge->is_order_only(i - edge->inputs_.begin())) { // If a regular input is dirty (or missing), we're dirty. // Otherwise consider mtime. if ((*i)->dirty()) { EXPLAIN("%s is dirty", (*i)->path().c_str()); dirty = true; } else { if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime()) { most_recent_input = *i; } } } } // We may also be dirty due to output state: missing outputs, out of // date outputs, etc. Visit all outputs and determine whether they're dirty. if (!dirty) dirty = RecomputeOutputsDirty(edge, most_recent_input); // Finally, visit each output to mark off that we've visited it, and update // their dirty state if necessary. for (vector<Node*>::iterator i = edge->outputs_.begin(); i != edge->outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface_); if (dirty) (*i)->MarkDirty(); } // If an edge is dirty, its outputs are normally not ready. (It's // possible to be clean but still not be ready in the presence of // order-only inputs.) // But phony edges with no inputs have nothing to do, so are always // ready. if (dirty && !(edge->is_phony() && edge->inputs_.empty())) edge->outputs_ready_ = false; return true; } bool DependencyScan::RecomputeOutputsDirty(Edge* edge, Node* most_recent_input) { string command = edge->EvaluateCommand(true); for (vector<Node*>::iterator i = edge->outputs_.begin(); i != edge->outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface_); if (RecomputeOutputDirty(edge, most_recent_input, command, *i)) return true; } return false; } bool DependencyScan::RecomputeOutputDirty(Edge* edge, Node* most_recent_input, const string& command, Node* output) { if (edge->is_phony()) { // Phony edges don't write any output. Outputs are only dirty if // there are no inputs and we're missing the output. return edge->inputs_.empty() && !output->exists(); } BuildLog::LogEntry* entry = 0; // Dirty if we're missing the output. if (!output->exists()) { EXPLAIN("output %s doesn't exist", output->path().c_str()); return true; } // Dirty if the output is older than the input. if (most_recent_input && output->mtime() < most_recent_input->mtime()) { TimeStamp output_mtime = output->mtime(); // If this is a restat rule, we may have cleaned the output with a restat // rule in a previous run and stored the most recent input mtime in the // build log. Use that mtime instead, so that the file will only be // considered dirty if an input was modified since the previous run. bool used_restat = false; if (edge->GetBindingBool("restat") && build_log() && (entry = build_log()->LookupByOutput(output->path()))) { output_mtime = entry->restat_mtime; used_restat = true; } if (output_mtime < most_recent_input->mtime()) { EXPLAIN("%soutput %s older than most recent input %s " "(%d vs %d)", used_restat ? "restat of " : "", output->path().c_str(), most_recent_input->path().c_str(), output_mtime, most_recent_input->mtime()); return true; } } // May also be dirty due to the command changing since the last build. // But if this is a generator rule, the command changing does not make us // dirty. if (!edge->GetBindingBool("generator") && build_log()) { if (entry || (entry = build_log()->LookupByOutput(output->path()))) { if (BuildLog::LogEntry::HashCommand(command) != entry->command_hash) { EXPLAIN("command line changed for %s", output->path().c_str()); return true; } } if (!entry) { EXPLAIN("command line not found in log for %s", output->path().c_str()); return true; } } return false; } bool Edge::AllInputsReady() const { for (vector<Node*>::const_iterator i = inputs_.begin(); i != inputs_.end(); ++i) { if ((*i)->in_edge() && !(*i)->in_edge()->outputs_ready()) return false; } return true; } /// An Env for an Edge, providing $in and $out. struct EdgeEnv : public Env { explicit EdgeEnv(Edge* edge) : edge_(edge) {} virtual string LookupVariable(const string& var); /// Given a span of Nodes, construct a list of paths suitable for a command /// line. string MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end, char sep); Edge* edge_; }; string EdgeEnv::LookupVariable(const string& var) { if (var == "in" || var == "in_newline") { int explicit_deps_count = edge_->inputs_.size() - edge_->implicit_deps_ - edge_->order_only_deps_; return MakePathList(edge_->inputs_.begin(), edge_->inputs_.begin() + explicit_deps_count, var == "in" ? ' ' : '\n'); } else if (var == "out") { return MakePathList(edge_->outputs_.begin(), edge_->outputs_.end(), ' '); } // See notes on BindingEnv::LookupWithFallback. const EvalString* eval = edge_->rule_->GetBinding(var); return edge_->env_->LookupWithFallback(var, eval, this); } string EdgeEnv::MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end, char sep) { string result; for (vector<Node*>::iterator i = begin; i != end; ++i) { if (!result.empty()) result.push_back(sep); const string& path = (*i)->path(); if (path.find(" ") != string::npos) { result.append("\""); result.append(path); result.append("\""); } else { result.append(path); } } return result; } string Edge::EvaluateCommand(bool incl_rsp_file) { string command = GetBinding("command"); if (incl_rsp_file) { string rspfile_content = GetBinding("rspfile_content"); if (!rspfile_content.empty()) command += ";rspfile=" + rspfile_content; } return command; } string Edge::GetBinding(const string& key) { EdgeEnv env(this); return env.LookupVariable(key); } bool Edge::GetBindingBool(const string& key) { return !GetBinding(key).empty(); } void Edge::Dump(const char* prefix) const { printf("%s[ ", prefix); for (vector<Node*>::const_iterator i = inputs_.begin(); i != inputs_.end() && *i != NULL; ++i) { printf("%s ", (*i)->path().c_str()); } printf("--%s-> ", rule_->name().c_str()); for (vector<Node*>::const_iterator i = outputs_.begin(); i != outputs_.end() && *i != NULL; ++i) { printf("%s ", (*i)->path().c_str()); } if (pool_) { if (!pool_->name().empty()) { printf("(in pool '%s')", pool_->name().c_str()); } } else { printf("(null pool?)"); } printf("] 0x%p\n", this); } bool Edge::is_phony() const { return rule_ == &State::kPhonyRule; } void Node::Dump(const char* prefix) const { printf("%s <%s 0x%p> mtime: %d%s, (:%s), ", prefix, path().c_str(), this, mtime(), mtime() ? "" : " (:missing)", dirty() ? " dirty" : " clean"); if (in_edge()) { in_edge()->Dump("in-edge: "); } else { printf("no in-edge\n"); } printf(" out edges:\n"); for (vector<Edge*>::const_iterator e = out_edges().begin(); e != out_edges().end() && *e != NULL; ++e) { (*e)->Dump(" +- "); } } bool ImplicitDepLoader::LoadDeps(Edge* edge, string* err) { string deps_type = edge->GetBinding("deps"); if (!deps_type.empty()) { if (!LoadDepsFromLog(edge, err)) { if (!err->empty()) return false; return false; } return true; } string depfile = edge->GetBinding("depfile"); if (!depfile.empty()) { if (!LoadDepFile(edge, depfile, err)) { if (!err->empty()) return false; EXPLAIN("depfile '%s' is missing", depfile.c_str()); return false; } return true; } // No deps to load. return true; } bool ImplicitDepLoader::LoadDepFile(Edge* edge, const string& path, string* err) { METRIC_RECORD("depfile load"); string content = disk_interface_->ReadFile(path, err); if (!err->empty()) { *err = "loading '" + path + "': " + *err; return false; } // On a missing depfile: return false and empty *err. if (content.empty()) return false; DepfileParser depfile; string depfile_err; if (!depfile.Parse(&content, &depfile_err)) { *err = path + ": " + depfile_err; return false; } // Check that this depfile matches the edge's output. Node* first_output = edge->outputs_[0]; StringPiece opath = StringPiece(first_output->path()); if (opath != depfile.out_) { *err = "expected depfile '" + path + "' to mention '" + first_output->path() + "', got '" + depfile.out_.AsString() + "'"; return false; } // Preallocate space in edge->inputs_ to be filled in below. vector<Node*>::iterator implicit_dep = PreallocateSpace(edge, depfile.ins_.size()); // Add all its in-edges. for (vector<StringPiece>::iterator i = depfile.ins_.begin(); i != depfile.ins_.end(); ++i, ++implicit_dep) { if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, err)) return false; Node* node = state_->GetNode(*i); *implicit_dep = node; node->AddOutEdge(edge); CreatePhonyInEdge(node); } return true; } bool ImplicitDepLoader::LoadDepsFromLog(Edge* edge, string* err) { // NOTE: deps are only supported for single-target edges. Node* output = edge->outputs_[0]; DepsLog::Deps* deps = deps_log_->GetDeps(output); if (!deps) { EXPLAIN("deps for '%s' are missing", output->path().c_str()); return false; } // Deps are invalid if the output is newer than the deps. if (output->mtime() > deps->mtime) { EXPLAIN("stored deps info out of date for for '%s' (%d vs %d)", output->path().c_str(), deps->mtime, output->mtime()); return false; } vector<Node*>::iterator implicit_dep = PreallocateSpace(edge, deps->node_count); for (int i = 0; i < deps->node_count; ++i, ++implicit_dep) { Node* node = deps->nodes[i]; *implicit_dep = node; node->AddOutEdge(edge); CreatePhonyInEdge(node); } return true; } vector<Node*>::iterator ImplicitDepLoader::PreallocateSpace(Edge* edge, int count) { edge->inputs_.insert(edge->inputs_.end() - edge->order_only_deps_, (size_t)count, 0); edge->implicit_deps_ += count; return edge->inputs_.end() - edge->order_only_deps_ - count; } void ImplicitDepLoader::CreatePhonyInEdge(Node* node) { if (node->in_edge()) return; Edge* phony_edge = state_->AddEdge(&State::kPhonyRule); node->set_in_edge(phony_edge); phony_edge->outputs_.push_back(node); // RecomputeDirty might not be called for phony_edge if a previous call // to RecomputeDirty had caused the file to be stat'ed. Because previous // invocations of RecomputeDirty would have seen this node without an // input edge (and therefore ready), we have to set outputs_ready_ to true // to avoid a potential stuck build. If we do call RecomputeDirty for // this node, it will simply set outputs_ready_ to the correct value. phony_edge->outputs_ready_ = true; } <commit_msg>Simplify.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "graph.h" #include <assert.h> #include <stdio.h> #include "build_log.h" #include "depfile_parser.h" #include "deps_log.h" #include "disk_interface.h" #include "explain.h" #include "manifest_parser.h" #include "metrics.h" #include "state.h" #include "util.h" bool Node::Stat(DiskInterface* disk_interface) { METRIC_RECORD("node stat"); mtime_ = disk_interface->Stat(path_); return mtime_ > 0; } void Rule::AddBinding(const string& key, const EvalString& val) { bindings_[key] = val; } const EvalString* Rule::GetBinding(const string& key) const { map<string, EvalString>::const_iterator i = bindings_.find(key); if (i == bindings_.end()) return NULL; return &i->second; } // static bool Rule::IsReservedBinding(const string& var) { return var == "command" || var == "depfile" || var == "description" || var == "deps" || var == "generator" || var == "pool" || var == "restat" || var == "rspfile" || var == "rspfile_content"; } bool DependencyScan::RecomputeDirty(Edge* edge, string* err) { bool dirty = false; edge->outputs_ready_ = true; edge->deps_missing_ = false; if (!dep_loader_.LoadDeps(edge, err)) { if (!err->empty()) return false; // Failed to load dependency info: rebuild to regenerate it. dirty = edge->deps_missing_ = true; } // Visit all inputs; we're dirty if any of the inputs are dirty. Node* most_recent_input = NULL; for (vector<Node*>::iterator i = edge->inputs_.begin(); i != edge->inputs_.end(); ++i) { if ((*i)->StatIfNecessary(disk_interface_)) { if (Edge* in_edge = (*i)->in_edge()) { if (!RecomputeDirty(in_edge, err)) return false; } else { // This input has no in-edge; it is dirty if it is missing. if (!(*i)->exists()) EXPLAIN("%s has no in-edge and is missing", (*i)->path().c_str()); (*i)->set_dirty(!(*i)->exists()); } } // If an input is not ready, neither are our outputs. if (Edge* in_edge = (*i)->in_edge()) { if (!in_edge->outputs_ready_) edge->outputs_ready_ = false; } if (!edge->is_order_only(i - edge->inputs_.begin())) { // If a regular input is dirty (or missing), we're dirty. // Otherwise consider mtime. if ((*i)->dirty()) { EXPLAIN("%s is dirty", (*i)->path().c_str()); dirty = true; } else { if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime()) { most_recent_input = *i; } } } } // We may also be dirty due to output state: missing outputs, out of // date outputs, etc. Visit all outputs and determine whether they're dirty. if (!dirty) dirty = RecomputeOutputsDirty(edge, most_recent_input); // Finally, visit each output to mark off that we've visited it, and update // their dirty state if necessary. for (vector<Node*>::iterator i = edge->outputs_.begin(); i != edge->outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface_); if (dirty) (*i)->MarkDirty(); } // If an edge is dirty, its outputs are normally not ready. (It's // possible to be clean but still not be ready in the presence of // order-only inputs.) // But phony edges with no inputs have nothing to do, so are always // ready. if (dirty && !(edge->is_phony() && edge->inputs_.empty())) edge->outputs_ready_ = false; return true; } bool DependencyScan::RecomputeOutputsDirty(Edge* edge, Node* most_recent_input) { string command = edge->EvaluateCommand(true); for (vector<Node*>::iterator i = edge->outputs_.begin(); i != edge->outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface_); if (RecomputeOutputDirty(edge, most_recent_input, command, *i)) return true; } return false; } bool DependencyScan::RecomputeOutputDirty(Edge* edge, Node* most_recent_input, const string& command, Node* output) { if (edge->is_phony()) { // Phony edges don't write any output. Outputs are only dirty if // there are no inputs and we're missing the output. return edge->inputs_.empty() && !output->exists(); } BuildLog::LogEntry* entry = 0; // Dirty if we're missing the output. if (!output->exists()) { EXPLAIN("output %s doesn't exist", output->path().c_str()); return true; } // Dirty if the output is older than the input. if (most_recent_input && output->mtime() < most_recent_input->mtime()) { TimeStamp output_mtime = output->mtime(); // If this is a restat rule, we may have cleaned the output with a restat // rule in a previous run and stored the most recent input mtime in the // build log. Use that mtime instead, so that the file will only be // considered dirty if an input was modified since the previous run. bool used_restat = false; if (edge->GetBindingBool("restat") && build_log() && (entry = build_log()->LookupByOutput(output->path()))) { output_mtime = entry->restat_mtime; used_restat = true; } if (output_mtime < most_recent_input->mtime()) { EXPLAIN("%soutput %s older than most recent input %s " "(%d vs %d)", used_restat ? "restat of " : "", output->path().c_str(), most_recent_input->path().c_str(), output_mtime, most_recent_input->mtime()); return true; } } // May also be dirty due to the command changing since the last build. // But if this is a generator rule, the command changing does not make us // dirty. if (!edge->GetBindingBool("generator") && build_log()) { if (entry || (entry = build_log()->LookupByOutput(output->path()))) { if (BuildLog::LogEntry::HashCommand(command) != entry->command_hash) { EXPLAIN("command line changed for %s", output->path().c_str()); return true; } } if (!entry) { EXPLAIN("command line not found in log for %s", output->path().c_str()); return true; } } return false; } bool Edge::AllInputsReady() const { for (vector<Node*>::const_iterator i = inputs_.begin(); i != inputs_.end(); ++i) { if ((*i)->in_edge() && !(*i)->in_edge()->outputs_ready()) return false; } return true; } /// An Env for an Edge, providing $in and $out. struct EdgeEnv : public Env { explicit EdgeEnv(Edge* edge) : edge_(edge) {} virtual string LookupVariable(const string& var); /// Given a span of Nodes, construct a list of paths suitable for a command /// line. string MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end, char sep); Edge* edge_; }; string EdgeEnv::LookupVariable(const string& var) { if (var == "in" || var == "in_newline") { int explicit_deps_count = edge_->inputs_.size() - edge_->implicit_deps_ - edge_->order_only_deps_; return MakePathList(edge_->inputs_.begin(), edge_->inputs_.begin() + explicit_deps_count, var == "in" ? ' ' : '\n'); } else if (var == "out") { return MakePathList(edge_->outputs_.begin(), edge_->outputs_.end(), ' '); } // See notes on BindingEnv::LookupWithFallback. const EvalString* eval = edge_->rule_->GetBinding(var); return edge_->env_->LookupWithFallback(var, eval, this); } string EdgeEnv::MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end, char sep) { string result; for (vector<Node*>::iterator i = begin; i != end; ++i) { if (!result.empty()) result.push_back(sep); const string& path = (*i)->path(); if (path.find(" ") != string::npos) { result.append("\""); result.append(path); result.append("\""); } else { result.append(path); } } return result; } string Edge::EvaluateCommand(bool incl_rsp_file) { string command = GetBinding("command"); if (incl_rsp_file) { string rspfile_content = GetBinding("rspfile_content"); if (!rspfile_content.empty()) command += ";rspfile=" + rspfile_content; } return command; } string Edge::GetBinding(const string& key) { EdgeEnv env(this); return env.LookupVariable(key); } bool Edge::GetBindingBool(const string& key) { return !GetBinding(key).empty(); } void Edge::Dump(const char* prefix) const { printf("%s[ ", prefix); for (vector<Node*>::const_iterator i = inputs_.begin(); i != inputs_.end() && *i != NULL; ++i) { printf("%s ", (*i)->path().c_str()); } printf("--%s-> ", rule_->name().c_str()); for (vector<Node*>::const_iterator i = outputs_.begin(); i != outputs_.end() && *i != NULL; ++i) { printf("%s ", (*i)->path().c_str()); } if (pool_) { if (!pool_->name().empty()) { printf("(in pool '%s')", pool_->name().c_str()); } } else { printf("(null pool?)"); } printf("] 0x%p\n", this); } bool Edge::is_phony() const { return rule_ == &State::kPhonyRule; } void Node::Dump(const char* prefix) const { printf("%s <%s 0x%p> mtime: %d%s, (:%s), ", prefix, path().c_str(), this, mtime(), mtime() ? "" : " (:missing)", dirty() ? " dirty" : " clean"); if (in_edge()) { in_edge()->Dump("in-edge: "); } else { printf("no in-edge\n"); } printf(" out edges:\n"); for (vector<Edge*>::const_iterator e = out_edges().begin(); e != out_edges().end() && *e != NULL; ++e) { (*e)->Dump(" +- "); } } bool ImplicitDepLoader::LoadDeps(Edge* edge, string* err) { string deps_type = edge->GetBinding("deps"); if (!deps_type.empty()) return LoadDepsFromLog(edge, err); string depfile = edge->GetBinding("depfile"); if (!depfile.empty()) return LoadDepFile(edge, depfile, err); // No deps to load. return true; } bool ImplicitDepLoader::LoadDepFile(Edge* edge, const string& path, string* err) { METRIC_RECORD("depfile load"); string content = disk_interface_->ReadFile(path, err); if (!err->empty()) { *err = "loading '" + path + "': " + *err; return false; } // On a missing depfile: return false and empty *err. if (content.empty()) { EXPLAIN("depfile '%s' is missing", path.c_str()); return false; } DepfileParser depfile; string depfile_err; if (!depfile.Parse(&content, &depfile_err)) { *err = path + ": " + depfile_err; return false; } // Check that this depfile matches the edge's output. Node* first_output = edge->outputs_[0]; StringPiece opath = StringPiece(first_output->path()); if (opath != depfile.out_) { *err = "expected depfile '" + path + "' to mention '" + first_output->path() + "', got '" + depfile.out_.AsString() + "'"; return false; } // Preallocate space in edge->inputs_ to be filled in below. vector<Node*>::iterator implicit_dep = PreallocateSpace(edge, depfile.ins_.size()); // Add all its in-edges. for (vector<StringPiece>::iterator i = depfile.ins_.begin(); i != depfile.ins_.end(); ++i, ++implicit_dep) { if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, err)) return false; Node* node = state_->GetNode(*i); *implicit_dep = node; node->AddOutEdge(edge); CreatePhonyInEdge(node); } return true; } bool ImplicitDepLoader::LoadDepsFromLog(Edge* edge, string* err) { // NOTE: deps are only supported for single-target edges. Node* output = edge->outputs_[0]; DepsLog::Deps* deps = deps_log_->GetDeps(output); if (!deps) { EXPLAIN("deps for '%s' are missing", output->path().c_str()); return false; } // Deps are invalid if the output is newer than the deps. if (output->mtime() > deps->mtime) { EXPLAIN("stored deps info out of date for for '%s' (%d vs %d)", output->path().c_str(), deps->mtime, output->mtime()); return false; } vector<Node*>::iterator implicit_dep = PreallocateSpace(edge, deps->node_count); for (int i = 0; i < deps->node_count; ++i, ++implicit_dep) { Node* node = deps->nodes[i]; *implicit_dep = node; node->AddOutEdge(edge); CreatePhonyInEdge(node); } return true; } vector<Node*>::iterator ImplicitDepLoader::PreallocateSpace(Edge* edge, int count) { edge->inputs_.insert(edge->inputs_.end() - edge->order_only_deps_, (size_t)count, 0); edge->implicit_deps_ += count; return edge->inputs_.end() - edge->order_only_deps_ - count; } void ImplicitDepLoader::CreatePhonyInEdge(Node* node) { if (node->in_edge()) return; Edge* phony_edge = state_->AddEdge(&State::kPhonyRule); node->set_in_edge(phony_edge); phony_edge->outputs_.push_back(node); // RecomputeDirty might not be called for phony_edge if a previous call // to RecomputeDirty had caused the file to be stat'ed. Because previous // invocations of RecomputeDirty would have seen this node without an // input edge (and therefore ready), we have to set outputs_ready_ to true // to avoid a potential stuck build. If we do call RecomputeDirty for // this node, it will simply set outputs_ready_ to the correct value. phony_edge->outputs_ready_ = true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Yahoo Inc. All rights reserved. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ #include <vector> #include "graph.h" struct EdgeSorter { const Graph & graph_; EdgeSorter(const Graph & g) : graph_(g) { } bool operator () (const Graph::edge_descriptor & a, const Graph::edge_descriptor & b) const { return graph_[a] < graph_[b]; } }; void contextSort(Graph & g) { typedef std::pair< Graph::edge_iterator, Graph::edge_iterator > Pair; Pair p = boost::edges(g); std::vector< Graph::edge_descriptor > edges(p.first, p.second); std::sort(std::begin(edges), std::end(edges), EdgeSorter(g)); const size_t size = edges.size(); for (size_t i = 0; i < size; ++i) { const Graph::edge_descriptor a = edges[i]; for (size_t j = i + 1; j < size; ++j) { const Graph::edge_descriptor b = edges[j]; if (g[a].contains(g[b])) { const Context r = g[b]; edges.push_back(add_edge(target(a, g), target(b, g), r, g).first); } } } reverse(std::begin(edges), std::end(edges)); size_t newSize = edges.size(); size_t additionalSize = newSize - size; for (size_t i = 0; i < additionalSize; ++i) { const Graph::edge_descriptor a = edges[i]; for (size_t j = i + 1; j < newSize; ++j) { const Graph::edge_descriptor b = edges[j]; if (target(a, g) == target(b, g)) { remove_edge(b, g); edges.erase(std::begin(edges) + j); --newSize; if (j < additionalSize) { --additionalSize; } } } } } <commit_msg>we need to sort the edges<commit_after>/* * Copyright (c) 2015, Yahoo Inc. All rights reserved. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ #include <vector> #include "graph.h" struct EdgeSorter { const Graph & graph_; EdgeSorter(const Graph & g) : graph_(g) { } bool operator () (const Graph::edge_descriptor & a, const Graph::edge_descriptor & b) const { return graph_[a] < graph_[b]; } }; void contextSort(Graph & g) { typedef std::pair< Graph::edge_iterator, Graph::edge_iterator > Pair; Pair p = boost::edges(g); std::vector< Graph::edge_descriptor > edges(p.first, p.second); std::sort(std::begin(edges), std::end(edges), EdgeSorter(g)); const size_t size = edges.size(); for (size_t i = 0; i < size; ++i) { const Graph::edge_descriptor a = edges[i]; for (size_t j = i + 1; j < size; ++j) { const Graph::edge_descriptor b = edges[j]; const Context r = g[b]; if (g[a].contains(g[b])) { edges.push_back(add_edge(target(a, g), target(b, g), r, g).first); } else { edges.push_back(add_edge(*vertices(g).first, target(b, g), r, g).first); } } } reverse(std::begin(edges), std::end(edges)); size_t newSize = edges.size(); size_t additionalSize = newSize - size; for (size_t i = 0; i < additionalSize; ++i) { const Graph::edge_descriptor a = edges[i]; for (size_t j = i + 1; j < newSize; ++j) { const Graph::edge_descriptor b = edges[j]; if (target(a, g) == target(b, g)) { remove_edge(b, g); edges.erase(std::begin(edges) + j); --newSize; if (j < additionalSize) { --additionalSize; } } } } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "help.hpp" void budget::help_module::handle(const std::vector<std::string>&){ std::cout << "Usage: budget Display the overview of the current month" << std::endl << std::endl; std::cout << " budget account [show] Show the current accounts" << std::endl; std::cout << " budget account all Show all the accounts" << std::endl; std::cout << " budget account add Add a new account" << std::endl; std::cout << " budget account delete (id) Delete the given account" << std::endl; std::cout << " budget account edit (id) Edit the given account" << std::endl; std::cout << " budget account migrate Merge two accounts together" << std::endl << std::endl; std::cout << " budget account archive Archive the current accounts to start new accounts" << std::endl << std::endl; std::cout << " budget expense [show] Display the expenses of the current month" << std::endl; std::cout << " budget expense show (month) (year) Display the expenses of the specified month of the specified year" << std::endl; std::cout << " budget expense all Display all the expenses" << std::endl; std::cout << " budget expense add Add a new expense" << std::endl; std::cout << " budget expense add (template name) Add a new expense from a template or create a new template" << std::endl; std::cout << " budget expense delete (id) Remove completely the expense with the given id" << std::endl; std::cout << " budget expense edit (id) Modify the expense with the given id" << std::endl << std::endl; std::cout << " budget expense template Display the templates" << std::endl << std::endl; std::cout << " budget earning [earnings] Display the earnings of the current month" << std::endl; std::cout << " budget earning show (month) (year) Display the earnings of the specified month of the specified year" << std::endl; std::cout << " budget earning all Display all the earnings" << std::endl; std::cout << " budget earning add Add a new earning" << std::endl; std::cout << " budget earning delete (id) Remove completely the earning with the given id" << std::endl; std::cout << " budget earning edit (id) Modify the earning with the given id" << std::endl << std::endl; std::cout << " budget overview [month] Display the overvew of the current month" << std::endl; std::cout << " budget overview month (month) (year) Display the overvew of the specified month of the current year" << std::endl; std::cout << " budget overview year (year) Display the overvew of the specified year" << std::endl; std::cout << " budget overview aggregate Display the aggregated expenses for the current year" << std::endl; std::cout << " budget overview aggregate year (year) Display the aggregated expenses for the given year" << std::endl << std::endl; std::cout << " budget recurring [show] Display the recurring expenses" << std::endl; std::cout << " budget recurring add Add a new recurring expense" << std::endl; std::cout << " budget recurring delete (id) Remove completely the recurring expense with the given id" << std::endl; std::cout << " budget recurring edit (id) Modify the recurring expense with the given id" << std::endl << std::endl; std::cout << " budget fortune [status] Display the status of the fortune checks" << std::endl; std::cout << " budget fortune list Display the list of all the fortune checks" << std::endl; std::cout << " budget fortune check Create a new fortune check" << std::endl; std::cout << " budget fortune edit (id) Edit a fortune check" << std::endl; std::cout << " budget fortune delete (id) Delete a fortune check" << std::endl << std::endl; std::cout << " budget objective [status] Show the status of the objectives for the current year" << std::endl; std::cout << " budget objective list List all the defined objectives" << std::endl; std::cout << " budget objective add Add a new objective" << std::endl; std::cout << " budget objective edit (id) Edit an objective" << std::endl; std::cout << " budget objective delete (id) Delete an objective" << std::endl; std::cout << " budget wish [status] Show the status of the wishes" << std::endl; std::cout << " budget wish list List all the wishes" << std::endl; std::cout << " budget wish estimate Estimate the best date to buy something" << std::endl; std::cout << " budget wish add Add a new wish" << std::endl; std::cout << " budget wish edit (id) Edit a wish" << std::endl; std::cout << " budget wish delete (id) Delete a wish" << std::endl; std::cout << " budget debt [list] Display the unpaid debts" << std::endl; std::cout << " budget debt all Display all debts" << std::endl; std::cout << " budget debt paid (id) Mark the given debt as paid" << std::endl; std::cout << " budget debt delete (id) Delete the given debt" << std::endl; std::cout << " budget debt edit (id) Edit the given debt" << std::endl << std::endl; std::cout << " budget versioning save Commit the budget directory changes with Git" << std::endl; std::cout << " budget versioning sync Pull the remote changes on the budget directory with Git and push" << std::endl; std::cout << " budget report [monthly] Display monthly report in form of bar plot" << std::endl; std::cout << " budget gc Make sure all IDs are contiguous" << std::endl; } <commit_msg>Complete help<commit_after>//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "help.hpp" void budget::help_module::handle(const std::vector<std::string>&){ std::cout << "Usage: budget Display the overview of the current month" << std::endl << std::endl; std::cout << " budget account [show] Show the current accounts" << std::endl; std::cout << " budget account all Show all the accounts" << std::endl; std::cout << " budget account add Add a new account" << std::endl; std::cout << " budget account delete (id) Delete the given account" << std::endl; std::cout << " budget account edit (id) Edit the given account" << std::endl; std::cout << " budget account migrate Merge two accounts together" << std::endl << std::endl; std::cout << " budget account archive Archive the current accounts to start new accounts" << std::endl << std::endl; std::cout << " budget expense [show] Display the expenses of the current month" << std::endl; std::cout << " budget expense show (month) (year) Display the expenses of the specified month of the specified year" << std::endl; std::cout << " budget expense all Display all the expenses" << std::endl; std::cout << " budget expense add Add a new expense" << std::endl; std::cout << " budget expense add (template name) Add a new expense from a template or create a new template" << std::endl; std::cout << " budget expense delete (id) Remove completely the expense with the given id" << std::endl; std::cout << " budget expense edit (id) Modify the expense with the given id" << std::endl << std::endl; std::cout << " budget expense template Display the templates" << std::endl << std::endl; std::cout << " budget earning [earnings] Display the earnings of the current month" << std::endl; std::cout << " budget earning show (month) (year) Display the earnings of the specified month of the specified year" << std::endl; std::cout << " budget earning all Display all the earnings" << std::endl; std::cout << " budget earning add Add a new earning" << std::endl; std::cout << " budget earning delete (id) Remove completely the earning with the given id" << std::endl; std::cout << " budget earning edit (id) Modify the earning with the given id" << std::endl << std::endl; std::cout << " budget overview [month] Display the overvew of the current month" << std::endl; std::cout << " budget overview month (month) (year) Display the overvew of the specified month of the current year" << std::endl; std::cout << " budget overview year (year) Display the overvew of the specified year" << std::endl; std::cout << " budget overview aggregate Display the aggregated expenses for the current year" << std::endl; std::cout << " budget overview aggregate year (year) Display the aggregated expenses for the given year" << std::endl << std::endl; std::cout << " budget recurring [show] Display the recurring expenses" << std::endl; std::cout << " budget recurring add Add a new recurring expense" << std::endl; std::cout << " budget recurring delete (id) Remove completely the recurring expense with the given id" << std::endl; std::cout << " budget recurring edit (id) Modify the recurring expense with the given id" << std::endl << std::endl; std::cout << " budget fortune [status] Display the status of the fortune checks" << std::endl; std::cout << " budget fortune list Display the list of all the fortune checks" << std::endl; std::cout << " budget fortune check Create a new fortune check" << std::endl; std::cout << " budget fortune edit (id) Edit a fortune check" << std::endl; std::cout << " budget fortune delete (id) Delete a fortune check" << std::endl << std::endl; std::cout << " budget objective [status] Show the status of the objectives for the current year" << std::endl; std::cout << " budget objective list List all the defined objectives" << std::endl; std::cout << " budget objective add Add a new objective" << std::endl; std::cout << " budget objective edit (id) Edit an objective" << std::endl; std::cout << " budget objective delete (id) Delete an objective" << std::endl; std::cout << " budget wish [status] Show the status of the wishes" << std::endl; std::cout << " budget wish list List all the wishes" << std::endl; std::cout << " budget wish estimate Estimate the best date to buy something" << std::endl; std::cout << " budget wish add Add a new wish" << std::endl; std::cout << " budget wish edit (id) Edit a wish" << std::endl; std::cout << " budget wish delete (id) Delete a wish" << std::endl; std::cout << " budget debt [list] Display the unpaid debts" << std::endl; std::cout << " budget debt all Display all debts" << std::endl; std::cout << " budget debt paid (id) Mark the given debt as paid" << std::endl; std::cout << " budget debt delete (id) Delete the given debt" << std::endl; std::cout << " budget debt edit (id) Edit the given debt" << std::endl << std::endl; std::cout << " budget versioning save Commit the budget directory changes with Git" << std::endl; std::cout << " budget versioning sync Pull the remote changes on the budget directory with Git and push" << std::endl; std::cout << " budget report [monthly] Display monthly report in form of bar plot" << std::endl; std::cout << " budget report account [monthly] Display monthly report of a specific account in form of bar plot" << std::endl; std::cout << " budget gc Make sure all IDs are contiguous" << std::endl; } <|endoftext|>
<commit_before>#ifndef HEADER_GUARD_HOOKS_H #define HEADER_GUARD_HOOKS_H #include "contents.hh" namespace vick { /*! * \file hooks.hh * * \brief Defines how to hook processes in with one another so that one * action will always accompany another. * * proc_hook(hook) will call all the functions added in add_hook(hook, *void(*)()) * */ /*! * \brief Distinguishes normal <code>unsigned int</code>s from being confused as * hooks. */ using hook_t = unsigned int; namespace hook { extern hook_t save; extern hook_t refresh; extern hook_t mode_enter; extern hook_t open_file; extern hook_t contents_created; extern hook_t contents_deleted; /*! * \brief Generates a unique hook id * * This id is made at runtime and is <i>not</i> thread safe. */ hook_t gen(); /*! * \brief Calls all the functions associated to the hook given * * To associate a function with a hook use add() */ void proc(hook_t, contents&); /*! * \brief Associates the function given with a hook * * The function argumen is guarenteed to be called whenever * proc_hook() is called with the same hook as this method is called * with. * * There can be multiple functions for a certain hook. They will be * called in the order they were added with add() */ void add(hook_t, void (*)(contents&)); } } #endif <commit_msg>Add spaces between method documentation<commit_after>#ifndef HEADER_GUARD_HOOKS_H #define HEADER_GUARD_HOOKS_H #include "contents.hh" namespace vick { /*! * \file hooks.hh * * \brief Defines how to hook processes in with one another so that one * action will always accompany another. * * proc_hook(hook) will call all the functions added in add_hook(hook, *void(*)()) * */ /*! * \brief Distinguishes normal <code>unsigned int</code>s from being confused as * hooks. */ using hook_t = unsigned int; namespace hook { extern hook_t save; extern hook_t refresh; extern hook_t mode_enter; extern hook_t open_file; extern hook_t contents_created; extern hook_t contents_deleted; /*! * \brief Generates a unique hook id * * This id is made at runtime and is <i>not</i> thread safe. */ hook_t gen(); /*! * \brief Calls all the functions associated to the hook given * * To associate a function with a hook use add() */ void proc(hook_t, contents&); /*! * \brief Associates the function given with a hook * * The function argumen is guarenteed to be called whenever * proc_hook() is called with the same hook as this method is called * with. * * There can be multiple functions for a certain hook. They will be * called in the order they were added with add() */ void add(hook_t, void (*)(contents&)); } } #endif <|endoftext|>
<commit_before>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "configuration.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ static const int TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; void inc_speed_counter() { Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; const int sx = 640; const int sy = 480; out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; set_color_depth( 16 ); out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; srand( time( NULL ) ); set_display_switch_mode( SWITCH_BACKGROUND ); atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); Network::init(); Configuration::loadConfigurations(); pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; /* Bitmap::Screen = new Bitmap( screen ); if ( ! Bitmap::Screen ){ return false; } */ return true; } <commit_msg>add close hook. the game segfaults currently<commit_after>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "configuration.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ static const int TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; void inc_speed_counter() { Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } static void close_paintown(){ exit(0); } END_OF_FUNCTION(close_paintown) bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; const int sx = 640; const int sy = 480; out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; set_color_depth( 16 ); out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; srand( time( NULL ) ); set_display_switch_mode( SWITCH_BACKGROUND ); LOCK_FUNCTION(close_paintown); set_close_button_callback(close_paintown); atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); Network::init(); Configuration::loadConfigurations(); pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; /* Bitmap::Screen = new Bitmap( screen ); if ( ! Bitmap::Screen ){ return false; } */ return true; } <|endoftext|>
<commit_before>#include "json.hpp" using namespace std; ptree json_decode(string s) { ptree p; std::istringstream ss (s); try { read_json (ss,p); } catch (exception e) { cerr << "*CRITICAL: CANNOT PARSE/MALFORMED JSON '" << s << "'" << endl; } } std::string json_escape(const std::string& input) { std::ostringstream ss; for (std::string::const_iterator iter = input.begin(); iter != input.end(); iter++) { switch (*iter) { case '\\': ss << "\\\\"; break; case '"': ss << "\\\""; break; case '/': ss << "\\/"; break; case '\b': ss << "\\b"; break; case '\f': ss << "\\f"; break; case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; default: ss << *iter; break; } } return ss.str(); } <commit_msg>Mods on json_decode<commit_after>#include "json.hpp" using namespace std; ptree json_decode(string s) { ptree* p = new ptree(); std::istringstream ss (s); try { read_json (ss,*p); } catch (exception e) { cerr << "*CRITICAL: CANNOT PARSE/MALFORMED JSON '" << s << "'" << endl; } return *p; } std::string json_escape(const std::string& input) { std::ostringstream ss; for (std::string::const_iterator iter = input.begin(); iter != input.end(); iter++) { switch (*iter) { case '\\': ss << "\\\\"; break; case '"': ss << "\\\""; break; case '/': ss << "\\/"; break; case '\b': ss << "\\b"; break; case '\f': ss << "\\f"; break; case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; default: ss << *iter; break; } } return ss.str(); } <|endoftext|>
<commit_before>/* Copyright (C) 2002 by Marten Svanfeldt Anders Stenberg 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/objreg.h" #include "csutil/ref.h" #include "csutil/scf.h" #include "csutil/stringreader.h" #include "iutil/databuff.h" #include "iutil/document.h" #include "iutil/string.h" #include "ivaria/reporter.h" #include "ivideo/graph3d.h" #include "ivideo/shader/shader.h" #include "glshader_cgfp.h" CS_PLUGIN_NAMESPACE_BEGIN(GLShaderCg) { CS_LEAKGUARD_IMPLEMENT (csShaderGLCGFP); void csShaderGLCGFP::Activate() { if (pswrap) { pswrap->Activate (); return; } csShaderGLCGCommon::Activate(); } void csShaderGLCGFP::Deactivate() { if (pswrap) { pswrap->Deactivate (); return; } csShaderGLCGCommon::Deactivate(); } void csShaderGLCGFP::SetupState (const CS::Graphics::RenderMesh* mesh, CS::Graphics::RenderMeshModes& modes, const csShaderVariableStack& stack) { if (pswrap) { pswrap->SetupState (mesh, modes, stack); return; } csShaderGLCGCommon::SetupState (mesh, modes, stack); } void csShaderGLCGFP::ResetState() { if (pswrap) { pswrap->ResetState (); return; } csShaderGLCGCommon::ResetState(); } bool csShaderGLCGFP::Compile () { if (!shaderPlug->enableFP) return false; csRef<iDataBuffer> programBuffer = GetProgramData(); if (!programBuffer.IsValid()) return false; csString programStr; programStr.Append ((char*)programBuffer->GetData(), programBuffer->GetSize()); size_t i; // See if we want to wrap through the PS plugin // (psplg will be 0 if wrapping isn't wanted) if (shaderPlug->psplg) { ArgumentArray args; shaderPlug->GetProfileCompilerArgs ("fragment", shaderPlug->psProfile, args); for (i = 0; i < compilerArgs.GetSize(); i++) args.Push (compilerArgs[i]); args.Push (0); program = cgCreateProgram (shaderPlug->context, CG_SOURCE, programStr, shaderPlug->psProfile, !entrypoint.IsEmpty() ? entrypoint : "main", args.GetArray()); if (!program) return false; pswrap = shaderPlug->psplg->CreateProgram ("fp"); if (!pswrap) return false; csArray<csShaderVarMapping> mappings; for (i = 0; i < variablemap.GetSize (); i++) { // Get the Cg parameter CGparameter parameter = cgGetNamedParameter ( program, variablemap[i].destination); // Check if it's found, and just skip it if not. if (!parameter) continue; if (!cgIsParameterReferenced (parameter)) continue; // Make sure it's a C-register CGresource resource = cgGetParameterResource (parameter); if (resource == CG_C) { // Get the register number, and create a mapping csString regnum; regnum.Format ("c%lu", cgGetParameterResourceIndex (parameter)); mappings.Push (csShaderVarMapping (variablemap[i].name, regnum)); } } if (pswrap->Load (0, cgGetProgramString (program, CG_COMPILED_PROGRAM), mappings)) { bool ret = pswrap->Compile (); if (shaderPlug->debugDump) DoDebugDump(); return ret; } else { return false; } } else { csStringArray testForUnused; csStringReader lines (programStr); while (lines.HasMoreLines()) { csString line; lines.GetLine (line); if (line.StartsWith ("//@@UNUSED? ")) { line.DeleteAt (0, 12); testForUnused.Push (line); } } if (testForUnused.GetSize() > 0) { /* A list of unused variables to test for has been given. Test piecemeal * which variables are really unused */ csSet<csString> allNewUnusedParams; size_t step = 8; size_t offset = 0; while (offset < testForUnused.GetSize()) { unusedParams.DeleteAll(); for (size_t i = 0; i < offset; i++) unusedParams.Add (testForUnused[i]); for (size_t i = offset+step; i < testForUnused.GetSize(); i++) unusedParams.Add (testForUnused[i]); if (DefaultLoadProgram (0, programStr, CG_GL_FRAGMENT, shaderPlug->maxProfileFragment, loadIgnoreErrors)) { csSet<csString> newUnusedParams; CollectUnusedParameters (newUnusedParams); for (size_t i = 0; i < step; i++) { if (offset+i >= testForUnused.GetSize()) break; const char* s = testForUnused[offset+i]; if (newUnusedParams.Contains (s)) allNewUnusedParams.Add (s); } } offset += step; } unusedParams = allNewUnusedParams; } else { unusedParams.DeleteAll(); } if (!DefaultLoadProgram (0, programStr, CG_GL_FRAGMENT, shaderPlug->maxProfileFragment, loadLoadToGL)) return false; /* Compile twice to be able to filter out unused vertex2fragment stuff on * pass 2. * @@@ FIXME: two passes are not always needed. */ CollectUnusedParameters (unusedParams); return DefaultLoadProgram (this, programStr, CG_GL_FRAGMENT, shaderPlug->maxProfileFragment); } return true; } int csShaderGLCGFP::ResolveTU (const char* binding) { int newTU = -1; if (program) { CGparameter parameter = cgGetNamedParameter (program, binding); if (parameter) { if ((cgGetParameterBaseResource (parameter) == CG_TEXUNIT0) || (cgGetParameterBaseResource (parameter) == CG_TEX0)) { newTU = cgGetParameterResourceIndex (parameter); } } } return newTU; } } CS_PLUGIN_NAMESPACE_END(GLShaderCg) <commit_msg>Don't bind textures which aren't actually used<commit_after>/* Copyright (C) 2002 by Marten Svanfeldt Anders Stenberg 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/objreg.h" #include "csutil/ref.h" #include "csutil/scf.h" #include "csutil/stringreader.h" #include "iutil/databuff.h" #include "iutil/document.h" #include "iutil/string.h" #include "ivaria/reporter.h" #include "ivideo/graph3d.h" #include "ivideo/shader/shader.h" #include "glshader_cgfp.h" CS_PLUGIN_NAMESPACE_BEGIN(GLShaderCg) { CS_LEAKGUARD_IMPLEMENT (csShaderGLCGFP); void csShaderGLCGFP::Activate() { if (pswrap) { pswrap->Activate (); return; } csShaderGLCGCommon::Activate(); } void csShaderGLCGFP::Deactivate() { if (pswrap) { pswrap->Deactivate (); return; } csShaderGLCGCommon::Deactivate(); } void csShaderGLCGFP::SetupState (const CS::Graphics::RenderMesh* mesh, CS::Graphics::RenderMeshModes& modes, const csShaderVariableStack& stack) { if (pswrap) { pswrap->SetupState (mesh, modes, stack); return; } csShaderGLCGCommon::SetupState (mesh, modes, stack); } void csShaderGLCGFP::ResetState() { if (pswrap) { pswrap->ResetState (); return; } csShaderGLCGCommon::ResetState(); } bool csShaderGLCGFP::Compile () { if (!shaderPlug->enableFP) return false; csRef<iDataBuffer> programBuffer = GetProgramData(); if (!programBuffer.IsValid()) return false; csString programStr; programStr.Append ((char*)programBuffer->GetData(), programBuffer->GetSize()); size_t i; // See if we want to wrap through the PS plugin // (psplg will be 0 if wrapping isn't wanted) if (shaderPlug->psplg) { ArgumentArray args; shaderPlug->GetProfileCompilerArgs ("fragment", shaderPlug->psProfile, args); for (i = 0; i < compilerArgs.GetSize(); i++) args.Push (compilerArgs[i]); args.Push (0); program = cgCreateProgram (shaderPlug->context, CG_SOURCE, programStr, shaderPlug->psProfile, !entrypoint.IsEmpty() ? entrypoint : "main", args.GetArray()); if (!program) return false; pswrap = shaderPlug->psplg->CreateProgram ("fp"); if (!pswrap) return false; csArray<csShaderVarMapping> mappings; for (i = 0; i < variablemap.GetSize (); i++) { // Get the Cg parameter CGparameter parameter = cgGetNamedParameter ( program, variablemap[i].destination); // Check if it's found, and just skip it if not. if (!parameter) continue; if (!cgIsParameterReferenced (parameter)) continue; // Make sure it's a C-register CGresource resource = cgGetParameterResource (parameter); if (resource == CG_C) { // Get the register number, and create a mapping csString regnum; regnum.Format ("c%lu", cgGetParameterResourceIndex (parameter)); mappings.Push (csShaderVarMapping (variablemap[i].name, regnum)); } } if (pswrap->Load (0, cgGetProgramString (program, CG_COMPILED_PROGRAM), mappings)) { bool ret = pswrap->Compile (); if (shaderPlug->debugDump) DoDebugDump(); return ret; } else { return false; } } else { csStringArray testForUnused; csStringReader lines (programStr); while (lines.HasMoreLines()) { csString line; lines.GetLine (line); if (line.StartsWith ("//@@UNUSED? ")) { line.DeleteAt (0, 12); testForUnused.Push (line); } } if (testForUnused.GetSize() > 0) { /* A list of unused variables to test for has been given. Test piecemeal * which variables are really unused */ csSet<csString> allNewUnusedParams; size_t step = 8; size_t offset = 0; while (offset < testForUnused.GetSize()) { unusedParams.DeleteAll(); for (size_t i = 0; i < offset; i++) unusedParams.Add (testForUnused[i]); for (size_t i = offset+step; i < testForUnused.GetSize(); i++) unusedParams.Add (testForUnused[i]); if (DefaultLoadProgram (0, programStr, CG_GL_FRAGMENT, shaderPlug->maxProfileFragment, loadIgnoreErrors)) { csSet<csString> newUnusedParams; CollectUnusedParameters (newUnusedParams); for (size_t i = 0; i < step; i++) { if (offset+i >= testForUnused.GetSize()) break; const char* s = testForUnused[offset+i]; if (newUnusedParams.Contains (s)) allNewUnusedParams.Add (s); } } offset += step; } unusedParams = allNewUnusedParams; } else { unusedParams.DeleteAll(); } if (!DefaultLoadProgram (0, programStr, CG_GL_FRAGMENT, shaderPlug->maxProfileFragment, loadLoadToGL)) return false; /* Compile twice to be able to filter out unused vertex2fragment stuff on * pass 2. * @@@ FIXME: two passes are not always needed. */ CollectUnusedParameters (unusedParams); return DefaultLoadProgram (this, programStr, CG_GL_FRAGMENT, shaderPlug->maxProfileFragment); } return true; } int csShaderGLCGFP::ResolveTU (const char* binding) { int newTU = -1; if (program) { CGparameter parameter = cgGetNamedParameter (program, binding); if (parameter) { CGresource baseRes = cgGetParameterBaseResource (parameter); if (((baseRes == CG_TEXUNIT0) || (baseRes == CG_TEX0)) && (cgIsParameterUsed (parameter, program) || cgIsParameterReferenced (parameter))) { newTU = cgGetParameterResourceIndex (parameter); } } } return newTU; } } CS_PLUGIN_NAMESPACE_END(GLShaderCg) <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; typedef tuple<int, int> edge; typedef tuple<int, int, int> uvc; int N, M; vector<edge> V[310]; bool subroutine(uvc e) { int u0 = get<0>(e); edge edge0 = edge(get<1>(e), get<2>(e)); int u1 = get<1>(e); edge edge1 = edge(get<0>(e), -get<2>(e)); // Make an dfs tree without (u0, edge0) and (u1, edge1). stack<edge> S; S.push(edge(0, 0)); int height[310]; fill(height, height+310, -1); uvc parent[310]; parent[0] = uvc(-1, 0, -1); while (!S.empty()) { int now = get<0>(S.top()); int h = get<1>(S.top()); S.pop(); if (height[now] == -1) { height[now] = h; for (auto x : V[now]) { if ((now == u0 && x == edge0) || (now == u1 && x == edge1)) { continue; } int dst = get<0>(x); int cost = h + get<1>(x); if (height[dst] == -1) { parent[dst] = uvc(now, dst, cost); S.push(edge(dst, cost)); } } } } for (auto i = 0; i < N; ++i) { for (auto x : V[i]) { int j = get<0>(x); int cost = get<1>(x); if (height[j] - height[i] != cost) { return false; } } } return true; } int main () { cin >> N >> M; for (auto i = 0; i < M; ++i) { int a, b, c; cin >> a >> b >> c; --a; --b; V[a].push_back(edge(b, c)); V[b].push_back(edge(a, -c)); } // Make an initial dfs tree. stack<edge> S; S.push(edge(0, 0)); int height[310]; fill(height, height+310, -1); uvc parent[310]; parent[0] = uvc(-1, 0, -1); while (!S.empty()) { int now = get<0>(S.top()); int h = get<1>(S.top()); S.pop(); if (height[now] == -1) { // cerr << now << " " << h << endl; height[now] = h; for (auto x : V[now]) { int dst = get<0>(x); int cost = h + get<1>(x); if (height[dst] == -1) { parent[dst] = uvc(now, dst, cost); S.push(edge(dst, cost)); } } } } bool initial_ok = true; vector<uvc> forbid; for (auto i = 0; i < N; ++i) { for (auto x : V[i]) { int j = get<0>(x); int cost = get<1>(x); if (height[j] - height[i] != cost) { cerr << "height[" << j << "] - height[" << i << "] = " << height[j] << " - " << height[i] << " != " << cost << endl; initial_ok = false; int now = i; while (now != 0) { forbid.push_back(parent[now]); now = get<0>(parent[now]); } now = j; while (now != 0) { forbid.push_back(parent[now]); now = get<0>(parent[now]); } break; } } if (!initial_ok) break; } if (initial_ok) { cout << "Yes" << endl; return 0; } for (auto e : forbid) { if (subroutine(e)) { cout << "Yes" << endl; return 0; } } cout << "No" << endl; return 0; } <commit_msg>tried C.cpp to 'C'<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; typedef tuple<int, int> edge; typedef tuple<int, int, int> uvc; int N, M; vector<edge> V[310]; bool subroutine(uvc e) { int u0 = get<0>(e); edge edge0 = edge(get<1>(e), get<2>(e)); int u1 = get<1>(e); edge edge1 = edge(get<0>(e), -get<2>(e)); cerr << u0 << " " << u1 << " is not used." << endl; // Make an dfs tree without (u0, edge0) and (u1, edge1). stack<edge> S; S.push(edge(0, 0)); int height[310]; fill(height, height+310, -1); uvc parent[310]; parent[0] = uvc(-1, 0, -1); while (!S.empty()) { int now = get<0>(S.top()); int h = get<1>(S.top()); S.pop(); if (height[now] == -1) { height[now] = h; for (auto x : V[now]) { if ((now == u0 && x == edge0) || (now == u1 && x == edge1)) { continue; } int dst = get<0>(x); int cost = h + get<1>(x); if (height[dst] == -1) { parent[dst] = uvc(now, dst, cost); S.push(edge(dst, cost)); } } } } for (auto i = 0; i < N; ++i) { for (auto x : V[i]) { int j = get<0>(x); int cost = get<1>(x); if (height[j] - height[i] != cost) { cerr << "height[" << j << "] - height[" << i << "] = " << height[j] << " - " << height[i] << " != " << cost << endl; return false; } } } return true; } int main () { cin >> N >> M; for (auto i = 0; i < M; ++i) { int a, b, c; cin >> a >> b >> c; --a; --b; V[a].push_back(edge(b, c)); V[b].push_back(edge(a, -c)); } // Make an initial dfs tree. stack<edge> S; S.push(edge(0, 0)); int height[310]; fill(height, height+310, -1); uvc parent[310]; parent[0] = uvc(-1, 0, -1); while (!S.empty()) { int now = get<0>(S.top()); int h = get<1>(S.top()); S.pop(); if (height[now] == -1) { // cerr << now << " " << h << endl; height[now] = h; for (auto x : V[now]) { int dst = get<0>(x); int cost = h + get<1>(x); if (height[dst] == -1) { parent[dst] = uvc(now, dst, cost); S.push(edge(dst, cost)); } } } } bool initial_ok = true; vector<uvc> forbid; for (auto i = 0; i < N; ++i) { for (auto x : V[i]) { int j = get<0>(x); int cost = get<1>(x); if (height[j] - height[i] != cost) { cerr << "height[" << j << "] - height[" << i << "] = " << height[j] << " - " << height[i] << " != " << cost << endl; initial_ok = false; int now = i; while (now != 0) { forbid.push_back(parent[now]); now = get<0>(parent[now]); } now = j; while (now != 0) { forbid.push_back(parent[now]); now = get<0>(parent[now]); } break; } } if (!initial_ok) break; } if (initial_ok) { cout << "Yes" << endl; return 0; } for (auto e : forbid) { if (subroutine(e)) { cout << "Yes" << endl; return 0; } } cout << "No" << endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dlelstnr.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: tl $ $Date: 2001-02-27 14:53:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DLELSTNR_HXX_ #define _DLELSTNR_HXX_ #include <cppuhelper/weak.hxx> #ifndef _COM_SUN_STAR_LINGUISTIC2_XDICTIONARYLISTEVENTLISTENER_HPP_ #include <com/sun/star/linguistic2/XDictionaryListEventListener.hpp> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEEVENTLISTENER_HPP_ #include <com/sun/star/linguistic2/XLinguServiceEventListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_ #include <com/sun/star/frame/XTerminateListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> // helper for implementations #endif namespace com { namespace sun { namespace star { namespace linguistic2 { class XDictionaryList; class XLinguServiceManager; } namespace frame { class XTerminateListener; } } } } /////////////////////////////////////////////////////////////////////////// // SwLinguServiceEventListener // is a EventListener that triggers spellchecking // and hyphenation when relevant changes (to the // dictionaries of the dictionary list, or properties) were made. // class SwLinguServiceEventListener : public cppu::WeakImplHelper2 < com::sun::star::linguistic2::XLinguServiceEventListener, com::sun::star::frame::XTerminateListener > { com::sun::star::uno::Reference< com::sun::star::frame::XDesktop > xDesktop; com::sun::star::uno::Reference< com::sun::star::linguistic2::XLinguServiceManager > xLngSvcMgr; // disallow use of copy-constructor and assignment operator SwLinguServiceEventListener(const SwLinguServiceEventListener &); SwLinguServiceEventListener & operator = (const SwLinguServiceEventListener &); public: SwLinguServiceEventListener(); virtual ~SwLinguServiceEventListener(); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& rEventObj ) throw(::com::sun::star::uno::RuntimeException); // XDictionaryListEventListener virtual void SAL_CALL processDictionaryListEvent( const ::com::sun::star::linguistic2::DictionaryListEvent& rDicListEvent) throw( ::com::sun::star::uno::RuntimeException ); // XLinguServiceEventListener virtual void SAL_CALL processLinguServiceEvent( const ::com::sun::star::linguistic2::LinguServiceEvent& rLngSvcEvent ) throw(::com::sun::star::uno::RuntimeException); // XTerminateListener virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& rEventObj ) throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& rEventObj ) throw(::com::sun::star::uno::RuntimeException); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.1454); FILE MERGED 2005/09/05 13:35:50 rt 1.4.1454.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlelstnr.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:40:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DLELSTNR_HXX_ #define _DLELSTNR_HXX_ #include <cppuhelper/weak.hxx> #ifndef _COM_SUN_STAR_LINGUISTIC2_XDICTIONARYLISTEVENTLISTENER_HPP_ #include <com/sun/star/linguistic2/XDictionaryListEventListener.hpp> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEEVENTLISTENER_HPP_ #include <com/sun/star/linguistic2/XLinguServiceEventListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_ #include <com/sun/star/frame/XTerminateListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> // helper for implementations #endif namespace com { namespace sun { namespace star { namespace linguistic2 { class XDictionaryList; class XLinguServiceManager; } namespace frame { class XTerminateListener; } } } } /////////////////////////////////////////////////////////////////////////// // SwLinguServiceEventListener // is a EventListener that triggers spellchecking // and hyphenation when relevant changes (to the // dictionaries of the dictionary list, or properties) were made. // class SwLinguServiceEventListener : public cppu::WeakImplHelper2 < com::sun::star::linguistic2::XLinguServiceEventListener, com::sun::star::frame::XTerminateListener > { com::sun::star::uno::Reference< com::sun::star::frame::XDesktop > xDesktop; com::sun::star::uno::Reference< com::sun::star::linguistic2::XLinguServiceManager > xLngSvcMgr; // disallow use of copy-constructor and assignment operator SwLinguServiceEventListener(const SwLinguServiceEventListener &); SwLinguServiceEventListener & operator = (const SwLinguServiceEventListener &); public: SwLinguServiceEventListener(); virtual ~SwLinguServiceEventListener(); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& rEventObj ) throw(::com::sun::star::uno::RuntimeException); // XDictionaryListEventListener virtual void SAL_CALL processDictionaryListEvent( const ::com::sun::star::linguistic2::DictionaryListEvent& rDicListEvent) throw( ::com::sun::star::uno::RuntimeException ); // XLinguServiceEventListener virtual void SAL_CALL processLinguServiceEvent( const ::com::sun::star::linguistic2::LinguServiceEvent& rLngSvcEvent ) throw(::com::sun::star::uno::RuntimeException); // XTerminateListener virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& rEventObj ) throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& rEventObj ) throw(::com::sun::star::uno::RuntimeException); }; #endif <|endoftext|>
<commit_before><commit_msg>提高兼容性<commit_after><|endoftext|>
<commit_before><commit_msg>Minor update.<commit_after><|endoftext|>
<commit_before>// -*- c++ -*- /*! * * Copyright (C) 2012 Jolla Ltd. * * Contact: Mohammed Hassan <mohammed.hassan@jollamobile.com> * Author: Andres Gomez <agomez@igalia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "simple-model.h" #include <GriloRegistry> #include <GriloBrowse> #include <GriloMedia> #include <QVariant> SimpleModel::SimpleModel(QObject *parent) : GriloModel(parent), m_grlRegistry(0), m_grlBrowse(0) { m_grlRegistry = new GriloRegistry(); // Not nice that we have to call this ... m_grlRegistry->componentComplete(); m_grlRegistry->loadPluginById("grl-filesystem"); m_grlBrowse = new GriloBrowse(); m_grlBrowse->setSource("grl-filesystem"); m_grlBrowse->setRegistry(m_grlRegistry); QVariantList metaDataKeys; metaDataKeys.append(QVariant(GriloDataSource::Title)); QVariantList typeFilter; typeFilter.append(QVariant(GriloDataSource::Audio)); m_grlBrowse->setMetadataKeys(metaDataKeys); m_grlBrowse->setTypeFilter(typeFilter); QObject::connect(m_grlBrowse, SIGNAL(baseMediaChanged()), m_grlBrowse, SLOT(refresh())); setSource(m_grlBrowse); } SimpleModel::~SimpleModel() { if (m_grlBrowse) { delete m_grlBrowse; } if (m_grlRegistry) { delete m_grlRegistry; } } QVariant SimpleModel::data(const QModelIndex& index, int role) const { if (index.row() < 0 || index.row() >= rowCount()) { return QVariant(); } switch (role) { case GriloModel::MediaRole: return QVariant::fromValue(get(index.row())); case Qt::DisplayRole: return qobject_cast<GriloMedia*>(get(index.row()))->title(); } return QVariant(); } void SimpleModel::onItemClicked(const QModelIndex& index) { QVariant mediaVariant = data(index, GriloModel::MediaRole); GriloMedia *media = mediaVariant.value<GriloMedia*>(); if (!media) { return; } if (media->isContainer()) { m_grlBrowse->setBaseMedia(media->serialize()); qWarning() << media->serialize(); } } <commit_msg>[example] Removed left qWarning<commit_after>// -*- c++ -*- /*! * * Copyright (C) 2012 Jolla Ltd. * * Contact: Mohammed Hassan <mohammed.hassan@jollamobile.com> * Author: Andres Gomez <agomez@igalia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "simple-model.h" #include <GriloRegistry> #include <GriloBrowse> #include <GriloMedia> #include <QVariant> SimpleModel::SimpleModel(QObject *parent) : GriloModel(parent), m_grlRegistry(0), m_grlBrowse(0) { m_grlRegistry = new GriloRegistry(); // Not nice that we have to call this ... m_grlRegistry->componentComplete(); m_grlRegistry->loadPluginById("grl-filesystem"); m_grlBrowse = new GriloBrowse(); m_grlBrowse->setSource("grl-filesystem"); m_grlBrowse->setRegistry(m_grlRegistry); QVariantList metaDataKeys; metaDataKeys.append(QVariant(GriloDataSource::Title)); QVariantList typeFilter; typeFilter.append(QVariant(GriloDataSource::Audio)); m_grlBrowse->setMetadataKeys(metaDataKeys); m_grlBrowse->setTypeFilter(typeFilter); QObject::connect(m_grlBrowse, SIGNAL(baseMediaChanged()), m_grlBrowse, SLOT(refresh())); setSource(m_grlBrowse); } SimpleModel::~SimpleModel() { if (m_grlBrowse) { delete m_grlBrowse; } if (m_grlRegistry) { delete m_grlRegistry; } } QVariant SimpleModel::data(const QModelIndex& index, int role) const { if (index.row() < 0 || index.row() >= rowCount()) { return QVariant(); } switch (role) { case GriloModel::MediaRole: return QVariant::fromValue(get(index.row())); case Qt::DisplayRole: return qobject_cast<GriloMedia*>(get(index.row()))->title(); } return QVariant(); } void SimpleModel::onItemClicked(const QModelIndex& index) { QVariant mediaVariant = data(index, GriloModel::MediaRole); GriloMedia *media = mediaVariant.value<GriloMedia*>(); if (!media) { return; } if (media->isContainer()) { m_grlBrowse->setBaseMedia(media->serialize()); } } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2015 LXQt team * Authors: * Dmitriy Zhukov <zjesclean@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <QDebug> #include <QProcess> #include "kbdstateconfig.h" #include "ui_kbdstateconfig.h" #include "settings.h" KbdStateConfig::KbdStateConfig(QWidget *parent) : QDialog(parent), m_ui(new Ui::KbdStateConfig) { setAttribute(Qt::WA_DeleteOnClose); m_ui->setupUi(this); connect(m_ui->showCaps, &QCheckBox::clicked, this, &KbdStateConfig::save); connect(m_ui->showNum, &QCheckBox::clicked, this, &KbdStateConfig::save); connect(m_ui->showScroll, &QCheckBox::clicked, this, &KbdStateConfig::save); connect(m_ui->showLayout, &QGroupBox::clicked, this, &KbdStateConfig::save); connect(m_ui->modes, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked), [this](int){ KbdStateConfig::save(); } ); connect(m_ui->btns, &QDialogButtonBox::clicked, [this](QAbstractButton *btn){ if (m_ui->btns->buttonRole(btn) == QDialogButtonBox::ResetRole){ Settings::instance().restore(); load(); } }); connect(m_ui->configureLayouts, &QPushButton::clicked, this, &KbdStateConfig::configureLayouts); load(); } KbdStateConfig::~KbdStateConfig() { delete m_ui; } void KbdStateConfig::load() { Settings & sets = Settings::instance(); m_ui->showCaps->setChecked(sets.showCapLock()); m_ui->showNum->setChecked(sets.showNumLock()); m_ui->showScroll->setChecked(sets.showScrollLock()); m_ui->showLayout->setChecked(sets.showLayout()); switch(sets.keeperType()){ case KeeperType::Global: m_ui->switchGlobal->setChecked(true); break; case KeeperType::Window: m_ui->switchWindow->setChecked(true); break; case KeeperType::Application: m_ui->switchApplication->setChecked(true); break; } } void KbdStateConfig::save() { Settings & sets = Settings::instance(); sets.setShowCapLock(m_ui->showCaps->isChecked()); sets.setShowNumLock(m_ui->showNum->isChecked()); sets.setShowScrollLock(m_ui->showScroll->isChecked()); sets.setShowLayout(m_ui->showLayout->isChecked()); if (m_ui->switchGlobal->isChecked()) sets.setKeeperType(KeeperType::Global); if (m_ui->switchWindow->isChecked()) sets.setKeeperType(KeeperType::Window); if (m_ui->switchApplication->isChecked()) sets.setKeeperType(KeeperType::Application); } void KbdStateConfig::configureLayouts() { QProcess::startDetached(QLatin1String("lxqt-config-input")); } <commit_msg>plugin-kbindicator: Go directly to the Keyboard Layout config page<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2015 LXQt team * Authors: * Dmitriy Zhukov <zjesclean@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <LXQt/Globals> #include <QDebug> #include <QProcess> #include "kbdstateconfig.h" #include "ui_kbdstateconfig.h" #include "settings.h" KbdStateConfig::KbdStateConfig(QWidget *parent) : QDialog(parent), m_ui(new Ui::KbdStateConfig) { setAttribute(Qt::WA_DeleteOnClose); m_ui->setupUi(this); connect(m_ui->showCaps, &QCheckBox::clicked, this, &KbdStateConfig::save); connect(m_ui->showNum, &QCheckBox::clicked, this, &KbdStateConfig::save); connect(m_ui->showScroll, &QCheckBox::clicked, this, &KbdStateConfig::save); connect(m_ui->showLayout, &QGroupBox::clicked, this, &KbdStateConfig::save); connect(m_ui->modes, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked), [this](int){ KbdStateConfig::save(); } ); connect(m_ui->btns, &QDialogButtonBox::clicked, [this](QAbstractButton *btn){ if (m_ui->btns->buttonRole(btn) == QDialogButtonBox::ResetRole){ Settings::instance().restore(); load(); } }); connect(m_ui->configureLayouts, &QPushButton::clicked, this, &KbdStateConfig::configureLayouts); load(); } KbdStateConfig::~KbdStateConfig() { delete m_ui; } void KbdStateConfig::load() { Settings & sets = Settings::instance(); m_ui->showCaps->setChecked(sets.showCapLock()); m_ui->showNum->setChecked(sets.showNumLock()); m_ui->showScroll->setChecked(sets.showScrollLock()); m_ui->showLayout->setChecked(sets.showLayout()); switch(sets.keeperType()){ case KeeperType::Global: m_ui->switchGlobal->setChecked(true); break; case KeeperType::Window: m_ui->switchWindow->setChecked(true); break; case KeeperType::Application: m_ui->switchApplication->setChecked(true); break; } } void KbdStateConfig::save() { Settings & sets = Settings::instance(); sets.setShowCapLock(m_ui->showCaps->isChecked()); sets.setShowNumLock(m_ui->showNum->isChecked()); sets.setShowScrollLock(m_ui->showScroll->isChecked()); sets.setShowLayout(m_ui->showLayout->isChecked()); if (m_ui->switchGlobal->isChecked()) sets.setKeeperType(KeeperType::Global); if (m_ui->switchWindow->isChecked()) sets.setKeeperType(KeeperType::Window); if (m_ui->switchApplication->isChecked()) sets.setKeeperType(KeeperType::Application); } void KbdStateConfig::configureLayouts() { QProcess::startDetached(QL1S("lxqt-config-input --show-page \"Keyboard Layout\"")); } <|endoftext|>
<commit_before>#include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> #include "game.h" #include "particlesystem.h" #include "util.h" #include <sstream> #include <fstream> using namespace std; const char* savefile = "save"; int loadHighscore() { int ret = 0; ifstream f(savefile); if (f.good()) { f >> ret; } f.close(); return ret; } void saveHighscore(int high) { ofstream f(savefile); f << high << endl; f.close(); } int main() { // Create the main window sf::RenderWindow window(sf::VideoMode(800, 600), "Icebearino"); Game game; game.init(&window); // Create a graphical text to display sf::Font font; if (!font.loadFromFile("res/fonts/Cinzel-Bold.ttf")) return EXIT_FAILURE; // Death sound sf::SoundBuffer deathSoundBuffer; loadSoundBuffer(deathSoundBuffer, "res/sound/death.ogg"); sf::Sound deathSound; deathSound.setBuffer(deathSoundBuffer); // Icebearino sound sf::SoundBuffer icebearinoBuffer; loadSoundBuffer(icebearinoBuffer, "res/sound/icebearino.ogg"); sf::Sound icebearinoSound; icebearinoSound.setBuffer(icebearinoBuffer); // Fact sounds sf::SoundBuffer factBuffers[6]; loadSoundBuffer(factBuffers[0], "res/sound/facts-01.ogg"); loadSoundBuffer(factBuffers[1], "res/sound/facts-02.ogg"); loadSoundBuffer(factBuffers[2], "res/sound/facts-03.ogg"); loadSoundBuffer(factBuffers[3], "res/sound/facts-04.ogg"); loadSoundBuffer(factBuffers[4], "res/sound/facts-05.ogg"); loadSoundBuffer(factBuffers[5], "res/sound/facts-06.ogg"); sf::Sound factSound; float elapsedTime = 0.0f; // Zimmer sound sf::SoundBuffer zimmerBuffer; loadSoundBuffer(zimmerBuffer, "res/sound/zimmer.ogg"); sf::Sound zimmerSound; zimmerSound.setBuffer(zimmerBuffer); // Snow effect ParticleSystem snow(1000, ParticleMode::Snow, "res/img/snowflake.png"); bool gamerunning = false; int highscore = loadHighscore(); sf::Clock gameTimer; sf::Text intro1("CLIMATE CHANGE IS REAL", font, 50.0f); sf::Text intro2a("THE ARCTIC WORLD", font, 50.0f); sf::Text intro2b("IS SHRINKING", font, 50.0f); sf::Text intro3a("YOU ARE THE LAST", font, 50.0f); sf::Text intro3b("OF YOUR KIND", font, 50.0f); sf::Text intro4("WILL YOU SURVIVE?", font, 50.0f); centerText(intro1); centerText(intro2a); centerText(intro2b); centerText(intro3a); centerText(intro3b); centerText(intro4); intro1.setPosition(400, 200); intro2a.setPosition(400, 200); intro2b.setPosition(400, 250); intro3a.setPosition(400, 200); intro3b.setPosition(400, 250); intro4.setPosition(400, 200); const float perText = 4.0f; const int numTexts = 4; sf::Music music; music.openFromFile("res/sound/music.ogg"); music.setLoop(true); music.setVolume(50); bool musicPlaying = false; bool gameStarted = false; // Start the game loop sf::Clock deltaClock; float dt = 0.0f; while (window.isOpen()) { // Process events sf::Event event; while (window.pollEvent(event)) { // Close window: exit if (event.type == sf::Event::Closed) window.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape)) window.close(); // Update game if (gamerunning) { game.update(dt); if (game.over) { highscore = max(game.score, highscore); saveHighscore(highscore); gamerunning = false; deathSound.play(); game.cleanup(); } } else { snow.update(dt); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Return)) { gameStarted = true; game.init(&window); gamerunning = true; deathSound.stop(); zimmerSound.stop(); icebearinoSound.stop(); } } float fade = 0.0f; // Clear screen window.clear(); // Render game if (gamerunning) { if (!musicPlaying){ musicPlaying = true; music.play(); } game.render(); } else if (!gamerunning) { if (musicPlaying) music.stop(), musicPlaying = false; sf::Text title("ICEBEARINO", font, 100.0f); sf::Text pressEnter("Press enter to start the game", font, 20.0f); sf::Text credits("Made by Karl Lundstig and Fredrik Hernqvist for Ludum Dare 38", font, 16.0f); stringstream ss; ss << "Highscore: " << highscore; sf::Text hs(ss.str(), font, 20.0f); centerText(title); title.setPosition(sf::Vector2f(400, 250)); centerText(pressEnter); pressEnter.setPosition(sf::Vector2f(400, 320)); centerText(hs); hs.setPosition(sf::Vector2f(400, 400)); centerText(credits); credits.setPosition(sf::Vector2f(400, 580)); auto curTime = gameTimer.getElapsedTime(); if (gameStarted || curTime > sf::seconds(numTexts * perText)) { float t = (curTime - sf::seconds(perText * numTexts)).asSeconds(); fade = gameStarted ? 1.0f : 1.0f - max(0.0f, min(1.0f, 2.0f - t)); if (t > 1.0f && t < 2.0f && icebearinoSound.getStatus() != sf::SoundSource::Status::Playing) icebearinoSound.play(); window.draw(title); window.draw(pressEnter); window.draw(hs); window.draw(credits); } if (!gameStarted) { if (curTime > sf::seconds(0.0f * perText) && curTime < sf::seconds(1.0f * perText)) { float t = (curTime - sf::seconds(perText * 0.0f)).asSeconds(); fade = 1.0f - max(0.0f, min(1.0f, abs(2.0f - t))); window.draw(intro1); if (t > 1.0f && t < 2.0f && zimmerSound.getStatus() != sf::SoundSource::Status::Playing) zimmerSound.play(); } if (curTime > sf::seconds(1.0f * perText) && curTime < sf::seconds(2.0f * perText)) { float t = (curTime - sf::seconds(perText * 1.0f)).asSeconds(); fade = 1.0f - max(0.0f, min(1.0f, abs(2.0f - t))); window.draw(intro2a); window.draw(intro2b); if (t > 1.0f && t < 2.0f && zimmerSound.getStatus() != sf::SoundSource::Status::Playing) zimmerSound.play(); } if (curTime > sf::seconds(2.0f * perText) && curTime < sf::seconds(3.0f * perText)) { float t = (curTime - sf::seconds(perText * 2.0f)).asSeconds(); fade = 1.0f - max(0.0f, min(1.0f, abs(2.0f - t))); window.draw(intro3a); window.draw(intro3b); if (t > 1.0f && t < 2.0f && zimmerSound.getStatus() != sf::SoundSource::Status::Playing) zimmerSound.play(); } if (curTime > sf::seconds(3.0f * perText) && curTime < sf::seconds(4.0f * perText)) { float t = (curTime - sf::seconds(perText * 3.0f)).asSeconds(); fade = 1.0f - max(0.0f, min(1.0f, abs(2.0f - t))); window.draw(intro4); if (t > 1.0f && t < 2.0f && zimmerSound.getStatus() != sf::SoundSource::Status::Playing) zimmerSound.play(); } } sf::RectangleShape fadeRect(sf::Vector2f(800.0f, 600.0f)); fadeRect.setPosition(0.0f, 0.0f); fadeRect.setFillColor(sf::Color(0, 0, 0, 255*(1.0f-fade))); window.draw(fadeRect); window.draw(snow); } elapsedTime += dt; if (elapsedTime > 15.0f && gameStarted) { elapsedTime = 0.0f; if (rnd() < 0.1f) { factSound.setBuffer(factBuffers[rand() % 6]); factSound.play(); } } // Update the window window.display(); dt = deltaClock.restart().asSeconds(); } return EXIT_SUCCESS; } <commit_msg>Center intro text<commit_after>#include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> #include "game.h" #include "particlesystem.h" #include "util.h" #include <sstream> #include <fstream> using namespace std; const char* savefile = "save"; int loadHighscore() { int ret = 0; ifstream f(savefile); if (f.good()) { f >> ret; } f.close(); return ret; } void saveHighscore(int high) { ofstream f(savefile); f << high << endl; f.close(); } int main() { // Create the main window sf::RenderWindow window(sf::VideoMode(800, 600), "Icebearino"); Game game; game.init(&window); // Create a graphical text to display sf::Font font; if (!font.loadFromFile("res/fonts/Cinzel-Bold.ttf")) return EXIT_FAILURE; // Death sound sf::SoundBuffer deathSoundBuffer; loadSoundBuffer(deathSoundBuffer, "res/sound/death.ogg"); sf::Sound deathSound; deathSound.setBuffer(deathSoundBuffer); // Icebearino sound sf::SoundBuffer icebearinoBuffer; loadSoundBuffer(icebearinoBuffer, "res/sound/icebearino.ogg"); sf::Sound icebearinoSound; icebearinoSound.setBuffer(icebearinoBuffer); // Fact sounds sf::SoundBuffer factBuffers[6]; loadSoundBuffer(factBuffers[0], "res/sound/facts-01.ogg"); loadSoundBuffer(factBuffers[1], "res/sound/facts-02.ogg"); loadSoundBuffer(factBuffers[2], "res/sound/facts-03.ogg"); loadSoundBuffer(factBuffers[3], "res/sound/facts-04.ogg"); loadSoundBuffer(factBuffers[4], "res/sound/facts-05.ogg"); loadSoundBuffer(factBuffers[5], "res/sound/facts-06.ogg"); sf::Sound factSound; float elapsedTime = 0.0f; // Zimmer sound sf::SoundBuffer zimmerBuffer; loadSoundBuffer(zimmerBuffer, "res/sound/zimmer.ogg"); sf::Sound zimmerSound; zimmerSound.setBuffer(zimmerBuffer); // Snow effect ParticleSystem snow(1000, ParticleMode::Snow, "res/img/snowflake.png"); bool gamerunning = false; int highscore = loadHighscore(); sf::Clock gameTimer; sf::Text intro1("CLIMATE CHANGE IS REAL", font, 50.0f); sf::Text intro2a("THE ARCTIC WORLD", font, 50.0f); sf::Text intro2b("IS SHRINKING", font, 50.0f); sf::Text intro3a("YOU ARE THE LAST", font, 50.0f); sf::Text intro3b("OF YOUR KIND", font, 50.0f); sf::Text intro4("WILL YOU SURVIVE?", font, 50.0f); centerText(intro1); centerText(intro2a); centerText(intro2b); centerText(intro3a); centerText(intro3b); centerText(intro4); intro1.setPosition(400, 300); intro2a.setPosition(400, 250); intro2b.setPosition(400, 300); intro3a.setPosition(400, 250); intro3b.setPosition(400, 300); intro4.setPosition(400, 300); const float perText = 4.0f; const int numTexts = 4; sf::Music music; music.openFromFile("res/sound/music.ogg"); music.setLoop(true); music.setVolume(50); bool musicPlaying = false; bool gameStarted = false; // Start the game loop sf::Clock deltaClock; float dt = 0.0f; while (window.isOpen()) { // Process events sf::Event event; while (window.pollEvent(event)) { // Close window: exit if (event.type == sf::Event::Closed) window.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape)) window.close(); // Update game if (gamerunning) { game.update(dt); if (game.over) { highscore = max(game.score, highscore); saveHighscore(highscore); gamerunning = false; deathSound.play(); game.cleanup(); } } else { snow.update(dt); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Return)) { gameStarted = true; game.init(&window); gamerunning = true; deathSound.stop(); zimmerSound.stop(); icebearinoSound.stop(); } } float fade = 0.0f; // Clear screen window.clear(); // Render game if (gamerunning) { if (!musicPlaying){ musicPlaying = true; music.play(); } game.render(); } else if (!gamerunning) { if (musicPlaying) music.stop(), musicPlaying = false; sf::Text title("ICEBEARINO", font, 100.0f); sf::Text pressEnter("Press enter to start the game", font, 20.0f); sf::Text credits("Made by Karl Lundstig and Fredrik Hernqvist for Ludum Dare 38", font, 16.0f); stringstream ss; ss << "Highscore: " << highscore; sf::Text hs(ss.str(), font, 20.0f); centerText(title); title.setPosition(sf::Vector2f(400, 250)); centerText(pressEnter); pressEnter.setPosition(sf::Vector2f(400, 320)); centerText(hs); hs.setPosition(sf::Vector2f(400, 400)); centerText(credits); credits.setPosition(sf::Vector2f(400, 580)); auto curTime = gameTimer.getElapsedTime(); if (gameStarted || curTime > sf::seconds(numTexts * perText)) { float t = (curTime - sf::seconds(perText * numTexts)).asSeconds(); fade = gameStarted ? 1.0f : 1.0f - max(0.0f, min(1.0f, 2.0f - t)); if (t > 1.0f && t < 2.0f && icebearinoSound.getStatus() != sf::SoundSource::Status::Playing) icebearinoSound.play(); window.draw(title); window.draw(pressEnter); window.draw(hs); window.draw(credits); } if (!gameStarted) { if (curTime > sf::seconds(0.0f * perText) && curTime < sf::seconds(1.0f * perText)) { float t = (curTime - sf::seconds(perText * 0.0f)).asSeconds(); fade = 1.0f - max(0.0f, min(1.0f, abs(2.0f - t))); window.draw(intro1); if (t > 1.0f && t < 2.0f && zimmerSound.getStatus() != sf::SoundSource::Status::Playing) zimmerSound.play(); } if (curTime > sf::seconds(1.0f * perText) && curTime < sf::seconds(2.0f * perText)) { float t = (curTime - sf::seconds(perText * 1.0f)).asSeconds(); fade = 1.0f - max(0.0f, min(1.0f, abs(2.0f - t))); window.draw(intro2a); window.draw(intro2b); if (t > 1.0f && t < 2.0f && zimmerSound.getStatus() != sf::SoundSource::Status::Playing) zimmerSound.play(); } if (curTime > sf::seconds(2.0f * perText) && curTime < sf::seconds(3.0f * perText)) { float t = (curTime - sf::seconds(perText * 2.0f)).asSeconds(); fade = 1.0f - max(0.0f, min(1.0f, abs(2.0f - t))); window.draw(intro3a); window.draw(intro3b); if (t > 1.0f && t < 2.0f && zimmerSound.getStatus() != sf::SoundSource::Status::Playing) zimmerSound.play(); } if (curTime > sf::seconds(3.0f * perText) && curTime < sf::seconds(4.0f * perText)) { float t = (curTime - sf::seconds(perText * 3.0f)).asSeconds(); fade = 1.0f - max(0.0f, min(1.0f, abs(2.0f - t))); window.draw(intro4); if (t > 1.0f && t < 2.0f && zimmerSound.getStatus() != sf::SoundSource::Status::Playing) zimmerSound.play(); } } sf::RectangleShape fadeRect(sf::Vector2f(800.0f, 600.0f)); fadeRect.setPosition(0.0f, 0.0f); fadeRect.setFillColor(sf::Color(0, 0, 0, 255*(1.0f-fade))); window.draw(fadeRect); window.draw(snow); } elapsedTime += dt; if (elapsedTime > 15.0f && gameStarted) { elapsedTime = 0.0f; if (rnd() < 0.1f) { factSound.setBuffer(factBuffers[rand() % 6]); factSound.play(); } } // Update the window window.display(); dt = deltaClock.restart().asSeconds(); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <cstring> using namespace std; #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <boost/tokenizer.hpp> #include "Base.h" #include "Cmd.h" #include "Or.h" #include "And.h" #include "Semi.h" using namespace std; using namespace boost; void Tokenize (const string& str, vector<string>& vec) { //splits string into tokens typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(";&|#()", ";&|#()", boost::keep_empty_tokens); tokenizer tok(str, sep); for(tokenizer::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) { vec.push_back(*tok_iter); if(*tok_iter == "&" || *tok_iter == "|") {tok_iter++; tok_iter++;} } for(unsigned int a = 0; a < vec.size(); ++a) { //check for a delete empty spaces if(vec.at(a) == " " || vec.at(a) == "") {vec.erase(vec.begin() + a);} } } void _Tokenize (const string& str, vector<string>& vec) { //splits string into tokens typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(" "); tokenizer tok(str, sep); for(tokenizer::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) { vec.push_back(*tok_iter); //if(*tok_iter == "&" || *tok_iter == "|") {tok_iter++;} } } void commentCheck(vector<string>& tok) { //if a # is detected, remove all following tokens if(tok.size() >= 2) { if (tok.at(1) == "#") {tok.clear();} } //else { for(unsigned int i = 0; i < tok.size(); ++i) { if(tok.at(i) == "#") { tok.erase(tok.begin() + i, tok.end()); } } //} } bool Execute(vector<string> input) { vector<string> arguments; string executable; Cmd* command; Connector* connect; bool done = false; bool skip = false; int i = 0; while(input.size() != 0) { if(input.size() == 1) { //base case: no connectors arguments.clear(); _Tokenize(input.at(i), arguments); //commentCheck(arguments); //if(arguments.size() == 0) {return true;} executable = arguments.front(); arguments.erase(arguments.begin()); //cout << executable << ", " << arguments.at(0) << endl; command = new Cmd(executable, arguments); return command->execute(done); } arguments.clear(); _Tokenize(input.at(i), arguments); executable = arguments.front(); arguments.erase(arguments.begin()); command = new Cmd(executable, arguments); input.erase(input.begin()); if(input.at(i) == ";") { connect = new Semi(command); } else if(input.at(i) == "&") { connect = new And(command); } else if(input.at(i) == "|") { connect = new Or(command); } input.erase(input.begin()); done = command->execute(done); skip = connect->execute(done); if(skip == true) { //check if the first OR condition executed input.erase(input.begin()); while(input.size() != 0) { if(input.at(0) == "|") { input.erase(input.begin()); input.erase(input.begin()); } if(input.size() == 0) {break;} if(input.at(0) == "&") { input.erase(input.begin()); break; } } } } return 0; } bool ParenthExecute(vector<string>& input, bool in) { vector<string> arguments; string executable; Cmd* command; Connector* connect; bool done = false; bool skip = false; bool recursion = false; bool rightClosed = false; int i = 0; while(input.size() != 0) { if(input.size() == 1) { //base case: no connectors arguments.clear(); _Tokenize(input.at(i), arguments); //commentCheck(arguments); //if(arguments.size() == 0) {return true;} executable = arguments.front(); arguments.erase(arguments.begin()); //cout << executable << ", " << arguments.at(0) << endl; command = new Cmd(executable, arguments); return command->execute(done); } // for(unsigned int a = 0; a < input.size(); ++a) {cout << input.at(a) << ", "; } cout << endl; if(input.at(i) == "(") { //check for beginning parentheses, if found ENTER RECURSION input.erase(input.begin()); recursion = ParenthExecute(input, recursion); rightClosed = true; //for(unsigned int a = 0; a < input.size(); ++a) {cout << input.at(a) << ", "; } cout << endl; if(input.size() == 0) {break;} } if(input.at(i) == ")") {/*return false;*/ return recursion;} if(input.at(i) != ";" && input.at(i) != "&" && input.at(i) != "|") { arguments.clear(); //parse first command _Tokenize(input.at(i), arguments); executable = arguments.front(); arguments.erase(arguments.begin()); command = new Cmd(executable, arguments); input.erase(input.begin()); } if(input.at(i) == ")") {return command->execute(done);} //check if there is a single command contained within parentheses if(input.at(i) == ";") { connect = new Semi(command); } else if(input.at(i) == "&") { connect = new And(command); } else if(input.at(i) == "|") { connect = new Or(command); } input.erase(input.begin()); if(rightClosed != true) {done = command->execute(done); rightClosed = false;} //execute command and return success skip = connect->execute(done); //execute connector to determine if rightCmd needs to be executed recursion = done; if(skip == true) { //verify that first OR condition succeeded input.erase(input.begin()); while(input.size() != 0) { if(input.at(0) == ")") {/*return done;*/ return recursion;} if(input.at(0) == "(") { input.erase(input.begin()); input.erase(input.begin()); } if(input.at(0) == "|") { input.erase(input.begin()); input.erase(input.begin()); } if(input.size() == 0) {break;} if(input.at(0) == "&") { input.erase(input.begin()); break; } } } } return 0; } void ParenthCheck(vector<string> input) { int leftParenth = 0; int rightParenth = 0; for(unsigned int i = 0; i < input.size(); ++i) { if(input.at(i) == "(") {leftParenth++;} if(input.at(i) == ")") {rightParenth++;} } if(leftParenth != rightParenth) { cout << "Error: Uneven number of parentheses." << endl; } if(leftParenth == rightParenth && leftParenth != 0 && rightParenth != 0) { ParenthExecute(input, 0); } if (leftParenth == 0 && rightParenth == 0) { Execute(input); } } int main() { string executable = ""; vector<string> tok; while(1) { tok.clear(); cout << "$ "; getline(cin, executable); Tokenize(executable, tok); commentCheck(tok); ParenthCheck(tok); //Execute(tok); } } <commit_msg>Precedence operators full functional<commit_after>#include <iostream> #include <vector> #include <cstring> using namespace std; #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <boost/tokenizer.hpp> #include "Base.h" #include "Cmd.h" #include "Or.h" #include "And.h" #include "Semi.h" using namespace std; using namespace boost; void Tokenize (const string& str, vector<string>& vec) { //splits string into tokens typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(";&|#()", ";&|#()", boost::keep_empty_tokens); tokenizer tok(str, sep); for(tokenizer::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) { vec.push_back(*tok_iter); if(*tok_iter == "&" || *tok_iter == "|") {tok_iter++; tok_iter++;} } for(unsigned int a = 0; a < vec.size(); ++a) { //check for a delete empty spaces if(vec.at(a) == " " || vec.at(a) == "") {vec.erase(vec.begin() + a);} } } void _Tokenize (const string& str, vector<string>& vec) { //splits string into tokens typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(" "); tokenizer tok(str, sep); for(tokenizer::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) { vec.push_back(*tok_iter); //if(*tok_iter == "&" || *tok_iter == "|") {tok_iter++;} } } void commentCheck(vector<string>& tok) { //if a # is detected, remove all following tokens if(tok.size() >= 2) { if (tok.at(1) == "#") {tok.clear();} } for(unsigned int i = 0; i < tok.size(); ++i) { if(tok.at(i) == "#") { tok.erase(tok.begin() + i, tok.end()); } } } bool Execute(vector<string> input) { vector<string> arguments; string executable; Cmd* command; Connector* connect; bool done = false; bool skip = false; int i = 0; while(input.size() != 0) { if(input.size() == 1) { //base case: no connectors arguments.clear(); _Tokenize(input.at(i), arguments); //commentCheck(arguments); //if(arguments.size() == 0) {return true;} executable = arguments.front(); arguments.erase(arguments.begin()); //cout << executable << ", " << arguments.at(0) << endl; command = new Cmd(executable, arguments); return command->execute(done); } arguments.clear(); _Tokenize(input.at(i), arguments); executable = arguments.front(); arguments.erase(arguments.begin()); command = new Cmd(executable, arguments); input.erase(input.begin()); if(input.at(i) == ";") { connect = new Semi(command); } else if(input.at(i) == "&") { connect = new And(command); } else if(input.at(i) == "|") { connect = new Or(command); } input.erase(input.begin()); done = command->execute(done); skip = connect->execute(done); if(skip == true) { //check if the first OR condition executed input.erase(input.begin()); while(input.size() != 0) { if(input.at(0) == "|") { input.erase(input.begin()); input.erase(input.begin()); } if(input.size() == 0) {break;} if(input.at(0) == "&") { input.erase(input.begin()); break; } } } } return 0; } bool ParenthExecute(vector<string>& input, bool in) { vector<string> arguments; string executable; Cmd* command; Connector* connect; bool done = false; bool skip = false; bool recursion = false; //used to track whether commands in parentheses succeeded bool rightClosed = false; //check if the parentheses have closed bool andVal = false; int i = 0; while(input.size() != 0) { //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; if(input.size() == 1) { //BASE CASE: no connectors left arguments.clear(); _Tokenize(input.at(i), arguments); executable = arguments.front(); arguments.erase(arguments.begin()); command = new Cmd(executable, arguments); return command->execute(done); } if(input.at(i) == "(") { //check for beginning parentheses, if found ENTER RECURSION input.erase(input.begin()); //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; recursion = ParenthExecute(input, recursion); rightClosed = true; if(input.size() == 0) {break;} } if(input.at(i) == ")") { //checks for empty parentheses input.erase(input.begin()); //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; return recursion; } if(input.at(i) != ";" && input.at(i) != "&" && input.at(i) != "|") { //check if a new command must be parsed arguments.clear(); //parse first command _Tokenize(input.at(i), arguments); executable = arguments.front(); arguments.erase(arguments.begin()); command = new Cmd(executable, arguments); input.erase(input.begin()); //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; } if(input.at(i) == ")") { //check if there is a single command left within parentheses input.erase(input.begin()); //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; return command->execute(done); } if(input.at(i) == ";") { //check for appropriate connector connect = new Semi(command); input.erase(input.begin()); andVal = true; } else if(input.at(i) == "&") { connect = new And(command); input.erase(input.begin()); andVal = true; } else if(input.at(i) == "|") { connect = new Or(command); input.erase(input.begin()); } //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; //if l-value is parentheses, set new command (r-value) if(rightClosed == true) { arguments.clear(); _Tokenize(input.at(i), arguments); executable = arguments.front(); arguments.erase(arguments.begin()); command = new Cmd(executable, arguments); input.erase(input.begin()); } if(recursion != true || andVal == true) { andVal = false; done = command->execute(done); //execute command and return success recursion = done; rightClosed = false; skip = connect->execute(done); } else { //if l-value succeeded, no need to re-execute command, simply figure out if skipping commands is necessary skip = connect->execute(recursion); } //execute connector to determine if rightCmd needs to be executed if(skip == true && input.size() >= 1) { //verify that first OR condition succeeded input.erase(input.begin()); while(input.size() != 0) { if(input.at(0) == ")") {input.erase(input.begin()); return recursion;} //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; return recursion;} if(input.at(0) == "(") { input.erase(input.begin()); input.erase(input.begin()); //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; } if(input.at(0) == "|") { input.erase(input.begin()); input.erase(input.begin()); //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; } if(input.size() == 0) {break;} if(input.at(0) == "&") { input.erase(input.begin()); //for(unsigned int j = 0; j < input.size(); ++j) {cout << input.at(j) << ", ";} cout << endl; break; } } } } return 0; } void ParenthCheck(vector<string> input) { int leftParenth = 0; int rightParenth = 0; for(unsigned int i = 0; i < input.size(); ++i) { if(input.at(i) == "(") {leftParenth++;} if(input.at(i) == ")") {rightParenth++;} } if(leftParenth != rightParenth) { cout << "Error: Uneven number of parentheses." << endl; } if(leftParenth == rightParenth && leftParenth != 0 && rightParenth != 0) { ParenthExecute(input, 0); } if (leftParenth == 0 && rightParenth == 0) { Execute(input); } } int main() { string executable = ""; vector<string> tok; while(1) { tok.clear(); cout << "$ "; getline(cin, executable); Tokenize(executable, tok); commentCheck(tok); ParenthCheck(tok); //Execute(tok); } } <|endoftext|>
<commit_before>#include "mraa.h" #include <chrono> #include <thread> #include <stdio.h> #include <string.h> #include <curl/curl.h> enum COMMAND { IDLE = 0, FORWARD = 1, REVERSE = 2, LEFT = 4, RIGHT = 8 }; const char* COMMAND_NAMES[] = {"IDLE","FORWARD","REVERSE","INVALID","LEFT","INVALID","INVALID","INVALID","RIGHT"}; int getCommand(); void loop(mraa_gpio_context gpio_context); int gMagnitude = 0; bool gReverseEnabled = false; const char* RC_ADDRESS = "http://192.168.1.243:8080/CommandServer/currentCommand"; #define DRIVE_MOTOR_GPIO 31 //GP44 #define REVERSE_ENGAGE_GPIO 32 //GP46 #define DEFAULT_WAIT_TIME_MS 300 int main(int argc, char** argv) { curl_global_init(CURL_GLOBAL_DEFAULT); mraa_init(); mraa_gpio_context drive_context = mraa_gpio_init(DRIVE_MOTOR_GPIO); if(drive_context == NULL || mraa_gpio_dir(drive_context, MRAA_GPIO_OUT) != MRAA_SUCCESS) exit(1); mraa_gpio_write(drive_context, false); mraa_gpio_context reverse_context = mraa_gpio_init(REVERSE_ENGAGE_GPIO); if(reverse_context == NULL || mraa_gpio_dir(reverse_context, MRAA_GPIO_OUT) != MRAA_SUCCESS) exit(1); mraa_gpio_write(reverse_context, false); printf("%s Wifi RC Interface\n", mraa_get_platform_name()); while(true) loop(drive_context); curl_global_cleanup(); mraa_deinit(); return 0; } size_t curl_write_function(void* buffer, size_t size, size_t nmemb, int* p) { static const char* NAME_STRING = "Name"; static const char* VALUE_STRING = "Value"; static const char* RESPONSE_STRING = "Response"; static const char* TERMINAL_STRING = "Terminal"; static const char* directionTerminal = "direction"; static const char* magnitudeTerminal = "magnitude"; char test[64]; char name[64]; char value[64]; char* parse = strstr((char*)buffer, RESPONSE_STRING)+strlen(RESPONSE_STRING)+1; memset(test, '\0', 64); memcpy(test, parse+3, strlen(RESPONSE_STRING)); while(strcmp(test, RESPONSE_STRING)) { parse = strstr(parse, TERMINAL_STRING)+strlen(TERMINAL_STRING)+1; parse = strstr(parse, NAME_STRING)+strlen(NAME_STRING)+1; int length = strchr(parse, '<')-parse; memset(name, '\0', 64); memcpy(name, parse, length); parse = strstr(parse, VALUE_STRING)+strlen(VALUE_STRING)+1; length = strchr(parse, '<')-parse; memset(value, '\0', 64); memcpy(value, parse, length); parse = strstr(parse, TERMINAL_STRING)+strlen(TERMINAL_STRING)+1; memset(test, '\0', 64); memcpy(test, parse+3, strlen(RESPONSE_STRING)); if(!strcmp(name, directionTerminal)) { *p = atoi(value); } if(!strcmp(name, magnitudeTerminal)) { gMagnitude = atoi(value); } } return size*nmemb; } int getCommand() { int command = IDLE; CURL* pCURL = curl_easy_init(); if(pCURL) { int temp; curl_easy_setopt(pCURL, CURLOPT_URL, RC_ADDRESS); curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, curl_write_function); curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, &temp); CURLcode result = curl_easy_perform(pCURL); if(result == CURLE_OK) { command = temp; } curl_easy_cleanup(pCURL); } return command; } void enableReverse(bool enabled, mraa_gpio_context gpio_context) { mraa_gpio_write(gpio_context, false); std::this_thread::sleep_for(std::chrono::milliseconds(DEFAULT_WAIT_TIME_MS)); //Shift into/out of reverse here gReverseEnabled = enabled; } void loop(mraa_gpio_context gpio_context) { int raw = getCommand(); int value = raw; if(value > 3) value &= 0xC; printf("%s\n", COMMAND_NAMES[value]); bool killReverse = true; bool shouldDrive = false; switch(raw &= 0x3) { case FORWARD: shouldDrive = true; break; case REVERSE: killReverse = false; if(!gReverseEnabled) enableReverse(true, gpio_context); shouldDrive = true; break; case IDLE: default: break; } if(gReverseEnabled && killReverse) enableReverse(false, gpio_context); mraa_gpio_write(gpio_context, shouldDrive); std::this_thread::sleep_for(std::chrono::milliseconds(gMagnitude > 0 ? gMagnitude: DEFAULT_WAIT_TIME_MS)); } <commit_msg>Enable reverse gear<commit_after>#include "mraa.h" #include <chrono> #include <thread> #include <stdio.h> #include <string.h> #include <curl/curl.h> enum COMMAND { IDLE = 0, FORWARD = 1, REVERSE = 2, LEFT = 4, RIGHT = 8 }; const char* COMMAND_NAMES[] = {"IDLE","FORWARD","REVERSE","INVALID","LEFT","INVALID","INVALID","INVALID","RIGHT"}; struct context { mraa_gpio_context drive_context; mraa_gpio_context reverse_context; }; int getCommand(); void loop(context& gpio_context); int gMagnitude = 0; bool gReverseEnabled = false; const char* RC_ADDRESS = "http://192.168.1.243:8080/CommandServer/currentCommand"; #define DRIVE_MOTOR_GPIO 31 //GP44 #define REVERSE_ENGAGE_GPIO 32 //GP46 #define DEFAULT_WAIT_TIME_MS 300 int main(int argc, char** argv) { curl_global_init(CURL_GLOBAL_DEFAULT); mraa_init(); mraa_gpio_context drive_context = mraa_gpio_init(DRIVE_MOTOR_GPIO); if(drive_context == NULL || mraa_gpio_dir(drive_context, MRAA_GPIO_OUT) != MRAA_SUCCESS) exit(1); mraa_gpio_write(drive_context, false); mraa_gpio_context reverse_context = mraa_gpio_init(REVERSE_ENGAGE_GPIO); if(reverse_context == NULL || mraa_gpio_dir(reverse_context, MRAA_GPIO_OUT) != MRAA_SUCCESS) exit(1); mraa_gpio_write(reverse_context, false); printf("%s Wifi RC Interface\n", mraa_get_platform_name()); context session; session.drive_context = drive_context; session.reverse_context = reverse_context; while(true) loop(session); curl_global_cleanup(); mraa_deinit(); return 0; } size_t curl_write_function(void* buffer, size_t size, size_t nmemb, int* p) { static const char* NAME_STRING = "Name"; static const char* VALUE_STRING = "Value"; static const char* RESPONSE_STRING = "Response"; static const char* TERMINAL_STRING = "Terminal"; static const char* directionTerminal = "direction"; static const char* magnitudeTerminal = "magnitude"; char test[64]; char name[64]; char value[64]; char* parse = strstr((char*)buffer, RESPONSE_STRING)+strlen(RESPONSE_STRING)+1; memset(test, '\0', 64); memcpy(test, parse+3, strlen(RESPONSE_STRING)); while(strcmp(test, RESPONSE_STRING)) { parse = strstr(parse, TERMINAL_STRING)+strlen(TERMINAL_STRING)+1; parse = strstr(parse, NAME_STRING)+strlen(NAME_STRING)+1; int length = strchr(parse, '<')-parse; memset(name, '\0', 64); memcpy(name, parse, length); parse = strstr(parse, VALUE_STRING)+strlen(VALUE_STRING)+1; length = strchr(parse, '<')-parse; memset(value, '\0', 64); memcpy(value, parse, length); parse = strstr(parse, TERMINAL_STRING)+strlen(TERMINAL_STRING)+1; memset(test, '\0', 64); memcpy(test, parse+3, strlen(RESPONSE_STRING)); if(!strcmp(name, directionTerminal)) { *p = atoi(value); } if(!strcmp(name, magnitudeTerminal)) { gMagnitude = atoi(value); } } return size*nmemb; } int getCommand() { int command = IDLE; CURL* pCURL = curl_easy_init(); if(pCURL) { int temp; curl_easy_setopt(pCURL, CURLOPT_URL, RC_ADDRESS); curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, curl_write_function); curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, &temp); CURLcode result = curl_easy_perform(pCURL); if(result == CURLE_OK) { command = temp; } curl_easy_cleanup(pCURL); } return command; } void enableReverse(bool enabled, context& gpio_context) { mraa_gpio_write(gpio_context.drive_context, false); std::this_thread::sleep_for(std::chrono::milliseconds(DEFAULT_WAIT_TIME_MS)); mraa_gpio_write(gpio_context.reverse_context, enabled); gReverseEnabled = enabled; } void loop(context& gpio_context) { int raw = getCommand(); int value = raw; if(value > 3) value &= 0xC; printf("%s\n", COMMAND_NAMES[value]); bool killReverse = true; bool shouldDrive = false; switch(raw &= 0x3) { case FORWARD: shouldDrive = true; break; case REVERSE: killReverse = false; if(!gReverseEnabled) enableReverse(true, gpio_context); shouldDrive = true; break; case IDLE: default: break; } if(gReverseEnabled && killReverse) enableReverse(false, gpio_context); mraa_gpio_write(gpio_context.drive_context, shouldDrive); std::this_thread::sleep_for(std::chrono::milliseconds(gMagnitude > 0 ? gMagnitude: DEFAULT_WAIT_TIME_MS)); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <cstdint> #include <algorithm> #include <memory> #include <chrono> #include <boost/thread.hpp> //#include <SFML/System.hpp> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML/Graphics/Texture.hpp> #include "dcpu.hpp" #include "disassembler.hpp" #include "gclock.hpp" //#include "fake_lem1802.hpp" #include "lem1802.hpp" #include "lem1803.hpp" #include "cgm.hpp" using namespace cpu; /* const long TOTALCPUS = 215*16; const long PERTHREAD = 16; // At 16 looks that is the ideal for the FX-4100 #define THREADS (TOTALCPUS/PERTHREAD) const long CYCLES = 1000*1000; const int BATCH = 10; */ //std::vector<std::vector<std::shared_ptr<DCPU>>> threads; uint16_t* data; size_t size = 0; //void benchmark(); void step(); void run(); void renderGuy(sf::RenderWindow* win, std::shared_ptr<cpu::AbstractMonitor> mon); //void cpu_in_thread(int n); int main (int argc, char **argv) { char* filename; std::ifstream binfile; if (argc <= 1) { std::cerr << "Missing input file\n"; return 0; } filename = argv[1]; std::cout << "Input BIN File : " << filename << "\n"; binfile.open (filename, std::ios::in | std::ios::binary ); if (!binfile) { std::cerr << "ERROR: I can open file\n"; exit (1); } // get length of file: binfile.seekg (0, binfile.end); size = binfile.tellg(); binfile.seekg (0, binfile.beg); data = new uint16_t[size / 2 + 1](); std::fill_n (data, size / 2, 0); // Clean it int i = 0; while (! binfile.eof() ) { uint16_t word = 0; binfile.read ( (char*) &word, 2); unsigned char tmp = ( (word & 0xFF00) >> 8) & 0x00FF; word = ( (word & 0x00FF) << 8) | tmp; data[i] = word; i++; } binfile.close(); std::cout << "Readed " << size << " bytes - " << size / 2 << " words\n"; size /= 2; badchar: std::cout << "Select what to do :" << std::endl; std::cout << "\ts -> step execution\n\tr-> run"; std::cout << std::endl << std::endl; char choose; std::cin >> choose; /* if (choose == 'b' || choose == 'B') { benchmark(); } else*/ if ( choose == 's' || choose == 'S') { step(); } else if ( choose == 'r' || choose == 'R') { run(); } else { goto badchar; /// HATE ME!!!! } delete[] data; return 0; } /* void benchmark() { // Load program to all CPUs for (int u=0; u< THREADS; u++) { std::vector<std::shared_ptr<DCPU>> cpus; cpus.reserve (PERTHREAD); for (int i = 0; i< PERTHREAD; i++) { auto cpu = std::make_shared<DCPU>(); //auto screen = std::make_shared<Fake_Lem1802>(); //screen->setEnable(false); // We not desire to write to stdout //cpu->attachHardware (screen); cpu->reset(); cpu->loadProgram (data, size); cpus.push_back(cpu); } threads.push_back(cpus); } sf::Thread* tds[THREADS]; std::cout << "Threads " << THREADS << "\t CPU PerThread " << PERTHREAD; std::cout << "\t N cpus " << PERTHREAD * THREADS << std::endl; std::cout << "Cycles " << CYCLES << std::endl; auto start = std::chrono::high_resolution_clock::now(); for (int i=0; i< THREADS; i++) { tds[i] = new sf::Thread(cpu_in_thread, i); tds[i]->launch(); } for (int i=0; i< THREADS; i++) { delete tds[i]; //wait() is automatically called } auto end = std::chrono::high_resolution_clock::now(); auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); std::cout << "Measured time: " << dur.count() << "ms" << std::endl; } */ void step() { using namespace std; auto cpu = make_shared<DCPU>(); auto screen = make_shared<lem::Lem1802>(); cpu->attachHardware (screen); sf::RenderWindow win(sf::VideoMode( screen->phyWidth() + screen->borderSize()*2, screen->phyHeight() + screen->borderSize()*2), "DCPU-16"); auto clock = make_shared<Generic_Clock>(); cpu->attachHardware (clock); cpu->reset(); cpu->loadProgram (data, size); char c = getchar(); while (1) { c = getchar(); if (c == 'f' || c == 'q' || c == '\n' ) break; } win.setActive(false); boost::thread thr_render (renderGuy, &win, std::static_pointer_cast<cpu::AbstractMonitor>(screen)); while (c != 'q' && win.isOpen()) { cout << cpu->dumpRegisters() << endl; cout << "T cycles " << dec << cpu->getTotCycles() << endl; cout << "> " << cpu->dumpRam() << " - "; string s = disassembly(cpu->getMem() + cpu->GetPC(), 3); cout << s << endl; if (cpu->GetSP() != 0x0000) cout << "STACK : "<< cpu->dumpRam(cpu->GetSP(), 0xFFFF) << endl; if (c == 'f') { for (int i = 0; i < 100; i++) cpu->step(); //cpu->tick(); } else { cpu->step(); /*if (cpu->tick()) cout << "Execute! ";*/ } cout << endl; while (1) { c = getchar(); if (c == 'f' || c == 'q' || c == '\n' ) break; } } if (win.isOpen()) win.close(); if (thr_render.joinable()) thr_render.join(); } void run() { using namespace std; using namespace std::chrono; auto cpu = make_shared<DCPU>(); auto screen = make_shared<cgm::CGM>(); cpu->attachHardware (screen); sf::RenderWindow win(sf::VideoMode( screen->phyWidth() + screen->borderSize()*2, screen->phyHeight() + screen->borderSize()*2), "DCPU-16"); auto clock = make_shared<Generic_Clock>(); cpu->attachHardware (clock); cpu->reset(); cpu->loadProgram (data, size); high_resolution_clock::time_point t = high_resolution_clock::now(); high_resolution_clock::time_point t2; win.setActive(false); boost::thread thr_render (renderGuy, &win, std::static_pointer_cast<cpu::AbstractMonitor>(screen)); while (win.isOpen() ) { //&& wincgm.isOpen()) { t2 = high_resolution_clock::now(); cpu->tick(); //auto rest = nanoseconds(1000000000/cpu->cpu_clock)-delta; if ((cpu->getTotCycles() % 50000) == 0) { // Not show running speed every clock tick auto delta = duration_cast<chrono::nanoseconds>(t2 - t); //double p = nanoseconds(1000000000/cpu->cpu_clock).count() / // (double)(delta.count() + rest.count()); cerr << "Delta :" << delta.count() << " ns " << endl; //cerr << "Rest :" << rest.count() << " ns "; //cerr << " Running at "<< p*100.0 << " % speed." << endl; } t = t2; } if (thr_render.joinable()) thr_render.join(); cout << "Finish" << endl; } /* // Runs PERTHREAD cpus, doing CYCLES cycles void cpu_in_thread(int n) { auto cpus = threads[n]; for (long i=0; i < CYCLES; i+= BATCH) { for (auto c = cpus.begin(); c != cpus.end(); c++) { for ( int j=0; j < BATCH; j++) (*c)->tick(); } } } */ void renderGuy(sf::RenderWindow* win, std::shared_ptr<cpu::AbstractMonitor> mon) { sf::Texture texture_lem; while (win->isOpen()) { sf::Event event; while (win->pollEvent(event)) { if (event.type == sf::Event::Closed) { win->close(); continue; } } win->clear(mon->getBorder()); sf::Image* scr = mon->updateScreen(); texture_lem.create(mon->width(), mon->height()); texture_lem.loadFromImage(*scr); sf::Sprite sprite_lem(texture_lem); sprite_lem.scale( mon->phyWidth() / (float)(mon->width() ) , mon->phyHeight() / (float)(mon->height()) ); sprite_lem.setPosition(mon->borderSize(), mon->borderSize()); win->draw(sprite_lem); win->display(); delete scr; } } <commit_msg>CGM and LEM1803 at sametime in run mode: TOFIX: error when finish execution and bad texture size<commit_after>#include <iostream> #include <fstream> #include <cstdint> #include <algorithm> #include <memory> #include <chrono> #include <boost/thread.hpp> //#include <SFML/System.hpp> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML/Graphics/Texture.hpp> #include "dcpu.hpp" #include "disassembler.hpp" #include "gclock.hpp" //#include "fake_lem1802.hpp" #include "lem1802.hpp" #include "lem1803.hpp" #include "cgm.hpp" using namespace cpu; /* const long TOTALCPUS = 215*16; const long PERTHREAD = 16; // At 16 looks that is the ideal for the FX-4100 #define THREADS (TOTALCPUS/PERTHREAD) const long CYCLES = 1000*1000; const int BATCH = 10; */ //std::vector<std::vector<std::shared_ptr<DCPU>>> threads; uint16_t* data; size_t size = 0; //void benchmark(); void step(); void run(); void renderGuy(sf::RenderWindow* win, std::shared_ptr<cpu::AbstractMonitor> mon); //void cpu_in_thread(int n); int main (int argc, char **argv) { char* filename; std::ifstream binfile; if (argc <= 1) { std::cerr << "Missing input file\n"; return 0; } filename = argv[1]; std::cout << "Input BIN File : " << filename << "\n"; binfile.open (filename, std::ios::in | std::ios::binary ); if (!binfile) { std::cerr << "ERROR: I can open file\n"; exit (1); } // get length of file: binfile.seekg (0, binfile.end); size = binfile.tellg(); binfile.seekg (0, binfile.beg); data = new uint16_t[size / 2 + 1](); std::fill_n (data, size / 2, 0); // Clean it int i = 0; while (! binfile.eof() ) { uint16_t word = 0; binfile.read ( (char*) &word, 2); unsigned char tmp = ( (word & 0xFF00) >> 8) & 0x00FF; word = ( (word & 0x00FF) << 8) | tmp; data[i] = word; i++; } binfile.close(); std::cout << "Readed " << size << " bytes - " << size / 2 << " words\n"; size /= 2; badchar: std::cout << "Select what to do :" << std::endl; std::cout << "\ts -> step execution\n\tr-> run"; std::cout << std::endl << std::endl; char choose; std::cin >> choose; /* if (choose == 'b' || choose == 'B') { benchmark(); } else*/ if ( choose == 's' || choose == 'S') { step(); } else if ( choose == 'r' || choose == 'R') { run(); } else { goto badchar; /// HATE ME!!!! } delete[] data; return 0; } /* void benchmark() { // Load program to all CPUs for (int u=0; u< THREADS; u++) { std::vector<std::shared_ptr<DCPU>> cpus; cpus.reserve (PERTHREAD); for (int i = 0; i< PERTHREAD; i++) { auto cpu = std::make_shared<DCPU>(); //auto screen = std::make_shared<Fake_Lem1802>(); //screen->setEnable(false); // We not desire to write to stdout //cpu->attachHardware (screen); cpu->reset(); cpu->loadProgram (data, size); cpus.push_back(cpu); } threads.push_back(cpus); } sf::Thread* tds[THREADS]; std::cout << "Threads " << THREADS << "\t CPU PerThread " << PERTHREAD; std::cout << "\t N cpus " << PERTHREAD * THREADS << std::endl; std::cout << "Cycles " << CYCLES << std::endl; auto start = std::chrono::high_resolution_clock::now(); for (int i=0; i< THREADS; i++) { tds[i] = new sf::Thread(cpu_in_thread, i); tds[i]->launch(); } for (int i=0; i< THREADS; i++) { delete tds[i]; //wait() is automatically called } auto end = std::chrono::high_resolution_clock::now(); auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); std::cout << "Measured time: " << dur.count() << "ms" << std::endl; } */ void step() { using namespace std; auto cpu = make_shared<DCPU>(); auto screen = make_shared<lem::Lem1802>(); cpu->attachHardware (screen); sf::RenderWindow win(sf::VideoMode( screen->phyWidth() + screen->borderSize()*2, screen->phyHeight() + screen->borderSize()*2), "DCPU-16"); auto clock = make_shared<Generic_Clock>(); cpu->attachHardware (clock); cpu->reset(); cpu->loadProgram (data, size); char c = getchar(); while (1) { c = getchar(); if (c == 'f' || c == 'q' || c == '\n' ) break; } win.setActive(false); boost::thread thr_render (renderGuy, &win, std::static_pointer_cast<cpu::AbstractMonitor>(screen)); while (c != 'q' && win.isOpen()) { cout << cpu->dumpRegisters() << endl; cout << "T cycles " << dec << cpu->getTotCycles() << endl; cout << "> " << cpu->dumpRam() << " - "; string s = disassembly(cpu->getMem() + cpu->GetPC(), 3); cout << s << endl; if (cpu->GetSP() != 0x0000) cout << "STACK : "<< cpu->dumpRam(cpu->GetSP(), 0xFFFF) << endl; if (c == 'f') { for (int i = 0; i < 100; i++) cpu->step(); //cpu->tick(); } else { cpu->step(); /*if (cpu->tick()) cout << "Execute! ";*/ } cout << endl; while (1) { c = getchar(); if (c == 'f' || c == 'q' || c == '\n' ) break; } } if (win.isOpen()) win.close(); if (thr_render.joinable()) thr_render.join(); } void run() { using namespace std; using namespace std::chrono; auto cpu = make_shared<DCPU>(); auto screen = make_shared<cgm::CGM>(); cpu->attachHardware (screen); sf::RenderWindow win(sf::VideoMode( screen->phyWidth() + screen->borderSize()*2, screen->phyHeight() + screen->borderSize()*2), "DCPU-16 CGM1084"); auto screen2 = make_shared<lem::Lem1803>(); cpu->attachHardware (screen2); sf::RenderWindow win2(sf::VideoMode( screen->phyWidth() + screen->borderSize()*2, screen->phyHeight() + screen->borderSize()*2), "DCPU-16 LEM1803"); auto clock = make_shared<Generic_Clock>(); cpu->attachHardware (clock); cpu->reset(); cpu->loadProgram (data, size); high_resolution_clock::time_point t = high_resolution_clock::now(); high_resolution_clock::time_point t2; win.setActive(false); boost::thread thr_render (renderGuy, &win, std::static_pointer_cast<cpu::AbstractMonitor>(screen)); win2.setActive(false); boost::thread thr_render2 (renderGuy, &win2, std::static_pointer_cast<cpu::AbstractMonitor>(screen2)); while (win.isOpen() && win2.isOpen() ) { //&& wincgm.isOpen()) { t2 = high_resolution_clock::now(); cpu->tick(); //auto rest = nanoseconds(1000000000/cpu->cpu_clock)-delta; if ((cpu->getTotCycles() % 50000) == 0) { // Not show running speed every clock tick auto delta = duration_cast<chrono::nanoseconds>(t2 - t); //double p = nanoseconds(1000000000/cpu->cpu_clock).count() / // (double)(delta.count() + rest.count()); cerr << "Delta :" << delta.count() << " ns " << endl; //cerr << "Rest :" << rest.count() << " ns "; //cerr << " Running at "<< p*100.0 << " % speed." << endl; } t = t2; } if (win.isOpen()) win.close(); if (win2.isOpen()) win2.close(); if (thr_render.joinable()) thr_render.join(); if (thr_render2.joinable()) thr_render.join(); cout << "Finish" << endl; } /* // Runs PERTHREAD cpus, doing CYCLES cycles void cpu_in_thread(int n) { auto cpus = threads[n]; for (long i=0; i < CYCLES; i+= BATCH) { for (auto c = cpus.begin(); c != cpus.end(); c++) { for ( int j=0; j < BATCH; j++) (*c)->tick(); } } } */ void renderGuy(sf::RenderWindow* win, std::shared_ptr<cpu::AbstractMonitor> mon) { sf::Texture texture_lem; while (win->isOpen()) { sf::Event event; while (win->pollEvent(event)) { if (event.type == sf::Event::Closed) { win->close(); continue; } } win->clear(mon->getBorder()); sf::Image* scr = mon->updateScreen(); texture_lem.create(mon->width(), mon->height()); texture_lem.loadFromImage(*scr); sf::Sprite sprite_lem(texture_lem); sprite_lem.scale( mon->phyWidth() / (float)(mon->width() ) , mon->phyHeight() / (float)(mon->height()) ); sprite_lem.setPosition(mon->borderSize(), mon->borderSize()); win->draw(sprite_lem); win->display(); delete scr; } } <|endoftext|>
<commit_before>/****************************************************************************** * Fake Frog * * An Arduino-based project to build a frog-shaped temperature logger. * * Author: David Lougheed. Copyright 2017. * ******************************************************************************/ #define VERSION "0.1.0" // Includes #include <Arduino.h> #include <Wire.h> #include <LiquidCrystal.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING true // Log to the serial display for debug. #define FILE_LOGGING true // Log to file on SD card. (recommended) #define DISPLAY_ENABLED true // Show menus and information on an LCD. #define NUM_SAMPLES 10 // Samples get averaged to reduce noise. #define SAMPLE_DELAY 10 // Milliseconds between samples. // Hardware Settings #define THERMISTOR_PIN A0 #define THERMISTOR_SERIES_RES 10000 #define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0. #define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor. #define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0. #define SD_CARD_PIN 10 #define RTC_PIN_1 4 #define RTC_PIN_2 5 #define LCD_PIN_RS 6 #define LCD_PIN_EN 7 #define LCD_PIN_DB4 8 #define LCD_PIN_DB5 9 #define LCD_PIN_DB6 11 #define LCD_PIN_DB7 12 #define LCD_ROWS 2 #define LCD_COLUMNS 16 #define RTC_TYPE RTC_PCF8523 // Other Compile-Time Constants #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; File log_file; File data_file; RTC_TYPE rtc; LiquidCrystal* lcd; // To save memory, use global data point variables. DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50); double latest_resistance; double latest_temperature; /* DISPLAY MODES (ALL WITH LOGGING) 0: Idle 1: Information (clock, space usage) 2: RTC Editor */ uint8_t display_mode = 0; uint16_t i; // 16-bit iterator // Utility Methods // Log a generic message. void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) { Serial.println(msg); } else { Serial.print(msg); } } if (FILE_LOGGING) { if (log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } log_file.flush(); } } } // Log an error message. Uses standard log method, then hangs forever. void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); while (true); // Loop forever } void update_screen() { if (DISPLAY_ENABLED && lcd) { lcd->clear(); switch (display_mode) { case 1: lcd->print("TBD"); break; case 2: lcd->print("TBD"); break; case 0: default: break; } } } void switch_display_mode(uint8_t m) { display_mode = m; update_screen(); } // Data Methods // Update the global formatted timestamp string with the contents of 'now'. void update_formatted_timestamp() { sprintf(formatted_timestamp, "%u-%u-%uT%u:%u:%u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } double resistance_to_temperature(double resistance) { // Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius) return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1 / (THERMISTOR_TEMP_NOM + 273.15)) - 273.15; } void take_reading() { now = rtc.now(); latest_resistance = 0; for (i = 0; i < NUM_SAMPLES; i++) { latest_resistance += (double) analogRead(THERMISTOR_PIN); delay(SAMPLE_DELAY); } // Formulas: R = sr / (1023 / mean_of_samples - 1) // sr = thermistor series resistance latest_resistance = THERMISTOR_SERIES_RES / (1023 / (latest_resistance / NUM_SAMPLES) - 1); // Resistance latest_temperature = resistance_to_temperature(latest_resistance); // TODO: Error calculations } void save_reading_to_card() { if (data_file) { update_formatted_timestamp(); sprintf(data_file_entry_buffer, "%.2f,%s", latest_temperature, formatted_timestamp); data_file.println(data_file_entry_buffer); data_file.flush(); } } // Main Methods void setup() { // TODO: Set up pins // SET UP EXTERNAL ANALOG VOLTAGE REFERENCE // Typically from 3.3V Arduino supply. This reduces the voltage noise seen // from reading analog values. analogReference(EXTERNAL); // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log_error("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_000.txt"; for (i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 32 to get ASCII number characters. log_file_name[6] = i / 100 + 32; log_file_name[7] = i / 10 + 32; log_file_name[8] = i % 10 + 32; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC...", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // TODO: Calibrate RTC // SET UP DATA FILE log("Creating data file..."); char data_file_name[] = "data_000.csv"; for (i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 32 to get ASCII digit characters. data_file_name[6] = i / 100 + 32; data_file_name[7] = i / 10 + 32; data_file_name[8] = i % 10 + 32; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // PRINT DATA FILE CSV HEADERS data_file.println("Timestamp,Temperature"); data_file.flush(); // SET UP LCD if (DISPLAY_ENABLED) { lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4, LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7); lcd->begin(LCD_COLUMNS, LCD_ROWS); } // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp, false); log(". Software version: ", false); log(VERSION); } void loop() { // TODO: (Optional) Exit sleep take_reading(); save_reading_to_card(); // TODO: (Optional) Enter sleep delay(1000); } <commit_msg>Add proper reading interval timing (without sleep).<commit_after>/****************************************************************************** * Fake Frog * * An Arduino-based project to build a frog-shaped temperature logger. * * Author: David Lougheed. Copyright 2017. * ******************************************************************************/ #define VERSION "0.1.0" // Includes #include <Arduino.h> #include <Wire.h> #include <LiquidCrystal.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING true // Log to the serial display for debug. #define FILE_LOGGING true // Log to file on SD card. (recommended) #define DISPLAY_ENABLED true // Show menus and information on an LCD. #define NUM_SAMPLES 10 // Samples get averaged to reduce noise. #define SAMPLE_DELAY 10 // Milliseconds between samples. #define READING_INTERVAL 60 // Seconds between readings. // Hardware Settings #define THERMISTOR_PIN A0 #define THERMISTOR_SERIES_RES 10000 #define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0. #define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor. #define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0. #define SD_CARD_PIN 10 #define RTC_PIN_1 4 #define RTC_PIN_2 5 #define LCD_PIN_RS 6 #define LCD_PIN_EN 7 #define LCD_PIN_DB4 8 #define LCD_PIN_DB5 9 #define LCD_PIN_DB6 11 #define LCD_PIN_DB7 12 #define LCD_ROWS 2 #define LCD_COLUMNS 16 #define RTC_TYPE RTC_PCF8523 // Other Compile-Time Constants #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; File log_file; File data_file; RTC_TYPE rtc; LiquidCrystal* lcd; // To save memory, use global data point variables. DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50); double latest_resistance; double latest_temperature; /* DISPLAY MODES (ALL WITH LOGGING) 0: Idle 1: Information (clock, space usage) 2: RTC Editor */ uint8_t display_mode = 0; uint16_t i; // 16-bit iterator uint8_t timer = 0; // Counts seconds // Utility Methods // Log a generic message. void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) { Serial.println(msg); } else { Serial.print(msg); } } if (FILE_LOGGING) { if (log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } log_file.flush(); } } } // Log an error message. Uses standard log method, then hangs forever. void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); while (true); // Loop forever } void update_screen() { if (DISPLAY_ENABLED && lcd) { lcd->clear(); switch (display_mode) { case 1: lcd->print("TBD"); break; case 2: lcd->print("TBD"); break; case 0: default: break; } } } void switch_display_mode(uint8_t m) { display_mode = m; update_screen(); } // Data Methods // Update the global formatted timestamp string with the contents of 'now'. void update_formatted_timestamp() { sprintf(formatted_timestamp, "%u-%u-%uT%u:%u:%u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } double resistance_to_temperature(double resistance) { // Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius) return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1 / (THERMISTOR_TEMP_NOM + 273.15)) - 273.15; } void take_reading() { now = rtc.now(); latest_resistance = 0; for (i = 0; i < NUM_SAMPLES; i++) { latest_resistance += (double) analogRead(THERMISTOR_PIN); delay(SAMPLE_DELAY); } // Formulas: R = sr / (1023 / mean_of_samples - 1) // sr = thermistor series resistance latest_resistance = THERMISTOR_SERIES_RES / (1023 / (latest_resistance / NUM_SAMPLES) - 1); // Resistance latest_temperature = resistance_to_temperature(latest_resistance); // TODO: Error calculations } void save_reading_to_card() { if (data_file) { update_formatted_timestamp(); sprintf(data_file_entry_buffer, "%.2f,%s", latest_temperature, formatted_timestamp); data_file.println(data_file_entry_buffer); data_file.flush(); } } // Main Methods void setup() { // TODO: Set up pins // SET UP EXTERNAL ANALOG VOLTAGE REFERENCE // Typically from 3.3V Arduino supply. This reduces the voltage noise seen // from reading analog values. analogReference(EXTERNAL); // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log_error("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_000.txt"; for (i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 32 to get ASCII number characters. log_file_name[6] = i / 100 + 32; log_file_name[7] = i / 10 + 32; log_file_name[8] = i % 10 + 32; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC...", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // TODO: Calibrate RTC // SET UP DATA FILE log("Creating data file..."); char data_file_name[] = "data_000.csv"; for (i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 32 to get ASCII digit characters. data_file_name[6] = i / 100 + 32; data_file_name[7] = i / 10 + 32; data_file_name[8] = i % 10 + 32; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // PRINT DATA FILE CSV HEADERS data_file.println("Timestamp,Temperature"); data_file.flush(); // SET UP LCD if (DISPLAY_ENABLED) { lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4, LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7); lcd->begin(LCD_COLUMNS, LCD_ROWS); } // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp, false); log(". Software version: ", false); log(VERSION); } void loop() { if (timer == READING_INTERVAL) { timer = 0; take_reading(); save_reading_to_card(); } timer++; delay(1000); } <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // Main //============================================================================== #include "common.h" #include "guiutils.h" #include "mainwindow.h" #include "splashscreenwindow.h" //============================================================================== #include <QDir> #include <QProcess> #include <QSettings> #ifdef Q_OS_WIN #include <QWebSettings> #endif //============================================================================== #include <QtSingleApplication> //============================================================================== #include <stdlib.h> //============================================================================== int main(int pArgC, char *pArgV[]) { // Create our application // Note: on Linux and OS X, we first try to run the CLI version of OpenCOR // while on Windows, we go straight for the GUI version. Indeed, in // the case of Windows, we have two binaries (.com and .exe that are // for the CLI and GUI versions of OpenCOR, respectively). This means // that when a console window is open, to enter something like: // C:\>OpenCOR // will effectively call OpenCOR.com. From there, should there be no // argument that requires CLI treatment, then the GUI version of // OpenCOR will be launched. This is, unfortunately, the only way to // have OpenCOR to behave as both a CLI and a GUI application on // Windows, hence the [OpenCOR]/windows/main.cpp file which is used to // generate the CLI version of OpenCOR... #if defined(Q_OS_WIN) SharedTools::QtSingleApplication *app = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(), pArgC, pArgV); #elif defined(Q_OS_LINUX) || defined(Q_OS_MAC) QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV); #else #error Unsupported platform #endif // Remove all 'global' instances, in case OpenCOR previously crashed or // something (and therefore didn't remove all of them before quitting) OpenCOR::removeGlobalInstances(); // Some general initialisations #if defined(Q_OS_WIN) OpenCOR::initApplication(app); #elif defined(Q_OS_LINUX) || defined(Q_OS_MAC) OpenCOR::initApplication(cliApp); #else #error Unsupported platform #endif // Try to run OpenCOR as a CLI application #if defined(Q_OS_WIN) // Do nothing... #elif defined(Q_OS_LINUX) || defined(Q_OS_MAC) int res; bool runCliApplication = OpenCOR::cliApplication(cliApp, &res); delete cliApp; if (runCliApplication) { // OpenCOR was run as a CLI application, so... OpenCOR::removeGlobalInstances(); return res; } // At this stage, we tried to run the CLI version of OpenCOR, but in the end // we need to run the GUI version, so start over but with the GUI version of // OpenCOR this time // Make sure that we always use indirect rendering on Linux // Note: indeed, depending on which plugins are selected, OpenCOR may need // LLVM. If that's the case, and in case the user's video card uses a // driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then // there may be a conflict between the version of LLVM used by // OpenCOR and the one used by the video card. One way to address this // issue is by using indirect rendering... #ifdef Q_OS_LINUX setenv("LIBGL_ALWAYS_INDIRECT", "1", 1); #endif // Create our application // Note: the CLI version of OpenCOR didn't actually do anything, so no need // to re-remove all 'global' instances... SharedTools::QtSingleApplication *app = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(), pArgC, pArgV); // Some general initialisations OpenCOR::initApplication(app); #else #error Unsupported platform #endif // Initialise our colours by 'updating' them OpenCOR::Core::updateColors(); #ifndef QT_DEBUG // Show our splash screen OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow(); splashScreen->show(); app->processEvents(); #endif // Send a message (containing the arguments that were passed to this // instance of OpenCOR minus the first one since it corresponds to the full // path to our executable, which we are not interested in) to our 'official' // instance of OpenCOR, should there be one. If there is no none, then just // carry on as normal, otherwise exit since we want only one instance of // OpenCOR at any given time QStringList appArguments = app->arguments(); appArguments.removeFirst(); QString arguments = appArguments.join("|"); if (app->isRunning()) { app->sendMessage(arguments); delete app; return 0; } #ifdef Q_OS_WIN // Specify where to find non-OpenCOR plugins (only required on Windows) app->addLibraryPath( QDir(app->applicationDirPath()).canonicalPath() +QDir::separator()+QString("..") +QDir::separator()+"plugins"); #endif // Create our main window OpenCOR::MainWindow *win = new OpenCOR::MainWindow(app); // Keep track of our main window (required by QtSingleApplication so that it // can do what it's supposed to be doing) app->setActivationWindow(win); // Handle our arguments win->handleArguments(arguments); // Show our main window win->show(); #ifndef QT_DEBUG // Get rid of our splash screen once our main window is visible splashScreen->finish(win); // Make sure that our main window is in the foreground // Note: indeed, on Linux, to show our splash screen may result in our main // window being shown in the background, so... win->showSelf(); #endif // Execute our application #ifdef Q_OS_WIN int #endif res = app->exec(); // Keep track of our application file and directory paths (in case we need // to restart OpenCOR) QString appFilePath = app->applicationFilePath(); QString appDirPath = app->applicationDirPath(); // Delete our main window delete win; // If we use QtWebKit, and QWebPage in particular, then leak messages will // get generated on Windows when leaving OpenCOR. This is because an object // cache is shared between all QWebPage instances. So to destroy a QWebPage // instance won't clear the cache, hence the leak messages. However, these // messages are 'only' warnings, so we can safely live with them. Still, it // doesn't look 'good', so we clear the memory caches, thus avoiding those // leak messages... // Note: the below must absolutely be done after calling app->exec() and // before deleting app... #ifdef Q_OS_WIN QWebSettings::clearMemoryCaches(); #endif // Delete our application delete app; // Remove all 'global' instances that were created and used during this // session OpenCOR::removeGlobalInstances(); // We are done with the execution of our application, so now the question is // whether we need to restart // Note: we do this here rather than 'within' the GUI because once we have // launched a new instance of OpenCOR, we want this instance of // OpenCOR to finish as soon as possible which will be the case here // since all that remains to be done is to return the result of the // execution of our application... if (res == OpenCOR::NeedRestart) // Restart OpenCOR, but without providing any of the arguments that were // originally passed to us since we want to reset everything QProcess::startDetached(appFilePath, QStringList(), appDirPath); // We are done, so... return res; } //============================================================================== // End of file //============================================================================== <commit_msg>Fixed a small memory leak [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // Main //============================================================================== #include "common.h" #include "guiutils.h" #include "mainwindow.h" #include "splashscreenwindow.h" //============================================================================== #include <QDir> #include <QProcess> #include <QSettings> #ifdef Q_OS_WIN #include <QWebSettings> #endif //============================================================================== #include <QtSingleApplication> //============================================================================== #include <stdlib.h> //============================================================================== int main(int pArgC, char *pArgV[]) { // Create our application // Note: on Linux and OS X, we first try to run the CLI version of OpenCOR // while on Windows, we go straight for the GUI version. Indeed, in // the case of Windows, we have two binaries (.com and .exe that are // for the CLI and GUI versions of OpenCOR, respectively). This means // that when a console window is open, to enter something like: // C:\>OpenCOR // will effectively call OpenCOR.com. From there, should there be no // argument that requires CLI treatment, then the GUI version of // OpenCOR will be launched. This is, unfortunately, the only way to // have OpenCOR to behave as both a CLI and a GUI application on // Windows, hence the [OpenCOR]/windows/main.cpp file which is used to // generate the CLI version of OpenCOR... #if defined(Q_OS_WIN) SharedTools::QtSingleApplication *app = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(), pArgC, pArgV); #elif defined(Q_OS_LINUX) || defined(Q_OS_MAC) QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV); #else #error Unsupported platform #endif // Remove all 'global' instances, in case OpenCOR previously crashed or // something (and therefore didn't remove all of them before quitting) OpenCOR::removeGlobalInstances(); // Some general initialisations #if defined(Q_OS_WIN) OpenCOR::initApplication(app); #elif defined(Q_OS_LINUX) || defined(Q_OS_MAC) OpenCOR::initApplication(cliApp); #else #error Unsupported platform #endif // Try to run OpenCOR as a CLI application #if defined(Q_OS_WIN) // Do nothing... #elif defined(Q_OS_LINUX) || defined(Q_OS_MAC) int res; bool runCliApplication = OpenCOR::cliApplication(cliApp, &res); delete cliApp; if (runCliApplication) { // OpenCOR was run as a CLI application, so... OpenCOR::removeGlobalInstances(); return res; } // At this stage, we tried to run the CLI version of OpenCOR, but in the end // we need to run the GUI version, so start over but with the GUI version of // OpenCOR this time // Make sure that we always use indirect rendering on Linux // Note: indeed, depending on which plugins are selected, OpenCOR may need // LLVM. If that's the case, and in case the user's video card uses a // driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then // there may be a conflict between the version of LLVM used by // OpenCOR and the one used by the video card. One way to address this // issue is by using indirect rendering... #ifdef Q_OS_LINUX setenv("LIBGL_ALWAYS_INDIRECT", "1", 1); #endif // Create our application // Note: the CLI version of OpenCOR didn't actually do anything, so no need // to re-remove all 'global' instances... SharedTools::QtSingleApplication *app = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(), pArgC, pArgV); // Some general initialisations OpenCOR::initApplication(app); #else #error Unsupported platform #endif // Initialise our colours by 'updating' them OpenCOR::Core::updateColors(); #ifndef QT_DEBUG // Show our splash screen OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow(); splashScreen->show(); app->processEvents(); #endif // Send a message (containing the arguments that were passed to this // instance of OpenCOR minus the first one since it corresponds to the full // path to our executable, which we are not interested in) to our 'official' // instance of OpenCOR, should there be one. If there is no none, then just // carry on as normal, otherwise exit since we want only one instance of // OpenCOR at any given time QStringList appArguments = app->arguments(); appArguments.removeFirst(); QString arguments = appArguments.join("|"); if (app->isRunning()) { app->sendMessage(arguments); delete app; return 0; } #ifdef Q_OS_WIN // Specify where to find non-OpenCOR plugins (only required on Windows) app->addLibraryPath( QDir(app->applicationDirPath()).canonicalPath() +QDir::separator()+QString("..") +QDir::separator()+"plugins"); #endif // Create our main window OpenCOR::MainWindow *win = new OpenCOR::MainWindow(app); // Keep track of our main window (required by QtSingleApplication so that it // can do what it's supposed to be doing) app->setActivationWindow(win); // Handle our arguments win->handleArguments(arguments); // Show our main window win->show(); #ifndef QT_DEBUG // Get rid of our splash screen once our main window is visible splashScreen->finish(win); delete splashScreen; // Make sure that our main window is in the foreground // Note: indeed, on Linux, to show our splash screen may result in our main // window being shown in the background, so... win->showSelf(); #endif // Execute our application #ifdef Q_OS_WIN int #endif res = app->exec(); // Keep track of our application file and directory paths (in case we need // to restart OpenCOR) QString appFilePath = app->applicationFilePath(); QString appDirPath = app->applicationDirPath(); // Delete our main window delete win; // If we use QtWebKit, and QWebPage in particular, then leak messages will // get generated on Windows when leaving OpenCOR. This is because an object // cache is shared between all QWebPage instances. So to destroy a QWebPage // instance won't clear the cache, hence the leak messages. However, these // messages are 'only' warnings, so we can safely live with them. Still, it // doesn't look 'good', so we clear the memory caches, thus avoiding those // leak messages... // Note: the below must absolutely be done after calling app->exec() and // before deleting app... #ifdef Q_OS_WIN QWebSettings::clearMemoryCaches(); #endif // Delete our application delete app; // Remove all 'global' instances that were created and used during this // session OpenCOR::removeGlobalInstances(); // We are done with the execution of our application, so now the question is // whether we need to restart // Note: we do this here rather than 'within' the GUI because once we have // launched a new instance of OpenCOR, we want this instance of // OpenCOR to finish as soon as possible which will be the case here // since all that remains to be done is to return the result of the // execution of our application... if (res == OpenCOR::NeedRestart) // Restart OpenCOR, but without providing any of the arguments that were // originally passed to us since we want to reset everything QProcess::startDetached(appFilePath, QStringList(), appDirPath); // We are done, so... return res; } //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/* Copyright (C) 2014-2015 INRA * * 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 <efyj/model.hpp> #include <efyj/exception.hpp> #include <efyj/problem.hpp> #include <iostream> #include <algorithm> #include <chrono> #include <fstream> #include <iterator> #include <random> #include <cstdlib> #include <ctime> #include <cstdlib> #include <cstring> #include <getopt.h> #ifdef EFYj_MPI_SUPPORT #include <mpi.h> #endif namespace { void usage() noexcept { std::cout << "efyj [-h][-m file.dexi][-o file.csv]\n\n" << "Options:\n" << " -h This help message\n" << " -m model.dexi The model file\n" << " -o options.csv The options file\n" << " -s solver_name Select the specified solver\n" << "\n" << "Available solvers:\n" << " classic the default tree path\n" << " stack stack and reverse polish notation\n" << " bigmem default solver fill a big memory space\n" << std::endl; } } // anonymous namespace int main(int argc, char *argv[]) { int ret = EXIT_SUCCESS; int opt; std::string modelfilepath, optionfilepath; std::string solvername; while ((opt = ::getopt(argc, argv, "m:o:s:h")) != -1) { switch (opt) { case 'm': modelfilepath.assign(::optarg); break; case 'o': optionfilepath.assign(::optarg); break; case 's': solvername.assign(::optarg); break; case 'h': default: ::usage(); exit(EXIT_SUCCESS); } } if (::optind > argc) { std::cerr << "Expected argument after -m, -o or -s options\n"; exit(EXIT_FAILURE); } try { efyj::Context ctx = std::make_shared <efyj::ContextImpl>(efyj::LOG_OPTION_ERR); efyj::problem pb(ctx, modelfilepath, optionfilepath); if (solvername == "stack") pb.compute <efyj::solver_stack>(0, 1); else if (solvername == "bigmem") pb.compute <efyj::solver_bigmem>(0, 1); else pb.compute <efyj::solver_basic>(0, 1); } catch (const std::exception &e) { std::cerr << "failure: " << e.what() << '\n'; } return ret; } <commit_msg>main: cleanup headers<commit_after>/* Copyright (C) 2014-2015 INRA * * 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 <efyj/model.hpp> #include <efyj/exception.hpp> #include <efyj/problem.hpp> #include <iostream> #include <chrono> #include <fstream> #include <getopt.h> #ifdef EFYj_MPI_SUPPORT #include <mpi.h> #endif namespace { void usage() noexcept { std::cout << "efyj [-h][-m file.dexi][-o file.csv]\n\n" << "Options:\n" << " -h This help message\n" << " -m model.dexi The model file\n" << " -o options.csv The options file\n" << " -s solver_name Select the specified solver\n" << "\n" << "Available solvers:\n" << " classic the default tree path\n" << " stack stack and reverse polish notation\n" << " bigmem default solver fill a big memory space\n" << std::endl; } } // anonymous namespace int main(int argc, char *argv[]) { int ret = EXIT_SUCCESS; int opt; std::string modelfilepath, optionfilepath; std::string solvername; while ((opt = ::getopt(argc, argv, "m:o:s:h")) != -1) { switch (opt) { case 'm': modelfilepath.assign(::optarg); break; case 'o': optionfilepath.assign(::optarg); break; case 's': solvername.assign(::optarg); break; case 'h': default: ::usage(); exit(EXIT_SUCCESS); } } if (::optind > argc) { std::cerr << "Expected argument after -m, -o or -s options\n"; exit(EXIT_FAILURE); } try { efyj::Context ctx = std::make_shared <efyj::ContextImpl>(efyj::LOG_OPTION_ERR); efyj::problem pb(ctx, modelfilepath, optionfilepath); if (solvername == "stack") pb.compute <efyj::solver_stack>(0, 1); else if (solvername == "bigmem") pb.compute <efyj::solver_bigmem>(0, 1); else pb.compute <efyj::solver_basic>(0, 1); } catch (const std::exception &e) { std::cerr << "failure: " << e.what() << '\n'; } return ret; } <|endoftext|>
<commit_before>#include "../ui/mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { #ifdef Q_OS_LINUX QCoreApplication::addLibraryPath("/usr/lib/viqo"); #endif QApplication a(argc, argv); QCoreApplication::setApplicationName("Viqo"); QCoreApplication::setApplicationVersion("2.3.1"); QCommandLineParser parser; parser.setApplicationDescription( QStringLiteral("Qt で作成されたマルチプラットフォームコメントビューワです")); parser.addHelpOption(); parser.addVersionOption(); // Process the actual command line arguments given by the user parser.process(a); MainWindow w; w.show(); return a.exec(); } <commit_msg>version 2.3.3<commit_after>#include "../ui/mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { #ifdef Q_OS_LINUX QCoreApplication::addLibraryPath("/usr/lib/viqo"); #endif QApplication a(argc, argv); QCoreApplication::setApplicationName("Viqo"); QCoreApplication::setApplicationVersion("2.3.3"); QCommandLineParser parser; parser.setApplicationDescription( QStringLiteral("Qt で作成されたマルチプラットフォームコメントビューワです")); parser.addHelpOption(); parser.addVersionOption(); // Process the actual command line arguments given by the user parser.process(a); MainWindow w; w.show(); return a.exec(); } <|endoftext|>
<commit_before>#include <QApplication> #include <QMessageBox> #include <QTranslator> #include <QLocale> #include <QLibraryInfo> #include <QWidget> #include <glib-object.h> #include "utils/process.h" #include "seafile-applet.h" #include "QtAwesome.h" #ifdef Q_OS_MAC static bool dockClickHandler(id self,SEL _cmd,...) { Q_UNUSED(self) Q_UNUSED(_cmd) if (seafApplet) { MainWindow *main_win = seafApplet->mainWindow(); main_win->showWindow(); } return true; } Application::Application (int& argc, char **argv) : QApplication(argc, argv) { objc_object* cls = objc_getClass("NSApplication"); SEL sharedApplication = sel_registerName("sharedApplication"); objc_object* appInst = objc_msgSend(cls,sharedApplication); if(appInst != NULL) { objc_object* delegate = objc_msgSend(appInst, sel_registerName("delegate")); objc_object* delClass = objc_msgSend(delegate, sel_registerName("class")); class_addMethod((objc_class*)delClass, sel_registerName("applicationShouldHandleReopen:hasVisibleWindows:"), (IMP)dockClickHandler,"B@:"); } } #endif int main(int argc, char *argv[]) { if (count_process("seafile-applet") > 1) { QMessageBox::warning(NULL, "Seafile", QObject::tr("Seafile is already running"), QMessageBox::Ok); return -1; } #ifdef Q_WS_MAC Application app(argc, argv); #else QApplication app(argc, argv); #endif app.setQuitOnLastWindowClosed(false); // see QSettings documentation QCoreApplication::setOrganizationName("Seafile"); QCoreApplication::setOrganizationDomain("seafile.com"); QCoreApplication::setApplicationName("Seafile Client"); // initialize i18n QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); QTranslator myappTranslator; myappTranslator.load(QString(":/i18n/seafile_%1.qm").arg(QLocale::system().name())); app.installTranslator(&myappTranslator); #if !GLIB_CHECK_VERSION(2, 35, 0) g_type_init(); #endif #if !GLIB_CHECK_VERSION(2, 31, 0) g_thread_init(NULL); #endif awesome = new QtAwesome(qApp); awesome->initFontAwesome(); seafApplet = new SeafileApplet; seafApplet->start(); return app.exec(); } <commit_msg>fixed a bug when running two instances of seafile-client<commit_after>#include <QApplication> #include <QMessageBox> #include <QTranslator> #include <QLocale> #include <QLibraryInfo> #include <QWidget> #include <glib-object.h> #include <stdio.h> #include "utils/process.h" #include "seafile-applet.h" #include "QtAwesome.h" #ifdef Q_OS_MAC static bool dockClickHandler(id self,SEL _cmd,...) { Q_UNUSED(self) Q_UNUSED(_cmd) if (seafApplet) { MainWindow *main_win = seafApplet->mainWindow(); main_win->showWindow(); } return true; } Application::Application (int& argc, char **argv) : QApplication(argc, argv) { objc_object* cls = objc_getClass("NSApplication"); SEL sharedApplication = sel_registerName("sharedApplication"); objc_object* appInst = objc_msgSend(cls,sharedApplication); if(appInst != NULL) { objc_object* delegate = objc_msgSend(appInst, sel_registerName("delegate")); objc_object* delClass = objc_msgSend(delegate, sel_registerName("class")); class_addMethod((objc_class*)delClass, sel_registerName("applicationShouldHandleReopen:hasVisibleWindows:"), (IMP)dockClickHandler,"B@:"); } } #endif int main(int argc, char *argv[]) { #ifdef Q_WS_MAC Application app(argc, argv); #else QApplication app(argc, argv); #endif if (count_process("seafile-applet") > 1) { QMessageBox::warning(NULL, "Seafile", QObject::tr("Seafile is already running"), QMessageBox::Ok); return -1; } app.setQuitOnLastWindowClosed(false); // see QSettings documentation QCoreApplication::setOrganizationName("Seafile"); QCoreApplication::setOrganizationDomain("seafile.com"); QCoreApplication::setApplicationName("Seafile Client"); // initialize i18n QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); QTranslator myappTranslator; myappTranslator.load(QString(":/i18n/seafile_%1.qm").arg(QLocale::system().name())); app.installTranslator(&myappTranslator); #if !GLIB_CHECK_VERSION(2, 35, 0) g_type_init(); #endif #if !GLIB_CHECK_VERSION(2, 31, 0) g_thread_init(NULL); #endif awesome = new QtAwesome(qApp); awesome->initFontAwesome(); seafApplet = new SeafileApplet; seafApplet->start(); return app.exec(); } <|endoftext|>
<commit_before>/** * * Terminology (Matroid - Graph) for escalated version of algorithm: * Basis - Spanning forest * Independent set - Tree (i.e. subset of a basis) * Circuit - cycle * Cocircuit - minimal edge-cut * Hyperplane - maximal set not containing any basis (= complement of a min-cut) * * Spanning forest - union of spanning trees of each component of an unconnected graph * */ enum { BLACK, RED, BLUE }; #include <iostream> #include <stdexcept> #include <ogdf/basic/Queue.h> #include <ogdf/basic/Graph.h> #include <ogdf/basic/Stack.h> #include <ogdf/basic/simple_graph_alg.h> #include "helpers.hpp" #include "graphcoloring.h" using namespace std; using namespace ogdf; int m; // Cocircuit size bound /** * @brief Takes a csv file with lines "<id>;<source>;<target>;<edge name>;..." and transforms it into graph * @param sEdgesFileName * @return Graph */ Graph csvToGraph(string sEdgesFileName) { // This copies Graph on exit, to speed up, extend Graph and let this be a new method in our extended class Graph G; ifstream fEdges(sEdgesFileName); if (!fEdges.is_open()) throw new invalid_argument("Edges file doesn't exist or could not be accessed"); vector<node> nodes; int id, u, v, nSize = 0; for (string line; getline(fEdges, line);) { sscanf(line.c_str(), "%d;%d;%d;", &id, &u, &v); if (u > nSize) { nodes.resize(u + 1); nSize = u; } if (v > nSize) { nodes.resize(v + 1); nSize = v; } if(nodes.at(u) == nullptr) nodes[u] = G.newNode(u); if(nodes[v] == nullptr) nodes[v] = G.newNode(v); G.newEdge(nodes[u], nodes[v], id); } return G; } /** * Performs BFS to find the shortest path from s to t in graph g without using any edge from the forbidden edges. * Returns empty set if no such path exists. */ List<edge> shortestPath(const Graph &G, const GraphColoring &coloring, node s, node t, const List<edge> &forbidden) { List<edge> path; node v, u; edge e; Queue<node> Q; NodeArray<node> predecessor(G); NodeArray<bool> visited(G, false); Q.append(s); visited[s] = true; while(!Q.empty()) { v = Q.pop(); if (v == t) { // traceback predecessors and reconstruct path for (node n = t; n != s; n = predecessor[n]) { path.pushFront(G.searchEdge(predecessor[n], n)); } break; } forall_adj_edges(e, v) { if (forbidden.search(e).valid() || coloring[e] == Color::RED) continue; // TODO: Use BST or array (id -> bool) to represent forbidden? u = e->opposite(v); if (!visited[u]) { predecessor[u] = v; // TODO: Unite predecessor and visited? visited[u] = true; Q.append(u); } } } return path; } /** * Explores the component from node s and counts nodes colored blue, stops if nBluesInGraph is reached */ int countConnectedBlueNodes(const Graph &G, const GraphColoring &coloring, const node &s, int nBluesInGraph) { int nFoundBlues = 0; NodeArray<bool> discovered(G, false); Stack<node> S; S.push(s); node v, u; adjEntry adj; while(!S.empty()) { v = S.pop(); if (!discovered[v]) { discovered[v] = true; if (coloring[v] == Color::BLUE) { nFoundBlues++; if (nFoundBlues == nBluesInGraph) break; // There can't be more blue vertices } forall_adj(adj, v) { u = adj->twinNode(); S.push(u); } } } return nFoundBlues; } /** * E(G)\X contains a k-way hyperplane of G\X iff G\V(R) contains a connected subgraph G_b spanning all the blue vertices of X * @param G * @param X * @param coloring * @param blue * @return */ bool hasHyperplane(Graph &G, const GraphColoring &coloring, const List<edge> &X) { for(List<edge>::const_iterator iterator = X.begin(); iterator != X.end(); ++iterator) { G.hideEdge(*iterator); } node v, s; int nBlues = 0; forall_nodes(v, G) { if (coloring[v] == Color::BLUE) { nBlues++; s = v; } } int nBluesReached = 0; if (nBlues == 0) { // TODO: THIS SHOULD NEVER HAPPEN (yet it does... how to fix? Never color red any blue node in X) G.restoreAllEdges(); //cout << "ups it happened" << endl; return false; } else { // Perform a DFS on G\X from s and see if all vertices are contained nBluesReached = countConnectedBlueNodes(G, coloring, s, nBlues); } G.restoreAllEdges(); return nBluesReached == nBlues; } void GenCocircuits(List<List<edge>> &Cocircuits, Graph &G, GraphColoring coloring, List<edge> X, node red, node blue) { if (X.size() > m) return; if(!hasHyperplane(G, coloring, X) ) { // E\X contains no hyperplane of M //cout << "NO HYPERPLANE END" << endl; // TODO: This should not happen return; } // Find set D = (a short circuit C in G, s. t. |C ∩ X| = 1) \ X List<edge> D = shortestPath(G, coloring, red, blue, X); //cout << "now in x: " << X << endl; //cout << "r(" << red->index() << ")-b(" << blue->index() << ") path: " << D << endl; if (D.size() > 0) { // for each c ∈ D, recursively call GenCocircuits(X ∪ {c}). for(List<edge>::iterator iterator = D.begin(); iterator != D.end(); iterator++) { edge c = *iterator; //cout << "PROcessing " << c->index() << "(" << c->source()->index() << "," << c->target()->index() << ")" << endl; //printColoring(G, coloring); List<edge> newX = X; newX.pushBack(c); //TODO: If c = (u, v) is blue, reconnect blue subgraph (find the shortest path from u to v using only nonred edges) node n1 = red, n2 = blue, // after the first of the following for cycles these are the // nodes of the last red edge (one of them has to be incident with c) // initialized to red and blue since the first for can have 0 iterations u, v; // c = (u,v), say u is red (and so will be all vertices on the path from the first red to u) for(List<edge>::iterator j = D.begin(); j != iterator; j++) { edge e = *j; n1 = e->source(); n2 = e->target(); coloring[n1] = Color::RED; coloring[n2] = Color::RED; coloring[e] = Color::RED; } if (c->source() == n1 || c->target() == n1) { // if n1 is in c then n1 == u u = n1; } else { // n2 is in c so n2 == u u = n2; } v = c->opposite(u); // Color the rest of the path blue for(List<edge>::iterator j = iterator.succ(); j != D.end(); j++) { edge e = *j; coloring[e->source()] = Color::BLUE; coloring[e->target()] = Color::BLUE; coloring[e] = Color::BLUE; } GenCocircuits(Cocircuits, G, coloring, newX, u, v); } } else { // If there is no such circuit C above (line 4), then return ‘Cocircuit: X’. //cout << "Cocircuit: " << X << endl; Cocircuits.pushBack(X); } } /** * Returns edges spanning forest of (possibly disconnected) graph G * @param G */ List<edge> spanningEdges(const Graph &G) { EdgeArray<bool> isBackedge(G, false); List<edge> backedges; isAcyclicUndirected(G, backedges); for(List<edge>::iterator i = backedges.begin(); i != backedges.end(); i++) { isBackedge[*i] = true; } List<edge> spanningEdges; edge e; forall_edges(e, G) { if (!isBackedge[e]) { spanningEdges.pushBack(e); } } return spanningEdges; } int main(int argc, char* argv[]) { if (argc != 3 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) { cout << "Usage: " << argv[0] << " <graph.csv> <cocircuit size bound>" << endl; exit(1); } string graphFile(argv[1]); m = stoi(argv[2]); if (m < 1) { cerr << "Cocircuit size bound lower than 1. Terminating." << endl; exit(2); } try { Graph G = csvToGraph(graphFile); List<edge> base = spanningEdges(G); List<List<edge> > Cocircuits; edge e; for(List<edge>::iterator i = base.begin(); i != base.end(); i++) { e = *i; List<edge> X; // (Indexes might be sufficient? Check later) GraphColoring coloring(G); X.pushBack(e); coloring[e->source()] = Color::RED; coloring[e->target()] = Color::BLUE; //cout << "STARTing with edge " << e->index() << " (vertex " << e->source()->index() << " is red)" << endl; GenCocircuits(Cocircuits, G, coloring, X, e->source(), e->target()); } for(List<List<edge> >::iterator it = Cocircuits.begin(); it != Cocircuits.end(); ++it) { cout << "Cocircuit: " << *it << endl; } } catch (invalid_argument *e) { cerr << "Error: " << e->what() << endl; return 1; } return 0; } <commit_msg>Don't check the existence of a hyperplane every time, just reconnect G_b if it has been disconnected<commit_after>/** * * Terminology (Matroid - Graph) for escalated version of algorithm: * Basis - Spanning forest * Independent set - Tree (i.e. subset of a basis) * Circuit - cycle * Cocircuit - minimal edge-cut * Hyperplane - maximal set not containing any basis (= complement of a min-cut) * * Spanning forest - union of spanning trees of each component of an unconnected graph * */ enum { BLACK, RED, BLUE }; #include <iostream> #include <stdexcept> #include <ogdf/basic/Queue.h> #include <ogdf/basic/Graph.h> #include <ogdf/basic/Stack.h> #include <ogdf/basic/simple_graph_alg.h> #include "helpers.hpp" #include "graphcoloring.h" using namespace std; using namespace ogdf; int m; // Cocircuit size bound /** * @brief Takes a csv file with lines "<id>;<source>;<target>;<edge name>;..." and transforms it into graph * @param sEdgesFileName * @return Graph */ Graph csvToGraph(string sEdgesFileName) { // This copies Graph on exit, to speed up, extend Graph and let this be a new method in our extended class Graph G; ifstream fEdges(sEdgesFileName); if (!fEdges.is_open()) throw new invalid_argument("Edges file doesn't exist or could not be accessed"); vector<node> nodes; int id, u, v, nSize = 0; for (string line; getline(fEdges, line);) { sscanf(line.c_str(), "%d;%d;%d;", &id, &u, &v); if (u > nSize) { nodes.resize(u + 1); nSize = u; } if (v > nSize) { nodes.resize(v + 1); nSize = v; } // Skip if there already is an edge between these two nodes if (nodes.at(u) && nodes.at(v) && (G.searchEdge(nodes.at(u), nodes.at(v)) || G.searchEdge(nodes.at(v), nodes.at(u)))) continue; if(nodes.at(u) == nullptr) nodes[u] = G.newNode(u); if(nodes[v] == nullptr) nodes[v] = G.newNode(v); G.newEdge(nodes[u], nodes[v], id); } return G; } /** * Performs BFS to find the shortest path from s to t in graph g without using any red edges and any edge from the forbidden edges. * Returns empty set if no such path exists. */ List<edge> shortestPath(const Graph &G, const GraphColoring &coloring, node s, node t, const List<edge> &forbidden) { List<edge> path; node v, u; edge e; Queue<node> Q; NodeArray<bool> visited(G, false); NodeArray<node> predecessor(G); Q.append(s); visited[s] = true; while(!Q.empty()) { v = Q.pop(); if (v == t) { // traceback predecessors and reconstruct path for (node n = t; n != s; n = predecessor[n]) { e = G.searchEdge(n, predecessor[n]); // Takes O(min(deg(v), deg(w))) (that's fast on sparse graphs) if (coloring[e] != Color::RED) path.pushFront(e); } break; } forall_adj_edges(e, v) { // TODO: Use BST or array (id -> bool) to represent forbidden and fasten the following search? (Probably not // necessary as forbidden size is bound by the constant m) if (forbidden.search(e).valid()) continue; u = e->opposite(v); if (!visited[u]) { predecessor[u] = v; visited[u] = true; Q.append(u); } } } return path; } /** * @brief hideConnectedBlueSubgraph * @param G * @param coloring * @param u */ void hideConnectedBlueSubgraph(Graph &G, const GraphColoring &coloring, node start) { Queue<node> Q; Q.append(start); NodeArray<bool> visited(G, false); node u, v; edge e; while(!Q.empty()) { u = Q.pop(); forall_adj_edges(e, u) { if (coloring[e] == Color::BLUE) { v = e->opposite(u); if (!visited[v]) { visited[v] = true; Q.append(v); } G.hideEdge(e); } } } } bool findPathToAnyBlueAndColorItBlue(const Graph &G, GraphColoring &coloring, node start) { Queue<node> Q; Q.append(start); NodeArray<bool> visited(G, false); NodeArray<edge> accessEdge(G); node u, n; edge e; while(!Q.empty()) { u = Q.pop(); if (coloring[u] == Color::BLUE && u != start) { // reconstruct path and go on edge ae; node n1, n2; for (n1 = u; n1 != start;) { // TODO: Use search edge instead? ae = accessEdge[n1]; n2 = ae->opposite(n1); coloring[n1] = Color::BLUE; coloring[n2] = Color::BLUE; coloring[ae] = Color::BLUE; n1 = n2; } return true; } forall_adj_edges(e, u) { n = e->opposite(u); if (!visited[n]) { visited[n] = true; accessEdge[n] = e; Q.append(n); } } } return false; } void GenCocircuits(List<List<edge>> &Cocircuits, Graph &G, GraphColoring coloring, List<edge> X, node red, node blue) { if (X.size() > m) return; // Find set D = (a short circuit C in G, s. t. |C ∩ X| = 1) \ X List<edge> D = shortestPath(G, coloring, red, blue, X); //cout << "now in x: " << X << endl; //cout << "r(" << red->index() << ")-b(" << blue->index() << ") path: " << D << endl; //printColoring(G, coloring); cout << endl; if (D.size() > 0) { // for each c ∈ D, recursively call GenCocircuits(X ∪ {c}). for(List<edge>::iterator iterator = D.begin(); iterator != D.end(); iterator++) { edge c = *iterator; //cout << "PROcessing " << c->index() << "(" << c->source()->index() << "," << c->target()->index() << ")" << endl; //printColoring(G, coloring); List<edge> newX = X; newX.pushBack(c); // Coloring red-c path red, determining u and v, coloring the rest blue node n1 = red, n2 = blue, // after the first of the following for cycles these are the // nodes of the last red edge (one of them has to be incident with c) // initialized to red and blue since the first for can have 0 iterations u, v; // c = (u,v), say u is red (and so will be all vertices on the path from the first red to u) for(List<edge>::iterator j = D.begin(); j != iterator; j++) { edge e = *j; n1 = e->source(); n2 = e->target(); coloring[n1] = Color::RED; coloring[n2] = Color::RED; coloring[e] = Color::RED; } // Determine u, v, s.t. u is really red and v blue if (c->source() == n1 || c->target() == n1) { // if n1 is in c then n1 == u u = n1; } else { // n2 is in c so n2 == u u = n2; } v = c->opposite(u); // Color the rest of the path blue for(List<edge>::iterator j = iterator.succ(); j != D.end(); j++) { edge e = *j; coloring[e->source()] = Color::BLUE; coloring[e->target()] = Color::BLUE; coloring[e] = Color::BLUE; } // If c = (u, v) is blue, reconnect blue subgraph (find the shortest path from u to v using only nonred edges) // if c = (u,v) is blue // if u has blue adjacent edges (except of c) AND v has blue adjacent edges (exc. of c) then // enumerate one blue subgraph, call it G_b1 // create graph G_rest = G \ X \ G_r \ G_b1 and BFS in it to until blue is found (use hideEdge!) // (or BFS (avoid red and X) from u to first blue edge not in G_b1) // -> path found, color it blue and continue // -> path not found, fail here (return;) if (coloring[c] == Color::BLUE) { G.hideEdge(c); // Don't consider c bool uaIsEmpty = true, vaIsEmpty = true; edge e; forall_adj_edges(e, u) { if (coloring[e] == Color::BLUE) { uaIsEmpty = false; break; } } forall_adj_edges(e, v) { if (coloring[e] == Color::BLUE) { vaIsEmpty = false; break; } } if (!uaIsEmpty && !vaIsEmpty) { //cout << "X: " << X << "; D: " << D << "; c = " << c->index() << " --- "; //printColoring(G, coloring); //cout<< endl; // G_b has been disconnected, hide X, G_r and one component of blue subgraph (TODO: Maintain G_rest through the whole algorithm and not recompute here every time?) for(List<edge>::iterator it = X.begin(); it != X.end(); it++) G.hideEdge(*it); forall_edges(e, G) { if(coloring[e] == Color::RED) G.hideEdge(e); } hideConnectedBlueSubgraph(G, coloring, u); // BFS in G from u to the first found blue edge // -> not found => fail here // -> path found => color it blue and continue if (!findPathToAnyBlueAndColorItBlue(G, coloring, u)) { G.restoreAllEdges(); return; } } // else c is just a branch with a single leaf, nothing happened G_b stays connected G.restoreAllEdges(); } GenCocircuits(Cocircuits, G, coloring, newX, u, v); } } else { // If there is no such circuit C above (line 4), then return ‘Cocircuit: X’. //cout << "Cocircuit: " << X << endl; Cocircuits.pushBack(X); } } /** * Returns edges spanning forest of (possibly disconnected) graph G * @param G */ List<edge> spanningEdges(const Graph &G) { EdgeArray<bool> isBackedge(G, false); List<edge> backedges; isAcyclicUndirected(G, backedges); for(List<edge>::iterator i = backedges.begin(); i != backedges.end(); i++) { isBackedge[*i] = true; } List<edge> spanningEdges; edge e; forall_edges(e, G) { if (!isBackedge[e]) { spanningEdges.pushBack(e); } } return spanningEdges; } int main(int argc, char* argv[]) { if (argc != 3 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) { cout << "Usage: " << argv[0] << " <graph.csv> <cocircuit size bound>" << endl; exit(1); } string graphFile(argv[1]); m = stoi(argv[2]); if (m < 1) { cerr << "Cocircuit size bound lower than 1. Terminating." << endl; exit(2); } int size[7] = {0}; try { Graph G = csvToGraph(graphFile); List<edge> base = spanningEdges(G); List<List<edge> > Cocircuits; edge e; for(List<edge>::iterator i = base.begin(); i != base.end(); i++) { e = *i; List<edge> X; // (Indexes might be sufficient? Check later) GraphColoring coloring(G); X.pushBack(e); coloring[e->source()] = Color::RED; coloring[e->target()] = Color::BLUE; //cout << "STARTing with edge " << e->index() << " (vertex " << e->source()->index() << " is red)" << endl; GenCocircuits(Cocircuits, G, coloring, X, e->source(), e->target()); } for(List<List<edge> >::iterator it = Cocircuits.begin(); it != Cocircuits.end(); ++it) { //cout << "Cocircuit: " << *it << endl; size[(*it).size()]++; } } catch (invalid_argument *e) { cerr << "Error: " << e->what() << endl; return 1; } cout << endl; for(int i = 1; i <= 6; i++) cout << "Size " << i << ": " << size[i] << endl; return 0; } <|endoftext|>
<commit_before>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include "qpp.h" //#include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: check that everything works for expressions in ALL FILES!!!! // TODO: Error class // TODO: .template issues... using namespace std; using namespace qpp; using namespace qpp::types; //int main(int argc, char **argv) int main() { _init(); cout << "Starting qpp..." << endl; displn(rand_unitary(3)); cout << endl << "Exiting qpp..." << endl; } <commit_msg>commit<commit_after>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include "qpp.h" //#include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: check that everything works for expressions in ALL FILES!!!! // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping using namespace std; using namespace qpp; using namespace qpp::types; //int main(int argc, char **argv) int main() { _init(); cout << "Starting qpp..." << endl; displn(rand_unitary(3)); cout << endl << "Exiting qpp..." << endl; } <|endoftext|>
<commit_before>#include <iostream> #include <numeric> #include <algorithm> #include <vector> #include <map> #include <chrono> #include <memory> #include <typeinfo> #include <hpx/hpx.hpp> #include <hpx/hpx_init.hpp> #include <hpx/include/lcos.hpp> #include <hpx/include/iostreams.hpp> #include <hpx/include/serialization.hpp> #include "incumbent_component.hpp" #include "workqueue_component.hpp" #include "DimacsParser.hpp" #include "BitGraph.hpp" #include "BitSet.hpp" // 64 bit words // 8 words covers 400 vertices // Later we can specialise this at compile time #define NWORDS 8 // Forward action decls namespace graph { template<unsigned n_words_> auto maxcliqueTask(const BitGraph<n_words_> graph, hpx::naming::id_type incumbent, std::vector<unsigned> c, BitSet<n_words_> p, hpx::naming::id_type promise) -> void; std::atomic<int> globalBound(0); // Atomically update the global bound auto updateBound(int newBound) -> void { while(true) { auto curBnd = globalBound.load(); if (newBound < curBnd) { break; } if (globalBound.compare_exchange_weak(curBnd, newBound)) { break; } } } } HPX_PLAIN_ACTION(graph::maxcliqueTask<NWORDS>, maxcliqueTask400Action) HPX_PLAIN_ACTION(graph::updateBound, updateBoundAction) // For distributed promises HPX_REGISTER_ACTION(hpx::lcos::base_lco_with_value<int>::set_value_action, set_value_action_int); namespace graph { // Order a graphFromFile and return an ordered graph alongside a map to invert // the vertex numbering at the end. template<unsigned n_words_> auto orderGraphFromFile(const dimacs::GraphFromFile & g, std::map<int,int> & inv) -> BitGraph<n_words_> { std::vector<int> order(g.first); std::iota(order.begin(), order.end(), 0); // Order by degree, tie break on number std::vector<int> degrees; std::transform(order.begin(), order.end(), std::back_inserter(degrees), [&] (int v) { return g.second.find(v)->second.size(); }); std::sort(order.begin(), order.end(), [&] (int a, int b) { return ! (degrees[a] < degrees[b] || (degrees[a] == degrees[b] && a > b)); }); // Construct a new graph with this new ordering BitGraph<n_words_> graph; graph.resize(g.first); for (unsigned i = 0 ; i < g.first ; ++i) for (unsigned j = 0 ; j < g.first ; ++j) if (g.second.find(order[i])->second.count(order[j])) graph.add_edge(i, j); // Create inv map (maybe just return order?) for (int i = 0; i < order.size(); i++) { inv[i] = order[i]; } return graph; } template<unsigned n_words_> auto colour_class_order(const BitGraph<n_words_> & graph, const BitSet<n_words_> & p, std::array<unsigned, n_words_ * bits_per_word> & p_order, std::array<unsigned, n_words_ * bits_per_word> & p_bounds) -> void { BitSet<n_words_> p_left = p; // not coloured yet unsigned colour = 0; // current colour unsigned i = 0; // position in p_bounds // while we've things left to colour while (! p_left.empty()) { // next colour ++colour; // things that can still be given this colour BitSet<n_words_> q = p_left; // while we can still give something this colour while (! q.empty()) { // first thing we can colour int v = q.first_set_bit(); p_left.unset(v); q.unset(v); // can't give anything adjacent to this the same colour graph.intersect_with_row_complement(v, q); // record in result p_bounds[i] = colour; p_order[i] = v; ++i; } } } template <unsigned n_words_> auto expand(const BitGraph<n_words_> & graph, const hpx::naming::id_type & incumbent, std::vector<unsigned> & c, BitSet<n_words_> & p) -> void { // initial colouring std::array<unsigned, n_words_ * bits_per_word> p_order; std::array<unsigned, n_words_ * bits_per_word> p_bounds; colour_class_order(graph, p, p_order, p_bounds); // for each v in p... (v comes later) for (int n = p.popcount() - 1 ; n >= 0 ; --n) { auto bnd = globalBound.load(); if (c.size() + p_bounds[n] <= bnd) return; auto v = p_order[n]; // consider taking v c.push_back(v); // filter p to contain vertices adjacent to v BitSet<n_words_> new_p = p; graph.intersect_with_row(v, new_p); if (new_p.empty()) { if (c.size() > bnd) { std::set<int> members; for (auto & v : c) { members.insert(v); } // Fire and forget updates hpx::apply<globalBound::incumbent::updateBound_action>(incumbent, c.size(), members); hpx::async<updateBoundAction>(hpx::find_here(), c.size()).get(); } } else { expand(graph, incumbent, c, new_p); } // now consider not taking v c.pop_back(); p.unset(v); } } template<unsigned n_words_> auto runMaxClique(const BitGraph<n_words_> & graph, hpx::naming::id_type incumbent, hpx::naming::id_type workqueue) -> void { BitSet<n_words_> p; p.resize(graph.size()); p.set_all(); // Spawn top level only (for now) std::array<unsigned, n_words_ * bits_per_word> p_order; std::array<unsigned, n_words_ * bits_per_word> p_bounds; colour_class_order(graph, p, p_order, p_bounds); std::vector<std::shared_ptr<hpx::promise<int>>> promises; std::vector<hpx::future<int>> futures; for (int n = p.popcount() - 1 ; n >= 0 ; --n) { std::vector<unsigned> c; c.reserve(graph.size()); auto v = p_order[n]; c.push_back(v); // filter p to contain vertices adjacent to v BitSet<n_words_> new_p = p; graph.intersect_with_row(v, new_p); if (new_p.empty()) { auto bnd = hpx::async<globalBound::incumbent::getBound_action>(incumbent).get(); if (c.size() > bnd) { std::set<int> members; for (auto & v : c) { members.insert(v); } hpx::apply<globalBound::incumbent::updateBound_action>(incumbent, c.size(), members); } } else { // This spawning isn't quite right, need to avoid spawning duplicates. // Spawn it as a new task auto promise = std::shared_ptr<hpx::promise<int>>(new hpx::promise<int>()); auto f = promise->get_future(); auto promise_id = promise->get_id(); promises.push_back(std::move(promise)); futures.push_back(std::move(f)); hpx::util::function<void(hpx::naming::id_type)> task = hpx::util::bind(maxcliqueTask400Action(), _1, graph, incumbent, c, new_p, promise_id); hpx::apply<workstealing::workqueue::addWork_action>(workqueue, task); c.pop_back(); p.unset(v); } } hpx::wait_all(futures); } template<unsigned n_words_> void maxcliqueTask(const BitGraph<n_words_> graph, hpx::naming::id_type incumbent, std::vector<unsigned> c, BitSet<n_words_> p, hpx::naming::id_type promise) { expand(graph, incumbent, c, p); hpx::apply<hpx::lcos::base_lco_with_value<int>::set_value_action>(promise, 1); return; } } void scheduler(hpx::naming::id_type workqueue) { auto threads = hpx::get_os_thread_count() == 1 ? 1 : hpx::get_os_thread_count() - 1; hpx::threads::executors::local_queue_executor scheduler(threads); // Debugging std::cout << "Running with: " << threads << " scheduler threads" << std::endl; bool running = true; while (running) { auto pending = scheduler.num_pending_closures(); if (pending < threads) { auto task = hpx::async<workstealing::workqueue::steal_action>(workqueue).get(); if (task) { auto t = hpx::util::bind(task, hpx::find_here()); scheduler.add(t); } } else { hpx::this_thread::suspend(); } } } int hpx_main(int argc, char* argv[]) { if (2 != argc) { std::cout << "Usage: " << argv[0] << " file" << std::endl; hpx::finalize(); return EXIT_FAILURE; } auto gFile = dimacs::read_dimacs(std::string(argv[1])); // Order the graph (keep a hold of the map) std::map<int, int> invMap; auto graph = graph::orderGraphFromFile<NWORDS>(gFile, invMap); // Run Maxclique auto incumbent = hpx::new_<globalBound::incumbent>(hpx::find_here()).get(); auto workqueue = hpx::new_<workstealing::workqueue>(hpx::find_here()).get(); // Start a scheduler threads hpx::apply(scheduler, workqueue); auto start_time = std::chrono::steady_clock::now(); graph::runMaxClique(graph, incumbent, workqueue); auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - start_time); // Output result hpx::cout << "Size: " << hpx::async<globalBound::incumbent::getBound_action>(incumbent).get() << hpx::endl; auto members = hpx::async<globalBound::incumbent::getMembers_action>(incumbent).get(); hpx::cout << "Members: " << hpx::endl; for (auto const& m : members) { hpx::cout << invMap[m] + 1 << " "; } hpx::cout << hpx::endl << hpx::flush; hpx::cout << "cpu = " << overall_time.count() << std::endl; // TODO: A nicer termination //hpx::finalize(); hpx::this_thread::suspend(2000); hpx::terminate(); } int main (int argc, char* argv[]) { return hpx::init(argc, argv); } <commit_msg>Have update bounds force updates on all nodes<commit_after>#include <iostream> #include <numeric> #include <algorithm> #include <vector> #include <map> #include <chrono> #include <memory> #include <typeinfo> #include <hpx/hpx.hpp> #include <hpx/hpx_init.hpp> #include <hpx/include/lcos.hpp> #include <hpx/include/iostreams.hpp> #include <hpx/include/serialization.hpp> #include "incumbent_component.hpp" #include "workqueue_component.hpp" #include "DimacsParser.hpp" #include "BitGraph.hpp" #include "BitSet.hpp" // 64 bit words // 8 words covers 400 vertices // Later we can specialise this at compile time #define NWORDS 8 // Forward action decls namespace graph { template<unsigned n_words_> auto maxcliqueTask(const BitGraph<n_words_> graph, hpx::naming::id_type incumbent, std::vector<unsigned> c, BitSet<n_words_> p, hpx::naming::id_type promise) -> void; std::atomic<int> globalBound(0); auto updateBound(int newBound) -> void; } HPX_PLAIN_ACTION(graph::maxcliqueTask<NWORDS>, maxcliqueTask400Action) HPX_PLAIN_ACTION(graph::updateBound, updateBoundAction) // For distributed promises HPX_REGISTER_ACTION(hpx::lcos::base_lco_with_value<int>::set_value_action, set_value_action_int); namespace graph { // Order a graphFromFile and return an ordered graph alongside a map to invert // the vertex numbering at the end. template<unsigned n_words_> auto orderGraphFromFile(const dimacs::GraphFromFile & g, std::map<int,int> & inv) -> BitGraph<n_words_> { std::vector<int> order(g.first); std::iota(order.begin(), order.end(), 0); // Order by degree, tie break on number std::vector<int> degrees; std::transform(order.begin(), order.end(), std::back_inserter(degrees), [&] (int v) { return g.second.find(v)->second.size(); }); std::sort(order.begin(), order.end(), [&] (int a, int b) { return ! (degrees[a] < degrees[b] || (degrees[a] == degrees[b] && a > b)); }); // Construct a new graph with this new ordering BitGraph<n_words_> graph; graph.resize(g.first); for (unsigned i = 0 ; i < g.first ; ++i) for (unsigned j = 0 ; j < g.first ; ++j) if (g.second.find(order[i])->second.count(order[j])) graph.add_edge(i, j); // Create inv map (maybe just return order?) for (int i = 0; i < order.size(); i++) { inv[i] = order[i]; } return graph; } template<unsigned n_words_> auto colour_class_order(const BitGraph<n_words_> & graph, const BitSet<n_words_> & p, std::array<unsigned, n_words_ * bits_per_word> & p_order, std::array<unsigned, n_words_ * bits_per_word> & p_bounds) -> void { BitSet<n_words_> p_left = p; // not coloured yet unsigned colour = 0; // current colour unsigned i = 0; // position in p_bounds // while we've things left to colour while (! p_left.empty()) { // next colour ++colour; // things that can still be given this colour BitSet<n_words_> q = p_left; // while we can still give something this colour while (! q.empty()) { // first thing we can colour int v = q.first_set_bit(); p_left.unset(v); q.unset(v); // can't give anything adjacent to this the same colour graph.intersect_with_row_complement(v, q); // record in result p_bounds[i] = colour; p_order[i] = v; ++i; } } } template <unsigned n_words_> auto expand(const BitGraph<n_words_> & graph, const hpx::naming::id_type & incumbent, std::vector<unsigned> & c, BitSet<n_words_> & p) -> void { // initial colouring std::array<unsigned, n_words_ * bits_per_word> p_order; std::array<unsigned, n_words_ * bits_per_word> p_bounds; colour_class_order(graph, p, p_order, p_bounds); // for each v in p... (v comes later) for (int n = p.popcount() - 1 ; n >= 0 ; --n) { auto bnd = globalBound.load(); if (c.size() + p_bounds[n] <= bnd) return; auto v = p_order[n]; // consider taking v c.push_back(v); // filter p to contain vertices adjacent to v BitSet<n_words_> new_p = p; graph.intersect_with_row(v, new_p); if (new_p.empty()) { if (c.size() > bnd) { std::set<int> members; for (auto & v : c) { members.insert(v); } // Fire and forget updates hpx::apply<globalBound::incumbent::updateBound_action>(incumbent, c.size(), members); hpx::async<updateBoundAction>(hpx::find_here(), c.size()).get(); } } else { expand(graph, incumbent, c, new_p); } // now consider not taking v c.pop_back(); p.unset(v); } } template<unsigned n_words_> auto runMaxClique(const BitGraph<n_words_> & graph, hpx::naming::id_type incumbent, hpx::naming::id_type workqueue) -> void { BitSet<n_words_> p; p.resize(graph.size()); p.set_all(); // Spawn top level only (for now) std::array<unsigned, n_words_ * bits_per_word> p_order; std::array<unsigned, n_words_ * bits_per_word> p_bounds; colour_class_order(graph, p, p_order, p_bounds); std::vector<std::shared_ptr<hpx::promise<int>>> promises; std::vector<hpx::future<int>> futures; for (int n = p.popcount() - 1 ; n >= 0 ; --n) { std::vector<unsigned> c; c.reserve(graph.size()); auto v = p_order[n]; c.push_back(v); // filter p to contain vertices adjacent to v BitSet<n_words_> new_p = p; graph.intersect_with_row(v, new_p); if (new_p.empty()) { auto bnd = hpx::async<globalBound::incumbent::getBound_action>(incumbent).get(); if (c.size() > bnd) { std::set<int> members; for (auto & v : c) { members.insert(v); } hpx::apply<globalBound::incumbent::updateBound_action>(incumbent, c.size(), members); } } else { // This spawning isn't quite right, need to avoid spawning duplicates. // Spawn it as a new task auto promise = std::shared_ptr<hpx::promise<int>>(new hpx::promise<int>()); auto f = promise->get_future(); auto promise_id = promise->get_id(); promises.push_back(std::move(promise)); futures.push_back(std::move(f)); hpx::util::function<void(hpx::naming::id_type)> task = hpx::util::bind(maxcliqueTask400Action(), _1, graph, incumbent, c, new_p, promise_id); hpx::apply<workstealing::workqueue::addWork_action>(workqueue, task); c.pop_back(); p.unset(v); } } hpx::wait_all(futures); } template<unsigned n_words_> void maxcliqueTask(const BitGraph<n_words_> graph, hpx::naming::id_type incumbent, std::vector<unsigned> c, BitSet<n_words_> p, hpx::naming::id_type promise) { expand(graph, incumbent, c, p); hpx::apply<hpx::lcos::base_lco_with_value<int>::set_value_action>(promise, 1); return; } // Atomically update the global bound on all localities auto updateBound(int newBound) -> void { while(true) { auto curBnd = globalBound.load(); if (newBound < curBnd) { break; } if (globalBound.compare_exchange_weak(curBnd, newBound)) { break; } } // Broadcast it by pushing work items to all other nodes auto localities = hpx::find_all_localities(); for (auto const & node : localities) { hpx::apply<updateBoundAction>(node, newBound); } } } void scheduler(hpx::naming::id_type workqueue) { auto threads = hpx::get_os_thread_count() == 1 ? 1 : hpx::get_os_thread_count() - 1; hpx::threads::executors::local_queue_executor scheduler(threads); // Debugging std::cout << "Running with: " << threads << " scheduler threads" << std::endl; bool running = true; while (running) { auto pending = scheduler.num_pending_closures(); if (pending < threads) { auto task = hpx::async<workstealing::workqueue::steal_action>(workqueue).get(); if (task) { auto t = hpx::util::bind(task, hpx::find_here()); scheduler.add(t); } } else { hpx::this_thread::suspend(); } } } int hpx_main(int argc, char* argv[]) { if (2 != argc) { std::cout << "Usage: " << argv[0] << " file" << std::endl; hpx::finalize(); return EXIT_FAILURE; } auto gFile = dimacs::read_dimacs(std::string(argv[1])); // Order the graph (keep a hold of the map) std::map<int, int> invMap; auto graph = graph::orderGraphFromFile<NWORDS>(gFile, invMap); // Run Maxclique auto incumbent = hpx::new_<globalBound::incumbent>(hpx::find_here()).get(); auto workqueue = hpx::new_<workstealing::workqueue>(hpx::find_here()).get(); // Start a scheduler threads hpx::apply(scheduler, workqueue); auto start_time = std::chrono::steady_clock::now(); graph::runMaxClique(graph, incumbent, workqueue); auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - start_time); // Output result hpx::cout << "Size: " << hpx::async<globalBound::incumbent::getBound_action>(incumbent).get() << hpx::endl; auto members = hpx::async<globalBound::incumbent::getMembers_action>(incumbent).get(); hpx::cout << "Members: " << hpx::endl; for (auto const& m : members) { hpx::cout << invMap[m] + 1 << " "; } hpx::cout << hpx::endl << hpx::flush; hpx::cout << "cpu = " << overall_time.count() << std::endl; // TODO: A nicer termination //hpx::finalize(); hpx::this_thread::suspend(2000); hpx::terminate(); } int main (int argc, char* argv[]) { return hpx::init(argc, argv); } <|endoftext|>
<commit_before>#include <GLFW/glfw3.h> #include "PhysSystem.h" #include "microprofile/microprofile.h" #include "microprofile/microprofileui.h" struct Vertex { Vector2f position; unsigned char r, g, b, a; }; void RenderBox(std::vector<Vertex>& vertices, Coords2f coords, Vector2f size, int r, int g, int b, int a) { Vector2f axisX = coords.xVector * size.x; Vector2f axisY = coords.yVector * size.y; Vertex v; v.r = r; v.g = g; v.b = b; v.a = a; v.position = coords.pos - axisX - axisY; vertices.push_back(v); v.position = coords.pos + axisX - axisY; vertices.push_back(v); v.position = coords.pos + axisX + axisY; vertices.push_back(v); v.position = coords.pos - axisX + axisY; vertices.push_back(v); } float random(float min, float max) { return min + (max - min) * (float(rand()) / float(RAND_MAX)); } const struct { PhysSystem::SolveMode mode; const char* name; } kModes[] = { {PhysSystem::Solve_Baseline, "Baseline"}, {PhysSystem::Solve_AoS, "AoS"}, {PhysSystem::Solve_SoA_Scalar, "SoA Scalar"}, {PhysSystem::Solve_SoA_SSE2, "SoA SSE2"}, #ifdef __AVX2__ {PhysSystem::Solve_SoA_AVX2, "SoA AVX2"}, #endif {PhysSystem::Solve_SoAPacked_Scalar, "SoA Packed Scalar"}, {PhysSystem::Solve_SoAPacked_SSE2, "SoA Packed SSE2"}, #ifdef __AVX2__ {PhysSystem::Solve_SoAPacked_AVX2, "SoA Packed AVX2"}, #endif #if defined(__AVX2__) && defined(__FMA__) {PhysSystem::Solve_SoAPacked_FMA, "SoA Packed FMA"}, #endif }; bool keyPressed[GLFW_KEY_LAST + 1]; int mouseScrollDelta = 0; static void errorCallback(int error, const char* description) { fputs(description, stderr); } static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { keyPressed[key] = (action == GLFW_PRESS); } static void scrollCallback(GLFWwindow* window, double x, double y) { mouseScrollDelta = y; } void MicroProfileDrawInit(); void MicroProfileBeginDraw(); void MicroProfileEndDraw(); int main(int argc, char** argv) { MicroProfileOnThreadCreate("Main"); int windowWidth = 1280, windowHeight = 1024; std::unique_ptr<WorkQueue> queue(new WorkQueue(WorkQueue::getIdealWorkerCount())); PhysSystem physSystem; RigidBody* groundBody = physSystem.AddBody(Coords2f(Vector2f(0, 0), 0.0f), Vector2f(10000.f, 10.0f)); groundBody->invInertia = 0.0f; groundBody->invMass = 0.0f; int currentMode = sizeof(kModes) / sizeof(kModes[0]) - 1; const float gravity = -200.0f; const float integrationTime = 1 / 60.f; const int contactIterationsCount = 15; const int penetrationIterationsCount = 15; physSystem.gravity = gravity; physSystem.AddBody(Coords2f(Vector2f(-500, 500), 0.0f), Vector2f(30.0f, 30.0f)); float bodyRadius = 2.f; int bodyCount = 20000; for (int bodyIndex = 0; bodyIndex < bodyCount; bodyIndex++) { Vector2f pos = Vector2f(random(-500.0f, 500.0f), random(50.f, 1000.0f)); Vector2f size(bodyRadius * 2.f, bodyRadius * 2.f); physSystem.AddBody(Coords2f(pos, 0.f), size); } if (argc > 1 && strcmp(argv[1], "profile") == 0) { for (int mode = 0; mode < sizeof(kModes) / sizeof(kModes[0]); ++mode) { PhysSystem testSystem; testSystem.gravity = gravity; for (auto& body: physSystem.bodies) { RigidBody* testBody = testSystem.AddBody(body.coords, body.geom.size); testBody->invInertia = body.invInertia; testBody->invMass = body.invMass; } double collisionTime = 0; double mergeTime = 0; double solveTime = 0; float iterations = 0; for (int i = 0; i < 50; ++i) { testSystem.Update(*queue, 1.f / 30.f, kModes[mode].mode, contactIterationsCount, penetrationIterationsCount); collisionTime += testSystem.collisionTime; mergeTime += testSystem.mergeTime; solveTime += testSystem.solveTime; iterations += testSystem.iterations; } printf("%s: collision %.2f ms, merge %.2f ms, solve %.2f ms, %.2f iterations\n", kModes[mode].name, collisionTime * 1000, mergeTime * 1000, solveTime * 1000, iterations); } return 0; } glfwSetErrorCallback(errorCallback); if (!glfwInit()) return 1; GLFWwindow* window = glfwCreateWindow(windowWidth, windowHeight, "PhyX", NULL, NULL); if (!window) return 1; glfwMakeContextCurrent(window); glfwSwapInterval(0); glfwSetKeyCallback(window, keyCallback); glfwSetScrollCallback(window, scrollCallback); MicroProfileDrawInit(); MicroProfileToggleDisplayMode(); double prevUpdateTime = 0.0f; std::vector<Vertex> vertices; while (!glfwWindowShouldClose(window)) { MICROPROFILE_SCOPEI("MAIN", "Frame", 0xffee00); int width, height; glfwGetWindowSize(window, &width, &height); int frameWidth, frameHeight; glfwGetFramebufferSize(window, &frameWidth, &frameHeight); double mouseX, mouseY; glfwGetCursorPos(window, &mouseX, &mouseY); glViewport(0, 0, frameWidth, frameHeight); glClearColor(0.2f, 0.2f, 0.2f, 1.f); glClear(GL_COLOR_BUFFER_BIT); float offsetx = -width / 2; float offsety = -40; float scale = 0.5f; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(offsetx / scale, width / scale + offsetx / scale, offsety / scale, height / scale + offsety / scale, 1.f, -1.f); vertices.clear(); if (glfwGetTime() > prevUpdateTime + integrationTime) { prevUpdateTime += integrationTime; float time = integrationTime; Vector2f mousePos = Vector2f(mouseX + offsetx, height + offsety - mouseY) / scale; RigidBody* draggedBody = &physSystem.bodies[1]; Vector2f dstVelocity = (mousePos - draggedBody->coords.pos) * 5e1f; draggedBody->acceleration += (dstVelocity - draggedBody->velocity) * 5e0; physSystem.Update(*queue, time, kModes[currentMode].mode, contactIterationsCount, penetrationIterationsCount); } { MICROPROFILE_SCOPEI("Render", "Prepare", 0xff0000); for (size_t bodyIndex = 0; bodyIndex < physSystem.bodies.size(); bodyIndex++) { RigidBody* body = &physSystem.bodies[bodyIndex]; Coords2f bodyCoords = body->coords; Vector2f size = body->geom.size; float colorMult = float(bodyIndex) / float(physSystem.bodies.size()) * 0.5f + 0.5f; int r = 50 * colorMult; int g = 125 * colorMult; int b = 218 * colorMult; if (bodyIndex == 1) //dragged body { r = 242; g = 236; b = 164; } RenderBox(vertices, bodyCoords, size, r, g, b, 255); } if (glfwGetKey(window, GLFW_KEY_V)) { for (size_t manifoldIndex = 0; manifoldIndex < physSystem.collider.manifolds.size(); manifoldIndex++) { Manifold& man = physSystem.collider.manifolds[manifoldIndex]; for (int collisionNumber = 0; collisionNumber < man.collisionsCount; collisionNumber++) { Coords2f coords = Coords2f(Vector2f(0.0f, 0.0f), 3.1415f / 4.0f); coords.pos = man.body1->coords.pos + man.collisions[collisionNumber].delta1; float redMult = man.collisions[collisionNumber].isNewlyCreated ? 0.5f : 1.0f; RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 100, 100 * redMult, 100 * redMult, 100); coords.pos = man.body2->coords.pos + man.collisions[collisionNumber].delta2; RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 150, 150 * redMult, 150 * redMult, 100); } } } } { MICROPROFILE_SCOPEI("Render", "Perform", 0xff0000); if (!vertices.empty()) { glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &vertices[0].position); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &vertices[0].r); glDrawArrays(GL_QUADS, 0, vertices.size()); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } } //MICROPROFILEUI_API void MicroProfileDrawText(int nX, int nY, uint32_t nColor, const char* pText, uint32_t nNumCharacters); /* << "Bodies: " << physSystem.bodies.size() << " Contacts: " << physSystem.solver.contactJoints.size() << " Iterations: " << physSystem.iterations; << queue->getWorkerCount() << " cores; " << "Mode: " << kModes[currentMode].name << "; " << "Physics time: " << std::setw(5) << physicsTime * 1000.0f << "ms (c: " << std::setw(5) << physSystem.collisionTime * 1000.0f << "ms, m: " << std::setw(5) << physSystem.mergeTime * 1000.0f << "ms, s: " << std::setw(5) << physSystem.solveTime * 1000.0f << "ms)"; */ MicroProfileFlip(); { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, width, height, 0, 1.f, -1.f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); MicroProfileBeginDraw(); MicroProfileDraw(width, height); MicroProfileEndDraw(); glDisable(GL_BLEND); } { MICROPROFILE_SCOPEI("MAIN", "Flip", 0xffee00); glfwSwapBuffers(window); } { MICROPROFILE_SCOPEI("MAIN", "Input", 0xffee00); // Handle input memset(keyPressed, 0, sizeof(keyPressed)); mouseScrollDelta = 0; glfwPollEvents(); bool mouseDown0 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; bool mouseDown1 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS; MicroProfileMouseButton(mouseDown0, mouseDown1); MicroProfileMousePosition(mouseX, mouseY, mouseScrollDelta); MicroProfileModKey(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS); if (keyPressed[GLFW_KEY_ESCAPE]) break; if (keyPressed[GLFW_KEY_O]) MicroProfileToggleDisplayMode(); if (keyPressed[GLFW_KEY_P]) MicroProfileTogglePause(); if (keyPressed[GLFW_KEY_M]) currentMode = (currentMode + 1) % (sizeof(kModes) / sizeof(kModes[0])); if (keyPressed[GLFW_KEY_C]) { size_t workers = (queue->getWorkerCount() == WorkQueue::getIdealWorkerCount()) ? 1 : std::min(queue->getWorkerCount() * 2, WorkQueue::getIdealWorkerCount()); queue.reset(new WorkQueue(workers)); } } } glfwDestroyWindow(window); glfwTerminate(); }<commit_msg>Add stats display back<commit_after>#include <GLFW/glfw3.h> #include "PhysSystem.h" #include "microprofile/microprofile.h" #include "microprofile/microprofileui.h" struct Vertex { Vector2f position; unsigned char r, g, b, a; }; void RenderBox(std::vector<Vertex>& vertices, Coords2f coords, Vector2f size, int r, int g, int b, int a) { Vector2f axisX = coords.xVector * size.x; Vector2f axisY = coords.yVector * size.y; Vertex v; v.r = r; v.g = g; v.b = b; v.a = a; v.position = coords.pos - axisX - axisY; vertices.push_back(v); v.position = coords.pos + axisX - axisY; vertices.push_back(v); v.position = coords.pos + axisX + axisY; vertices.push_back(v); v.position = coords.pos - axisX + axisY; vertices.push_back(v); } float random(float min, float max) { return min + (max - min) * (float(rand()) / float(RAND_MAX)); } const struct { PhysSystem::SolveMode mode; const char* name; } kModes[] = { {PhysSystem::Solve_Baseline, "Baseline"}, {PhysSystem::Solve_AoS, "AoS"}, {PhysSystem::Solve_SoA_Scalar, "SoA Scalar"}, {PhysSystem::Solve_SoA_SSE2, "SoA SSE2"}, #ifdef __AVX2__ {PhysSystem::Solve_SoA_AVX2, "SoA AVX2"}, #endif {PhysSystem::Solve_SoAPacked_Scalar, "SoA Packed Scalar"}, {PhysSystem::Solve_SoAPacked_SSE2, "SoA Packed SSE2"}, #ifdef __AVX2__ {PhysSystem::Solve_SoAPacked_AVX2, "SoA Packed AVX2"}, #endif #if defined(__AVX2__) && defined(__FMA__) {PhysSystem::Solve_SoAPacked_FMA, "SoA Packed FMA"}, #endif }; bool keyPressed[GLFW_KEY_LAST + 1]; int mouseScrollDelta = 0; static void errorCallback(int error, const char* description) { fputs(description, stderr); } static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { keyPressed[key] = (action == GLFW_PRESS); } static void scrollCallback(GLFWwindow* window, double x, double y) { mouseScrollDelta = y; } void MicroProfileDrawInit(); void MicroProfileBeginDraw(); void MicroProfileEndDraw(); int main(int argc, char** argv) { MicroProfileOnThreadCreate("Main"); int windowWidth = 1280, windowHeight = 1024; std::unique_ptr<WorkQueue> queue(new WorkQueue(WorkQueue::getIdealWorkerCount())); PhysSystem physSystem; RigidBody* groundBody = physSystem.AddBody(Coords2f(Vector2f(0, 0), 0.0f), Vector2f(10000.f, 10.0f)); groundBody->invInertia = 0.0f; groundBody->invMass = 0.0f; int currentMode = sizeof(kModes) / sizeof(kModes[0]) - 1; const float gravity = -200.0f; const float integrationTime = 1 / 60.f; const int contactIterationsCount = 15; const int penetrationIterationsCount = 15; physSystem.gravity = gravity; physSystem.AddBody(Coords2f(Vector2f(-500, 500), 0.0f), Vector2f(30.0f, 30.0f)); float bodyRadius = 2.f; int bodyCount = 20000; for (int bodyIndex = 0; bodyIndex < bodyCount; bodyIndex++) { Vector2f pos = Vector2f(random(-500.0f, 500.0f), random(50.f, 1000.0f)); Vector2f size(bodyRadius * 2.f, bodyRadius * 2.f); physSystem.AddBody(Coords2f(pos, 0.f), size); } if (argc > 1 && strcmp(argv[1], "profile") == 0) { for (int mode = 0; mode < sizeof(kModes) / sizeof(kModes[0]); ++mode) { PhysSystem testSystem; testSystem.gravity = gravity; for (auto& body: physSystem.bodies) { RigidBody* testBody = testSystem.AddBody(body.coords, body.geom.size); testBody->invInertia = body.invInertia; testBody->invMass = body.invMass; } double collisionTime = 0; double mergeTime = 0; double solveTime = 0; float iterations = 0; for (int i = 0; i < 50; ++i) { testSystem.Update(*queue, 1.f / 30.f, kModes[mode].mode, contactIterationsCount, penetrationIterationsCount); collisionTime += testSystem.collisionTime; mergeTime += testSystem.mergeTime; solveTime += testSystem.solveTime; iterations += testSystem.iterations; } printf("%s: collision %.2f ms, merge %.2f ms, solve %.2f ms, %.2f iterations\n", kModes[mode].name, collisionTime * 1000, mergeTime * 1000, solveTime * 1000, iterations); } return 0; } glfwSetErrorCallback(errorCallback); if (!glfwInit()) return 1; GLFWwindow* window = glfwCreateWindow(windowWidth, windowHeight, "PhyX", NULL, NULL); if (!window) return 1; glfwMakeContextCurrent(window); glfwSwapInterval(0); glfwSetKeyCallback(window, keyCallback); glfwSetScrollCallback(window, scrollCallback); MicroProfileDrawInit(); double prevUpdateTime = 0.0f; std::vector<Vertex> vertices; while (!glfwWindowShouldClose(window)) { MICROPROFILE_SCOPEI("MAIN", "Frame", 0xffee00); int width, height; glfwGetWindowSize(window, &width, &height); int frameWidth, frameHeight; glfwGetFramebufferSize(window, &frameWidth, &frameHeight); double mouseX, mouseY; glfwGetCursorPos(window, &mouseX, &mouseY); glViewport(0, 0, frameWidth, frameHeight); glClearColor(0.2f, 0.2f, 0.2f, 1.f); glClear(GL_COLOR_BUFFER_BIT); float offsetx = -width / 2; float offsety = -40; float scale = 0.5f; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(offsetx / scale, width / scale + offsetx / scale, offsety / scale, height / scale + offsety / scale, 1.f, -1.f); vertices.clear(); if (glfwGetTime() > prevUpdateTime + integrationTime) { prevUpdateTime += integrationTime; float time = integrationTime; Vector2f mousePos = Vector2f(mouseX + offsetx, height + offsety - mouseY) / scale; RigidBody* draggedBody = &physSystem.bodies[1]; Vector2f dstVelocity = (mousePos - draggedBody->coords.pos) * 5e1f; draggedBody->acceleration += (dstVelocity - draggedBody->velocity) * 5e0; physSystem.Update(*queue, time, kModes[currentMode].mode, contactIterationsCount, penetrationIterationsCount); } { MICROPROFILE_SCOPEI("Render", "Prepare", 0xff0000); for (size_t bodyIndex = 0; bodyIndex < physSystem.bodies.size(); bodyIndex++) { RigidBody* body = &physSystem.bodies[bodyIndex]; Coords2f bodyCoords = body->coords; Vector2f size = body->geom.size; float colorMult = float(bodyIndex) / float(physSystem.bodies.size()) * 0.5f + 0.5f; int r = 50 * colorMult; int g = 125 * colorMult; int b = 218 * colorMult; if (bodyIndex == 1) //dragged body { r = 242; g = 236; b = 164; } RenderBox(vertices, bodyCoords, size, r, g, b, 255); } if (glfwGetKey(window, GLFW_KEY_V)) { for (size_t manifoldIndex = 0; manifoldIndex < physSystem.collider.manifolds.size(); manifoldIndex++) { Manifold& man = physSystem.collider.manifolds[manifoldIndex]; for (int collisionNumber = 0; collisionNumber < man.collisionsCount; collisionNumber++) { Coords2f coords = Coords2f(Vector2f(0.0f, 0.0f), 3.1415f / 4.0f); coords.pos = man.body1->coords.pos + man.collisions[collisionNumber].delta1; float redMult = man.collisions[collisionNumber].isNewlyCreated ? 0.5f : 1.0f; RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 100, 100 * redMult, 100 * redMult, 100); coords.pos = man.body2->coords.pos + man.collisions[collisionNumber].delta2; RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 150, 150 * redMult, 150 * redMult, 100); } } } } { MICROPROFILE_SCOPEI("Render", "Perform", 0xff0000); if (!vertices.empty()) { glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &vertices[0].position); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &vertices[0].r); glDrawArrays(GL_QUADS, 0, vertices.size()); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } } char stats[256]; sprintf(stats, "Bodies: %d Manifolds: %d Contacts: %d | Cores: %d; Mode: %s; Iterations: %.2f", int(physSystem.bodies.size()), int(physSystem.collider.manifolds.size()), int(physSystem.solver.contactJoints.size()), int(queue->getWorkerCount()), kModes[currentMode].name, physSystem.iterations); MicroProfileFlip(); { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, width, height, 0, 1.f, -1.f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); MicroProfileBeginDraw(); MicroProfileDraw(width, height); MicroProfileDrawText(2, height - 12, 0xffffffff, stats, strlen(stats)); MicroProfileEndDraw(); glDisable(GL_BLEND); } { MICROPROFILE_SCOPEI("MAIN", "Flip", 0xffee00); glfwSwapBuffers(window); } { MICROPROFILE_SCOPEI("MAIN", "Input", 0xffee00); // Handle input memset(keyPressed, 0, sizeof(keyPressed)); mouseScrollDelta = 0; glfwPollEvents(); bool mouseDown0 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; bool mouseDown1 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS; MicroProfileMouseButton(mouseDown0, mouseDown1); MicroProfileMousePosition(mouseX, mouseY, mouseScrollDelta); MicroProfileModKey(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS); if (keyPressed[GLFW_KEY_ESCAPE]) break; if (keyPressed[GLFW_KEY_O]) MicroProfileToggleDisplayMode(); if (keyPressed[GLFW_KEY_P]) MicroProfileTogglePause(); if (keyPressed[GLFW_KEY_M]) currentMode = (currentMode + 1) % (sizeof(kModes) / sizeof(kModes[0])); if (keyPressed[GLFW_KEY_C]) { size_t workers = (queue->getWorkerCount() == WorkQueue::getIdealWorkerCount()) ? 1 : std::min(queue->getWorkerCount() * 2, WorkQueue::getIdealWorkerCount()); queue.reset(new WorkQueue(workers)); } } } glfwDestroyWindow(window); glfwTerminate(); }<|endoftext|>
<commit_before><commit_msg>add seperate all nodes by hierarchy<commit_after>// C++ program to generate long DFS traversal from a given vertex in a given graph #include <iostream> #include <list> #include <fstream> #include <string> #include <sstream> #include <vector> #include <map> using namespace std; // Pre-define hierarchy array // CUI: array of top nodes concept id of each hierarchy // ConName: array of the name of each hierarchy const long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001}; const string ConName[19] = {"Body_structure", "Clinical_finding", "Environment_or_geographical_location", "Event", "Observable_entity", "Organism", "Pharmaceutical_biologic_product", "Physical_force", "Physical_object", "Procedure", "Qualifier_value", "Record_artifact", "Situation_with_explicit_context", "SNOMED_CT_Model_Component", "Social_context", "Special_Concept", "Specimen", "Staging_and_scales", "Substance"}; // define global variables // nodeMap: store all the concepts [key,value] // reversedNodeMap: store reversed nodeMap [value,key] // nodeFile, relationFile, outputFile, as variable name std::map<long long, int> nodeMap; std::map<int, long long> reversedNodeMap; string nodeFile = "2016nodes.txt"; string relationFile = "2016relation.txt"; string outPutFolder = "/Users/zhuwei/Desktop/sct_nodes_within_hierarchy/"; std::vector<long long> outPutVec; // Graph class represents a directed graph using adjacency list representation class Graph { long long V; list<long long> *adj; void DFSUtil(long long v, bool visited[]); public: Graph(long long V); void addEdge(long long v, long long w); void DFS(long long v); }; Graph::Graph(long long V) { this->V = V; adj = new list<long long>[V]; } void Graph::addEdge(long long v, long long w) { adj[v].push_back(w); } void Graph::DFSUtil(long long v, bool visited[]) { visited[v] = true; // output to terminal // cout << reversedNodeMap[v] << " "; // output to file outPutVec.push_back(reversedNodeMap[v]); list<long long>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited); } void Graph::DFS(long long v) { bool *visited = new bool[V]; for (long long i = 0; i < V; i++) visited[i] = false; DFSUtil(v, visited); } // string split function: split(s,d) // input: s: string, d: delimiter // output: a vector of splitted strings void split(const string &s, char delim, vector<string> &elems) { stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } } vector<long long> split(const string &s, char delim) { vector<string> elems; vector<long long> res; split(s, delim, elems); for(auto i : elems){ res.push_back(std::stoll(i)); } return res; } int main() { long long topNode; // cin >> outputFile >> topNode; string sline; vector<string> relation; std::vector<string> nodes; fstream fin; fin.open(nodeFile,ios::in); while (getline(fin, sline)){ nodes.push_back(sline); } fin.close(); for (int i = 0; i < nodes.size(); ++i){ nodeMap[std::stoll(nodes[i])] = i; } for (map<long long, int>::iterator i = nodeMap.begin(); i != nodeMap.end(); ++i) reversedNodeMap[i->second] = i->first; int nodeSize = nodeMap.size(); fin.open(relationFile,ios::in); while (getline(fin, sline)){ relation.push_back(sline); } fin.close(); Graph g(nodeSize); std::vector<long long> vres; for (auto i : relation){ vres.clear(); vres = split(i, ','); g.addEdge(nodeMap[vres[1]],nodeMap[vres[0]]); } // g.addEdge(1, 2); // g.DFS(nodeMap[vres[0]]); // g.DFS(nodeMap[105590001]); string outPutFile; for (int i = 0; i < 19; ++i){ outPutVec.clear(); outPutFile.clear(); outPutFile = outPutFolder + ConName[i]; topNode = CUI[i]; g.DFS(nodeMap[topNode]); fstream fout; fout.open(outPutFile,ios::app); for (auto o : outPutVec){ fout << o << endl; } fout.close(); // cout << outPutVec.size() << endl; } return 0; }<|endoftext|>
<commit_before> #include <initializer_list> #include <iostream> #include <fstream> #include <array> #include <type_traits> #include <algorithm> #include <memory> #include <stdio.h> #include <utility> #include <vector> #include <map> #include "ast.h" #include "helpers.h" #include "llvm.h" #include "parser.h" int main(int argc, char **argv) { Llvm vm; vm.registerExtern(vm.intTy(), "printf", true); std::unique_ptr<Reader> r; std::ifstream src; if (argc == 2) { src.open(argv[1]); r.reset(new Reader(argv[1], src)); } else { r.reset(new Reader("-", std::cin)); } msg("Parse:"); std::vector<std::unique_ptr<SExpr>> toplevel; while (SExpr *e = sexpr(*r)) toplevel.emplace_back(e); msg("Compile:"); llvm::Value *last; for (auto &e : toplevel) last = e->codegen(vm); vm.builder.CreateRet(last); vm.module->dump(); std::string err; std::unique_ptr<llvm::ExecutionEngine> ee( llvm::EngineBuilder(std::move(vm.module)).setErrorStr(&err).create()); if (!ee) { std::cerr << "Could not create exe engine: " << err << std::endl; return 1; } ee->runFunction(vm.prog, {}); } <commit_msg>Add verification check for module.<commit_after> #include <initializer_list> #include <iostream> #include <fstream> #include <array> #include <type_traits> #include <algorithm> #include <memory> #include <stdio.h> #include <utility> #include <vector> #include <map> #include <llvm/IR/Verifier.h> #include "ast.h" #include "helpers.h" #include "llvm.h" #include "parser.h" int main(int argc, char **argv) { Llvm vm; vm.registerExtern(vm.intTy(), "printf", true); std::unique_ptr<Reader> r; std::ifstream src; if (argc == 2) { src.open(argv[1]); r.reset(new Reader(argv[1], src)); } else { r.reset(new Reader("-", std::cin)); } msg("Parse:"); std::vector<std::unique_ptr<SExpr>> toplevel; while (SExpr *e = sexpr(*r)) toplevel.emplace_back(e); msg("Compile:"); llvm::Value *last; for (auto &e : toplevel) last = e->codegen(vm); vm.builder.CreateRet(last); vm.module->dump(); if (!llvm::verifyModule(*vm.module)) return 1; std::string err; std::unique_ptr<llvm::ExecutionEngine> ee( llvm::EngineBuilder(std::move(vm.module)).setErrorStr(&err).create()); if (!ee) { std::cerr << "Could not create exe engine: " << err << std::endl; return 1; } ee->runFunction(vm.prog, {}); } <|endoftext|>
<commit_before>#include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <limits> #include <string> #include <utility> #include <vector> #include "closestPairInLine.hpp" #include "cmdline.h" #define WIDTH 28 #define HEIGHT 28 #define TRY_TIME 100 using namespace std; int d, n; string path; cmdline::parser p; short s[60020][800] = {0}; double ans; int cpx, cpy; vector<double> line; vector<pair<double, int>> pos; void setCmdParser() { // -n command p.add<int>("number", 'n', "the number of images", true, 0); // -d command p.add<int>("dimensions", 'd', "the dimensions of images", true, 0); // -f command p.add<string>("file", 'f', "the path to dataset", true, ""); } void readDataset(int n, int d, string path) { ifstream input(path); if (!input.is_open()) { cout << "input file doesn't exist!" << endl; exit(0); } for (int w = 1; w <= n; w++) { int i, j; input >> i; for (j = 1; j <= d; j++) input >> s[i][j]; } } void printImage(int x) { for (int i = 1; i <= HEIGHT; i++) { for (int j = 1; j <= WIDTH; j++) if (s[x][(i - 1) * 28 + j] == 0) cout << '*'; else cout << ' '; cout << '\n'; } } double getStandardNormalDistribution() { const double epsilon = numeric_limits<double>::min(); const double twoPi = 2.0 * 3.14159265358979323846; double x, y, flag; do { x = rand() * (1.0 / RAND_MAX); y = rand() * (1.0 / RAND_MAX); flag = rand() * (1.0 / RAND_MAX); } while (x <= epsilon); if (flag > 0.5) return sqrt(-2.0 * log(x)) * cos(twoPi * y); else return sqrt(-2.0 * log(x)) * sin(twoPi * y); } void getRandomLine(int d) { line.clear(); for (int i = 1; i <= d; i++) { line.push_back(getStandardNormalDistribution() * 1000); } } double euclideanDistance(int x, int y, int d) { double ans = 0; for (int i = 1; i <= d; i++) { ans = ans + (s[x][i] - s[y][i]) * (s[x][i] - s[y][i]); } return ans; } void findClosestPair(int flag) { for (int k = 1; k <= TRY_TIME; k++) { getRandomLine(d); pos.clear(); for (int i = 1; i <= n; i++) { double temp = 0; for (int j = 1; j <= d; j++) temp = temp + s[i][j] * line[j - 1]; pos.push_back(make_pair(temp, i)); } pair<int, int> p = getClosestPairInLine(n, flag); double temp = euclideanDistance(p.first, p.second, d); if (temp < ans || ans < 0) { ans = temp; cpx = p.first; cpy = p.second; } } } int main(int argc, char* argv[]) { setCmdParser(); p.parse_check(argc, argv); // get arguments n = p.get<int>("number"); d = p.get<int>("dimensions"); path = p.get<string>("file"); readDataset(n, d, path); srand(time(NULL)); ans = -1; findClosestPair(PIVOT_FLAG); //findClosestPair(MEDIAN_FLAG); cout << "Closest Pair is Image No." << cpx << " and Image No." << cpy << endl; cout << "Image No." << cpx << endl; printImage(cpx); cout << "Image No." << cpy << endl; printImage(cpy); return 0; } <commit_msg>fix bug<commit_after>#include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <limits> #include <string> #include <utility> #include <vector> #include "closestPairInLine.hpp" #include "cmdline.h" #define WIDTH 28 #define HEIGHT 28 #define TRY_TIME 100 using namespace std; int d, n; string path; cmdline::parser p; short s[60020][800] = {0}; double ans; int cpx, cpy; vector<double> line; vector<pair<double, int>> pos; void setCmdParser() { // -n command p.add<int>("number", 'n', "the number of images", true, 0); // -d command p.add<int>("dimensions", 'd', "the dimensions of images", true, 0); // -f command p.add<string>("file", 'f', "the path to dataset", true, ""); } void readDataset(int n, int d, string path) { ifstream input(path); if (!input.is_open()) { cout << "input file doesn't exist!" << endl; exit(0); } for (int w = 1; w <= n; w++) { int i, j; input >> i; for (j = 1; j <= d; j++) input >> s[i][j]; } } void printImage(int x) { for (int i = 1; i <= HEIGHT; i++) { for (int j = 1; j <= WIDTH; j++) if (s[x][(i - 1) * 28 + j] == 0) cout << '*'; else cout << ' '; cout << '\n'; } } double getStandardNormalDistribution() { const double epsilon = numeric_limits<double>::min(); const double twoPi = 2.0 * 3.14159265358979323846; double x, y, flag; do { x = rand() * (1.0 / RAND_MAX); y = rand() * (1.0 / RAND_MAX); flag = rand() * (1.0 / RAND_MAX); } while (x <= epsilon); if (flag > 0) return sqrt(-2.0 * log(x)) * cos(twoPi * y); else return sqrt(-2.0 * log(x)) * sin(twoPi * y); } void getRandomLine(int d) { line.clear(); for (int i = 1; i <= d; i++) { line.push_back(getStandardNormalDistribution()); } } double euclideanDistance(int x, int y, int d) { double ans = 0; for (int i = 1; i <= d; i++) { ans = ans + (s[x][i] - s[y][i]) * (s[x][i] - s[y][i]); } return ans; } void findClosestPair(int flag) { for (int k = 1; k <= TRY_TIME; k++) { getRandomLine(d); pos.clear(); for (int i = 1; i <= n; i++) { double temp = 0; for (int j = 1; j <= d; j++) temp = temp + s[i][j] * line[j - 1]; pos.push_back(make_pair(temp, i)); } pair<int, int> p = getClosestPairInLine(n, flag); double temp = euclideanDistance(p.first, p.second, d); if (temp < ans || ans < 0) { ans = temp; cpx = p.first; cpy = p.second; } } } int main(int argc, char* argv[]) { setCmdParser(); p.parse_check(argc, argv); // get arguments n = p.get<int>("number"); d = p.get<int>("dimensions"); path = p.get<string>("file"); readDataset(n, d, path); srand(time(NULL)); ans = -1; //findClosestPair(PIVOT_FLAG); findClosestPair(MEDIAN_FLAG); cout << "Closest Pair is Image No." << cpx << " and Image No." << cpy << endl; cout << "Image No." << cpx << endl; printImage(cpx); cout << "Image No." << cpy << endl; printImage(cpy); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 findrec developers * * See the file license.txt for copying permission. */ #include "findfiles.h" #include "filematch.h" #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <boost/utility/binary.hpp> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) # define IS_WINDOWS 1 #endif static struct Options { enum StatusCode : int { Success = 0, EarlyExit = -1, MissingArg = -2, InvalidArg = -3, }; enum ExecMode { NoExec = BOOST_BINARY(000), ExecAll = BOOST_BINARY(001), ExecEach = BOOST_BINARY(010), }; std::string needle; MatchType match_type; MatchFileType match_file_type; ExecMode exec_mode; std::vector<std::string> exec_command; Options() : match_type(Expansion), match_file_type((MatchFileType)(Directories | Files)), exec_mode(NoExec) {} } options; static void print_usage(const char* progname) { printf("Usage: %s [options] search_term\n", progname); printf( "\nOptions are:\n" " --regex, -r The search term is a regular expression.\n" " --directories, -d\n" " Match only directories.\n" " --files, -f Match only files that are not directories.\n" " --exec-all command\n" " Execute a command with the matched files as arguments\n" ); } static Options::StatusCode parse_args(int argc, char** argv) { using namespace std; for (int i = 1; i < argc; i++) { string arg = argv[i]; const bool is_short_opt = arg.length() && arg.at(0) == '-'; const bool is_long_opt = arg.compare(0, 2, "--") == 0; if (arg == "--help" || arg == "-h") { print_usage(argv[0]); return Options::EarlyExit; } else if (arg == "--regex" || arg == "-r") { options.match_type = Regex; } else if (arg == "--directories" || arg == "-d") { options.match_file_type = (MatchFileType)(options.match_file_type & ~Files); } else if (arg == "--files" || arg == "-f") { options.match_file_type = (MatchFileType)(options.match_file_type & ~Directories); } else if (arg == "--exec-all") { options.exec_mode = Options::ExecAll; if (i >= argc - 1) { fprintf(stderr, "Missing argument to %s\n", argv[i]); return Options::MissingArg; } while (i < argc - 1) { string arg = argv[++i]; if (arg == "end") break; options.exec_command.push_back(std::move(arg)); } } else if (is_long_opt) { fprintf(stderr, "Unrecognized option: %s\n", argv[i]); return Options::InvalidArg; } else if (is_short_opt) { const char ch = arg.length() >= 2 ? arg.at(0) : ' '; fprintf(stderr, "Unrecognized option: %c\n", ch); return Options::InvalidArg; } else { options.needle = arg; } } return Options::Success; } static void matched_plain_printer(const boost::filesystem::path& path) { printf("%s\n", path.string().c_str()); } static void matched_vector_pusher(std::vector<boost::filesystem::path>& matched_paths, const boost::filesystem::path& path) { matched_paths.push_back(path); matched_plain_printer(path); } // Create command from executable, params, and matched paths static std::string create_command(const std::vector<std::string>& exe_pieces, const std::vector<boost::filesystem::path>& paths) { std::string command; for (size_t i = 0; i < exe_pieces.size(); i++) { command += "\"" + exe_pieces.at(i) + "\" "; } for (size_t i = 0; i < paths.size(); i++) { std::string absolute_path = boost::filesystem::canonical(paths.at(i)).string(); command += " \"" + absolute_path + "\""; } #if IS_WINDOWS command = "\"" + command + "\""; // cmd gets really confused about spaces and quotations #endif return command; } int main(int argc, char** argv) { using namespace std; using namespace std::placeholders; Options::StatusCode rv = parse_args(argc, argv); if (rv) return rv; boost::filesystem::path root = "."; Matcher matcher = create_matcher(options.needle, options.match_type, options.match_file_type); // Figure out what callback to call on match function<void(const boost::filesystem::path&)> match_callback = matched_plain_printer; vector<boost::filesystem::path> matched_paths; if (options.exec_mode == Options::ExecAll) match_callback = std::bind(&matched_vector_pusher, std::ref(matched_paths), _1); find_files(root, matcher, match_callback); if (options.exec_mode == Options::ExecAll && options.exec_command.size() && matched_paths.size()) { const std::string command = create_command(options.exec_command, matched_paths); system(command.c_str()); } return 0; } <commit_msg>Add placement parameter to --exec-all<commit_after>/* * Copyright (c) 2013 findrec developers * * See the file license.txt for copying permission. */ #include "findfiles.h" #include "filematch.h" #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <boost/utility/binary.hpp> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) # define IS_WINDOWS 1 #endif static struct Options { enum StatusCode : int { Success = 0, EarlyExit = -1, MissingArg = -2, InvalidArg = -3, }; enum ExecMode { NoExec = BOOST_BINARY(000), ExecAll = BOOST_BINARY(001), ExecEach = BOOST_BINARY(010), }; std::string needle; MatchType match_type; MatchFileType match_file_type; ExecMode exec_mode; std::vector<std::string> exec_command; Options() : match_type(Expansion), match_file_type((MatchFileType)(Directories | Files)), exec_mode(NoExec) {} } options; static void print_usage(const char* progname) { printf("Usage: %s [options] search_term\n", progname); printf( "\nOptions are:\n" " --regex, -r The search term is a regular expression.\n" " --directories, -d\n" " Match only directories.\n" " --files, -f Match only files that are not directories.\n" " --exec-all command\n" " Execute a command with the matched files as arguments.\n" " Specify $* to specify where in the command matched paths\n" " should be placed. If omitted, they will be appended to the\n" " end of the command.\n" ); } static Options::StatusCode parse_args(int argc, char** argv) { using namespace std; for (int i = 1; i < argc; i++) { string arg = argv[i]; const bool is_short_opt = arg.length() && arg.at(0) == '-'; const bool is_long_opt = arg.compare(0, 2, "--") == 0; if (arg == "--help" || arg == "-h") { print_usage(argv[0]); return Options::EarlyExit; } else if (arg == "--regex" || arg == "-r") { options.match_type = Regex; } else if (arg == "--directories" || arg == "-d") { options.match_file_type = (MatchFileType)(options.match_file_type & ~Files); } else if (arg == "--files" || arg == "-f") { options.match_file_type = (MatchFileType)(options.match_file_type & ~Directories); } else if (arg == "--exec-all") { options.exec_mode = Options::ExecAll; if (i >= argc - 1) { fprintf(stderr, "Missing argument to %s\n", argv[i]); return Options::MissingArg; } while (i < argc - 1) { string arg = argv[++i]; if (arg == "end") break; options.exec_command.push_back(std::move(arg)); } } else if (is_long_opt) { fprintf(stderr, "Unrecognized option: %s\n", argv[i]); return Options::InvalidArg; } else if (is_short_opt) { const char ch = arg.length() >= 2 ? arg.at(0) : ' '; fprintf(stderr, "Unrecognized option: %c\n", ch); return Options::InvalidArg; } else { options.needle = arg; } } return Options::Success; } static void matched_plain_printer(const boost::filesystem::path& path) { printf("%s\n", path.string().c_str()); } static void matched_vector_pusher(std::vector<boost::filesystem::path>& matched_paths, const boost::filesystem::path& path) { matched_paths.push_back(path); matched_plain_printer(path); } // Create command from executable, params, and matched paths static std::string create_command(const std::vector<std::string>& exe_pieces, const std::vector<boost::filesystem::path>& paths) { using namespace std; // Concatenate matched paths string paths_param; for (size_t i = 0; i < paths.size(); i++) { string absolute_path = boost::filesystem::canonical(paths.at(i)).string(); paths_param += " \"" + absolute_path + "\""; } // Concatenate exec, params, and matched paths string command; bool contains_placement = false; for (size_t i = 0; i < exe_pieces.size(); i++) { if (exe_pieces.at(i) == "$*") // Look for placement parameter { contains_placement = true; command += " " + paths_param; } else command += " \"" + exe_pieces.at(i) + "\" "; } // If placement parameter is not specified, put the matched paths at the end if (!contains_placement) command += paths_param; #if IS_WINDOWS command = "\"" + command + "\""; // cmd gets really confused about spaces and quotations #endif return command; } int main(int argc, char** argv) { using namespace std; using namespace std::placeholders; Options::StatusCode rv = parse_args(argc, argv); if (rv) return rv; boost::filesystem::path root = "."; Matcher matcher = create_matcher(options.needle, options.match_type, options.match_file_type); // Figure out what callback to call on match function<void(const boost::filesystem::path&)> match_callback = matched_plain_printer; vector<boost::filesystem::path> matched_paths; if (options.exec_mode == Options::ExecAll) match_callback = std::bind(&matched_vector_pusher, std::ref(matched_paths), _1); find_files(root, matcher, match_callback); if (options.exec_mode == Options::ExecAll && options.exec_command.size() && matched_paths.size()) { const std::string command = create_command(options.exec_command, matched_paths); #if 0 printf("Executing:\n%s\n", command.c_str()); #endif system(command.c_str()); } return 0; } <|endoftext|>
<commit_before>#include "custer.h" #include "CusterServer.h" #include <boost/program_options/options_description.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/program_options/parsers.hpp> #include <iostream> namespace bpo = boost::program_options; int main(int argc, char* argv[]) { bpo::options_description custer_options("Opciones permitidas"); custer_options.add_options() ("help,h", "muestra este mensaje de ayuda") ("port,p", bpo::value<int>()->default_value(80, " 80"), "puerto al que asociarse") ("directory,d", bpo::value<std::string>()->default_value(".", " dir. actual"), "directorio que se servira") ("verbose,v", "imprime más informacion durante la ejecucion") ("debug,d", "imprime informacion de depuracion"); bpo::variables_map cmdline_variables; try { bpo::store(bpo::command_line_parser(argc, argv). options(custer_options).run(), cmdline_variables); bpo::notify(cmdline_variables); } catch (bpo::error& err) { fatal("%s", err.what()); } if (cmdline_variables.count("help")) { std::cout << custer_options << std::endl; return 0; } if (cmdline_variables.count("verbose")) { logLevel = LOG_INFO; } if (cmdline_variables.count("debug")) { logLevel = LOG_DEBUG; } uint16_t port = cmdline_variables["port"].as<int>(); std::string directory = cmdline_variables["directory"].as<std::string>(); debug("Puerto: %u", port); debug("Directorio: '%s'", directory.c_str()); boost::shared_ptr<custer::CusterServer> custerServer( new custer::CusterServer(port, directory)); std::cout << "Iniciando servidor..." << std::endl; custerServer->run(); return 0; }<commit_msg>Llamada a WSAStartup para la implementacion de Windows<commit_after>#include "custer.h" #include "CusterServer.h" #include <boost/program_options/options_description.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/program_options/parsers.hpp> #include <iostream> namespace bpo = boost::program_options; int main(int argc, char* argv[]) { bpo::options_description custer_options("Opciones permitidas"); custer_options.add_options() ("help,h", "muestra este mensaje de ayuda") ("port,p", bpo::value<int>()->default_value(80, " 80"), "puerto al que asociarse") ("directory,d", bpo::value<std::string>()->default_value(".", " dir. actual"), "directorio que se servira") ("verbose,v", "imprime más informacion durante la ejecucion") ("debug,d", "imprime informacion de depuracion"); bpo::variables_map cmdline_variables; try { bpo::store(bpo::command_line_parser(argc, argv). options(custer_options).run(), cmdline_variables); bpo::notify(cmdline_variables); } catch (bpo::error& err) { fatal("%s", err.what()); } if (cmdline_variables.count("help")) { std::cout << custer_options << std::endl; return 0; } if (cmdline_variables.count("verbose")) { logLevel = LOG_INFO; } if (cmdline_variables.count("debug")) { logLevel = LOG_DEBUG; } uint16_t port = cmdline_variables["port"].as<int>(); std::string directory = cmdline_variables["directory"].as<std::string>(); debug("Puerto: %u", port); debug("Directorio: '%s'", directory.c_str()); boost::shared_ptr<custer::CusterServer> custerServer( new custer::CusterServer(port, directory)); #ifdef WIN32 // Inicializamos WinSock WSADATA wsaData; int returnCode; if ((returnCode = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0) { fatal("Inicializando WinSock 2.2 (codigo: %d)", returnCode); } if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); fatal("Version WinSock 2.2 no disponible (version disponible: %d.%d)", LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion)); } #endif std::cout << "Iniciando servidor..." << std::endl; custerServer->run(); return 0; }<|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, Institute for Artificial Intelligence, * Universität Bremen. * 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 Institute for Artificial Intelligence, * Universität Bremen, nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /** \author Jan Winkler */ // System #include <iostream> #include <cstdlib> #include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include <string> // Private #include <semrec/SemanticHierarchyRecorderROS.h> // Storage of former signal handlers typedef void (*Handler)(int signum); Handler hdlrOldSIGWINCH = SIG_IGN; // Global variable for shutdown triggering semrec::SemanticHierarchyRecorderROS* g_srRecorder; void printHelp(std::string strExecutableName) { std::cout << "Semantic Hierarchy Recorder System (version \033[1;37m" + g_srRecorder->version() + "\033[0;37m) by Jan Winkler <winkler@cs.uni-bremen.de>" << std::endl; std::cout << "Licensed under BSD. https://www.github.com/code-iai/ros-semrec" << std::endl << std::endl; std::cout << "Usage: " << strExecutableName << " [options]" << std::endl << std::endl; std::cout << "Available options are:" << std::endl; std::cout << " -h, --help\t\tPrint this help" << std::endl; std::cout << " -c, --config <file>\tLoad config file <file> instead of the default one" << std::endl; std::cout << " -q, --quiet\t\tStart in quiet mode (command line output is suppressed)" << std::endl; std::cout << " -s, --signify\t\tPrint single message when init is done (for automation)" << std::endl; std::cout << std::endl; std::cout << "Should any questions arise, feel free to send an email to winkler@cs.uni-bremen.de" << std::endl; } void catchHandler(int nSignum) { switch(nSignum) { case SIGTERM: case SIGINT: { g_srRecorder->triggerShutdown(); } break; case SIGWINCH: { if(hdlrOldSIGWINCH != SIG_IGN && hdlrOldSIGWINCH != SIG_DFL) { (*hdlrOldSIGWINCH)(SIGWINCH); } g_srRecorder->triggerTerminalResize(); } break; default: break; } } int main(int argc, char** argv) { g_srRecorder = new semrec::SemanticHierarchyRecorderROS(argc, argv); // Read command line parameters int nC, option_index = 0; static struct option long_options[] = {{"config", required_argument, 0, 'c'}, {"quiet", no_argument, 0, 'q'}, {"help", no_argument, 0, 'h'}, {"signify", no_argument, 0, 's'}, {0, 0, 0, 0}}; std::string strConfigFile = ""; bool bQuit = false; bool bQuiet = false; bool bSignify = false; while((nC = getopt_long(argc, argv, "c:qhs", long_options, &option_index)) != -1) { switch(nC) { case 'c': { strConfigFile = std::string(optarg); } break; case 'q': { bQuiet = true; } break; case 'h': { printHelp(std::string(argv[0])); bQuit = true; } break; case 's': { bSignify = true; } break; default: { } break; } } if(bQuit == false) { g_srRecorder->setQuiet(bQuiet); g_srRecorder->info("Starting semantic hierarchy recorder system (version \033[1;37m" + g_srRecorder->version() + "\033[0;37m)."); semrec::Result resInit = g_srRecorder->init(strConfigFile); if(resInit.bSuccess) { // Catch SIGTERM and SIGINT and bind them to the callback function // catchSIGTERMandSIGINT. This will trigger the shutdown mechanism // in the semrec instance. struct sigaction action; memset(&action, 0, sizeof(struct sigaction)); action.sa_handler = catchHandler; sigaction(SIGTERM, &action, NULL); sigaction(SIGINT, &action, NULL); hdlrOldSIGWINCH = signal(SIGWINCH, SIG_IGN); sigaction(SIGWINCH, &action, NULL); g_srRecorder->info("Initialization complete, ready for action.", true); if(bSignify) { std::cout << "Signify: semrec init complete (version " + g_srRecorder->version() << ")" << std::endl; } while(g_srRecorder->cycle()) { // Idle here at will. usleep(10); } } else { g_srRecorder->fail("Initialization of the recorder system failed. Being a quitter."); } std::cout << "\r"; g_srRecorder->info("Exiting gracefully."); g_srRecorder->cycle(); g_srRecorder->deinit(); g_srRecorder->cycle(); delete g_srRecorder; } return EXIT_SUCCESS; } <commit_msg>A bit of help output and source code comments<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, Institute for Artificial Intelligence, * Universität Bremen. * 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 Institute for Artificial Intelligence, * Universität Bremen, nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /** \author Jan Winkler */ // System #include <iostream> #include <cstdlib> #include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include <string> // Private #include <semrec/SemanticHierarchyRecorderROS.h> // Storage of former signal handlers typedef void (*Handler)(int signum); Handler hdlrOldSIGWINCH = SIG_IGN; // Global variable for shutdown triggering semrec::SemanticHierarchyRecorderROS* g_srRecorder; void printHelp(std::string strExecutableName) { std::cout << "Semantic Hierarchy Recorder System (version \033[1;37m" + g_srRecorder->version() + "\033[0;37m) by Jan Winkler <winkler@cs.uni-bremen.de>" << std::endl; std::cout << "Licensed under BSD. https://www.github.com/code-iai/ros-semrec" << std::endl << std::endl; std::cout << "Usage: " << strExecutableName << " [options]" << std::endl << std::endl; std::cout << "Available options are:" << std::endl; std::cout << " -h, --help\t\tPrint this help" << std::endl; std::cout << " -c, --config <file>\tLoad config file <file> instead of the default one" << std::endl; std::cout << " -q, --quiet\t\tStart in quiet mode (command line output is suppressed)" << std::endl; std::cout << " -s, --signify\t\tPrint single message when init is done (for automation)" << std::endl; std::cout << std::endl; std::cout << "Should any questions arise, feel free to send an email to winkler@cs.uni-bremen.de" << std::endl; std::cout << "Get the source here: https://github.com/code-iai/semrec" << std::endl; } void catchHandler(int nSignum) { switch(nSignum) { case SIGTERM: case SIGINT: { g_srRecorder->triggerShutdown(); } break; case SIGWINCH: { if(hdlrOldSIGWINCH != SIG_IGN && hdlrOldSIGWINCH != SIG_DFL) { (*hdlrOldSIGWINCH)(SIGWINCH); } g_srRecorder->triggerTerminalResize(); } break; default: break; } } int main(int argc, char** argv) { g_srRecorder = new semrec::SemanticHierarchyRecorderROS(argc, argv); // Read command line parameters int nC, option_index = 0; static struct option long_options[] = {{"config", required_argument, 0, 'c'}, {"quiet", no_argument, 0, 'q'}, {"help", no_argument, 0, 'h'}, {"signify", no_argument, 0, 's'}, {0, 0, 0, 0}}; std::string strConfigFile = ""; bool bQuit = false; bool bQuiet = false; bool bSignify = false; while((nC = getopt_long(argc, argv, "c:qhs", long_options, &option_index)) != -1) { switch(nC) { case 'c': { strConfigFile = std::string(optarg); } break; case 'q': { bQuiet = true; } break; case 'h': { printHelp(std::string(argv[0])); bQuit = true; } break; case 's': { bSignify = true; } break; default: { } break; } } if(bQuit == false) { g_srRecorder->setQuiet(bQuiet); g_srRecorder->info("Starting semantic hierarchy recorder system (version \033[1;37m" + g_srRecorder->version() + "\033[0;37m)."); semrec::Result resInit = g_srRecorder->init(strConfigFile); if(resInit.bSuccess) { // Catch SIGTERM and SIGINT and bind them to the callback // function `catchHandler`. This will trigger the shutdown // mechanism in the global semrec instance. struct sigaction action; memset(&action, 0, sizeof(struct sigaction)); action.sa_handler = catchHandler; sigaction(SIGTERM, &action, NULL); sigaction(SIGINT, &action, NULL); // Catch SIGWINCH to tell semrec about terminal resizes, and // store the original signal handler to invoke it, too. hdlrOldSIGWINCH = signal(SIGWINCH, SIG_IGN); sigaction(SIGWINCH, &action, NULL); g_srRecorder->info("Initialization complete, ready for action.", true); if(bSignify) { std::cout << "Signify: semrec init complete (version " + g_srRecorder->version() << ")" << std::endl; } while(g_srRecorder->cycle()) { // Idle here at will. usleep(10); } } else { g_srRecorder->fail("Initialization of the recorder system failed. Being a quitter."); } std::cout << "\r"; g_srRecorder->info("Exiting gracefully."); g_srRecorder->cycle(); g_srRecorder->deinit(); g_srRecorder->cycle(); delete g_srRecorder; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <cassert> #include <functional> #include <iostream> #include <map> #include <string> #include <vector> #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include "lz4.h" #include "lz4hc.h" #include "xxhash.h" #include "lz4mt.h" #include "lz4mt_benchmark.h" #include "lz4mt_io_cstdio.h" #include "test_clock.h" namespace { const char LZ4MT_EXTENSION[] = ".lz4"; const char usage[] = "usage :\n" " lz4mt [switch...] <input> [output]\n" "switch :\n" " -c0/-c : Compress (lz4) (default)\n" " -c1/-hc : Compress (lz4hc)\n" " -d : Decompress\n" " -y : Overwrite without prompting\n" " -H : Help (this text + advanced options)\n" ; const char usage_advanced[] = "\nAdvanced options :\n" " -t : decode test mode (do not output anything)\n" " -B# : Block size [4-7](default : 7)\n" " -BX : enable block checksum (default:disabled)\n" " -Sx : disable stream checksum (default:enabled)\n" " -b# : benchmark files, using # [0-1] compression level\n" " -i# : iteration loops [1-9](default : 3), benchmark mode" " only\n" " -s : Single thread mode\n" " -m : Multi thread mode (default)\n" " input : can be 'stdin' (pipe) or a filename\n" " output : can be 'stdout'(pipe) or a filename or 'null'\n" ; struct Option { Option(int argc, char* argv[]) : error(false) , exitFlag(false) , compMode(CompMode::COMPRESS_C0) , sd(lz4mtInitStreamDescriptor()) , mode(LZ4MT_MODE_DEFAULT) , inpFilename() , outFilename() , nullWrite(false) , overwrite(false) , benchmark() { static const std::string nullFilename = "null"; std::map<std::string, std::function<void ()>> opts; opts["-c0"] = opts["-c" ] = [&] { compMode = CompMode::COMPRESS_C0; }; opts["-c1"] = opts["-hc"] = [&] { compMode = CompMode::COMPRESS_C1; }; opts["-d" ] = [&] { compMode = CompMode::DECOMPRESS; }; opts["-y" ] = [&] { overwrite = true; }; opts["-s" ] = [&] { mode |= LZ4MT_MODE_SEQUENTIAL; }; opts["-m" ] = [&] { mode &= ~LZ4MT_MODE_SEQUENTIAL; }; opts["--help"] = opts["-h" ] = opts["/?" ] = [&] { std::cerr << usage; exitFlag = true; }; opts["-H" ] = [&] { std::cerr << usage << usage_advanced; exitFlag = true; }; for(int i = 4; i <= 7; ++i) { opts[std::string("-B") + std::to_string(i)] = [&, i] { sd.bd.blockMaximumSize = static_cast<char>(i); }; } opts["-BX"] = [&] { sd.flg.blockChecksum = 1; }; opts["-Sx"] = [&] { sd.flg.streamChecksum = 0; }; opts["-t" ] = [&] { compMode = CompMode::DECOMPRESS; outFilename = nullFilename; }; for(int i = 0; i <= 1; ++i) { opts["-b" + std::to_string(i)] = [&, i] { if(i == 0) { compMode = CompMode::COMPRESS_C0; } else { compMode = CompMode::COMPRESS_C1; } benchmark.enable = true; }; } for(int i = 1; i <= 9; ++i) { opts[std::string("-i") + std::to_string(i)] = [&, i] { benchmark.nIter = i; benchmark.enable = true; }; } for(int iarg = 1; iarg < argc && !error && !exitFlag; ++iarg) { const auto a = std::string(argv[iarg]); const auto i = opts.find(a); if(opts.end() != i) { i->second(); } else if(a[0] == '-') { std::cerr << "ERROR: bad switch [" << a << "]\n"; error = true; } else if(benchmark.enable) { benchmark.files.push_back(a); } else if(inpFilename.empty()) { inpFilename = a; } else if(outFilename.empty()) { outFilename = a; } else { std::cerr << "ERROR: Bad argument [" << a << "]\n"; error = true; } } if(cmpFilename(nullFilename, outFilename)) { nullWrite = true; } } bool isCompress() const { return CompMode::COMPRESS_C0 == compMode || CompMode::COMPRESS_C1 == compMode; } bool isDecompress() const { return CompMode::DECOMPRESS == compMode; } static bool cmpFilename(const std::string& lhs, const std::string& rhs) { const auto pLhs = lhs.c_str(); const auto pRhs = rhs.c_str(); #if defined(_WIN32) return 0 == _stricmp(pLhs, pRhs); #else return 0 == strcmp(pLhs, pRhs); #endif } enum class CompMode { DECOMPRESS , COMPRESS_C0 , COMPRESS_C1 }; bool error; bool exitFlag; CompMode compMode; Lz4MtStreamDescriptor sd; int mode; std::string inpFilename; std::string outFilename; bool nullWrite; bool overwrite; Lz4Mt::Benchmark benchmark; }; } // anonymous namespace int main(int argc, char* argv[]) { using namespace Lz4Mt::Cstdio; Option opt(argc, argv); if(opt.exitFlag) { exit(EXIT_SUCCESS); } else if(opt.error) { exit(EXIT_FAILURE); } Lz4MtContext ctx = lz4mtInitContext(); ctx.mode = static_cast<Lz4MtMode>(opt.mode); ctx.read = read; ctx.readSeek = readSeek; ctx.readEof = readEof; ctx.write = write; ctx.compress = LZ4_compress_limitedOutput; ctx.compressBound = LZ4_compressBound; ctx.decompress = LZ4_decompress_safe; if(Option::CompMode::COMPRESS_C1 == opt.compMode) { ctx.compress = LZ4_compressHC_limitedOutput; } if(opt.benchmark.enable) { opt.benchmark.openIstream = openIstream; opt.benchmark.closeIstream = closeIstream; opt.benchmark.getFilesize = getFilesize; opt.benchmark.measure(ctx, opt.sd); exit(EXIT_SUCCESS); } if(opt.inpFilename.empty()) { std::cerr << "ERROR: No input filename\n"; exit(EXIT_FAILURE); } if(opt.outFilename.empty()) { if(opt.isCompress()) { if("stdin" == opt.inpFilename) { opt.outFilename = "stdout"; } else { opt.outFilename = opt.inpFilename + LZ4MT_EXTENSION; } } else { std::cerr << "ERROR: No output filename\n"; exit(EXIT_FAILURE); } } if(!openIstream(&ctx, opt.inpFilename)) { std::cerr << "ERROR: Can't open input file " << "[" << opt.inpFilename << "]\n"; exit(EXIT_FAILURE); } if(!opt.nullWrite && !opt.overwrite && fileExist(opt.outFilename)) { const int ch = [&]() -> int { if("stdin" != opt.inpFilename) { std::cerr << "Overwrite [y/N]? "; return std::cin.get(); } else { return 0; } } (); if('y' != ch && 'Y' != ch) { std::cerr << "Abort: " << opt.outFilename << " already exists\n"; exit(EXIT_FAILURE); } } if(!openOstream(&ctx, opt.outFilename, opt.nullWrite)) { std::cerr << "ERROR: Can't open output file [" << opt.outFilename << "]\n"; exit(EXIT_FAILURE); } const auto t0 = Clock::now(); const auto e = [&]() -> Lz4MtResult { if(opt.isCompress()) { return lz4mtCompress(&ctx, &opt.sd); } else if(opt.isDecompress()) { return lz4mtDecompress(&ctx, &opt.sd); } else { assert(0); std::cerr << "ERROR: You must specify a switch -c or -d\n"; return LZ4MT_RESULT_BAD_ARG; } } (); const auto t1 = Clock::now(); closeOstream(&ctx); closeIstream(&ctx); const auto dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0).count(); std::cerr << "Total time: " << dt << "sec\n"; if(LZ4MT_RESULT_OK != e) { std::cerr << "ERROR: " << lz4mtResultToString(e) << "\n"; exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } <commit_msg>Add <string.h><commit_after>#include <cassert> #include <functional> #include <iostream> #include <map> #include <string> #include <string.h> #include <vector> #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include "lz4.h" #include "lz4hc.h" #include "xxhash.h" #include "lz4mt.h" #include "lz4mt_benchmark.h" #include "lz4mt_io_cstdio.h" #include "test_clock.h" namespace { const char LZ4MT_EXTENSION[] = ".lz4"; const char usage[] = "usage :\n" " lz4mt [switch...] <input> [output]\n" "switch :\n" " -c0/-c : Compress (lz4) (default)\n" " -c1/-hc : Compress (lz4hc)\n" " -d : Decompress\n" " -y : Overwrite without prompting\n" " -H : Help (this text + advanced options)\n" ; const char usage_advanced[] = "\nAdvanced options :\n" " -t : decode test mode (do not output anything)\n" " -B# : Block size [4-7](default : 7)\n" " -BX : enable block checksum (default:disabled)\n" " -Sx : disable stream checksum (default:enabled)\n" " -b# : benchmark files, using # [0-1] compression level\n" " -i# : iteration loops [1-9](default : 3), benchmark mode" " only\n" " -s : Single thread mode\n" " -m : Multi thread mode (default)\n" " input : can be 'stdin' (pipe) or a filename\n" " output : can be 'stdout'(pipe) or a filename or 'null'\n" ; struct Option { Option(int argc, char* argv[]) : error(false) , exitFlag(false) , compMode(CompMode::COMPRESS_C0) , sd(lz4mtInitStreamDescriptor()) , mode(LZ4MT_MODE_DEFAULT) , inpFilename() , outFilename() , nullWrite(false) , overwrite(false) , benchmark() { static const std::string nullFilename = "null"; std::map<std::string, std::function<void ()>> opts; opts["-c0"] = opts["-c" ] = [&] { compMode = CompMode::COMPRESS_C0; }; opts["-c1"] = opts["-hc"] = [&] { compMode = CompMode::COMPRESS_C1; }; opts["-d" ] = [&] { compMode = CompMode::DECOMPRESS; }; opts["-y" ] = [&] { overwrite = true; }; opts["-s" ] = [&] { mode |= LZ4MT_MODE_SEQUENTIAL; }; opts["-m" ] = [&] { mode &= ~LZ4MT_MODE_SEQUENTIAL; }; opts["--help"] = opts["-h" ] = opts["/?" ] = [&] { std::cerr << usage; exitFlag = true; }; opts["-H" ] = [&] { std::cerr << usage << usage_advanced; exitFlag = true; }; for(int i = 4; i <= 7; ++i) { opts[std::string("-B") + std::to_string(i)] = [&, i] { sd.bd.blockMaximumSize = static_cast<char>(i); }; } opts["-BX"] = [&] { sd.flg.blockChecksum = 1; }; opts["-Sx"] = [&] { sd.flg.streamChecksum = 0; }; opts["-t" ] = [&] { compMode = CompMode::DECOMPRESS; outFilename = nullFilename; }; for(int i = 0; i <= 1; ++i) { opts["-b" + std::to_string(i)] = [&, i] { if(i == 0) { compMode = CompMode::COMPRESS_C0; } else { compMode = CompMode::COMPRESS_C1; } benchmark.enable = true; }; } for(int i = 1; i <= 9; ++i) { opts[std::string("-i") + std::to_string(i)] = [&, i] { benchmark.nIter = i; benchmark.enable = true; }; } for(int iarg = 1; iarg < argc && !error && !exitFlag; ++iarg) { const auto a = std::string(argv[iarg]); const auto i = opts.find(a); if(opts.end() != i) { i->second(); } else if(a[0] == '-') { std::cerr << "ERROR: bad switch [" << a << "]\n"; error = true; } else if(benchmark.enable) { benchmark.files.push_back(a); } else if(inpFilename.empty()) { inpFilename = a; } else if(outFilename.empty()) { outFilename = a; } else { std::cerr << "ERROR: Bad argument [" << a << "]\n"; error = true; } } if(cmpFilename(nullFilename, outFilename)) { nullWrite = true; } } bool isCompress() const { return CompMode::COMPRESS_C0 == compMode || CompMode::COMPRESS_C1 == compMode; } bool isDecompress() const { return CompMode::DECOMPRESS == compMode; } static bool cmpFilename(const std::string& lhs, const std::string& rhs) { const auto pLhs = lhs.c_str(); const auto pRhs = rhs.c_str(); #if defined(_WIN32) return 0 == _stricmp(pLhs, pRhs); #else return 0 == strcmp(pLhs, pRhs); #endif } enum class CompMode { DECOMPRESS , COMPRESS_C0 , COMPRESS_C1 }; bool error; bool exitFlag; CompMode compMode; Lz4MtStreamDescriptor sd; int mode; std::string inpFilename; std::string outFilename; bool nullWrite; bool overwrite; Lz4Mt::Benchmark benchmark; }; } // anonymous namespace int main(int argc, char* argv[]) { using namespace Lz4Mt::Cstdio; Option opt(argc, argv); if(opt.exitFlag) { exit(EXIT_SUCCESS); } else if(opt.error) { exit(EXIT_FAILURE); } Lz4MtContext ctx = lz4mtInitContext(); ctx.mode = static_cast<Lz4MtMode>(opt.mode); ctx.read = read; ctx.readSeek = readSeek; ctx.readEof = readEof; ctx.write = write; ctx.compress = LZ4_compress_limitedOutput; ctx.compressBound = LZ4_compressBound; ctx.decompress = LZ4_decompress_safe; if(Option::CompMode::COMPRESS_C1 == opt.compMode) { ctx.compress = LZ4_compressHC_limitedOutput; } if(opt.benchmark.enable) { opt.benchmark.openIstream = openIstream; opt.benchmark.closeIstream = closeIstream; opt.benchmark.getFilesize = getFilesize; opt.benchmark.measure(ctx, opt.sd); exit(EXIT_SUCCESS); } if(opt.inpFilename.empty()) { std::cerr << "ERROR: No input filename\n"; exit(EXIT_FAILURE); } if(opt.outFilename.empty()) { if(opt.isCompress()) { if("stdin" == opt.inpFilename) { opt.outFilename = "stdout"; } else { opt.outFilename = opt.inpFilename + LZ4MT_EXTENSION; } } else { std::cerr << "ERROR: No output filename\n"; exit(EXIT_FAILURE); } } if(!openIstream(&ctx, opt.inpFilename)) { std::cerr << "ERROR: Can't open input file " << "[" << opt.inpFilename << "]\n"; exit(EXIT_FAILURE); } if(!opt.nullWrite && !opt.overwrite && fileExist(opt.outFilename)) { const int ch = [&]() -> int { if("stdin" != opt.inpFilename) { std::cerr << "Overwrite [y/N]? "; return std::cin.get(); } else { return 0; } } (); if('y' != ch && 'Y' != ch) { std::cerr << "Abort: " << opt.outFilename << " already exists\n"; exit(EXIT_FAILURE); } } if(!openOstream(&ctx, opt.outFilename, opt.nullWrite)) { std::cerr << "ERROR: Can't open output file [" << opt.outFilename << "]\n"; exit(EXIT_FAILURE); } const auto t0 = Clock::now(); const auto e = [&]() -> Lz4MtResult { if(opt.isCompress()) { return lz4mtCompress(&ctx, &opt.sd); } else if(opt.isDecompress()) { return lz4mtDecompress(&ctx, &opt.sd); } else { assert(0); std::cerr << "ERROR: You must specify a switch -c or -d\n"; return LZ4MT_RESULT_BAD_ARG; } } (); const auto t1 = Clock::now(); closeOstream(&ctx); closeIstream(&ctx); const auto dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0).count(); std::cerr << "Total time: " << dt << "sec\n"; if(LZ4MT_RESULT_OK != e) { std::cerr << "ERROR: " << lz4mtResultToString(e) << "\n"; exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>#include "circuits/element.h" #include "matrix/solve.h" #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <cstdlib> using namespace std; #define DEBUG static const int MAX_LINHA = 80; static const int MAX_NOME = 11; static const int MAX_ELEM = 50; int main(int argc, char **argv){ cout << endl; cout << "Modified Nodal Analysis" << endl; cout << "Originally by Antonio Carlos M. de Queiroz (acmq@coe.ufrj.br)" << endl; cout << "Modified by Dhiana Deva, Felipe de Leo and Silvino Vieira" << endl; cout << endl; ifstream netlistFile; string filepath; switch(argc) { case 1: { cout << "Enter path to netlist file: "; cin >> filepath; break; } case 2: { filepath = argv[1]; break; } default: cerr << "FAILURE: Too much information!" << endl; #if defined (WIN32) || defined(_WIN32) cin.get(); #endif exit(EXIT_FAILURE); } netlistFile.open(filepath.c_str(), ifstream::in); if(!netlistFile.is_open()){ cerr << "FAILURE: Cannot open file " << filepath << endl; #if defined (WIN32) || defined(_WIN32) cin.get(); #endif exit(EXIT_FAILURE); } string txt; vector<string> lista(MAX_NOME+2); /*Tem que caber jx antes do nome */ lista[0] = "0"; vector<Element> netlist(MAX_ELEM); int nv=0, /* Variaveis */ nn=0; /* Nos */ /* Foram colocados limites nos formatos de leitura para alguma protecao contra excesso de caracteres nestas variaveis */ char tipo; double g, Yn[MAX_NOS+1][MAX_NOS+2]; cout << "Lendo netlist:" << endl; getline(netlistFile, txt); cout << "Titulo: " << txt; while (getline(netlistFile, txt)) { Element::ne++; /* Nao usa o netlist[0] */ if (Element::ne>MAX_ELEM) { cout << "O programa so aceita ate " << MAX_ELEM << " elementos" << endl; #if defined (WIN32) || defined(_WIN32) cin.get(); #endif exit(EXIT_FAILURE); } netlist[Element::ne] = Element(txt, nv, lista); } netlistFile.close(); /* Acrescenta variaveis de corrente acima dos nos, anotando no netlist */ nn=nv; for (int i=1; i<=Element::ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') { nv++; if (nv>MAX_NOS) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl; #if defined (WIN32) || defined(_WIN32) cin.get(); #endif exit(EXIT_FAILURE); } lista[nv] = "j"; /* Tem espaco para mais dois caracteres */ lista[nv].append( netlist[i].nome ); netlist[i].x=nv; } else if (tipo=='H') { nv=nv+2; if (nv>MAX_NOS) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl; #if defined (WIN32) || defined(_WIN32) cin.get(); #endif exit(EXIT_FAILURE); } lista[nv-1] = "jx"; lista[nv-1].append(netlist[i].nome); netlist[i].x=nv-1; lista[nv] = "jy"; lista[nv].append( netlist[i].nome ); netlist[i].y=nv; } } cout << endl; /* Lista tudo */ cout << "Variaveis internas: " << endl; for (int i=0; i<=nv; i++) cout << i << " -> " << lista[i] << endl; cout << endl; cout << "Netlist interno final" << endl; for (int i=1; i<=Element::ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='R' || tipo=='I' || tipo=='V') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].valor << endl; } else if (tipo=='G' || tipo=='E' || tipo=='F' || tipo=='H') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].c << " " << netlist[i].d << " " << netlist[i].valor << endl; } else if (tipo=='O') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].c << " " << netlist[i].d << endl; } if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') cout << "Corrente jx: " << netlist[i].x << endl; else if (tipo=='H') cout << "Correntes jx e jy: " << netlist[i].x << ", " << netlist[i].y << endl; } cout << endl; /* Monta o sistema nodal modificado */ cout << "O circuito tem " << nn << " nos, " << nv << " variaveis e " << Element::ne << " elementos" << endl; cout << endl; /* Zera sistema */ for (int i=0; i<=nv; i++) { for (int j=0; j<=nv+1; j++) Yn[i][j]=0; } /* Monta estampas */ for (int i=1; i<=Element::ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='R') { g=1/netlist[i].valor; Yn[netlist[i].a][netlist[i].a]+=g; Yn[netlist[i].b][netlist[i].b]+=g; Yn[netlist[i].a][netlist[i].b]-=g; Yn[netlist[i].b][netlist[i].a]-=g; } else if (tipo=='G') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].c]+=g; Yn[netlist[i].b][netlist[i].d]+=g; Yn[netlist[i].a][netlist[i].d]-=g; Yn[netlist[i].b][netlist[i].c]-=g; } else if (tipo=='I') { g=netlist[i].valor; Yn[netlist[i].a][nv+1]-=g; Yn[netlist[i].b][nv+1]+=g; } else if (tipo=='V') { Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].a]-=1; Yn[netlist[i].x][netlist[i].b]+=1; Yn[netlist[i].x][nv+1]-=netlist[i].valor; } else if (tipo=='E') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].a]-=1; Yn[netlist[i].x][netlist[i].b]+=1; Yn[netlist[i].x][netlist[i].c]+=g; Yn[netlist[i].x][netlist[i].d]-=g; } else if (tipo=='F') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].x]+=g; Yn[netlist[i].b][netlist[i].x]-=g; Yn[netlist[i].c][netlist[i].x]+=1; Yn[netlist[i].d][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].c]-=1; Yn[netlist[i].x][netlist[i].d]+=1; } else if (tipo=='H') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].y]+=1; Yn[netlist[i].b][netlist[i].y]-=1; Yn[netlist[i].c][netlist[i].x]+=1; Yn[netlist[i].d][netlist[i].x]-=1; Yn[netlist[i].y][netlist[i].a]-=1; Yn[netlist[i].y][netlist[i].b]+=1; Yn[netlist[i].x][netlist[i].c]-=1; Yn[netlist[i].x][netlist[i].d]+=1; Yn[netlist[i].y][netlist[i].x]+=g; } else if (tipo=='O') { Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].c]+=1; Yn[netlist[i].x][netlist[i].d]-=1; } #ifdef DEBUG /* Opcional: Mostra o sistema apos a montagem da estampa */ cout << "Sistema apos a estampa de " << netlist[i].nome << endl; for (int k=1; k<=nv; k++) { for (int j=1; j<=nv+1; j++) if (Yn[k][j]!=0){ cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos; cout << Yn[k][j] << " "; } else cout << " ... "; cout << endl; } cout << endl; #endif } /* Resolve o sistema */ if (solve(nv, Yn)) { cout << "FAILURE: Could not solve!" << endl; #if defined (WIN32) || defined(_WIN32) cin.get(); #endif exit(EXIT_FAILURE); } #ifdef DEBUG /* Opcional: Mostra o sistema resolvido */ cout << "Sistema resolvido:" << endl; for (int i=1; i<=nv; i++) { for (int j=1; j<=nv+1; j++) if (Yn[i][j]!=0){ cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos; cout << Yn[i][j] << " "; } else cout << " ... "; cout << endl; } cout << endl; #endif /* Mostra solucao */ cout << "Solucao:" << endl; txt = "Tensao"; for (int i=1; i<=nv; i++) { if (i==nn+1) txt = "Corrente"; cout << txt << " " << lista[i] << ": " << Yn[i][nv+1] << endl; } #if defined (WIN32) || defined(_WIN32) cin.get(); #endif } <commit_msg>Implements polite exit :crown:<commit_after>#include "circuits/element.h" #include "matrix/solve.h" #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <cstdlib> using namespace std; #define DEBUG static const int MAX_LINHA = 80; static const int MAX_NOME = 11; static const int MAX_ELEM = 50; void exitPolitely(int exitCode) { #if defined (WIN32) || defined(_WIN32) cout << endl << "Press any key to exit..."; cin.get(); cin.get(); #endif exit(exitCode); } int main(int argc, char **argv){ cout << endl; cout << "Modified Nodal Analysis" << endl; cout << "Originally by Antonio Carlos M. de Queiroz (acmq@coe.ufrj.br)" << endl; cout << "Modified by Dhiana Deva, Felipe de Leo and Silvino Vieira" << endl; cout << endl; ifstream netlistFile; string filepath; switch(argc) { case 1: { cout << "Enter path to netlist file: "; cin >> filepath; break; } case 2: { filepath = argv[1]; break; } default: cerr << "FAILURE: Too much information!" << endl; exitPolitely(EXIT_FAILURE); } netlistFile.open(filepath.c_str(), ifstream::in); if(!netlistFile.is_open()){ cerr << "FAILURE: Cannot open file " << filepath << endl; exitPolitely(EXIT_FAILURE); } string txt; vector<string> lista(MAX_NOME+2); /*Tem que caber jx antes do nome */ lista[0] = "0"; vector<Element> netlist(MAX_ELEM); int nv=0, /* Variaveis */ nn=0; /* Nos */ /* Foram colocados limites nos formatos de leitura para alguma protecao contra excesso de caracteres nestas variaveis */ char tipo; double g, Yn[MAX_NOS+1][MAX_NOS+2]; cout << "Lendo netlist:" << endl; getline(netlistFile, txt); cout << "Titulo: " << txt; while (getline(netlistFile, txt)) { Element::ne++; /* Nao usa o netlist[0] */ if (Element::ne>MAX_ELEM) { cout << "O programa so aceita ate " << MAX_ELEM << " elementos" << endl; exitPolitely(EXIT_FAILURE); } netlist[Element::ne] = Element(txt, nv, lista); } netlistFile.close(); /* Acrescenta variaveis de corrente acima dos nos, anotando no netlist */ nn=nv; for (int i=1; i<=Element::ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') { nv++; if (nv>MAX_NOS) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl; exitPolitely(EXIT_FAILURE); } lista[nv] = "j"; /* Tem espaco para mais dois caracteres */ lista[nv].append( netlist[i].nome ); netlist[i].x=nv; } else if (tipo=='H') { nv=nv+2; if (nv>MAX_NOS) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl; exitPolitely(EXIT_FAILURE); } lista[nv-1] = "jx"; lista[nv-1].append(netlist[i].nome); netlist[i].x=nv-1; lista[nv] = "jy"; lista[nv].append( netlist[i].nome ); netlist[i].y=nv; } } cout << endl; /* Lista tudo */ cout << "Variaveis internas: " << endl; for (int i=0; i<=nv; i++) cout << i << " -> " << lista[i] << endl; cout << endl; cout << "Netlist interno final" << endl; for (int i=1; i<=Element::ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='R' || tipo=='I' || tipo=='V') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].valor << endl; } else if (tipo=='G' || tipo=='E' || tipo=='F' || tipo=='H') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].c << " " << netlist[i].d << " " << netlist[i].valor << endl; } else if (tipo=='O') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].c << " " << netlist[i].d << endl; } if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') cout << "Corrente jx: " << netlist[i].x << endl; else if (tipo=='H') cout << "Correntes jx e jy: " << netlist[i].x << ", " << netlist[i].y << endl; } cout << endl; /* Monta o sistema nodal modificado */ cout << "O circuito tem " << nn << " nos, " << nv << " variaveis e " << Element::ne << " elementos" << endl; cout << endl; /* Zera sistema */ for (int i=0; i<=nv; i++) { for (int j=0; j<=nv+1; j++) Yn[i][j]=0; } /* Monta estampas */ for (int i=1; i<=Element::ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='R') { g=1/netlist[i].valor; Yn[netlist[i].a][netlist[i].a]+=g; Yn[netlist[i].b][netlist[i].b]+=g; Yn[netlist[i].a][netlist[i].b]-=g; Yn[netlist[i].b][netlist[i].a]-=g; } else if (tipo=='G') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].c]+=g; Yn[netlist[i].b][netlist[i].d]+=g; Yn[netlist[i].a][netlist[i].d]-=g; Yn[netlist[i].b][netlist[i].c]-=g; } else if (tipo=='I') { g=netlist[i].valor; Yn[netlist[i].a][nv+1]-=g; Yn[netlist[i].b][nv+1]+=g; } else if (tipo=='V') { Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].a]-=1; Yn[netlist[i].x][netlist[i].b]+=1; Yn[netlist[i].x][nv+1]-=netlist[i].valor; } else if (tipo=='E') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].a]-=1; Yn[netlist[i].x][netlist[i].b]+=1; Yn[netlist[i].x][netlist[i].c]+=g; Yn[netlist[i].x][netlist[i].d]-=g; } else if (tipo=='F') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].x]+=g; Yn[netlist[i].b][netlist[i].x]-=g; Yn[netlist[i].c][netlist[i].x]+=1; Yn[netlist[i].d][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].c]-=1; Yn[netlist[i].x][netlist[i].d]+=1; } else if (tipo=='H') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].y]+=1; Yn[netlist[i].b][netlist[i].y]-=1; Yn[netlist[i].c][netlist[i].x]+=1; Yn[netlist[i].d][netlist[i].x]-=1; Yn[netlist[i].y][netlist[i].a]-=1; Yn[netlist[i].y][netlist[i].b]+=1; Yn[netlist[i].x][netlist[i].c]-=1; Yn[netlist[i].x][netlist[i].d]+=1; Yn[netlist[i].y][netlist[i].x]+=g; } else if (tipo=='O') { Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].c]+=1; Yn[netlist[i].x][netlist[i].d]-=1; } #ifdef DEBUG /* Opcional: Mostra o sistema apos a montagem da estampa */ cout << "Sistema apos a estampa de " << netlist[i].nome << endl; for (int k=1; k<=nv; k++) { for (int j=1; j<=nv+1; j++) if (Yn[k][j]!=0){ cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos; cout << Yn[k][j] << " "; } else cout << " ... "; cout << endl; } cout << endl; #endif } /* Resolve o sistema */ if (solve(nv, Yn)) { cout << "FAILURE: Could not solve!" << endl; exitPolitely(EXIT_FAILURE); } #ifdef DEBUG /* Opcional: Mostra o sistema resolvido */ cout << "Sistema resolvido:" << endl; for (int i=1; i<=nv; i++) { for (int j=1; j<=nv+1; j++) if (Yn[i][j]!=0){ cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos; cout << Yn[i][j] << " "; } else cout << " ... "; cout << endl; } cout << endl; #endif /* Mostra solucao */ cout << "Solucao:" << endl; txt = "Tensao"; for (int i=1; i<=nv; i++) { if (i==nn+1) txt = "Corrente"; cout << txt << " " << lista[i] << ": " << Yn[i][nv+1] << endl; } exitPolitely(EXIT_SUCCESS); } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks> * * 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/>. */ #include <cstdlib> // EXIT_SUCCESS, EXIT_FAILURE #include <pybind11/embed.h> #include "item.hpp" #include "utils.hpp" #include "components/command_line.hpp" #include "components/searcher.hpp" #include "version.hpp" namespace py = pybind11; int main(int argc, char *argv[]) { using valid_opts = std::initializer_list<string>; const auto main = command_line::option_group("Main", "necessarily inclusive arguments; at least one required") ("-a", "--author", "Specify authors", "AUTHOR") ("-t", "--title", "Specify title", "TITLE") ("-s", "--serie", "Specify serie", "SERIE") ("-p", "--publisher", "Specify publisher", "PUBLISHER"); const auto excl = command_line::option_group("Exclusive", "cannot be combined with any other arguments") ("-d", "--ident", "Specify an item identification (such as DOI, URL, etc.)", "IDENT"); const auto exact = command_line::option_group("Exact", "all are optional") ("-y", "--year", "Specify year of release. " "A prefix modifier can be used to broaden the search. " "Available prefixes are <, >, <=, >=.", "YEAR") ("-L", "--language", "Specify text language", "LANG") ("-e", "--edition", "Specify item edition", "EDITION") ("-E", "--extension", "Specify item extension", "EXT", valid_opts{"epub", "pdf", "djvu"}) ("-i", "--isbn", "Specify item ISBN", "ISBN"); const auto misc = command_line::option_group("Miscellaneous") ("-h", "--help", "Display this text and exit") ("-v", "--version", "Print version information (" + build_info_short + ")") ("-D", "--debug", "Set logging level to debug"); const command_line::groups groups = {main, excl, exact, misc}; auto logger = logger::create("main"); logger->set_pattern("%l: %v"); logger->set_level(spdlog::level::warn); spdlog::register_logger(logger); try { /* Parse command line arguments. */ string progname = argv[0]; vector<string> args(argv + 1, argv + argc); auto cli = cliparser::make(std::move(progname), std::move(groups)); cli->process_arguments(args); if (cli->has("debug")) logger->set_level(spdlog::level::debug); logger->debug("the mighty eldwyrm has been summoned!"); if (cli->has("help")) { cli->usage(); return EXIT_SUCCESS; } else if (cli->has("version")) { print_build_info(); return EXIT_SUCCESS; } else if (args.empty()) { cli->usage(); return EXIT_FAILURE; } cli->validate_arguments(); const auto err = utils::validate_download_dir(cli->get(0)); if (err) { logger->error("invalid download directory: {}.", err.message()); return EXIT_FAILURE; } /* * Start the Python interpreter and keep it alive until * program termination. */ py::scoped_interpreter guard{}; const bookwyrm::item wanted(cli); bookwyrm::searcher(wanted).search(); } catch (const cli_error &err) { logger->error(err.what() + string("; see --help")); return EXIT_FAILURE; } logger->debug("terminating successfully..."); return EXIT_SUCCESS; } <commit_msg>"hath" is cooler than "has"<commit_after>/* * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks> * * 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/>. */ #include <cstdlib> // EXIT_SUCCESS, EXIT_FAILURE #include <pybind11/embed.h> #include "item.hpp" #include "utils.hpp" #include "components/command_line.hpp" #include "components/searcher.hpp" #include "version.hpp" namespace py = pybind11; int main(int argc, char *argv[]) { using valid_opts = std::initializer_list<string>; const auto main = command_line::option_group("Main", "necessarily inclusive arguments; at least one required") ("-a", "--author", "Specify authors", "AUTHOR") ("-t", "--title", "Specify title", "TITLE") ("-s", "--serie", "Specify serie", "SERIE") ("-p", "--publisher", "Specify publisher", "PUBLISHER"); const auto excl = command_line::option_group("Exclusive", "cannot be combined with any other arguments") ("-d", "--ident", "Specify an item identification (such as DOI, URL, etc.)", "IDENT"); const auto exact = command_line::option_group("Exact", "all are optional") ("-y", "--year", "Specify year of release. " "A prefix modifier can be used to broaden the search. " "Available prefixes are <, >, <=, >=.", "YEAR") ("-L", "--language", "Specify text language", "LANG") ("-e", "--edition", "Specify item edition", "EDITION") ("-E", "--extension", "Specify item extension", "EXT", valid_opts{"epub", "pdf", "djvu"}) ("-i", "--isbn", "Specify item ISBN", "ISBN"); const auto misc = command_line::option_group("Miscellaneous") ("-h", "--help", "Display this text and exit") ("-v", "--version", "Print version information (" + build_info_short + ")") ("-D", "--debug", "Set logging level to debug"); const command_line::groups groups = {main, excl, exact, misc}; auto logger = logger::create("main"); logger->set_pattern("%l: %v"); logger->set_level(spdlog::level::warn); spdlog::register_logger(logger); try { /* Parse command line arguments. */ string progname = argv[0]; vector<string> args(argv + 1, argv + argc); auto cli = cliparser::make(std::move(progname), std::move(groups)); cli->process_arguments(args); if (cli->has("debug")) logger->set_level(spdlog::level::debug); logger->debug("the mighty eldwyrm hath been summoned!"); if (cli->has("help")) { cli->usage(); return EXIT_SUCCESS; } else if (cli->has("version")) { print_build_info(); return EXIT_SUCCESS; } else if (args.empty()) { cli->usage(); return EXIT_FAILURE; } cli->validate_arguments(); const auto err = utils::validate_download_dir(cli->get(0)); if (err) { logger->error("invalid download directory: {}.", err.message()); return EXIT_FAILURE; } /* * Start the Python interpreter and keep it alive until * program termination. */ py::scoped_interpreter guard{}; const bookwyrm::item wanted(cli); bookwyrm::searcher(wanted).search(); } catch (const cli_error &err) { logger->error(err.what() + string("; see --help")); return EXIT_FAILURE; } logger->debug("terminating successfully..."); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <irrlicht.h> using namespace irr; namespace ic = irr::core; namespace is = irr::scene; namespace iv = irr::video; struct MyEventReceiver : IEventReceiver { bool OnEvent(const SEvent &event) { // If input is of keyboard type (KEY_INPUT) // and a pressed key // and the key is ESCAPE if (event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown && event.KeyInput.Key == KEY_ESCAPE) exit(0); return false; } }; int main() { // Event Receiver MyEventReceiver receiver; // Initialization of the rendering system and window IrrlichtDevice *device = createDevice(iv::EDT_OPENGL, ic::dimension2d<u32>(640, 480), 16, false, false, false, &receiver); iv::IVideoDriver *driver = device->getVideoDriver(); is::ISceneManager *smgr = device->getSceneManager(); // // Loading a mesh // is::IAnimatedMesh *mesh = smgr->getMesh("data/tris.md2"); // // Creating node from mesh // is::IAnimatedMeshSceneNode *node = smgr->addAnimatedMeshSceneNode(mesh); is::ICameraSceneNode *camera = smgr->addCameraSceneNodeMaya(); // camera->setTarget(node->getPosition()); while(device->run()) { driver->beginScene(true, true, iv::SColor(0,50,100,255)); // Draw the scene smgr->drawAll(); // driver->endScene(); } device->drop(); return 0; } <commit_msg>ENH: first keyboard input for the character movement<commit_after>#include <irrlicht.h> using namespace irr; namespace ic = irr::core; namespace is = irr::scene; namespace iv = irr::video; class MyEventReceiver : public IEventReceiver { public: bool OnEvent(const SEvent &event) { // If input is of keyboard type (KEY_INPUT) // and a pressed key // and the key is ESCAPE if (event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown && event.KeyInput.Key == KEY_ESCAPE) exit(0); if (event.EventType == irr::EET_KEY_INPUT_EVENT) KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown; return false; } virtual bool IsKeyDown(EKEY_CODE keyCode) const { return KeyIsDown[keyCode]; } MyEventReceiver() { for (u32 i=0; i<KEY_KEY_CODES_COUNT; ++i) KeyIsDown[i] = false; } private: //store the state of each key bool KeyIsDown[KEY_KEY_CODES_COUNT]; }; int main() { // Event Receiver MyEventReceiver receiver; // Initialization of the rendering system and window IrrlichtDevice *device = createDevice(iv::EDT_OPENGL, ic::dimension2d<u32>(640, 480), 16, false, false, false, &receiver); iv::IVideoDriver *driver = device->getVideoDriver(); is::ISceneManager *smgr = device->getSceneManager(); // // Loading a mesh is::IAnimatedMesh *mesh = smgr->getMesh("data/test_with_bones_and_skinweights_and_modif.x"); // // Creating node from mesh is::IAnimatedMeshSceneNode *node = smgr->addAnimatedMeshSceneNode(mesh); //ic::vector3df scale(0.005,0.005,0.005); //node->setScale( scale ); is::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS(); //camera->setTarget(node->getPosition()); //is::ICameraSceneNode *camera = smgr->addCameraSceneNode(node, ic::vector3df(0,0,0),ic::vector3df(0,0,5),-1, true); // In order to do framerate independent movement, we have to know // how long it was since the last frame u32 then = device->getTimer()->getTime(); // This is the movemen speed in units per second. const f32 movementSpeed = 5.f; while(device->run()) { const u32 now = device->getTimer()->getTime(); const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds int lastFPS = -1; then = now; driver->beginScene(true, true, iv::SColor(0,50,100,255)); core::vector3df nodePosition = node->getPosition(); if(receiver.IsKeyDown(irr::KEY_KEY_Q)) nodePosition.X -= movementSpeed * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_KEY_D)) nodePosition.X += movementSpeed * frameDeltaTime; node->setPosition(nodePosition); // Draw the scene smgr->drawAll(); driver->endScene(); int fps = driver->getFPS(); if (lastFPS != fps) { core::stringw tmp(L"Movement Example - Irrlicht Engine ["); tmp += driver->getName(); tmp += L"] fps: "; tmp += fps; device->setWindowCaption(tmp.c_str()); lastFPS = fps; } } device->drop(); return 0; } <|endoftext|>
<commit_before>#include "camera/perspective.h" #include "engine/cosine_debugger.h" #include "geom/rect.h" #include "geom/vector.h" #include "geom/point.h" #include "image/image.h" #include "node/group/simple.h" #include "node/solid/sphere.h" #include "node/solid/infinite_plane.h" #include "renderer/settings.h" #include "renderer/serial/serial.h" #include "renderer/parallel/parallel.h" #include "supersampling/random.h" #include "world/world.h" #include <iostream> #include <cmath> using namespace Svit; int main (void) { Settings settings; settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.max_thread_count = 4; settings.tile_size = Vector2i(100, 100); settings.max_sample_count = 20; settings.adaptive_sample_step = 2; SimpleGroup scene; InfinitePlane infinite_plane(Point3(0.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0)); scene.add(infinite_plane); Sphere* spheres[100]; int i = 0; for (float x = -3.0; x < 3.0; x += 0.5) for (float z = 0.0; z < 6.0; z += 0.5) { spheres[i] = new Sphere(Point3(x, 0.5, z), (float)(rand() % 15)/100.0); scene.add(*spheres[i]); i++; } PerspectiveCamera camera( Point3(0.0, 0.75, -2.0), Vector3(0.0, 0.0, 1.0), Vector3(0.0, 1.0, 0.0), settings.whole_area.get_aspect_ratio(), M_PI/2.0); World world; world.scene = &scene; world.camera = &camera; CosineDebuggerEngine engine; ParallelRenderer renderer; //SerialRenderer renderer; RandomSuperSampling super_sampling(true); Image image = renderer.render(world, settings, engine, super_sampling); image.write(std::string("output.png")); return 0; } <commit_msg>Adaptive thread count<commit_after>#include "camera/perspective.h" #include "engine/cosine_debugger.h" #include "geom/rect.h" #include "geom/vector.h" #include "geom/point.h" #include "image/image.h" #include "node/group/simple.h" #include "node/solid/sphere.h" #include "node/solid/infinite_plane.h" #include "renderer/settings.h" #include "renderer/serial/serial.h" #include "renderer/parallel/parallel.h" #include "supersampling/random.h" #include "world/world.h" #include <iostream> #include <cmath> #include <thread> using namespace Svit; int main (void) { Settings settings; settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.max_thread_count = std::thread::hardware_concurrency(); settings.tile_size = Vector2i(100, 100); settings.max_sample_count = 20; settings.adaptive_sample_step = 2; SimpleGroup scene; InfinitePlane infinite_plane(Point3(0.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0)); scene.add(infinite_plane); Sphere* spheres[100]; int i = 0; for (float x = -3.0; x < 3.0; x += 0.5) for (float z = 0.0; z < 6.0; z += 0.5) { spheres[i] = new Sphere(Point3(x, 0.5, z), (float)(rand() % 15)/100.0); scene.add(*spheres[i]); i++; } PerspectiveCamera camera( Point3(0.0, 0.75, -2.0), Vector3(0.0, 0.0, 1.0), Vector3(0.0, 1.0, 0.0), settings.whole_area.get_aspect_ratio(), M_PI/2.0); World world; world.scene = &scene; world.camera = &camera; CosineDebuggerEngine engine; ParallelRenderer renderer; //SerialRenderer renderer; RandomSuperSampling super_sampling(true); Image image = renderer.render(world, settings, engine, super_sampling); image.write(std::string("output.png")); return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <fstream> #include <string> #include <map> #include <memory> #include <SDL.h> #include <Console.h> #include <Cart.h> #include <Controller.h> #include <APU.h> #include <SoundQueue.h> const unsigned int WINDOW_WIDTH = 256*2; const unsigned int WINDOW_HEIGHT = 240*2; const unsigned int GAME_FPS = 60; const unsigned int TICKS_PER_FRAME = 1000 / GAME_FPS; SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; SDL_Texture *frameTexture = NULL; std::unique_ptr<SoundQueue> soundQueue; Console console; std::map<SDL_Keycode,Controller::Button> controllerKeyBinds; bool initVideo() { // init SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL_Init() failed: %s\n", SDL_GetError()); return false; } // set texture scaling to nearest pixel sampling (sharp pixels) if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0")) { printf("SDL_SetHint() failed\n"); return false; } // create window window = SDL_CreateWindow( "ScootNES", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (window == NULL) { printf("SDL_CreateWindow() failed: %s\n", SDL_GetError()); return false; } // create renderer for window renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED); // | SDL_RENDERER_PRESENTVSYNC); if (renderer == NULL) { printf("SDL_CreateRederer() failed: %s\n", SDL_GetError()); return false; } // set colour used for drawing operations e.g. SDL_RenderClear SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); // create texture that we'll display and update each frame frameTexture = SDL_CreateTexture( renderer, SDL_GetWindowPixelFormat(window), SDL_TEXTUREACCESS_STREAMING, 256, 240); if (frameTexture == NULL) { printf("SDL_CreateTexture() failed: %s\n", SDL_GetError()); return false; } return true; } bool initSound() { if (SDL_Init(SDL_INIT_AUDIO) < 0) { printf("SDL_Init() failed: %s\n", SDL_GetError()); return false; } soundQueue = std::unique_ptr<SoundQueue>(new SoundQueue); if (!soundQueue || soundQueue->init(44100)) { printf("Sound queue init failed: %s\n", SDL_GetError()); return false; } return true; } void freeAndQuitSDL() { SDL_DestroyTexture(frameTexture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); window = NULL; renderer = NULL; frameTexture = NULL; SDL_Quit(); } void addControllerKeyBinds() { controllerKeyBinds[SDLK_UP] = Controller::BUTTON_UP; controllerKeyBinds[SDLK_DOWN] = Controller::BUTTON_DOWN; controllerKeyBinds[SDLK_LEFT] = Controller::BUTTON_LEFT; controllerKeyBinds[SDLK_RIGHT] = Controller::BUTTON_RIGHT; controllerKeyBinds[SDLK_z] = Controller::BUTTON_A; controllerKeyBinds[SDLK_x] = Controller::BUTTON_B; controllerKeyBinds[SDLK_SPACE] = Controller::BUTTON_SELECT; controllerKeyBinds[SDLK_RETURN] = Controller::BUTTON_START; } int main(int argc, char *args[]) { if (argc < 2) { printf("Rom path not provided\n"); return 1; } if (!initVideo()) { printf("initVideo() failed\n"); return 1; } if (!initSound()) { printf("initSound() failed\n"); return 1; } std::string romFileName(args[1]); if (!console.loadINesFile(romFileName)) { printf("failed to read file\n"); return 1; } console.boot(); addControllerKeyBinds(); // main loop bool isQuitting = false; bool isPaused = false; SDL_Event event; while (!isQuitting) { // track time elapsed during frame/loop unsigned int frameTimer = SDL_GetTicks(); // handle events while (SDL_PollEvent(&event) != 0) { if (event.type == SDL_QUIT) { isQuitting = true; } else if (event.type == SDL_KEYDOWN) { SDL_Keycode sym = event.key.keysym.sym; if (controllerKeyBinds.count(sym) > 0) { console.controller1.press(controllerKeyBinds[sym]); } else if (sym == SDLK_ESCAPE) { isQuitting = true; } else if (sym == SDLK_p) { isPaused ^= 1; } } else if (event.type == SDL_KEYUP) { SDL_Keycode sym = event.key.keysym.sym; if (controllerKeyBinds.count(sym) > 0) { console.controller1.release(controllerKeyBinds[sym]); } } } // clear screen to black SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(renderer); // spin cpu for 1 frame if (!isPaused) { console.runForOneFrame(); } // apply frame buffer data to texture SDL_UpdateTexture(frameTexture, NULL, console.getFrameBuffer(), 256 * sizeof(uint32_t)); // render the texture SDL_RenderCopy(renderer, frameTexture, NULL, NULL); // finally present render target to the window SDL_RenderPresent(renderer); // retrieve buffered sound samples APU::sample_t soundBuf[2048]; long soundBufLength = console.apu.readSamples(soundBuf, 2048); // play samples in the buffer soundQueue->write(soundBuf, soundBufLength); // delay frame to enforce framerate frameTimer = SDL_GetTicks() - frameTimer; if (frameTimer < TICKS_PER_FRAME) { SDL_Delay(TICKS_PER_FRAME - frameTimer); } } // cleanup freeAndQuitSDL(); return 0; } <commit_msg>Use exceptions when initializing video and audio<commit_after>#include <cstdio> #include <fstream> #include <string> #include <map> #include <memory> #include <exception> #include <stdexcept> #include <SDL.h> #include <Console.h> #include <Cart.h> #include <Controller.h> #include <APU.h> #include <SoundQueue.h> const unsigned int WINDOW_WIDTH = 256*2; const unsigned int WINDOW_HEIGHT = 240*2; const unsigned int GAME_FPS = 60; const unsigned int TICKS_PER_FRAME = 1000 / GAME_FPS; SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; SDL_Texture *frameTexture = NULL; std::unique_ptr<SoundQueue> soundQueue; Console console; std::map<SDL_Keycode,Controller::Button> controllerKeyBinds; void initSDL() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { throw std::runtime_error(std::string("SDL_Init() failed: ") + SDL_GetError()); } } void setTextureScaling() { // nearest pixel sampling (i.e. sharp pixels, no aliasing) if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0")) { throw std::runtime_error(std::string("SDL_SetHint() failed: ") + SDL_GetError()); } } void createWindow() { window = SDL_CreateWindow( "ScootNES", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (window == NULL) { throw std::runtime_error(std::string("SDL_CreateWindow() failed: ") + SDL_GetError()); } } void createRendererForWindow() { renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED); // | SDL_RENDERER_PRESENTVSYNC); if (renderer == NULL) { throw std::runtime_error(std::string("SDL_CreateRenderer() failed: ") + SDL_GetError()); } } void setRendererDrawColor() { // set colour used for drawing operations e.g. SDL_RenderClear SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); } void createTextureForRenderer() { // create texture that we'll display and update each frame frameTexture = SDL_CreateTexture( renderer, SDL_GetWindowPixelFormat(window), SDL_TEXTUREACCESS_STREAMING, 256, 240); if (frameTexture == NULL) { throw std::runtime_error(std::string("SDL_CreateTexture() failed: ") + SDL_GetError()); } } void initVideo() { initSDL(); createWindow(); createRendererForWindow(); setRendererDrawColor(); createTextureForRenderer(); setTextureScaling(); } void initSDLAudio() { if (SDL_Init(SDL_INIT_AUDIO) < 0) { throw std::runtime_error(std::string("SDL_Init() failed: ") + SDL_GetError()); } } void initSoundQueue() { soundQueue = std::unique_ptr<SoundQueue>(new SoundQueue); if (!soundQueue || soundQueue->init(44100)) { throw std::runtime_error(std::string("Sound queue init failed: ") + SDL_GetError()); } } bool initSound() { initSDLAudio(); initSoundQueue(); } void freeAndQuitSDL() { SDL_DestroyTexture(frameTexture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); window = NULL; renderer = NULL; frameTexture = NULL; SDL_Quit(); } void addControllerKeyBinds() { controllerKeyBinds[SDLK_UP] = Controller::BUTTON_UP; controllerKeyBinds[SDLK_DOWN] = Controller::BUTTON_DOWN; controllerKeyBinds[SDLK_LEFT] = Controller::BUTTON_LEFT; controllerKeyBinds[SDLK_RIGHT] = Controller::BUTTON_RIGHT; controllerKeyBinds[SDLK_z] = Controller::BUTTON_A; controllerKeyBinds[SDLK_x] = Controller::BUTTON_B; controllerKeyBinds[SDLK_SPACE] = Controller::BUTTON_SELECT; controllerKeyBinds[SDLK_RETURN] = Controller::BUTTON_START; } int main(int argc, char *args[]) { if (argc < 2) { printf("Rom path not provided\n"); return 1; } try { initVideo(); initSound(); } catch (std::exception const& e) { printf(e.what()); SDL_Quit(); return 1; } std::string romFileName(args[1]); if (!console.loadINesFile(romFileName)) { printf("failed to read file\n"); return 1; } console.boot(); addControllerKeyBinds(); // main loop bool isQuitting = false; bool isPaused = false; SDL_Event event; while (!isQuitting) { // track time elapsed during frame/loop unsigned int frameTimer = SDL_GetTicks(); // handle events while (SDL_PollEvent(&event) != 0) { if (event.type == SDL_QUIT) { isQuitting = true; } else if (event.type == SDL_KEYDOWN) { SDL_Keycode sym = event.key.keysym.sym; if (controllerKeyBinds.count(sym) > 0) { console.controller1.press(controllerKeyBinds[sym]); } else if (sym == SDLK_ESCAPE) { isQuitting = true; } else if (sym == SDLK_p) { isPaused ^= 1; } } else if (event.type == SDL_KEYUP) { SDL_Keycode sym = event.key.keysym.sym; if (controllerKeyBinds.count(sym) > 0) { console.controller1.release(controllerKeyBinds[sym]); } } } // clear screen to black SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(renderer); // spin cpu for 1 frame if (!isPaused) { console.runForOneFrame(); } // apply frame buffer data to texture SDL_UpdateTexture(frameTexture, NULL, console.getFrameBuffer(), 256 * sizeof(uint32_t)); // render the texture SDL_RenderCopy(renderer, frameTexture, NULL, NULL); // finally present render target to the window SDL_RenderPresent(renderer); // retrieve buffered sound samples APU::sample_t soundBuf[2048]; long soundBufLength = console.apu.readSamples(soundBuf, 2048); // play samples in the buffer soundQueue->write(soundBuf, soundBufLength); // delay frame to enforce framerate frameTimer = SDL_GetTicks() - frameTimer; if (frameTimer < TICKS_PER_FRAME) { SDL_Delay(TICKS_PER_FRAME - frameTimer); } } // cleanup freeAndQuitSDL(); return 0; } <|endoftext|>
<commit_before>#include "stdafx.h" int main( int argc, char** argv ) { return 0; } <commit_msg>Fox unused parameters in main().<commit_after>#include "stdafx.h" int main( int /*argc*/, char** /*argv*/ ) { return 0; } <|endoftext|>
<commit_before>//#include <exception> #include <iostream> #include <unistd.h> #include <ctime> //#include <cstdlib> #include <cstring> #include <sys/socket.h> #include <netdb.h> //#include <fastcgi.h> #include <fcgio.h> int getSocket(int port); void diff(timespec start, timespec end); int main(int argc, char** argv){ timespec init, end; std::cout << "[INFO] Starting Server on port 1234" << std::endl; int serverSocket = getSocket(9999); std::cout << "Got socket number " << serverSocket << std::endl; std::streambuf * cin_streambuf = std::cin.rdbuf(); std::streambuf * cout_streambuf = std::cout.rdbuf(); std::streambuf * cerr_streambuf = std::cerr.rdbuf(); FCGX_Request request; FCGX_Init(); FCGX_InitRequest(&request, serverSocket, 0); int status = FCGX_Accept_r(&request); std::cout << "Accept status is " << status << std::endl; while(status == 0) { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &init); std::cout << "Have a request" << std::endl; fcgi_streambuf cin_fcgi_streambuf(request.in); fcgi_streambuf cout_fcgi_streambuf(request.out); fcgi_streambuf cerr_fcgi_streambuf(request.err); std::cin.rdbuf(&cin_fcgi_streambuf); std::cout.rdbuf(&cout_fcgi_streambuf); std::cerr.rdbuf(&cerr_fcgi_streambuf); std::cout << "Centent-type: text/html\r\n\r\n"; std::cout << "<html><body>Hi there</body></html>" << std::endl; FCGX_Finish_r(&request); std::cin.rdbuf(cin_streambuf); std::cout.rdbuf(cout_streambuf); std::cerr.rdbuf(cerr_streambuf); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); diff(init, end); status = FCGX_Accept_r(&request); } } int getSocket(int port) { int status = 0; int socketNumber = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); std::cout << "Socket number " << socketNumber << std::endl; struct sockaddr_in server; memset(&server, 0 , sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(port); status = bind(socketNumber, (struct sockaddr *) & server, sizeof(server)); std::cout << "Bind status " << status << std::endl; listen(socketNumber, 32); return socketNumber; } void diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } std::cout << temp.tv_sec << ":" << temp.tv_nsec/1000000.0f << std::endl; } <commit_msg>/media/ -> Displayes all the fastcgi env variables received.<commit_after>//#include <exception> #include <iostream> #include <unistd.h> #include <ctime> //#include <cstdlib> #include <cstring> #include <sys/socket.h> #include <netdb.h> //#include <fastcgi.h> #include <fcgio.h> int getSocket(int port); void diff(timespec start, timespec end); int main(int argc, char** argv){ timespec init, end; std::cout << "[INFO] Starting Server on port 1234" << std::endl; int serverSocket = getSocket(9999); std::cout << "Got socket number " << serverSocket << std::endl; std::streambuf * cin_streambuf = std::cin.rdbuf(); std::streambuf * cout_streambuf = std::cout.rdbuf(); std::streambuf * cerr_streambuf = std::cerr.rdbuf(); FCGX_Request request; FCGX_Init(); FCGX_InitRequest(&request, serverSocket, 0); int status = FCGX_Accept_r(&request); std::cout << "Accept status is " << status << std::endl; while(status == 0) { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &init); std::cout << "Have a request" << std::endl; fcgi_streambuf cin_fcgi_streambuf(request.in); fcgi_streambuf cout_fcgi_streambuf(request.out); fcgi_streambuf cerr_fcgi_streambuf(request.err); std::cin.rdbuf(&cin_fcgi_streambuf); std::cout.rdbuf(&cout_fcgi_streambuf); std::cerr.rdbuf(&cerr_fcgi_streambuf); std::cout << "Centent-type: text/html\r\n\r\n"; std::cout << "<html><body>Hi there<p>" << std::endl; char **env = request.envp; while (*(++env)) std::cout << *env << "<p>" << std::endl; std::cout << "</body></html>" << std::endl; FCGX_Finish_r(&request); std::cin.rdbuf(cin_streambuf); std::cout.rdbuf(cout_streambuf); std::cerr.rdbuf(cerr_streambuf); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); diff(init, end); status = FCGX_Accept_r(&request); } } int getSocket(int port) { int status = 0; int socketNumber = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); std::cout << "Socket number " << socketNumber << std::endl; struct sockaddr_in server; memset(&server, 0 , sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(port); status = bind(socketNumber, (struct sockaddr *) & server, sizeof(server)); std::cout << "Bind status " << status << std::endl; listen(socketNumber, 32); return socketNumber; } void diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } std::cout << temp.tv_sec << ":" << temp.tv_nsec/1000000.0f << std::endl; } <|endoftext|>
<commit_before>#include <ArkeIndustries.CPPUtilities/Common.h> #include <iostream> #include <fstream> #include <memory> #include <string> #include <chrono> #include <vector> using namespace std; class bf_interpreter { struct instruction { enum class opcode { add_to_dp, add_to_cell, output, input, branch_if_zero, branch_if_nonzero, store, add_cells }; opcode op; sword data1; sword data2; }; unique_ptr<uint8[]> memory; unique_ptr<uint8[]> raw_program; vector<instruction> program; word raw_size; word ip; word dp; word find_run(word start_index); word find_matched(word start_index); public: bf_interpreter(string filename); void parse(); void print(string filename); void run(); }; bf_interpreter::bf_interpreter(string filename) { ifstream file(filename, ios::ate | ios::binary); this->raw_size = static_cast<word>(file.tellg()); this->ip = 0; this->dp = 0; this->raw_program = make_unique<uint8[]>(this->raw_size); this->memory = make_unique<uint8[]>(65536); file.seekg(ios::beg); file.read(reinterpret_cast<char*>(this->raw_program.get()), this->raw_size); file.close(); } void bf_interpreter::print(string filename) { ofstream file(filename); for (auto& i : this->program) { switch (i.op) { case instruction::opcode::add_to_dp: file << "ADD_DP\t" << i.data1; break; case instruction::opcode::add_to_cell: file << "ADD_CL\t" << i.data1; break; case instruction::opcode::add_cells: file << "ADD\t" << i.data1 << "\t" << i.data2; break; case instruction::opcode::output: file << "OUT\t"; break; case instruction::opcode::input: file << "IN\t"; break; case instruction::opcode::store: file << "STORE\t" << i.data1; break; case instruction::opcode::branch_if_zero: file << "BZ\t" << i.data1; break; case instruction::opcode::branch_if_nonzero: file << "BNZ\t" << i.data1; break; } file << endl; } } word bf_interpreter::find_run(word start_index) { auto character = this->raw_program[start_index]; word count = 0; while (start_index < this->raw_size && this->raw_program[start_index++] == character) count++; return count; } word bf_interpreter::find_matched(word start_index) { word needed = 1; sword direction = this->program[start_index].op == instruction::opcode::branch_if_zero ? 1 : -1; while (needed) { start_index += direction; if (this->program[start_index].op == instruction::opcode::branch_if_zero) needed += direction; else if (this->program[start_index].op == instruction::opcode::branch_if_nonzero) needed -= direction; } return start_index; } void bf_interpreter::parse() { for (word i = 0; i < this->raw_size; i++) { instruction instr; instr.data1 = 0; instr.data2 = 0; switch (this->raw_program[i]) { case '>': instr.op = instruction::opcode::add_to_dp; instr.data1 = this->find_run(i); i += instr.data1 - 1; break; case '<': instr.op = instruction::opcode::add_to_dp; instr.data1 = -1 * this->find_run(i); i -= instr.data1 + 1; break; case '+': instr.op = instruction::opcode::add_to_cell; instr.data1 = this->find_run(i); i += instr.data1 - 1; break; case '-': instr.op = instruction::opcode::add_to_cell; instr.data1 = -1 * this->find_run(i); i -= instr.data1 + 1; break; case '.': instr.op = instruction::opcode::output; break; case ',': instr.op = instruction::opcode::input; break; case '[': instr.op = instruction::opcode::branch_if_zero; break; case ']': instr.op = instruction::opcode::branch_if_nonzero; break; default: continue; } this->program.push_back(instr); } for (word i = 0; i < this->program.size(); i++) { switch (this->program[i].op) { case instruction::opcode::branch_if_zero: if (i + 2 < this->program.size() && this->program[i + 1].op == instruction::opcode::add_to_cell && this->program[i + 1].data1 % 2 == 0 && this->program[i + 2].op == instruction::opcode::branch_if_nonzero) { this->program[i].op = instruction::opcode::store; this->program[i].data1 = 0; this->program.erase(this->program.begin() + i + 1, this->program.begin() + i + 3); continue; } else if (i + 5 < this->program.size() && this->program[i + 1].op == instruction::opcode::add_to_cell && this->program[i + 1].data1 == -1 && this->program[i + 5].op == instruction::opcode::branch_if_nonzero) { if (this->program[i + 2].op != instruction::opcode::add_to_dp || this->program[i + 4].op != instruction::opcode::add_to_dp || this->program[i + 3].op != instruction::opcode::add_to_cell) continue; if (this->program[i + 2].data1 < 0 && this->program[i + 4].data1 < 0) continue; if (this->program[i + 2].data1 >= 0 && this->program[i + 4].data1 >= 0) continue; this->program[i].op = instruction::opcode::add_cells; this->program[i].data1 = this->program[i + 2].data1; this->program[i].data2 = this->program[i + 3].data1; this->program[i + 1].op = instruction::opcode::store; this->program[i + 1].data1 = 0; this->program.erase(this->program.begin() + i + 2, this->program.begin() + i + 6); } break; } } for (word i = 0; i < this->program.size(); i++) { switch (this->program[i].op) { case instruction::opcode::branch_if_zero: case instruction::opcode::branch_if_nonzero: this->program[i].data1 = this->find_matched(i) + 1; break; } } } void bf_interpreter::run() { while (this->ip < this->program.size()) { auto instr = this->program[this->ip++]; switch (instr.op) { case instruction::opcode::add_to_dp: this->dp += instr.data1; break; case instruction::opcode::add_to_cell: this->memory[this->dp] += static_cast<uint8>(instr.data1); break; case instruction::opcode::output: cout << this->memory[this->dp]; break; case instruction::opcode::input: cin >> this->memory[this->dp]; break; case instruction::opcode::store: this->memory[this->dp] = static_cast<uint8>(instr.data1); break; case instruction::opcode::add_cells: this->memory[this->dp + instr.data1] += static_cast<uint8>(instr.data2 * this->memory[this->dp]); break; case instruction::opcode::branch_if_zero: if (this->memory[this->dp] == 0) this->ip = instr.data1; break; case instruction::opcode::branch_if_nonzero: if (this->memory[this->dp] != 0) this->ip = instr.data1; break; } } } int main() { bf_interpreter bf("Mandlebrot.txt"); bf.parse(); bf.print("Output.txt"); auto start = chrono::system_clock::now(); bf.run(); auto end = chrono::system_clock::now(); cout << endl << endl << "Total Time: " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << endl; system("pause"); return 0; } <commit_msg>Removed dependency on util.<commit_after>#include <iostream> #include <fstream> #include <memory> #include <string> #include <chrono> #include <vector> #include <cstdint> using namespace std; class bf_interpreter { struct instruction { enum class opcode { add_to_dp, add_to_cell, output, input, branch_if_zero, branch_if_nonzero, store, add_cells }; opcode op; int data1; int data2; }; unique_ptr<uint8_t[]> memory; unique_ptr<uint8_t[]> raw_program; vector<instruction> program; size_t raw_size; size_t ip; size_t dp; size_t find_run(size_t start_index); size_t find_matched(size_t start_index); public: bf_interpreter(string filename); void parse(); void print(string filename); void run(); }; bf_interpreter::bf_interpreter(string filename) { ifstream file(filename, ios::ate | ios::binary); this->raw_size = static_cast<size_t>(file.tellg()); this->ip = 0; this->dp = 0; this->raw_program = make_unique<uint8_t[]>(this->raw_size); this->memory = make_unique<uint8_t[]>(65536); file.seekg(ios::beg); file.read(reinterpret_cast<char*>(this->raw_program.get()), this->raw_size); file.close(); } void bf_interpreter::print(string filename) { ofstream file(filename); for (auto& i : this->program) { switch (i.op) { case instruction::opcode::add_to_dp: file << "ADD_DP\t" << i.data1; break; case instruction::opcode::add_to_cell: file << "ADD_CL\t" << i.data1; break; case instruction::opcode::add_cells: file << "ADD\t" << i.data1 << "\t" << i.data2; break; case instruction::opcode::output: file << "OUT\t"; break; case instruction::opcode::input: file << "IN\t"; break; case instruction::opcode::store: file << "STORE\t" << i.data1; break; case instruction::opcode::branch_if_zero: file << "BZ\t" << i.data1; break; case instruction::opcode::branch_if_nonzero: file << "BNZ\t" << i.data1; break; } file << endl; } } size_t bf_interpreter::find_run(size_t start_index) { auto character = this->raw_program[start_index]; size_t count = 0; while (start_index < this->raw_size && this->raw_program[start_index++] == character) count++; return count; } size_t bf_interpreter::find_matched(size_t start_index) { size_t needed = 1; auto direction = this->program[start_index].op == instruction::opcode::branch_if_zero ? 1 : -1; while (needed) { start_index += direction; if (this->program[start_index].op == instruction::opcode::branch_if_zero) needed += direction; else if (this->program[start_index].op == instruction::opcode::branch_if_nonzero) needed -= direction; } return start_index; } void bf_interpreter::parse() { for (size_t i = 0; i < this->raw_size; i++) { instruction instr; instr.data1 = 0; instr.data2 = 0; switch (this->raw_program[i]) { case '>': instr.op = instruction::opcode::add_to_dp; instr.data1 = this->find_run(i); i += instr.data1 - 1; break; case '<': instr.op = instruction::opcode::add_to_dp; instr.data1 = -1 * this->find_run(i); i -= instr.data1 + 1; break; case '+': instr.op = instruction::opcode::add_to_cell; instr.data1 = this->find_run(i); i += instr.data1 - 1; break; case '-': instr.op = instruction::opcode::add_to_cell; instr.data1 = -1 * this->find_run(i); i -= instr.data1 + 1; break; case '.': instr.op = instruction::opcode::output; break; case ',': instr.op = instruction::opcode::input; break; case '[': instr.op = instruction::opcode::branch_if_zero; break; case ']': instr.op = instruction::opcode::branch_if_nonzero; break; default: continue; } this->program.push_back(instr); } for (size_t i = 0; i < this->program.size(); i++) { switch (this->program[i].op) { case instruction::opcode::branch_if_zero: if (i + 2 < this->program.size() && this->program[i + 1].op == instruction::opcode::add_to_cell && this->program[i + 1].data1 % 2 == 0 && this->program[i + 2].op == instruction::opcode::branch_if_nonzero) { this->program[i].op = instruction::opcode::store; this->program[i].data1 = 0; this->program.erase(this->program.begin() + i + 1, this->program.begin() + i + 3); continue; } else if (i + 5 < this->program.size() && this->program[i + 1].op == instruction::opcode::add_to_cell && this->program[i + 1].data1 == -1 && this->program[i + 5].op == instruction::opcode::branch_if_nonzero) { if (this->program[i + 2].op != instruction::opcode::add_to_dp || this->program[i + 4].op != instruction::opcode::add_to_dp || this->program[i + 3].op != instruction::opcode::add_to_cell) continue; if (this->program[i + 2].data1 < 0 && this->program[i + 4].data1 < 0) continue; if (this->program[i + 2].data1 >= 0 && this->program[i + 4].data1 >= 0) continue; this->program[i].op = instruction::opcode::add_cells; this->program[i].data1 = this->program[i + 2].data1; this->program[i].data2 = this->program[i + 3].data1; this->program[i + 1].op = instruction::opcode::store; this->program[i + 1].data1 = 0; this->program.erase(this->program.begin() + i + 2, this->program.begin() + i + 6); } break; } } for (size_t i = 0; i < this->program.size(); i++) { switch (this->program[i].op) { case instruction::opcode::branch_if_zero: case instruction::opcode::branch_if_nonzero: this->program[i].data1 = this->find_matched(i) + 1; break; } } } void bf_interpreter::run() { while (this->ip < this->program.size()) { auto instr = this->program[this->ip++]; switch (instr.op) { case instruction::opcode::add_to_dp: this->dp += instr.data1; break; case instruction::opcode::add_to_cell: this->memory[this->dp] += static_cast<uint8_t>(instr.data1); break; case instruction::opcode::output: cout << this->memory[this->dp]; break; case instruction::opcode::input: cin >> this->memory[this->dp]; break; case instruction::opcode::store: this->memory[this->dp] = static_cast<uint8_t>(instr.data1); break; case instruction::opcode::add_cells: this->memory[this->dp + instr.data1] += static_cast<uint8_t>(instr.data2 * this->memory[this->dp]); break; case instruction::opcode::branch_if_zero: if (this->memory[this->dp] == 0) this->ip = instr.data1; break; case instruction::opcode::branch_if_nonzero: if (this->memory[this->dp] != 0) this->ip = instr.data1; break; } } } int main() { bf_interpreter bf("Hello World.txt"); bf.parse(); bf.print("Output.txt"); auto start = chrono::system_clock::now(); bf.run(); auto end = chrono::system_clock::now(); cout << endl << endl << "Total Time: " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << endl; system("pause"); return 0; } <|endoftext|>
<commit_before>#include "twsDL.h" #include "utilities/debug.h" #include <QtCore/QCoreApplication> #include <stdio.h> int main(int argc, char *argv[]) { QCoreApplication app( argc, argv ); if( argc > 3 ) { fprintf( stderr, "Usage: %s [configuration file] [worktodo file]\n", argv[0] ); return 2; } QString workfile; if( argc == 3 ) { workfile = argv[2]; } Test::TwsDL twsDL( argc == 2 ? argv[1] : "twsDL.cfg", workfile ); QObject::connect( &twsDL, SIGNAL(finished()), &app, SLOT(quit()) ); twsDL.start(); int ret = app.exec(); Q_ASSERT( ret == 0 ); Test::TwsDL::State state = twsDL.currentState(); Q_ASSERT( (state == Test::TwsDL::QUIT_READY) || (state == Test::TwsDL::QUIT_ERROR) ); if( state == Test::TwsDL::QUIT_READY ) { return 0; } else { qDebug() << "Finished with errors."; return 1; } } <commit_msg>twsDL, followup "reading workFile"<commit_after>#include "twsDL.h" #include "utilities/debug.h" #include <QtCore/QCoreApplication> #include <stdio.h> int main(int argc, char *argv[]) { QCoreApplication app( argc, argv ); if( argc > 3 ) { fprintf( stderr, "Usage: %s [configuration file] [worktodo file]\n", argv[0] ); return 2; } QString workfile; if( argc == 3 ) { workfile = argv[2]; } Test::TwsDL twsDL( argc >= 2 ? argv[1] : "twsDL.cfg", workfile ); QObject::connect( &twsDL, SIGNAL(finished()), &app, SLOT(quit()) ); twsDL.start(); int ret = app.exec(); Q_ASSERT( ret == 0 ); Test::TwsDL::State state = twsDL.currentState(); Q_ASSERT( (state == Test::TwsDL::QUIT_READY) || (state == Test::TwsDL::QUIT_ERROR) ); if( state == Test::TwsDL::QUIT_READY ) { return 0; } else { qDebug() << "Finished with errors."; return 1; } } <|endoftext|>
<commit_before>#include <SDL2/SDL.h> #include <GL/gl.h> #include <GL/glu.h> #include <cstdlib> struct Window { const char * name = (const char *) "Game Of Life On fieldace"; SDL_Window * window = nullptr; SDL_Renderer * render = nullptr; SDL_GLContext context; SDL_Event event; bool quit_flag = false; // bool button_left_set = false; // bool button_right_set = false; // bool game_step = false; // bool help_flag = false; int width = 640; int height = 640; // int counter = 0; // int mouse_x, mouse_y; } gw; GLUquadricObj * sphere; void golos_panic( void ) { SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Error", SDL_GetError(), nullptr ); exit( EXIT_FAILURE ); } void golos_init( void ) { // init SDL subsystems if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ) ) { golos_panic(); } // init double buffer SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // color configuration SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 6 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); // create SDL window gw.window = SDL_CreateWindow( gw.name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, gw.width, gw.height, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL ); if ( gw.window == nullptr ) { golos_panic(); } // init OpenGL context gw.context = SDL_GL_CreateContext( gw.window ); // init OpenGL params glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); glClearDepth( 1.0 ); glDepthFunc( GL_LESS ); glEnable( GL_DEPTH_TEST ); glShadeModel( GL_SMOOTH ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 45.0f, (float) gw.width / (float) gw.height, 0.1f, 100.0f ); glMatrixMode( GL_MODELVIEW ); // init sphere sphere = gluNewQuadric(); } void golos_event( void ) { SDL_PollEvent( &( gw.event ) ); switch ( gw.event.type ) { case SDL_QUIT: gw.quit_flag = true; break; default: break; } } void golos_loop( void ) { // input code } void golos_render( void ) { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glColor3f( 0.0f, 1.0f, 0.0f ); glLoadIdentity(); glTranslatef( 0.0f, 0.0f, -4.0f ); glRotatef( -45.0f, 1.0f, 0.0f, 0.0f ); glPolygonMode( GL_BACK, GL_POINT ); glPolygonMode( GL_FRONT, GL_LINE ); glColor3f( 0.0f, 1.0f, 0.0f ); gluSphere( sphere, 1.0f, 16, 16 ); glFlush(); SDL_GL_SwapWindow( gw.window ); } void golos_destroy( void ) { gluDeleteQuadric( sphere ); SDL_DestroyWindow( gw.window ); SDL_Quit(); } int main( int argc, char ** argv ) { float current = 0.0f, last = 0.0f; golos_init(); while ( !gw.quit_flag ) { current = (float) SDL_GetTicks(); if ( current > last + 1000.0f / 60.0f ) { golos_event(); golos_loop(); golos_render(); last = current; } } golos_destroy(); return EXIT_SUCCESS; }<commit_msg>[add] camera rotation<commit_after>#include <SDL2/SDL.h> #include <GL/gl.h> #include <GL/glu.h> #include <cstdlib> float camera[] = {3,0,0}; // положение камеры в сферических координатах float dtheta = 0.012; float dphi = 0.01; struct Window { const char * name = (const char *) "Game Of Life On sphere"; SDL_Window * window = nullptr; SDL_Renderer * render = nullptr; SDL_GLContext context; SDL_Event event; bool quit_flag = false; // bool button_left_set = false; // bool button_right_set = false; // bool game_step = false; // bool help_flag = false; int width = 640; int height = 640; // int counter = 0; // int mouse_x, mouse_y; } gw; GLUquadricObj * sphere; void golos_panic( void ) { SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Error", SDL_GetError(), nullptr ); exit( EXIT_FAILURE ); } void golos_init( void ) { // init SDL subsystems if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ) ) { golos_panic(); } // init double buffer SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // color configuration SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 6 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); // create SDL window gw.window = SDL_CreateWindow( gw.name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, gw.width, gw.height, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL ); if ( gw.window == nullptr ) { golos_panic(); } // init OpenGL context gw.context = SDL_GL_CreateContext( gw.window ); // init OpenGL params glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); glClearDepth( 1.0 ); glDepthFunc( GL_LESS ); glEnable( GL_DEPTH_TEST ); glShadeModel( GL_SMOOTH ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 45.0f, (float) gw.width / (float) gw.height, 0.1f, 100.0f ); glMatrixMode( GL_MODELVIEW ); // init sphere sphere = gluNewQuadric(); } void golos_event( void ) { SDL_PollEvent( &( gw.event ) ); switch ( gw.event.type ) { case SDL_QUIT: gw.quit_flag = true; break; default: break; } } void golos_loop( void ) { // input code } void golos_render( void ) { float rect_camera[3]; // положение камеры в прямоугольных координатах rect_camera[0] = camera[0] * sin(camera[1]) * cos(camera[2]); rect_camera[1] = camera[0] * sin(camera[1]) * sin(camera[2]); rect_camera[2] = camera[0] * cos(camera[1]); camera[1] += dtheta; camera[2] += dphi; glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glColor3f( 0.0f, 1.0f, 0.0f ); glLoadIdentity(); gluLookAt(rect_camera[0], rect_camera[1], rect_camera[2], 0, 0, 0, 0, 1, 0); glTranslatef( 0.0f, 0.0f, 0.0f ); glRotatef( -45.0f, 1.0f, 0.0f, 0.0f ); glPolygonMode( GL_BACK, GL_POINT ); glPolygonMode( GL_FRONT, GL_LINE ); glColor3f( 0.0f, 1.0f, 0.0f ); gluQuadricTexture(sphere, true); gluQuadricNormals(sphere, GLU_SMOOTH); gluSphere( sphere, 1.0f, 16, 16 ); glFlush(); SDL_GL_SwapWindow( gw.window ); } void golos_destroy( void ) { gluDeleteQuadric( sphere ); SDL_DestroyWindow( gw.window ); SDL_Quit(); } int main( int argc, char ** argv ) { float current = 0.0f, last = 0.0f; golos_init(); while ( !gw.quit_flag ) { current = (float) SDL_GetTicks(); if ( current > last + 1000.0f / 60.0f ) { golos_event(); golos_loop(); golos_render(); last = current; } } golos_destroy(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main() { return 0; } <commit_msg>began on the main part of the shell<commit_after>#include <iostream> #include <unistd.h> #include <pwd.h> #include <sys/types.h> using namespace std; int main() { string userinput = ""; while(userinput != "exit") { getline(cin, userinput); } return 0; } <|endoftext|>
<commit_before>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "callbacks.h" #include "worker/thread.h" using namespace v8; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{out, in, &event_handler} { int err; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } void use_main_log_file(string &&main_log_file) { Logger::to_file(main_log_file.c_str()); } void handle_events() { LOGGER << "Handling events." << endl; } private: Queue in; Queue out; uv_async_t event_handler; WorkerThread worker_thread; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]); if (maybe_options.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybe_options.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; Nan::Callback *callback = new Nan::Callback(info[1].As<Function>()); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } callback->Call(0, 0); delete callback; } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void initialize(Local<Object> exports) { exports->Set( Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); exports->Set( Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); exports->Set( Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); } NODE_MODULE(sfw, initialize); <commit_msg>Invoke a callback on configuration ack (and Command acks in general)<commit_after>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <utility> #include <unordered_map> #include <vector> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "worker/worker_thread.h" using v8::Local; using v8::Value; using v8::Object; using v8::String; using v8::Function; using v8::FunctionTemplate; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; using std::unordered_map; using std::vector; using std::move; using std::make_pair; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{&event_handler} { int err; next_command_id = 0; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } void use_main_log_file(string &&main_log_file) { Logger::to_file(main_log_file.c_str()); } void use_worker_log_file(string &&worker_log_file, unique_ptr<Nan::Callback> callback) { CommandID command_id = next_command_id; CommandPayload command_payload(next_command_id, COMMAND_LOG_FILE, move(worker_log_file)); Message log_file_message(move(command_payload)); pending_callbacks.emplace(command_id, move(callback)); next_command_id++; LOGGER << "Sending command " << log_file_message << " to worker thread." << endl; worker_thread.send(move(log_file_message)); } void handle_events() { Nan::HandleScope scope; LOGGER << "Handling messages from the worker thread." << endl; unique_ptr<vector<Message>> accepted = worker_thread.receive_all(); if (!accepted) { LOGGER << "No messages waiting." << endl; return; } LOGGER << accepted->size() << " messages to process." << endl; for (auto it = accepted->begin(); it != accepted->end(); ++it) { const AckPayload *ack_message = it->as_ack(); if (ack_message) { auto maybe_callback = pending_callbacks.find(ack_message->get_key()); if (maybe_callback == pending_callbacks.end()) { LOGGER << "Ignoring unexpected ack " << *it << endl; continue; } unique_ptr<Nan::Callback> callback = move(maybe_callback->second); pending_callbacks.erase(maybe_callback); callback->Call(0, nullptr); continue; } const FileSystemPayload *filesystem_message = it->as_filesystem(); if (filesystem_message) { LOGGER << "Received filesystem event message " << *it << endl; continue; } LOGGER << "Received unexpected message " << *it << endl; } } private: uv_async_t event_handler; WorkerThread worker_thread; CommandID next_command_id; unordered_map<CommandID, unique_ptr<Nan::Callback>> pending_callbacks; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; bool async = false; Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]); if (maybe_options.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybe_options.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; unique_ptr<Nan::Callback> callback(new Nan::Callback(info[1].As<Function>())); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } if (!worker_log_file.empty()) { instance.use_worker_log_file(move(worker_log_file), move(callback)); async = true; } if (!async) { callback->Call(0, 0); } } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void initialize(Local<Object> exports) { exports->Set( Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); exports->Set( Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); exports->Set( Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); } NODE_MODULE(sfw, initialize); <|endoftext|>
<commit_before>/***************************************************************************************** * * * MIT License * * * * Copyright (c) 2017 Maxime Pinard * * * * 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 <ext_headers.hpp> EXT_HEADERS_OPEN #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/System/Clock.hpp> #include <SFML/Window/Event.hpp> #include <imgui.h> #include <imgui-SFML.h> #include <iostream> #include <cstring> EXT_HEADERS_CLOSE #include <imgui_easy_theming.hpp> #include <ulltostr.hpp> #include <clamp.hpp> #define COUNT_OF(X) (sizeof(X)/sizeof(*(X))) static const int minBase = 2; static const int maxBase = 36; struct TextFilters { static int filterBase(ImGuiTextEditCallbackData* data) { if((data->EventChar >= '0' && data->EventChar < '0' + *(static_cast<int*>(data->UserData))) || (data->EventChar >= 'A' && data->EventChar < 'A' + *(static_cast<int*>(data->UserData)) - 10)) { return 0; } else { return 1; } } }; struct BaseBlock { int base; char txt[128]; explicit BaseBlock(int base_ = 10, const char* txt_ = "0") : base(base_), txt() { std::strncpy(txt, txt_, 128); } }; struct ThemeHolder { const char name[12]; const ImGuiColorTheme& colorTheme; bool enabled; }; static void setupStyle(); void setupStyle() { ImGuiStyle& style = ImGui::GetStyle(); style.WindowRounding = 0.0f; style.ScrollbarRounding = 0.0f; ImGuiEasyTheming(ImGuiColorTheme::ArcDark); } int main() { bool inputCustomBases = false; bool outputDefaultBases = true; bool outputCustomBases = false; int baseNb = 0; bool valUpd = false; bool baseUpd = false; bool tooBig = false; unsigned long long int value = 0; BaseBlock input{10}; BaseBlock defaultBasesOut[]{ BaseBlock{10}, BaseBlock{16}, BaseBlock{8}, BaseBlock{2} }; const char* defaultBasesOutDisplayTxt[]{ "DEC", "HEX", "OCT", "BIN" }; std::vector<BaseBlock> extraBasesOut{}; std::vector<ThemeHolder> themeHolders{ ThemeHolder{"Arc Dark", ImGuiColorTheme::ArcDark, true}, ThemeHolder{"Flat UI", ImGuiColorTheme::FlatUI, false}, ThemeHolder{"Mint-Y-Dark", ImGuiColorTheme::MintYDark, false}, }; sf::Clock deltaClock; ImGui::GetIO().IniFilename = nullptr; // disable .ini saving setupStyle(); sf::RenderWindow window(sf::VideoMode(300, 480), "Base converter"); window.setVerticalSyncEnabled(true); ImGui::SFML::Init(window); errno = 0; ImGui::SetNextWindowPos(ImVec2(0, 0)); while(window.isOpen()) { sf::Event event{}; while(window.pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if(event.type == sf::Event::Closed) { window.close(); } } ImGui::SFML::Update(window, deltaClock.restart()); ImGui::SetNextWindowSize(ImVec2{ static_cast<float>(window.getSize().x), static_cast<float>(window.getSize().y) }); ImGui::Begin("Main", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar); if(ImGui::BeginMenuBar()) { if(ImGui::BeginMenu("Options")) { if(ImGui::BeginMenu("Color theme", true)) { for(ThemeHolder& themeHolder : themeHolders) { if(ImGui::MenuItem(themeHolder.name, nullptr, themeHolder.enabled)) { ImGuiEasyTheming(themeHolder.colorTheme); for(ThemeHolder& themeHolderBis : themeHolders) { themeHolderBis.enabled = false; } themeHolder.enabled = true; } } ImGui::EndMenu(); } if(ImGui::MenuItem("Quit")) { ImGui::SFML::Shutdown(); return EXIT_SUCCESS; } ImGui::EndMenu(); } ImGui::EndMenuBar(); } ImGui::PushItemWidth(-1); if(ImGui::CollapsingHeader("Input", ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Leaf)) { if(inputCustomBases) { ImGui::PushItemWidth(-40); valUpd |= ImGui::InputText("Value##IN", input.txt, sizeof(input.txt), ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_CallbackCharFilter, TextFilters::filterBase, &input.base); baseUpd |= ImGui::DragInt("Base", &input.base, 1, minBase, maxBase, "%.0f"); input.base = clamp(input.base, minBase, maxBase); ImGui::PopItemWidth(); } else { ImGui::PushItemWidth(ImGui::GetWindowContentRegionWidth() - 50); valUpd |= ImGui::InputText("##IN", input.txt, sizeof(input.txt), ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_CallbackCharFilter, TextFilters::filterBase, &input.base); ImGui::PopItemWidth(); ImGui::PushItemWidth(50); ImGui::SameLine(); if(ImGui::Combo("##base", &baseNb, defaultBasesOutDisplayTxt, COUNT_OF(defaultBasesOutDisplayTxt))) { input.base = defaultBasesOut[baseNb].base; baseUpd = true; } ImGui::PopItemWidth(); } } if(valUpd) { errno = 0; value = std::strtoull(input.txt, nullptr, input.base); tooBig = errno != 0; if(tooBig) { for(BaseBlock& baseBlock : defaultBasesOut) { baseBlock.txt[0] = '\0'; } for(BaseBlock& baseBlock : extraBasesOut) { baseBlock.txt[0] = '\0'; } } else { for(BaseBlock& baseBlock : defaultBasesOut) { if(!ulltostr(value, baseBlock.base, baseBlock.txt, sizeof(baseBlock.txt))) { baseBlock.txt[0] = '\0'; } } for(BaseBlock& baseBlock : extraBasesOut) { if(!ulltostr(value, baseBlock.base, baseBlock.txt, sizeof(baseBlock.txt))) { baseBlock.txt[0] = '\0'; } } } valUpd = false; } if(baseUpd) { if(!ulltostr(value, input.base, input.txt, sizeof(input.txt))) { input.txt[0] = '0'; input.txt[1] = '\0'; valUpd = true; } baseUpd = false; } if(tooBig) { ImGui::TextColored(ImColor(255, 0, 0), "Value is too large"); } if(outputDefaultBases) { const char* defaultOutputTxt = outputCustomBases ? "Default output" : "Output"; if(ImGui::CollapsingHeader(defaultOutputTxt, ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Leaf)) { ImGui::PushItemWidth(-30); for(size_t i = 0; i < COUNT_OF(defaultBasesOut); ++i) { ImGui::InputText(defaultBasesOutDisplayTxt[i], defaultBasesOut[i].txt, sizeof(defaultBasesOut[i].txt), ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_ReadOnly); } ImGui::PopItemWidth(); } } if(outputCustomBases) { const char* customOutputTxt = outputDefaultBases ? "Custom output" : "Output"; if(ImGui::CollapsingHeader(customOutputTxt, ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Leaf)) { for(BaseBlock& baseBlock : extraBasesOut) { ImGui::PushItemWidth(-40); ImGui::PushID(&baseBlock); ImGui::InputText("Value", baseBlock.txt, sizeof(baseBlock.txt), ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_ReadOnly); if(ImGui::DragInt("Base", &baseBlock.base, 1, minBase, maxBase, "%.0f")) { baseBlock.base = clamp(baseBlock.base, minBase, maxBase); if(!ulltostr(value, baseBlock.base, baseBlock.txt, sizeof(baseBlock.txt))) { baseBlock.txt[0] = '\0'; } } ImGui::PopID(); ImGui::PopItemWidth(); ImGui::Separator(); } if(ImGui::Button("Add", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 20))) { extraBasesOut.emplace_back(defaultBasesOut[0].base, defaultBasesOut[0].txt); } ImGui::SameLine(); if(ImGui::Button("Remove", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 20))) { if(!extraBasesOut.empty()) { extraBasesOut.pop_back(); } } } } if(ImGui::CollapsingHeader("Config", ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Checkbox("Input custom bases", &inputCustomBases); ImGui::Checkbox("Output default bases", &outputDefaultBases); ImGui::Checkbox("Output custom base", &outputCustomBases); } ImGui::PopItemWidth(); ImGui::End(); window.clear(); ImGui::Render(); window.display(); } ImGui::SFML::Shutdown(); return EXIT_SUCCESS; } <commit_msg>Added missing 's'<commit_after>/***************************************************************************************** * * * MIT License * * * * Copyright (c) 2017 Maxime Pinard * * * * 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 <ext_headers.hpp> EXT_HEADERS_OPEN #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/System/Clock.hpp> #include <SFML/Window/Event.hpp> #include <imgui.h> #include <imgui-SFML.h> #include <iostream> #include <cstring> EXT_HEADERS_CLOSE #include <imgui_easy_theming.hpp> #include <ulltostr.hpp> #include <clamp.hpp> #define COUNT_OF(X) (sizeof(X)/sizeof(*(X))) static const int minBase = 2; static const int maxBase = 36; struct TextFilters { static int filterBase(ImGuiTextEditCallbackData* data) { if((data->EventChar >= '0' && data->EventChar < '0' + *(static_cast<int*>(data->UserData))) || (data->EventChar >= 'A' && data->EventChar < 'A' + *(static_cast<int*>(data->UserData)) - 10)) { return 0; } else { return 1; } } }; struct BaseBlock { int base; char txt[128]; explicit BaseBlock(int base_ = 10, const char* txt_ = "0") : base(base_), txt() { std::strncpy(txt, txt_, 128); } }; struct ThemeHolder { const char name[12]; const ImGuiColorTheme& colorTheme; bool enabled; }; static void setupStyle(); void setupStyle() { ImGuiStyle& style = ImGui::GetStyle(); style.WindowRounding = 0.0f; style.ScrollbarRounding = 0.0f; ImGuiEasyTheming(ImGuiColorTheme::ArcDark); } int main() { bool inputCustomBases = false; bool outputDefaultBases = true; bool outputCustomBases = false; int baseNb = 0; bool valUpd = false; bool baseUpd = false; bool tooBig = false; unsigned long long int value = 0; BaseBlock input{10}; BaseBlock defaultBasesOut[]{ BaseBlock{10}, BaseBlock{16}, BaseBlock{8}, BaseBlock{2} }; const char* defaultBasesOutDisplayTxt[]{ "DEC", "HEX", "OCT", "BIN" }; std::vector<BaseBlock> extraBasesOut{}; std::vector<ThemeHolder> themeHolders{ ThemeHolder{"Arc Dark", ImGuiColorTheme::ArcDark, true}, ThemeHolder{"Flat UI", ImGuiColorTheme::FlatUI, false}, ThemeHolder{"Mint-Y-Dark", ImGuiColorTheme::MintYDark, false}, }; sf::Clock deltaClock; ImGui::GetIO().IniFilename = nullptr; // disable .ini saving setupStyle(); sf::RenderWindow window(sf::VideoMode(300, 480), "Base converter"); window.setVerticalSyncEnabled(true); ImGui::SFML::Init(window); errno = 0; ImGui::SetNextWindowPos(ImVec2(0, 0)); while(window.isOpen()) { sf::Event event{}; while(window.pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if(event.type == sf::Event::Closed) { window.close(); } } ImGui::SFML::Update(window, deltaClock.restart()); ImGui::SetNextWindowSize(ImVec2{ static_cast<float>(window.getSize().x), static_cast<float>(window.getSize().y) }); ImGui::Begin("Main", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar); if(ImGui::BeginMenuBar()) { if(ImGui::BeginMenu("Options")) { if(ImGui::BeginMenu("Color theme", true)) { for(ThemeHolder& themeHolder : themeHolders) { if(ImGui::MenuItem(themeHolder.name, nullptr, themeHolder.enabled)) { ImGuiEasyTheming(themeHolder.colorTheme); for(ThemeHolder& themeHolderBis : themeHolders) { themeHolderBis.enabled = false; } themeHolder.enabled = true; } } ImGui::EndMenu(); } if(ImGui::MenuItem("Quit")) { ImGui::SFML::Shutdown(); return EXIT_SUCCESS; } ImGui::EndMenu(); } ImGui::EndMenuBar(); } ImGui::PushItemWidth(-1); if(ImGui::CollapsingHeader("Input", ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Leaf)) { if(inputCustomBases) { ImGui::PushItemWidth(-40); valUpd |= ImGui::InputText("Value##IN", input.txt, sizeof(input.txt), ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_CallbackCharFilter, TextFilters::filterBase, &input.base); baseUpd |= ImGui::DragInt("Base", &input.base, 1, minBase, maxBase, "%.0f"); input.base = clamp(input.base, minBase, maxBase); ImGui::PopItemWidth(); } else { ImGui::PushItemWidth(ImGui::GetWindowContentRegionWidth() - 50); valUpd |= ImGui::InputText("##IN", input.txt, sizeof(input.txt), ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_CallbackCharFilter, TextFilters::filterBase, &input.base); ImGui::PopItemWidth(); ImGui::PushItemWidth(50); ImGui::SameLine(); if(ImGui::Combo("##base", &baseNb, defaultBasesOutDisplayTxt, COUNT_OF(defaultBasesOutDisplayTxt))) { input.base = defaultBasesOut[baseNb].base; baseUpd = true; } ImGui::PopItemWidth(); } } if(valUpd) { errno = 0; value = std::strtoull(input.txt, nullptr, input.base); tooBig = errno != 0; if(tooBig) { for(BaseBlock& baseBlock : defaultBasesOut) { baseBlock.txt[0] = '\0'; } for(BaseBlock& baseBlock : extraBasesOut) { baseBlock.txt[0] = '\0'; } } else { for(BaseBlock& baseBlock : defaultBasesOut) { if(!ulltostr(value, baseBlock.base, baseBlock.txt, sizeof(baseBlock.txt))) { baseBlock.txt[0] = '\0'; } } for(BaseBlock& baseBlock : extraBasesOut) { if(!ulltostr(value, baseBlock.base, baseBlock.txt, sizeof(baseBlock.txt))) { baseBlock.txt[0] = '\0'; } } } valUpd = false; } if(baseUpd) { if(!ulltostr(value, input.base, input.txt, sizeof(input.txt))) { input.txt[0] = '0'; input.txt[1] = '\0'; valUpd = true; } baseUpd = false; } if(tooBig) { ImGui::TextColored(ImColor(255, 0, 0), "Value is too large"); } if(outputDefaultBases) { const char* defaultOutputTxt = outputCustomBases ? "Default output" : "Output"; if(ImGui::CollapsingHeader(defaultOutputTxt, ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Leaf)) { ImGui::PushItemWidth(-30); for(size_t i = 0; i < COUNT_OF(defaultBasesOut); ++i) { ImGui::InputText(defaultBasesOutDisplayTxt[i], defaultBasesOut[i].txt, sizeof(defaultBasesOut[i].txt), ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_ReadOnly); } ImGui::PopItemWidth(); } } if(outputCustomBases) { const char* customOutputTxt = outputDefaultBases ? "Custom output" : "Output"; if(ImGui::CollapsingHeader(customOutputTxt, ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Leaf)) { for(BaseBlock& baseBlock : extraBasesOut) { ImGui::PushItemWidth(-40); ImGui::PushID(&baseBlock); ImGui::InputText("Value", baseBlock.txt, sizeof(baseBlock.txt), ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_ReadOnly); if(ImGui::DragInt("Base", &baseBlock.base, 1, minBase, maxBase, "%.0f")) { baseBlock.base = clamp(baseBlock.base, minBase, maxBase); if(!ulltostr(value, baseBlock.base, baseBlock.txt, sizeof(baseBlock.txt))) { baseBlock.txt[0] = '\0'; } } ImGui::PopID(); ImGui::PopItemWidth(); ImGui::Separator(); } if(ImGui::Button("Add", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 20))) { extraBasesOut.emplace_back(defaultBasesOut[0].base, defaultBasesOut[0].txt); } ImGui::SameLine(); if(ImGui::Button("Remove", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 20))) { if(!extraBasesOut.empty()) { extraBasesOut.pop_back(); } } } } if(ImGui::CollapsingHeader("Config", ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Checkbox("Input custom bases", &inputCustomBases); ImGui::Checkbox("Output default bases", &outputDefaultBases); ImGui::Checkbox("Output custom bases", &outputCustomBases); } ImGui::PopItemWidth(); ImGui::End(); window.clear(); ImGui::Render(); window.display(); } ImGui::SFML::Shutdown(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright (c) 2014, Richard Martin 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 Richard Martin 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 RICHARD MARTIN 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 "BookReader.hpp" #include "MainWindow.hpp" #include <gtkmm/application.h> #include <gtkmm/window.h> using namespace Glib; using namespace Gtk; HeaderBar * header_bar; int main(int argc, char* argv[]) { /*Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example"); Gtk::Window window; window.set_title("Drawing text example"); window.set_default_size(600,900); BookReader area; window.add(area); area.show(); return app->run(window); */ RefPtr<Application> app = Application::create(argc, argv, "org.rmarti.dnd"); MainWindow window; // Shows the window and returns when it is closed. return app->run(window); }<commit_msg>Clean the cruft out of main<commit_after>/* Copyright (c) 2014, Richard Martin 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 Richard Martin 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 RICHARD MARTIN 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 "BookReader.hpp" #include "MainWindow.hpp" #include <gtkmm/application.h> #include <gtkmm/window.h> using namespace Glib; using namespace Gtk; HeaderBar * header_bar; int main(int argc, char* argv[]) { RefPtr<Application> app = Application::create(argc, argv, "org.rmarti.dnd"); MainWindow window; return app->run(window); }<|endoftext|>
<commit_before>/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "./optimization/Optimizer.h" #include "Compiler.h" #include "Precompiler.h" #include "Profiler.h" #include "concepts.h" #include "config.h" #include "log.h" #include "tools.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iomanip> #include <sstream> #include <unistd.h> #include <unordered_map> using namespace std; using namespace vc4c; extern void disassemble(const std::string& input, const std::string& output, const OutputMode outputMode); static void printHelp() { vc4c::Configuration defaultConfig; std::cout << "Usage: vc4c [flags] [options] -o <destination> <sources>" << std::endl; std::cout << "flags:" << std::endl; std::cout << "\t-h, --help\t\tPrints this help message and exits" << std::endl; std::cout << "\t-v, --version\t\tPrints version and build info and exists" << std::endl; std::cout << "\t--verbose\t\tEnables verbose debug logging" << std::endl; std::cout << "\t--quiet\t\t\tQuiet verbose debug logging" << std::endl; std::cout << "\t-l, --log <file>\tWrite log output to the given file, defaults to stdout ('-')" << std::endl; std::cout << "\t--hex\t\t\tGenerate hex output (e.g. included in source-code)" << std::endl; std::cout << "\t--bin\t\t\tGenerate binary output (as used by VC4CL run-time)" << std::endl; std::cout << "\t--asm\t\t\tGenerate assembler output (for analysis only)" << std::endl; std::cout << "optimizations:" << std::endl; std::cout << "\t-O0,-O1,-O2,-O3\t\t\tSwitches to the specific optimization level, defaults to -O2" << std::endl; for(const auto& pass : vc4c::optimizations::Optimizer::ALL_PASSES) { std::cout << "\t--f" << std::left << std::setw(28) << pass.parameterName << pass.description << std::endl; // TODO print which optimization level includes optimization std::cout << "\t--fno-" << std::left << std::setw(25) << pass.parameterName << "Disables the above optimization" << std::endl; } std::cout << "optimization parameters:" << std::endl; std::cout << "\t--fcombine-load-threshold=" << defaultConfig.additionalOptions.combineLoadThreshold << "\tThe maximum distance between two literal loads to combine" << std::endl; std::cout << "\t--faccumulator-threshold=" << defaultConfig.additionalOptions.accumulatorThreshold << "\tThe maximum live-range of a local still considered to be mapped to an accumulator" << std::endl; std::cout << "\t--freplace-nop-threshold=" << defaultConfig.additionalOptions.replaceNopThreshold << "\tThe number of instructions to search for a replacement for NOPs" << std::endl; std::cout << "\t--fregister-resolver-rounds=" << defaultConfig.additionalOptions.registerResolverMaxRounds << "\tThe maximum number of rows for the register allocator" << std::endl; std::cout << "\t--fmove-constants-depth=" << defaultConfig.additionalOptions.moveConstantsDepth << "\tThe maximum depth of nested loops to move constants out of" << std::endl; std::cout << "\t--foptimization-iterations=" << defaultConfig.additionalOptions.maxOptimizationIterations << "\tThe maximum number of iterations to repeat the optimizations in" << std::endl; std::cout << "options:" << std::endl; std::cout << "\t--kernel-info\t\tWrite the kernel-info meta-data (as required by VC4CL run-time, default)" << std::endl; std::cout << "\t--no-kernel-info\tDont write the kernel-info meta-data" << std::endl; std::cout << "\t--spirv\t\t\tExplicitely use the SPIR-V front-end" << std::endl; std::cout << "\t--llvm\t\t\tExplicitely use the LLVM-IR front-end" << std::endl; std::cout << "\t--disassemble\t\tDisassembles the binary input to either hex or assembler output" << std::endl; std::cout << "\tany other option is passed to the pre-compiler" << std::endl; } #ifndef LLVM_LIBRARY_VERSION #define LLVM_LIBRARY_VERSION 0 #endif #ifndef VC4C_VERSION #define VC4C_VERSION "" #endif static std::string toVersionString(unsigned version) { std::stringstream s; s << (version / 10.0f); return s.str(); } static void printInfo() { std::cout << "Running VC4C in version: " << VC4C_VERSION << std::endl; std::cout << "Build configuration:" << std::endl; static const std::vector<std::string> infoString = { #ifdef DEBUG_MODE "debug mode", #endif #ifdef MULTI_THREADED "multi-threaded optimization", #endif #ifdef USE_CLANG_OPENCL "clang 3.9+ OpenCL features", #endif #if defined SPIRV_CLANG_PATH "SPIRV-LLVM clang in " SPIRV_CLANG_PATH, #if defined SPIRV_LLVM_SPIRV_PATH and defined SPIRV_FRONTEND "SPIR-V front-end", #endif #elif defined CLANG_PATH "clang in " CLANG_PATH, #endif #ifdef USE_LLVM_LIBRARY std::string("LLVM library front-end with libLLVM ") + toVersionString(LLVM_LIBRARY_VERSION), #endif #ifdef VC4CL_STDLIB_HEADER "VC4CL standard-library in " VC4CL_STDLIB_HEADER, #endif #ifdef SPIRV_FRONTEND "SPIR-V linker", #endif #ifdef VERIFIER_HEADER "vc4asm verification" #endif }; std::cout << vc4c::to_string<std::string>(infoString, "; ") << std::endl; } static auto availableOptimizations = vc4c::optimizations::Optimizer::getPasses(OptimizationLevel::FULL); /* * */ int main(int argc, char** argv) { std::unique_ptr<std::wofstream> fileLog; std::reference_wrapper<std::wostream> logStream = std::wcout; bool colorLog = true; #if DEBUG_MODE LogLevel minLevel = LogLevel::DEBUG; #else LogLevel minLevel = LogLevel::WARNING; #endif Configuration config; std::vector<std::string> inputFiles; std::string outputFile; std::string options; bool runDisassembler = false; int i = 1; for(; i < argc; ++i) { // treat an argument, which first character isnt "-", as an input file if(argv[i][0] != '-') { inputFiles.emplace_back(argv[i]); } // flags else if(strcmp("--help", argv[i]) == 0 || strcmp("-h", argv[i]) == 0) { printHelp(); return 0; } else if(strcmp("--version", argv[i]) == 0 || strcmp("-v", argv[i]) == 0) { printInfo(); return 0; } else if(strcmp("--quiet", argv[i]) == 0) minLevel = LogLevel::WARNING; else if(strcmp("--verbose", argv[i]) == 0) minLevel = LogLevel::DEBUG; else if(strcmp("--log", argv[i]) == 0 || strcmp("-l", argv[i]) == 0) { if(strcmp("-", argv[i + 1]) == 0) { colorLog = true; logStream = std::wcout; } else { colorLog = false; fileLog.reset(new std::wofstream(argv[i + 1])); logStream = *fileLog; } ++i; } else if(strcmp("--disassemble", argv[i]) == 0) runDisassembler = true; else if(strcmp("-o", argv[i]) == 0) { outputFile = argv[i + 1]; // any further parameter is an input-file i += 2; break; } else if(!vc4c::tools::parseConfigurationParameter(config, argv[i]) || strstr(argv[i], "-cl") == argv[i]) // pass every not understood option to the pre-compiler, as well as every OpenCL compiler option options.append(argv[i]).append(" "); } if(&logStream.get() == &std::wcout && outputFile == "-") { std::cerr << "Cannot write both log and data to stdout, aborting" << std::endl; return 6; } setLogger(logStream, colorLog, minLevel); if(inputFiles.empty()) { std::cerr << "No input file(s) specified, aborting!" << std::endl; return 2; } if(outputFile.empty()) { // special case: if input files is just one, we specify the implicit output file. std::string postfix; if(inputFiles.size() == 1) { switch(config.outputMode) { case OutputMode::BINARY: postfix = ".bin"; break; case OutputMode::HEX: postfix = ".hex"; break; case OutputMode::ASSEMBLER: postfix = ".s"; break; } outputFile = inputFiles[0] + postfix; } else { std::cerr << "No output file specified, aborting!" << std::endl; return 3; } } if(runDisassembler) { if(inputFiles.size() != 1) { std::cerr << "For disassembling, a single input file must be specified, aborting!" << std::endl; return 4; } logging::debug() << "Disassembling '" << inputFiles[0] << "' into '" << outputFile << "'..." << logging::endl; disassemble(inputFiles[0], outputFile, config.outputMode); return 0; } logging::debug() << "Compiling '" << to_string<std::string>(inputFiles, "', '") << "' into '" << outputFile << "' with optimization level " << static_cast<unsigned>(config.optimizationLevel) << " and options '" << options << "' ..." << logging::endl; Optional<std::string> inputFile; std::unique_ptr<std::istream> input; // link if necessary if(inputFiles.size() > 1) { std::vector<std::unique_ptr<std::istream>> fileStreams; std::unordered_map<std::istream*, Optional<std::string>> inputs; for(const std::string& file : inputFiles) { auto ifs = new std::ifstream(file); if(!ifs->is_open()) throw CompilationError(CompilationStep::PRECOMPILATION, "cannot find file", file); fileStreams.emplace_back(ifs); inputs.emplace(fileStreams.back().get(), Optional<std::string>(file)); } input.reset(new std::stringstream()); SourceType linkedType = Precompiler::linkSourceCode(inputs, *reinterpret_cast<std::ostream*>(input.get())); if(!isSupportedByFrontend(linkedType, config.frontend)) { std::cerr << "Selected front-end does not support the input-format generated by the linker, aborting! " << std::endl; return 5; } } else { const auto& file = inputFiles[0]; auto ifs = new std::ifstream(file); if(!ifs->is_open()) throw CompilationError(CompilationStep::PRECOMPILATION, "cannot find file", file); input.reset(ifs); inputFile = inputFiles[0]; } std::ofstream output(outputFile == "-" ? "/dev/stdout" : outputFile, std::ios_base::out | std::ios_base::trunc | std::ios_base::binary); PROFILE_START(Compiler); Compiler::compile(*input, output, config, options, inputFile); PROFILE_END(Compiler); PROFILE_RESULTS(); return 0; } <commit_msg>Fix: add guard when there is no argument<commit_after>/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "./optimization/Optimizer.h" #include "Compiler.h" #include "Precompiler.h" #include "Profiler.h" #include "concepts.h" #include "config.h" #include "log.h" #include "tools.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iomanip> #include <sstream> #include <unistd.h> #include <unordered_map> using namespace std; using namespace vc4c; extern void disassemble(const std::string& input, const std::string& output, const OutputMode outputMode); static void printHelp() { vc4c::Configuration defaultConfig; std::cout << "Usage: vc4c [flags] [options] -o <destination> <sources>" << std::endl; std::cout << "flags:" << std::endl; std::cout << "\t-h, --help\t\tPrints this help message and exits" << std::endl; std::cout << "\t-v, --version\t\tPrints version and build info and exists" << std::endl; std::cout << "\t--verbose\t\tEnables verbose debug logging" << std::endl; std::cout << "\t--quiet\t\t\tQuiet verbose debug logging" << std::endl; std::cout << "\t-l, --log <file>\tWrite log output to the given file, defaults to stdout ('-')" << std::endl; std::cout << "\t--hex\t\t\tGenerate hex output (e.g. included in source-code)" << std::endl; std::cout << "\t--bin\t\t\tGenerate binary output (as used by VC4CL run-time)" << std::endl; std::cout << "\t--asm\t\t\tGenerate assembler output (for analysis only)" << std::endl; std::cout << "optimizations:" << std::endl; std::cout << "\t-O0,-O1,-O2,-O3\t\t\tSwitches to the specific optimization level, defaults to -O2" << std::endl; for(const auto& pass : vc4c::optimizations::Optimizer::ALL_PASSES) { std::cout << "\t--f" << std::left << std::setw(28) << pass.parameterName << pass.description << std::endl; // TODO print which optimization level includes optimization std::cout << "\t--fno-" << std::left << std::setw(25) << pass.parameterName << "Disables the above optimization" << std::endl; } std::cout << "optimization parameters:" << std::endl; std::cout << "\t--fcombine-load-threshold=" << defaultConfig.additionalOptions.combineLoadThreshold << "\tThe maximum distance between two literal loads to combine" << std::endl; std::cout << "\t--faccumulator-threshold=" << defaultConfig.additionalOptions.accumulatorThreshold << "\tThe maximum live-range of a local still considered to be mapped to an accumulator" << std::endl; std::cout << "\t--freplace-nop-threshold=" << defaultConfig.additionalOptions.replaceNopThreshold << "\tThe number of instructions to search for a replacement for NOPs" << std::endl; std::cout << "\t--fregister-resolver-rounds=" << defaultConfig.additionalOptions.registerResolverMaxRounds << "\tThe maximum number of rows for the register allocator" << std::endl; std::cout << "\t--fmove-constants-depth=" << defaultConfig.additionalOptions.moveConstantsDepth << "\tThe maximum depth of nested loops to move constants out of" << std::endl; std::cout << "\t--foptimization-iterations=" << defaultConfig.additionalOptions.maxOptimizationIterations << "\tThe maximum number of iterations to repeat the optimizations in" << std::endl; std::cout << "options:" << std::endl; std::cout << "\t--kernel-info\t\tWrite the kernel-info meta-data (as required by VC4CL run-time, default)" << std::endl; std::cout << "\t--no-kernel-info\tDont write the kernel-info meta-data" << std::endl; std::cout << "\t--spirv\t\t\tExplicitely use the SPIR-V front-end" << std::endl; std::cout << "\t--llvm\t\t\tExplicitely use the LLVM-IR front-end" << std::endl; std::cout << "\t--disassemble\t\tDisassembles the binary input to either hex or assembler output" << std::endl; std::cout << "\tany other option is passed to the pre-compiler" << std::endl; } #ifndef LLVM_LIBRARY_VERSION #define LLVM_LIBRARY_VERSION 0 #endif #ifndef VC4C_VERSION #define VC4C_VERSION "" #endif static std::string toVersionString(unsigned version) { std::stringstream s; s << (version / 10.0f); return s.str(); } static void printInfo() { std::cout << "Running VC4C in version: " << VC4C_VERSION << std::endl; std::cout << "Build configuration:" << std::endl; static const std::vector<std::string> infoString = { #ifdef DEBUG_MODE "debug mode", #endif #ifdef MULTI_THREADED "multi-threaded optimization", #endif #ifdef USE_CLANG_OPENCL "clang 3.9+ OpenCL features", #endif #if defined SPIRV_CLANG_PATH "SPIRV-LLVM clang in " SPIRV_CLANG_PATH, #if defined SPIRV_LLVM_SPIRV_PATH and defined SPIRV_FRONTEND "SPIR-V front-end", #endif #elif defined CLANG_PATH "clang in " CLANG_PATH, #endif #ifdef USE_LLVM_LIBRARY std::string("LLVM library front-end with libLLVM ") + toVersionString(LLVM_LIBRARY_VERSION), #endif #ifdef VC4CL_STDLIB_HEADER "VC4CL standard-library in " VC4CL_STDLIB_HEADER, #endif #ifdef SPIRV_FRONTEND "SPIR-V linker", #endif #ifdef VERIFIER_HEADER "vc4asm verification" #endif }; std::cout << vc4c::to_string<std::string>(infoString, "; ") << std::endl; } static auto availableOptimizations = vc4c::optimizations::Optimizer::getPasses(OptimizationLevel::FULL); /* * */ int main(int argc, char** argv) { std::unique_ptr<std::wofstream> fileLog; std::reference_wrapper<std::wostream> logStream = std::wcout; bool colorLog = true; #if DEBUG_MODE LogLevel minLevel = LogLevel::DEBUG; #else LogLevel minLevel = LogLevel::WARNING; #endif Configuration config; std::vector<std::string> inputFiles; std::string outputFile; std::string options; bool runDisassembler = false; if (argc == 1) { printHelp(); return 0; } int i = 1; for(; i < argc; ++i) { // treat an argument, which first character isnt "-", as an input file if(argv[i][0] != '-') { inputFiles.emplace_back(argv[i]); } // flags else if(strcmp("--help", argv[i]) == 0 || strcmp("-h", argv[i]) == 0) { printHelp(); return 0; } else if(strcmp("--version", argv[i]) == 0 || strcmp("-v", argv[i]) == 0) { printInfo(); return 0; } else if(strcmp("--quiet", argv[i]) == 0) minLevel = LogLevel::WARNING; else if(strcmp("--verbose", argv[i]) == 0) minLevel = LogLevel::DEBUG; else if(strcmp("--log", argv[i]) == 0 || strcmp("-l", argv[i]) == 0) { if(strcmp("-", argv[i + 1]) == 0) { colorLog = true; logStream = std::wcout; } else { colorLog = false; fileLog.reset(new std::wofstream(argv[i + 1])); logStream = *fileLog; } ++i; } else if(strcmp("--disassemble", argv[i]) == 0) runDisassembler = true; else if(strcmp("-o", argv[i]) == 0) { outputFile = argv[i + 1]; // any further parameter is an input-file i += 2; break; } else if(!vc4c::tools::parseConfigurationParameter(config, argv[i]) || strstr(argv[i], "-cl") == argv[i]) // pass every not understood option to the pre-compiler, as well as every OpenCL compiler option options.append(argv[i]).append(" "); } if(&logStream.get() == &std::wcout && outputFile == "-") { std::cerr << "Cannot write both log and data to stdout, aborting" << std::endl; return 6; } setLogger(logStream, colorLog, minLevel); if(inputFiles.empty()) { std::cerr << "No input file(s) specified, aborting!" << std::endl; return 2; } if(outputFile.empty()) { // special case: if input files is just one, we specify the implicit output file. std::string postfix; if(inputFiles.size() == 1) { switch(config.outputMode) { case OutputMode::BINARY: postfix = ".bin"; break; case OutputMode::HEX: postfix = ".hex"; break; case OutputMode::ASSEMBLER: postfix = ".s"; break; } outputFile = inputFiles[0] + postfix; } else { std::cerr << "No output file specified, aborting!" << std::endl; return 3; } } if(runDisassembler) { if(inputFiles.size() != 1) { std::cerr << "For disassembling, a single input file must be specified, aborting!" << std::endl; return 4; } logging::debug() << "Disassembling '" << inputFiles[0] << "' into '" << outputFile << "'..." << logging::endl; disassemble(inputFiles[0], outputFile, config.outputMode); return 0; } logging::debug() << "Compiling '" << to_string<std::string>(inputFiles, "', '") << "' into '" << outputFile << "' with optimization level " << static_cast<unsigned>(config.optimizationLevel) << " and options '" << options << "' ..." << logging::endl; Optional<std::string> inputFile; std::unique_ptr<std::istream> input; // link if necessary if(inputFiles.size() > 1) { std::vector<std::unique_ptr<std::istream>> fileStreams; std::unordered_map<std::istream*, Optional<std::string>> inputs; for(const std::string& file : inputFiles) { auto ifs = new std::ifstream(file); if(!ifs->is_open()) throw CompilationError(CompilationStep::PRECOMPILATION, "cannot find file", file); fileStreams.emplace_back(ifs); inputs.emplace(fileStreams.back().get(), Optional<std::string>(file)); } input.reset(new std::stringstream()); SourceType linkedType = Precompiler::linkSourceCode(inputs, *reinterpret_cast<std::ostream*>(input.get())); if(!isSupportedByFrontend(linkedType, config.frontend)) { std::cerr << "Selected front-end does not support the input-format generated by the linker, aborting! " << std::endl; return 5; } } else { const auto& file = inputFiles[0]; auto ifs = new std::ifstream(file); if(!ifs->is_open()) throw CompilationError(CompilationStep::PRECOMPILATION, "cannot find file", file); input.reset(ifs); inputFile = inputFiles[0]; } std::ofstream output(outputFile == "-" ? "/dev/stdout" : outputFile, std::ios_base::out | std::ios_base::trunc | std::ios_base::binary); PROFILE_START(Compiler); Compiler::compile(*input, output, config, options, inputFile); PROFILE_END(Compiler); PROFILE_RESULTS(); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <unistd.h> #include "cmdAnd.h" #include "cmdOr.h" #include "cmdBase.h" #include "cmdSemi.h" #include "cmdExecutable.h" #include <vector> #include <stack> #include <list> #include <iterator> using namespace std; void printPrompt(); char* getInput(); cmdBase* parse(char* input); vector<char*> infixToPostfix(list<char*> vInfix); int priority(char*); int main() { while(true) { printPrompt(); char* userInput = getInput(); if ( userInput != NULL ) { cmdBase* head = parse(userInput); if (head != NULL) { head->execute( ); } //delete userInput; //delete head; } } } // prints the prompt for the user // displays the user name and host name void printPrompt() { char *User; char host[30]; User = getlogin( ); gethostname( host, 30 ); cout << User << "@" << host << "$ "; } //takes in user input and returns the char* char* getInput() { //takes in user input as string w/ getline string temp; getline(cin, temp); if ( temp.size( ) == 0 ) { return NULL; } int i = 0; while (temp.at(i) == ' ') { i++; } if (temp.at(i) == ';' || temp.at(i) == '|' || temp.at(i) == '&') { cout << "syntax error found near unexpected token '" << temp.at(i) << "'" << endl; return NULL; } //creates char array and sets it equal to string char* input = new char[temp.size() + 1]; for (int i = 0, n = temp.size(); i < n; i++) { input[i] = temp.at(i); } input[temp.size()] = '\0'; //adds NULL to end of char array return input; } //creates tree of command connectors by parsing the entered line cmdBase* parse(char* input) { if ( input[0] == '\0' || input[0] == ';' ) return NULL; list<char*> vInfix; char* cmdPtr; cmdPtr = strtok(input, ";"); while (cmdPtr != NULL) { vInfix.push_back(cmdPtr); char* temp = new char[2]; temp[0] = ';'; temp[1] = '\0'; vInfix.push_back(temp); cmdPtr = strtok(NULL, ";"); } if (*vInfix.back() == ';') { vInfix.pop_back(); } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { cmdPtr = strtok(*it, "&"); char* cmdPtr2 = strtok(NULL, ""); if (cmdPtr2 != NULL) { cmdPtr2 += 1; *it = cmdPtr; char* temp = new char[3]; temp[0] = '&'; temp[1] = '&'; temp[2] = '\0'; it++; if(it == vInfix.end()) { it--; vInfix.push_back(temp); vInfix.push_back(cmdPtr2); it++; } else { vInfix.insert(it, temp); vInfix.insert(it, cmdPtr2); } } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { cmdPtr = strtok(*it, "|"); char* cmdPtr2 = strtok(NULL, ""); if (cmdPtr2 != NULL) { cmdPtr2 += 1; *it = cmdPtr; char* temp = new char[3]; temp[0] = '|'; temp[1] = '|'; temp[2] = '\0'; it++; if(it == vInfix.end()) { it--; vInfix.push_back(temp); vInfix.push_back(cmdPtr2); it++; } else { vInfix.insert(it, temp); vInfix.insert(it, cmdPtr2); } } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { char* c = *it; int i = 0; while (c[i] == ' ') { i++; } if (c[i] == '(') { char* temp = new char[2]; temp[0] = '('; temp[1] = '\0'; vInfix.insert(it, temp); c[i] = '\0'; c += i + 1; *it = c; it--; } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { char* c = strpbrk(*it, ")"); if (c != NULL) { c[0] = '\0'; int i = 1; while (c[i] == ' ') { i++; } if (c[i] != '\0') { c += i; it++; if (it == vInfix.end()) { it--; vInfix.push_back(c); it++; } else { vInfix.insert(it, c); } it--; } char* temp = new char[2]; temp[0] = ')'; temp[1] = '\0'; it++; if (it == vInfix.end()) { it--; vInfix.push_back(temp); it++; } else { vInfix.insert(it, temp); } } } int numOfLP = 0, numOfRP = 0, rptCmdCheck = 0; for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { char* wrdPtr = *it; if (strcmp(wrdPtr, "&&") == 0 || strcmp(wrdPtr, "||") == 0 || strcmp(wrdPtr, ";") == 0) { if (rptCmdCheck == 1) { cout << "syntax error near unexpected token '" << wrdPtr << "'" << endl;; return NULL; } else { rptCmdCheck++; } } else if (strcmp(wrdPtr, "(") == 0) { numOfLP++; } else if (strcmp(wrdPtr, ")") == 0) { numOfRP++; } else { int i = 0; while (wrdPtr[i] == ' ') { i++; } if (wrdPtr[i] != '\0') { rptCmdCheck = 0; } } } if (numOfRP != numOfLP) { cout << "Error: uneven number of parentheses" << endl; return NULL; } vector<char*> vPostfix = infixToPostfix(vInfix); stack<cmdBase*> cmdStack; for (int i = 0, n = vPostfix.size(); i < n; i++) { cmdBase* temp; if (strcmp(vPostfix.at(i), "&&") == 0) { cmdBase* right = cmdStack.top(); cmdStack.pop(); cmdBase* left = cmdStack.top(); cmdStack.pop(); temp = new cmdAnd(left, right); } else if (strcmp(vPostfix.at(i), "||") == 0) { cmdBase* right = cmdStack.top(); cmdStack.pop(); cmdBase* left = cmdStack.top(); cmdStack.pop(); temp = new cmdOr(left, right); } else if (strcmp(vPostfix.at(i), ";") == 0) { cmdBase* right = cmdStack.top(); cmdStack.pop(); cmdBase* left = cmdStack.top(); cmdStack.pop(); temp = new cmdSemi(left, right); } else { temp = new cmdExecutable(vPostfix.at(i)); } cmdStack.push(temp); } return cmdStack.top(); } vector<char*> infixToPostfix(list<char*> vInfix) { stack<char*> cntrStack; vector<char*> vPostfix; char* wrdPtr; for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { wrdPtr = *it; if (strcmp(wrdPtr, "&&") == 0 || strcmp(wrdPtr, "||") == 0 || strcmp(wrdPtr, ";") == 0 || strcmp(wrdPtr, "(") == 0 || strcmp(wrdPtr, ")") == 0) { if (strcmp(wrdPtr, "(") == 0) { cntrStack.push(wrdPtr); } else if (strcmp(wrdPtr, ")") == 0) { while (strcmp(cntrStack.top(), "(") != 0) { vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } cntrStack.pop(); } else { while (!cntrStack.empty() && priority(wrdPtr) <= priority(cntrStack.top())) { if (strcmp(cntrStack.top(), "(") == 0) { break; } vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } cntrStack.push(wrdPtr); } } else { vPostfix.push_back(wrdPtr); } } while (!cntrStack.empty()) { vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } return vPostfix; } int priority(char* c) { if (strcmp(c, "(") == 0) { return 3; } else if (strcmp(c, ";") == 0) { return 1; } return 2; } <commit_msg>Readded commenting parse<commit_after>#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <unistd.h> #include "cmdAnd.h" #include "cmdOr.h" #include "cmdBase.h" #include "cmdSemi.h" #include "cmdExecutable.h" #include <vector> #include <stack> #include <list> #include <iterator> using namespace std; void printPrompt(); char* getInput(); cmdBase* parse(char* input); vector<char*> infixToPostfix(list<char*> vInfix); int priority(char*); int main() { while(true) { printPrompt(); char* userInput = getInput(); if ( userInput != NULL ) { cmdBase* head = parse(userInput); if (head != NULL) { head->execute( ); } //delete userInput; //delete head; } } } // prints the prompt for the user // displays the user name and host name void printPrompt() { char *User; char host[30]; User = getlogin( ); gethostname( host, 30 ); cout << User << "@" << host << "$ "; } //takes in user input and returns the char* char* getInput() { //takes in user input as string w/ getline string temp; getline(cin, temp); if ( temp.size( ) == 0 ) { return NULL; } int i = 0; while (temp.at(i) == ' ') { i++; } if (temp.at(i) == ';' || temp.at(i) == '|' || temp.at(i) == '&') { cout << "syntax error found near unexpected token '" << temp.at(i) << "'" << endl; return NULL; } //creates char array and sets it equal to string char* input = new char[temp.size() + 1]; for (int i = 0, n = temp.size(); i < n; i++) { input[i] = temp.at(i); } input[temp.size()] = '\0'; //adds NULL to end of char array return input; } //creates tree of command connectors by parsing the entered line cmdBase* parse(char* input) { if ( input[0] == '\0' || input[0] == '#' ) return NULL; input = strtok(input, "#"); list<char*> vInfix; char* cmdPtr; cmdPtr = strtok(input, ";"); while (cmdPtr != NULL) { vInfix.push_back(cmdPtr); char* temp = new char[2]; temp[0] = ';'; temp[1] = '\0'; vInfix.push_back(temp); cmdPtr = strtok(NULL, ";"); } if (*vInfix.back() == ';') { vInfix.pop_back(); } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { cmdPtr = strtok(*it, "&"); char* cmdPtr2 = strtok(NULL, ""); if (cmdPtr2 != NULL) { cmdPtr2 += 1; *it = cmdPtr; char* temp = new char[3]; temp[0] = '&'; temp[1] = '&'; temp[2] = '\0'; it++; if(it == vInfix.end()) { it--; vInfix.push_back(temp); vInfix.push_back(cmdPtr2); it++; } else { vInfix.insert(it, temp); vInfix.insert(it, cmdPtr2); } } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { cmdPtr = strtok(*it, "|"); char* cmdPtr2 = strtok(NULL, ""); if (cmdPtr2 != NULL) { cmdPtr2 += 1; *it = cmdPtr; char* temp = new char[3]; temp[0] = '|'; temp[1] = '|'; temp[2] = '\0'; it++; if(it == vInfix.end()) { it--; vInfix.push_back(temp); vInfix.push_back(cmdPtr2); it++; } else { vInfix.insert(it, temp); vInfix.insert(it, cmdPtr2); } } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { char* c = *it; int i = 0; while (c[i] == ' ') { i++; } if (c[i] == '(') { char* temp = new char[2]; temp[0] = '('; temp[1] = '\0'; vInfix.insert(it, temp); c[i] = '\0'; c += i + 1; *it = c; it--; } } for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { char* c = strpbrk(*it, ")"); if (c != NULL) { c[0] = '\0'; int i = 1; while (c[i] == ' ') { i++; } if (c[i] != '\0') { c += i; it++; if (it == vInfix.end()) { it--; vInfix.push_back(c); it++; } else { vInfix.insert(it, c); } it--; } char* temp = new char[2]; temp[0] = ')'; temp[1] = '\0'; it++; if (it == vInfix.end()) { it--; vInfix.push_back(temp); it++; } else { vInfix.insert(it, temp); } } } int numOfLP = 0, numOfRP = 0, rptCmdCheck = 0; for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { char* wrdPtr = *it; if (strcmp(wrdPtr, "&&") == 0 || strcmp(wrdPtr, "||") == 0 || strcmp(wrdPtr, ";") == 0) { if (rptCmdCheck == 1) { cout << "syntax error near unexpected token '" << wrdPtr << "'" << endl;; return NULL; } else { rptCmdCheck++; } } else if (strcmp(wrdPtr, "(") == 0) { numOfLP++; } else if (strcmp(wrdPtr, ")") == 0) { numOfRP++; } else { int i = 0; while (wrdPtr[i] == ' ') { i++; } if (wrdPtr[i] != '\0') { rptCmdCheck = 0; } } } if (numOfRP != numOfLP) { cout << "Error: uneven number of parentheses" << endl; return NULL; } vector<char*> vPostfix = infixToPostfix(vInfix); stack<cmdBase*> cmdStack; for (int i = 0, n = vPostfix.size(); i < n; i++) { cmdBase* temp; if (strcmp(vPostfix.at(i), "&&") == 0) { cmdBase* right = cmdStack.top(); cmdStack.pop(); cmdBase* left = cmdStack.top(); cmdStack.pop(); temp = new cmdAnd(left, right); } else if (strcmp(vPostfix.at(i), "||") == 0) { cmdBase* right = cmdStack.top(); cmdStack.pop(); cmdBase* left = cmdStack.top(); cmdStack.pop(); temp = new cmdOr(left, right); } else if (strcmp(vPostfix.at(i), ";") == 0) { cmdBase* right = cmdStack.top(); cmdStack.pop(); cmdBase* left = cmdStack.top(); cmdStack.pop(); temp = new cmdSemi(left, right); } else { temp = new cmdExecutable(vPostfix.at(i)); } cmdStack.push(temp); } return cmdStack.top(); } vector<char*> infixToPostfix(list<char*> vInfix) { stack<char*> cntrStack; vector<char*> vPostfix; char* wrdPtr; for (list<char*>::iterator it = vInfix.begin(); it != vInfix.end(); it++) { wrdPtr = *it; if (strcmp(wrdPtr, "&&") == 0 || strcmp(wrdPtr, "||") == 0 || strcmp(wrdPtr, ";") == 0 || strcmp(wrdPtr, "(") == 0 || strcmp(wrdPtr, ")") == 0) { if (strcmp(wrdPtr, "(") == 0) { cntrStack.push(wrdPtr); } else if (strcmp(wrdPtr, ")") == 0) { while (strcmp(cntrStack.top(), "(") != 0) { vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } cntrStack.pop(); } else { while (!cntrStack.empty() && priority(wrdPtr) <= priority(cntrStack.top())) { if (strcmp(cntrStack.top(), "(") == 0) { break; } vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } cntrStack.push(wrdPtr); } } else { vPostfix.push_back(wrdPtr); } } while (!cntrStack.empty()) { vPostfix.push_back(cntrStack.top()); cntrStack.pop(); } return vPostfix; } int priority(char* c) { if (strcmp(c, "(") == 0) { return 3; } else if (strcmp(c, ";") == 0) { return 1; } return 2; } <|endoftext|>
<commit_before> #include <iostream> #include "Machine.h" enum states{ OFF, ON }; class AbstractLightState : public AbstractState { protected: bool* _lightSwitchOnPtr; bool* _lightSwitchOffPtr; public: AbstractLightState(Machine *context) : AbstractState(context) {} //Trick to pass next state in the case we use static memory, you will see.. AbstractLightState* _NextStateHolder; void attachSwitches(bool* onSig, bool* offsig){ _lightSwitchOffPtr = offsig; _lightSwitchOnPtr = onSig; } }; class LightOnState : public AbstractLightState{ public: LightOnState(Machine *context) : AbstractLightState(context) { setId(); } void setId() override { _id = states ::ON; } virtual void handle(){ if(*_lightSwitchOnPtr){ //Avoidable but for demonstration (we can manage multiple nextStates) //Stay in the same state if actual is ON and user pushes On button _context->setStatePtr(this); }else if (!*_lightSwitchOnPtr) { //Avoidable but for demonstration (we can manage multiple nextStates) //Stay in the same state if actual is ON and user pushes On button _context->setStatePtr(this); } if(*_lightSwitchOffPtr && _lightSwitchOnPtr){ //You can handle strange behaviors here std::cout << "WARNING: both signals ON. This will couse an infinite switching between states in this case."<<std::endl; } //Real state changer if (*_lightSwitchOffPtr){ //Next state is OFF _context->setStatePtr(_NextStateHolder); std::cout << "OFF" << std::endl; } } }; class LightOffState : public AbstractLightState{ public: LightOffState(Machine *context) : AbstractLightState(context) { setId(); } void setId() override { _id = states ::OFF; } virtual void handle(){ if(*_lightSwitchOffPtr){ //Avoidable but for demonstration (we can manage multiple nextStates) //Stay in the same state if actual is ON and user pushes On button _context->setStatePtr(this); }else if (!*_lightSwitchOffPtr) { //Avoidable but for demonstration (we can manage multiple nextStates) //Stay in the same state if actual is ON and user pushes On button _context->setStatePtr(this); } if(*_lightSwitchOffPtr && _lightSwitchOnPtr){ //You can handle strange behaviors here std::cout << "WARNING: both signals ON. This will couse an infinite switching between states in this case."<<std::endl; } //Real state changer if (*_lightSwitchOnPtr){ //Next state is OFF _context->setStatePtr(_NextStateHolder); } } }; /* * * This is an Example! * * Let us simulate a light with two switches, namely switchOn and switchOff. * The state machine has two states (ON (id=1),OFF(id=0)) depending on the status of the switches. * * If the light is OFF, we need to set the switchOn to true and the state will change. * In the off state, the switchOff signal will not affect the state. * * If the light is ON, we need to set the switchOff to true and the state will change. * In the on state, the switchOn signal will not affect the state. * */ int main() { std::cout << "Hello, this is an example for the superFantasticMachine library!" << std::endl; //Create a Machine Object Machine context; Machine* contextPtr = &context; //Simulate two switces bool switchOn = false; bool switchOff = true; //Create a bunch of nodes LightOnState on (contextPtr); LightOffState off(contextPtr); //Initialize to off context.setStatePtr(&off); //Initialize states on.attachSwitches(&switchOn,&switchOff); off.attachSwitches(&switchOn,&switchOff); //Set Holders on._NextStateHolder = &off; off._NextStateHolder = &on; char in; bool done = false; do { std::cout<<std::endl; std::cout << "***************************************"<<std::endl; std::cout << "ON BUTTON: " << switchOn << "; OFF BUTTON: " << switchOff<<std::endl; std::cout << "Press 'a' to switch the OFF button, 's' to switch the ON button or 'c' to continue"<<std::endl; std::cout << "Machine STATE is: "<<context.getActualNodeId() << std::endl; std::cout << "***************************************"<<std::endl; std::cin >> in; switch (in) { case 'a': switchOff = !switchOff; break; case 's': switchOn = !switchOn; break; case 'q': done = true; break; default : std::cout << "Wrong command"<< std::endl; done = false; break; } context.handle(); }while(!done); //Return the answer to life the universe and everything... std::cout << "Return the answer to life the universe and everything..."<< std::endl; return 42; }<commit_msg>fix bugs<commit_after> #include <iostream> #include "Machine.h" enum states{ OFF, ON }; class AbstractLightState : public AbstractState { protected: bool* _lightSwitchOnPtr; bool* _lightSwitchOffPtr; public: AbstractLightState(Machine *context) : AbstractState(context) {} //Trick to pass next state in the case we use static memory, you will see.. AbstractLightState* _NextStateHolder; void attachSwitches(bool* onSig, bool* offsig){ _lightSwitchOffPtr = offsig; _lightSwitchOnPtr = onSig; } }; class LightOnState : public AbstractLightState{ public: LightOnState(Machine *context) : AbstractLightState(context) { setId(); } void setId() override { _id = states ::ON; } virtual void handle(){ if(*_lightSwitchOnPtr){ //Avoidable but for demonstration (we can manage multiple nextStates) //Stay in the same state if actual is ON and user pushes On button _context->setStatePtr(this); }else if (!*_lightSwitchOnPtr) { //Avoidable but for demonstration (we can manage multiple nextStates) //Stay in the same state if actual is ON and user pushes On button _context->setStatePtr(this); } if(*_lightSwitchOffPtr && _lightSwitchOnPtr){ //You can handle strange behaviors here std::cout << "WARNING: both signals ON. This will couse an infinite switching between states in this case."<<std::endl; } //Real state changer if (*_lightSwitchOffPtr){ //Next state is OFF _context->setStatePtr(_NextStateHolder); std::cout << "OFF" << std::endl; } } }; class LightOffState : public AbstractLightState{ public: LightOffState(Machine *context) : AbstractLightState(context) { setId(); } void setId() override { _id = states ::OFF; } virtual void handle(){ if(*_lightSwitchOffPtr){ //Avoidable but for demonstration (we can manage multiple nextStates) //Stay in the same state if actual is ON and user pushes On button _context->setStatePtr(this); }else if (!*_lightSwitchOffPtr) { //Avoidable but for demonstration (we can manage multiple nextStates) //Stay in the same state if actual is ON and user pushes On button _context->setStatePtr(this); } if(*_lightSwitchOffPtr && _lightSwitchOnPtr){ //You can handle strange behaviors here std::cout << "WARNING: both signals ON. This will cause an infinite switching between states."<<std::endl; } //Real state changer if (*_lightSwitchOnPtr){ //Next state is OFF _context->setStatePtr(_NextStateHolder); } } }; /* * * This is an Example! * * Let us simulate a light with two switches, namely switchOn and switchOff. * The state machine has two states (ON (id=1),OFF(id=0)) depending on the status of the switches. * * If the light is OFF, we need to set the switchOn to true and the state will change. * In the off state, the switchOff signal will not affect the state. * * If the light is ON, we need to set the switchOff to true and the state will change. * In the on state, the switchOn signal will not affect the state. * */ int main() { std::cout << "Hello, this is an example for the superFantasticMachine library!" << std::endl; //Create a Machine Object Machine context; Machine* contextPtr = &context; //Simulate two switces bool switchOn = false; bool switchOff = true; //Create a bunch of nodes LightOnState on (contextPtr); LightOffState off(contextPtr); //Initialize to off context.setStatePtr(&off); //Initialize states on.attachSwitches(&switchOn,&switchOff); off.attachSwitches(&switchOn,&switchOff); //Set Holders on._NextStateHolder = &off; off._NextStateHolder = &on; char in; bool done = false; do { std::cout<<std::endl; std::cout << "***************************************"<<std::endl; std::cout << "ON BUTTON: " << switchOn << "; OFF BUTTON: " << switchOff<<std::endl; std::cout << "Press 'a' to switch the OFF button, 's' to switch the ON button or 'c' to continue"<<std::endl; std::cout << "Machine STATE is: "<<context.getActualNodeId() << std::endl; std::cout << "***************************************"<<std::endl; std::cin >> in; switch (in) { case 'a': switchOff = !switchOff; break; case 's': switchOn = !switchOn; break; case 'q': done = true; break; case 'c': break; default : std::cout << "Wrong command"<< std::endl; done = false; break; } context.handle(); }while(!done); //Return the answer to life the universe and everything... std::cout << "Return the answer to life the universe and everything..."<< std::endl; return 42; }<|endoftext|>
<commit_before>#include <iostream> #include <array> #include <vector> #define SDL_MAIN_HANDLED #include <SDL.h> #include <ospray.h> #include <ospcommon/vec.h> #include <openvr.h> #include "gl_core_3_3.h" #define TINYOBJLOADER_IMPLEMENTATION #include "tiny_obj_loader.h" static int WIN_WIDTH = 1280/2; static int WIN_HEIGHT = 720/2; // We only have final resolve textures for the eyes // since we don't need MSAA render targets on the GPU like // in the samples struct EyeResolveFB { GLuint resolve_fb; GLuint resolve_texture; }; int main(int argc, const char **argv) { if (argc < 2) { std::cerr << "You must specify a model to render\n"; return 1; } const std::string model_file = argv[1]; if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ std::cerr << "Failed to initialize SDL\n"; return 1; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); #ifndef NDEBUG SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); #endif SDL_Window *win = SDL_CreateWindow("OSPRay + Vive", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIN_WIDTH, WIN_HEIGHT, SDL_WINDOW_OPENGL); if (!win){ std::cout << "Failed to open SDL window: " << SDL_GetError() << "\n"; return 1; } SDL_GLContext ctx = SDL_GL_CreateContext(win); if (!ctx){ std::cout << "Failed to get OpenGL context: " << SDL_GetError() << "\n"; return 1; } if (ogl_LoadFunctions() == ogl_LOAD_FAILED){ SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Failed to Load OpenGL Functions", "Could not load OpenGL functions for 3.3, OpenGL 3.3 or higher is required", NULL); SDL_GL_DeleteContext(ctx); SDL_DestroyWindow(win); SDL_Quit(); return 1; } SDL_GL_SetSwapInterval(0); // Setup OpenVR system vr::EVRInitError vr_error; vr::IVRSystem *vr_system = vr::VR_Init(&vr_error, vr::VRApplication_Scene); if (vr_error != vr::VRInitError_None) { std::cout << "OpenVR Init error " << vr_error << "\n"; return 1; } if (!vr_system->IsTrackedDeviceConnected(vr::k_unTrackedDeviceIndex_Hmd)) { std::cout << "OpenVR HMD not tracking! Check connection and restart\n"; return 1; } if (!vr::VRCompositor()) { std::cout << "OpenVR Failed to initialize compositor\n"; return 1; } std::array<uint32_t, 2> vr_render_dims; vr_system->GetRecommendedRenderTargetSize(&vr_render_dims[0], &vr_render_dims[1]); std::cout << "OpenVR recommended render target resolution = " << vr_render_dims[0] << "x" << vr_render_dims[1] << "\n"; GLuint fbo, texture; glGenFramebuffers(1, &fbo); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, vr_render_dims[0] * 2, vr_render_dims[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Setup resolve targets for the eyes std::array<EyeResolveFB, 2> eye_targets; for (size_t i = 0; i < eye_targets.size(); ++i) { glGenFramebuffers(1, &eye_targets[i].resolve_fb); glGenTextures(1, &eye_targets[i].resolve_texture); glBindTexture(GL_TEXTURE_2D, eye_targets[i].resolve_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, vr_render_dims[0], vr_render_dims[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindFramebuffer(GL_FRAMEBUFFER, eye_targets[i].resolve_fb); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye_targets[i].resolve_texture, 0); } glBindFramebuffer(GL_FRAMEBUFFER, 0); ospInit(&argc, argv); using namespace ospcommon; // We render both left/right eye to the same framebuffer so we need it to be // 2x the width const vec2i imageSize(vr_render_dims[0] * 2, vr_render_dims[1]); const vec3f camPos(0, 50, 240); const vec3f camDir = vec3f(0, 40, 0) - camPos; const vec3f camUp(0, 1, 0); OSPCamera camera = ospNewCamera("perspective"); ospSetf(camera, "aspect", imageSize.x / static_cast<float>(imageSize.y)); ospSet1i(camera, "stereoMode", 3); // TODO: Get this from OpenVR note that ospray's units are in meters ospSet1f(camera, "interpupillaryDistance", 0.0635); ospSetVec3f(camera, "pos", (osp::vec3f&)camPos); ospSetVec3f(camera, "dir", (osp::vec3f&)camDir); ospSetVec3f(camera, "up", (osp::vec3f&)camUp); ospCommit(camera); // Load the model w/ tinyobjloader tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, model_file.c_str(), nullptr, true); if (!err.empty()) { std::cerr << "Error loading model: " << err << "\n"; } if (!ret) { return 1; } OSPModel world = ospNewModel(); // Load all the objects into ospray OSPData pos_data = ospNewData(attrib.vertices.size() / 3, OSP_FLOAT3, attrib.vertices.data(), OSP_DATA_SHARED_BUFFER); ospCommit(pos_data); for (size_t s = 0; s < shapes.size(); ++s) { std::cout << "Loading mesh " << shapes[s].name << ", has " << shapes[s].mesh.indices.size() << " vertices\n"; const tinyobj::mesh_t &mesh = shapes[s].mesh; std::vector<int32_t> indices; indices.reserve(mesh.indices.size()); for (const auto &idx : mesh.indices) { indices.push_back(idx.vertex_index); } OSPData idx_data = ospNewData(indices.size() / 3, OSP_INT3, indices.data()); ospCommit(idx_data); OSPGeometry geom = ospNewGeometry("triangles"); ospSetObject(geom, "vertex", pos_data); ospSetObject(geom, "index", idx_data); ospCommit(geom); ospAddGeometry(world, geom); } ospCommit(world); OSPRenderer renderer = ospNewRenderer("ao"); ospSetObject(renderer, "model", world); ospSetObject(renderer, "camera", camera); ospSetVec3f(renderer, "bgColor", (osp::vec3f&)vec3f(0.05, 0.05, 0.05)); ospCommit(renderer); OSPFrameBuffer framebuffer = ospNewFrameBuffer((osp::vec2i&)imageSize, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_ACCUM); ospFrameBufferClear(framebuffer, OSP_FB_COLOR | OSP_FB_ACCUM); std::array<vr::TrackedDevicePose_t, vr::k_unMaxTrackedDeviceCount> tracked_device_poses; bool quit = false; uint32_t prev_time = SDL_GetTicks(); const std::string win_title = "OSPRay + Vive - frame time "; while (!quit) { vr::VRCompositor()->WaitGetPoses(tracked_device_poses.data(), tracked_device_poses.size(), NULL, 0); // TODO: update camera based on HMD position const uint32_t cur_time = SDL_GetTicks(); const float elapsed = (cur_time - prev_time) / 1000.f; prev_time = cur_time; SDL_Event e; while (SDL_PollEvent(&e)){ if (e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)){ quit = true; break; } } ospFrameBufferClear(framebuffer, OSP_FB_COLOR); ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM); const uint32_t *fb = static_cast<const uint32_t*>(ospMapFrameBuffer(framebuffer, OSP_FB_COLOR)); glBindTexture(GL_TEXTURE_2D, texture); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, vr_render_dims[0] * 2, vr_render_dims[1], GL_RGBA, GL_UNSIGNED_BYTE, fb); ospUnmapFrameBuffer(fb, framebuffer); glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); // Blit the left/right eye halves of the ospray framebuffer to the left/right resolve targets // and submit them for (size_t i = 0; i < eye_targets.size(); ++i) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, eye_targets[i].resolve_fb); glBlitFramebuffer(vr_render_dims[0] * i, 0, vr_render_dims[0] * i + vr_render_dims[0], vr_render_dims[1], 0, 0, vr_render_dims[0], vr_render_dims[1], GL_COLOR_BUFFER_BIT, GL_NEAREST); } vr::Texture_t left_eye = {}; left_eye.handle = reinterpret_cast<void*>(eye_targets[0].resolve_texture); left_eye.eType = vr::TextureType_OpenGL; left_eye.eColorSpace = vr::ColorSpace_Gamma; vr::Texture_t right_eye = {}; right_eye.handle = reinterpret_cast<void*>(eye_targets[1].resolve_texture); right_eye.eType = vr::TextureType_OpenGL; right_eye.eColorSpace = vr::ColorSpace_Gamma; vr::VRCompositor()->Submit(vr::Eye_Left, &left_eye); vr::VRCompositor()->Submit(vr::Eye_Right, &right_eye); // Blit the app window display #if 0 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBlitFramebuffer(0, 0, vr_render_dims[0] * 2, vr_render_dims[1], 0, 0, WIN_WIDTH, WIN_HEIGHT, GL_COLOR_BUFFER_BIT, GL_NEAREST); #endif SDL_GL_SwapWindow(win); #if 1 const std::string title = win_title + std::to_string(elapsed) + "ms"; SDL_SetWindowTitle(win, title.c_str()); #endif } vr::VR_Shutdown(); SDL_GL_DeleteContext(ctx); SDL_DestroyWindow(win); SDL_Quit(); return 0; } <commit_msg>Debugging incorrect stereo<commit_after>#include <iostream> #include <array> #include <vector> #define SDL_MAIN_HANDLED #include <SDL.h> #include <ospray.h> #include <ospcommon/vec.h> #include <openvr.h> #include "gl_core_3_3.h" #define TINYOBJLOADER_IMPLEMENTATION #include "tiny_obj_loader.h" static int WIN_WIDTH = 1280/2; static int WIN_HEIGHT = 720/2; // We only have final resolve textures for the eyes // since we don't need MSAA render targets on the GPU like // in the samples struct EyeResolveFB { GLuint resolve_fb; GLuint resolve_texture; }; int main(int argc, const char **argv) { if (argc < 2) { std::cerr << "You must specify a model to render\n"; return 1; } const std::string model_file = argv[1]; if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ std::cerr << "Failed to initialize SDL\n"; return 1; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); #ifndef NDEBUG SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); #endif SDL_Window *win = SDL_CreateWindow("OSPRay + Vive", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIN_WIDTH, WIN_HEIGHT, SDL_WINDOW_OPENGL); if (!win){ std::cout << "Failed to open SDL window: " << SDL_GetError() << "\n"; return 1; } SDL_GLContext ctx = SDL_GL_CreateContext(win); if (!ctx){ std::cout << "Failed to get OpenGL context: " << SDL_GetError() << "\n"; return 1; } if (ogl_LoadFunctions() == ogl_LOAD_FAILED){ SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Failed to Load OpenGL Functions", "Could not load OpenGL functions for 3.3, OpenGL 3.3 or higher is required", NULL); SDL_GL_DeleteContext(ctx); SDL_DestroyWindow(win); SDL_Quit(); return 1; } SDL_GL_SetSwapInterval(0); // Setup OpenVR system vr::EVRInitError vr_error; vr::IVRSystem *vr_system = vr::VR_Init(&vr_error, vr::VRApplication_Scene); if (vr_error != vr::VRInitError_None) { std::cout << "OpenVR Init error " << vr_error << "\n"; return 1; } if (!vr_system->IsTrackedDeviceConnected(vr::k_unTrackedDeviceIndex_Hmd)) { std::cout << "OpenVR HMD not tracking! Check connection and restart\n"; return 1; } if (!vr::VRCompositor()) { std::cout << "OpenVR Failed to initialize compositor\n"; return 1; } std::array<uint32_t, 2> vr_render_dims; vr_system->GetRecommendedRenderTargetSize(&vr_render_dims[0], &vr_render_dims[1]); std::cout << "OpenVR recommended render target resolution = " << vr_render_dims[0] << "x" << vr_render_dims[1] << "\n"; GLuint fbo, texture; glGenFramebuffers(1, &fbo); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, vr_render_dims[0] * 2, vr_render_dims[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Setup resolve targets for the eyes std::array<EyeResolveFB, 2> eye_targets; for (size_t i = 0; i < eye_targets.size(); ++i) { glGenFramebuffers(1, &eye_targets[i].resolve_fb); glGenTextures(1, &eye_targets[i].resolve_texture); glBindTexture(GL_TEXTURE_2D, eye_targets[i].resolve_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, vr_render_dims[0], vr_render_dims[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindFramebuffer(GL_FRAMEBUFFER, eye_targets[i].resolve_fb); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye_targets[i].resolve_texture, 0); } glBindFramebuffer(GL_FRAMEBUFFER, 0); ospInit(&argc, argv); using namespace ospcommon; // We render both left/right eye to the same framebuffer so we need it to be // 2x the width const vec2i image_size(vr_render_dims[0], vr_render_dims[1]); const vec3f cam_pos(0, 50, 280); const vec3f cam_target = vec3f(0, 40, 0); const vec3f cam_up(0, 1, 0); // TODO BUG: OSPRay's side-by-side camera can't do proper stereo because it // uses the same look direction for both eyes std::array<OSPCamera, 2> cameras; for (size_t i = 0; i < cameras.size(); ++i) { auto eye_mat = vr_system->GetEyeToHeadTransform(i == 0 ? vr::Eye_Left : vr::Eye_Right); std::cout << "[\n"; for (size_t r = 0; r < 3; ++r) { for (size_t c = 0; c < 4; ++c) { std::cout << eye_mat.m[r][c] << " "; } std::cout << "\n"; } std::cout << "]\n"; cameras[i] = ospNewCamera("perspective"); ospSetf(cameras[i], "aspect", image_size.x / static_cast<float>(image_size.y)); // TODO: How to query the HMD IPD? //ospSet1i(cameras[i], "stereoMode", 0); //ospSet1f(camera, "interpupillaryDistance", 0.0635); vec3f eye_pos = cam_pos; if (i == 0) { eye_pos = eye_pos - vec3f(0.0318, 0, 0); } else { eye_pos = eye_pos + vec3f(0.0318, 0, 0); } vec3f eye_dir = cam_target - eye_pos; ospSetVec3f(cameras[i], "pos", (osp::vec3f&)eye_pos); ospSetVec3f(cameras[i], "dir", (osp::vec3f&)eye_dir); ospSetVec3f(cameras[i], "up", (osp::vec3f&)cam_up); ospCommit(cameras[i]); } // Load the model w/ tinyobjloader tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, model_file.c_str(), nullptr, true); if (!err.empty()) { std::cerr << "Error loading model: " << err << "\n"; } if (!ret) { return 1; } OSPModel world = ospNewModel(); // Load all the objects into ospray OSPData pos_data = ospNewData(attrib.vertices.size() / 3, OSP_FLOAT3, attrib.vertices.data(), OSP_DATA_SHARED_BUFFER); ospCommit(pos_data); for (size_t s = 0; s < shapes.size(); ++s) { std::cout << "Loading mesh " << shapes[s].name << ", has " << shapes[s].mesh.indices.size() << " vertices\n"; const tinyobj::mesh_t &mesh = shapes[s].mesh; std::vector<int32_t> indices; indices.reserve(mesh.indices.size()); for (const auto &idx : mesh.indices) { indices.push_back(idx.vertex_index); } OSPData idx_data = ospNewData(indices.size() / 3, OSP_INT3, indices.data()); ospCommit(idx_data); OSPGeometry geom = ospNewGeometry("triangles"); ospSetObject(geom, "vertex", pos_data); ospSetObject(geom, "index", idx_data); ospCommit(geom); ospAddGeometry(world, geom); } ospCommit(world); OSPRenderer renderer = ospNewRenderer("ao"); ospSetObject(renderer, "model", world); ospSetObject(renderer, "camera", cameras[0]); ospSetVec3f(renderer, "bgColor", (osp::vec3f&)vec3f(0.05)); ospCommit(renderer); std::array<OSPFrameBuffer, 2> framebuffers; for (size_t i = 0; i < framebuffers.size(); ++i) { framebuffers[i] = ospNewFrameBuffer((osp::vec2i&)image_size, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_ACCUM); ospFrameBufferClear(framebuffers[i], OSP_FB_COLOR | OSP_FB_ACCUM); } std::array<vr::TrackedDevicePose_t, vr::k_unMaxTrackedDeviceCount> tracked_device_poses; bool quit = false; uint32_t prev_time = SDL_GetTicks(); const std::string win_title = "OSPRay + Vive - frame time "; while (!quit) { vr::VRCompositor()->WaitGetPoses(tracked_device_poses.data(), tracked_device_poses.size(), NULL, 0); // TODO: update camera based on HMD position const uint32_t cur_time = SDL_GetTicks(); const float elapsed = (cur_time - prev_time) / 1000.f; prev_time = cur_time; SDL_Event e; while (SDL_PollEvent(&e)){ if (e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)){ quit = true; break; } } // Render each eye and upload them for (size_t i = 0; i < framebuffers.size(); ++i) { ospSetObject(renderer, "camera", cameras[i]); // Debugging test #if 1 if (i == 0) { ospSetVec3f(renderer, "bgColor", (osp::vec3f&)vec3f(0.1, 0, 0)); } else { ospSetVec3f(renderer, "bgColor", (osp::vec3f&)vec3f(0, 0, 0.1)); } #endif ospCommit(renderer); ospFrameBufferClear(framebuffers[i], OSP_FB_COLOR); ospRenderFrame(framebuffers[i], renderer, OSP_FB_COLOR | OSP_FB_ACCUM); const uint32_t *fb = static_cast<const uint32_t*>(ospMapFrameBuffer(framebuffers[i], OSP_FB_COLOR)); glBindTexture(GL_TEXTURE_2D, texture); glTexSubImage2D(GL_TEXTURE_2D, 0, vr_render_dims[0] * i, 0, vr_render_dims[0], vr_render_dims[1], GL_RGBA, GL_UNSIGNED_BYTE, fb); ospUnmapFrameBuffer(fb, framebuffers[i]); } glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); // Blit the left/right eye halves of the ospray framebuffer to the left/right resolve targets // and submit them for (size_t i = 0; i < eye_targets.size(); ++i) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, eye_targets[i].resolve_fb); glBlitFramebuffer(vr_render_dims[0] * i, 0, vr_render_dims[0] * i + vr_render_dims[0], vr_render_dims[1], 0, 0, vr_render_dims[0], vr_render_dims[1], GL_COLOR_BUFFER_BIT, GL_NEAREST); } vr::Texture_t left_eye = {}; left_eye.handle = reinterpret_cast<void*>(eye_targets[0].resolve_texture); left_eye.eType = vr::TextureType_OpenGL; left_eye.eColorSpace = vr::ColorSpace_Gamma; vr::Texture_t right_eye = {}; right_eye.handle = reinterpret_cast<void*>(eye_targets[1].resolve_texture); right_eye.eType = vr::TextureType_OpenGL; right_eye.eColorSpace = vr::ColorSpace_Gamma; vr::VRCompositor()->Submit(vr::Eye_Left, &left_eye); vr::VRCompositor()->Submit(vr::Eye_Right, &right_eye); // Blit the app window display #if 1 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBlitFramebuffer(0, 0, vr_render_dims[0] * 2, vr_render_dims[1], 0, 0, WIN_WIDTH, WIN_HEIGHT, GL_COLOR_BUFFER_BIT, GL_NEAREST); #endif SDL_GL_SwapWindow(win); #if 1 const std::string title = win_title + std::to_string(elapsed) + "ms"; SDL_SetWindowTitle(win, title.c_str()); #endif } vr::VR_Shutdown(); SDL_GL_DeleteContext(ctx); SDL_DestroyWindow(win); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>#include "model.hxx" #include "3DView.hxx" #include "GameUpdater.hxx" #include "Cam.hxx" #include "Hand.hxx" #include "HistogramHand.hxx" #include "NetGame.hxx" #include "NetCam.hxx" #include "HandToModel.hxx" static const int redBalls = 3; static const int yellowBalls = 12; volatile bool running; void camLoop(Cam_ c, NetCam_ nc, Hand_ h, HandToModel_ htm) { do { c->grabImage(); nc->push(c->jpeg()); h->update(c->frame()); htm->update(h); } while (running); } int main(int argc, char * argv[]) { try { if (argc < 2) { std::cout << "Usage: " << argv[0] << " <cam id> [server]" << std::endl; return -1; } NetGame_ ng; NetCam_ nc; int ballof; if (argc < 3) { ng.reset(new NetGame()); nc.reset(new NetCam()); ballof = 0; } else { ng.reset(new NetGame(argv[2])); nc.reset(new NetCam(argv[2])); ballof = 0xffff; } Cam_ c = Cam::create(atoi(argv[1])); Hand_ hh(new HistogramHand(0.2, 0.1)); hh->calibrate(c); Tube tube; tube.halfSize = cv::Size2f(1.6, 1.2); tube.goal = 3; tube.separator = 13; tube.opponentGoal = 23; tube.handMovement = 5; tube.handMax = 8; tube.spawnArea = 4; ThreeDView view(cv::Size(1366, 768), tube); HandToModel_ htm = HandToModel::create(tube); GameState gs; gs.own_lives = 12; gs.opponent_lives = 12; GameUpdater game(tube); Balls balls; Ball b; b.owner = ballOwnerLocal; b.type = 0; for (int i = 0; i < yellowBalls; ++i) { game.randomizeBall(b); balls[ballof + i] = b; } b.type = 1; for (int i = 0; i < redBalls; ++i) { game.randomizeBall(b); balls[ballof + yellowBalls + i] = b; } running = true; boost::thread camThread(boost::bind(&camLoop, c, nc, hh, htm)); do { ng->sync(balls, gs, tube); nc->grabImage(); glfwSetTime(0.0); view.render(balls, htm, gs, nc->frame(), c->frame()); glfwSwapBuffers(); glfwSleep(0.01); game.tick(glfwGetTime(), balls, gs, htm); running = !glfwGetKey(GLFW_KEY_ESC) && (gs.own_lives > 0) && (gs.opponent_lives > 0); } while (running); int ret; if (gs.opponent_lives <= 0) { if (gs.own_lives <= 0) { std::cout << "\n\aTIE! Play another round?\n"; ret = 2; } else { std::cout << "\n\aOU WON! Congratulations.\n"; ret = 0; } } else if (gs.own_lives <= 0) { std::cout << "\n\aGAME OVER! Better luck next time.\n"; ret = 3; } else { std::cout << "\n\aGame terminated before conclusion.\n"; ret = 1; } std::cout << gs.own_ratio * 100 << "% of the balls were still in your court." << std::endl; camThread.join(); return ret; } catch (const std::string& str) { std::cerr << "exception: " << str << std::endl; return -1; } } <commit_msg>Sync oups<commit_after>#include "model.hxx" #include "3DView.hxx" #include "GameUpdater.hxx" #include "Cam.hxx" #include "Hand.hxx" #include "HistogramHand.hxx" #include "NetGame.hxx" #include "NetCam.hxx" #include "HandToModel.hxx" static const int redBalls = 3; static const int yellowBalls = 12; volatile bool running; void camLoop(Cam_ c, NetCam_ nc, Hand_ h, HandToModel_ htm) { do { c->grabImage(); nc->push(c->jpeg()); h->update(c->frame()); htm->update(h); } while (running); } int main(int argc, char * argv[]) { try { if (argc < 2) { std::cout << "Usage: " << argv[0] << " <cam id> [server]" << std::endl; return -1; } NetGame_ ng; NetCam_ nc; int ballof; if (argc < 3) { ng.reset(new NetGame()); nc.reset(new NetCam()); ballof = 0; } else { ng.reset(new NetGame(argv[2])); nc.reset(new NetCam(argv[2])); ballof = 0xffff; } Cam_ c = Cam::create(atoi(argv[1])); Hand_ hh(new HistogramHand(0.2, 0.1)); hh->calibrate(c); Tube tube; tube.halfSize = cv::Size2f(1.6, 1.2); tube.goal = 3; tube.separator = 13; tube.opponentGoal = 23; tube.handMovement = 5; tube.handMax = 8; tube.spawnArea = 4; ThreeDView view(cv::Size(1366, 768), tube); HandToModel_ htm = HandToModel::create(tube); GameState gs; gs.own_lives = 12; gs.opponent_lives = 12; GameUpdater game(tube); Balls balls; Ball b; b.owner = ballOwnerLocal; b.type = 0; for (int i = 0; i < yellowBalls; ++i) { game.randomizeBall(b); balls[ballof + i] = b; } b.type = 1; for (int i = 0; i < redBalls; ++i) { game.randomizeBall(b); balls[ballof + yellowBalls + i] = b; } running = true; boost::thread camThread(boost::bind(&camLoop, c, nc, hh, htm)); do { glfwSetTime(0.0); view.render(balls, htm, gs, nc->frame(), c->frame()); glfwSwapBuffers(); glfwSleep(0.01); game.tick(glfwGetTime(), balls, gs, htm); ng->sync(balls, gs, tube); nc->grabImage(); running = !glfwGetKey(GLFW_KEY_ESC) && (gs.own_lives > 0) && (gs.opponent_lives > 0); } while (running); int ret; if (gs.opponent_lives <= 0) { if (gs.own_lives <= 0) { std::cout << "\n\aTIE! Play another round?\n"; ret = 2; } else { std::cout << "\n\aOU WON! Congratulations.\n"; ret = 0; } } else if (gs.own_lives <= 0) { std::cout << "\n\aGAME OVER! Better luck next time.\n"; ret = 3; } else { std::cout << "\n\aGame terminated before conclusion.\n"; ret = 1; } std::cout << gs.own_ratio * 100 << "% of the balls were still in your court." << std::endl; camThread.join(); return ret; } catch (const std::string& str) { std::cerr << "exception: " << str << std::endl; return -1; } } <|endoftext|>
<commit_before>#include <stdio.h> #include <math.h> #include <pthread.h> #include "PO8e.h" #define SRATE_HZ (24414.0625) #define SRATE_KHZ (24.4140625) #define NCHAN 96 bool g_die = false; long double g_startTime = 0.0; long double gettime() //in seconds! { timespec pt ; clock_gettime(CLOCK_MONOTONIC, &pt); long double ret = (long double)(pt.tv_sec) ; ret += (long double)(pt.tv_nsec) / 1e9 ; return ret - g_startTime; } // service the po8e buffer // 96 channels of spike/lfp, followed by time (ticks) split across two chans // if there is no po8e card, simulate data with sines void *po8_thread(void *) { PO8e *card = NULL; bool simulate = false; int bufmax = 10000; // must be >= 10000 while (!g_die) { int totalcards = PO8e::cardCount(); int conn_cards = 0; printf("Found %d PO8e card(s) in the system.\n", totalcards); if (totalcards < 1) { printf(" simulating instead.\n"); simulate = true; } if (!simulate) { printf("Connecting to card 0\n"); card = PO8e::connectToCard(0); if (card == NULL) printf(" connection failed to card0 \n"); else { // todo: connect to multiple cards printf(" connection established to card0 at %p\n", (void *)card); if (!card->startCollecting()) { printf(" startCollecting() failed with: %d\n", card->getLastError()); card->stopCollecting(); printf(" releasing card0\n"); PO8e::releaseCard(card); card = NULL; } else { printf(" card is collecting incoming data.\n"); conn_cards++; printf("Waiting for the stream to start on card0 ... "); card->waitForDataReady(); // waits ~ 1200 hours ;-) printf("started\n"); } } } // start the timer used to compute the speed and set the collected bytes to 0 long double starttime = gettime(); long double totalSamples = 0.0; //for simulation. double sinSamples = 0.0; // for driving the sinusoids; resets every 4e4. long long bytes = 0; unsigned int frame = 0; unsigned int nchan = NCHAN; unsigned int bps = 2; //bytes/sample if (!simulate) { nchan = card->numChannels(); bps = card->dataSampleSize(); printf(" %d channels @ %d bytes/sample\n", nchan, bps); } short *temp = new short[bufmax*(nchan+2)]; // 10000 samples * 2 bytes/sample * (nChannels+time) short *temptemp = new short[bufmax]; while ((simulate || conn_cards > 0) && !g_die) { if (!card->waitForDataReady()) { // waits ~ 1200 hours ;-) // this occurs when the rpvdsex circuit is idled. // and potentially when a glitch happens printf(" waitForDataReady() failed with: %d\n", card->getLastError()); card->stopCollecting(); conn_cards--; printf(" releasing card0\n"); PO8e::releaseCard(card); card = NULL; break; } bool stopped = false; int numSamples = 0; if (!simulate) { numSamples = (int)card->samplesReady(&stopped); if (stopped) { printf(" stopped collecting data\n"); card->stopCollecting(); conn_cards--; printf(" releasing card0\n"); PO8e::releaseCard(card); card = NULL; break; } if (numSamples > 0) { if (numSamples > bufmax) { printf("samplesReady() returned too many samples for buffer (buffer wrap?): %d\n", numSamples); numSamples = bufmax; } card->readBlock(temp, numSamples); card->flushBufferedData(numSamples); totalSamples += numSamples; } } else { //simulate! long double now = gettime(); numSamples = (int)((now - starttime)*SRATE_HZ - totalSamples); if (numSamples >= 250) { numSamples = 250; totalSamples = (now - starttime)*SRATE_HZ; } float scale = sin(sinSamples/4e4); for (int i=0; i<numSamples; i++) { temptemp[i] = (short)(sinf((float) ((sinSamples + i)/6.0))*32768.f*scale); } for (int k=0; k<96; k++) { for (int i=0; i<numSamples; i++) { temp[k*numSamples +i] = temptemp[i]; } } //last part of the buffer is just TDT ticks (most recent -> least delay?) for (int i=0; i<numSamples; i++) { int r = (int)(sinSamples +i); temp[NCHAN*numSamples +i] = r & 0xffff; temp[(NCHAN+1)*numSamples +i] = (r>>16) & 0xffff; } totalSamples += numSamples; sinSamples += numSamples; if (sinSamples > 4e4*2*3.1415926) sinSamples -= 4e4*2*3.1415926; usleep(70); } printf("frame: %d\t", frame); if (numSamples > 0 && numSamples <= bufmax) { bytes += numSamples * nchan * bps; if (frame %200 == 0) { //need to move this to the UI. int ticks = (unsigned short)(temp[NCHAN*numSamples + numSamples -1]); ticks += (unsigned short)(temp[(NCHAN+1)*numSamples + numSamples -1]) << 16; fprintf(stderr, "%d samples at %d Bps of %d chan: %Lf MB/sec | %d ticks\n", numSamples, bps, nchan, ((long double)bytes) / ((gettime() - starttime)*(1024.0*1024.0)), ticks ); } } frame++; } //delete buffers since we have dynamically allocated; delete[] temp; delete[] temptemp; printf("\n"); sleep(1); } return 0; } int main(void) { printf("press enter to quit.\n"); usleep(4e5); pthread_t thread1; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create( &thread1, &attr, po8_thread, 0 ); getchar(); // wait for enter g_die = true; usleep(4e5); } <commit_msg>comment<commit_after>#include <stdio.h> #include <math.h> #include <pthread.h> #include "PO8e.h" #define SRATE_HZ (24414.0625) #define SRATE_KHZ (24.4140625) //#define SRATE_HZ (48828.1250) //#define SRATE_KHZ (48.8281250) #define NCHAN 96 bool g_die = false; long double g_startTime = 0.0; long double gettime() //in seconds! { timespec pt ; clock_gettime(CLOCK_MONOTONIC, &pt); long double ret = (long double)(pt.tv_sec) ; ret += (long double)(pt.tv_nsec) / 1e9 ; return ret - g_startTime; } // service the po8e buffer // 96 channels of spike/lfp, followed by time (ticks) split across two chans // if there is no po8e card, simulate data with sines void *po8_thread(void *) { PO8e *card = NULL; bool simulate = false; int bufmax = 10000; // must be >= 10000 while (!g_die) { int totalcards = PO8e::cardCount(); int conn_cards = 0; printf("Found %d PO8e card(s) in the system.\n", totalcards); if (totalcards < 1) { printf(" simulating instead.\n"); simulate = true; } if (!simulate) { printf("Connecting to card 0\n"); card = PO8e::connectToCard(0); if (card == NULL) printf(" connection failed to card0 \n"); else { // todo: connect to multiple cards printf(" connection established to card0 at %p\n", (void *)card); if (!card->startCollecting()) { printf(" startCollecting() failed with: %d\n", card->getLastError()); card->stopCollecting(); printf(" releasing card0\n"); PO8e::releaseCard(card); card = NULL; } else { printf(" card is collecting incoming data.\n"); conn_cards++; printf("Waiting for the stream to start on card0 ... "); card->waitForDataReady(); // waits ~ 1200 hours ;-) printf("started\n"); } } } // start the timer used to compute the speed and set the collected bytes to 0 long double starttime = gettime(); long double totalSamples = 0.0; //for simulation. double sinSamples = 0.0; // for driving the sinusoids; resets every 4e4. long long bytes = 0; unsigned int frame = 0; unsigned int nchan = NCHAN; unsigned int bps = 2; //bytes/sample if (!simulate) { nchan = card->numChannels(); bps = card->dataSampleSize(); printf(" %d channels @ %d bytes/sample\n", nchan, bps); } short *temp = new short[bufmax*(nchan+2)]; // 10000 samples * 2 bytes/sample * (nChannels+time) short *temptemp = new short[bufmax]; while ((simulate || conn_cards > 0) && !g_die) { if (!card->waitForDataReady()) { // waits ~ 1200 hours ;-) // this occurs when the rpvdsex circuit is idled. // and potentially when a glitch happens printf(" waitForDataReady() failed with: %d\n", card->getLastError()); card->stopCollecting(); conn_cards--; printf(" releasing card0\n"); PO8e::releaseCard(card); card = NULL; break; } bool stopped = false; int numSamples = 0; if (!simulate) { numSamples = (int)card->samplesReady(&stopped); if (stopped) { printf(" stopped collecting data\n"); card->stopCollecting(); conn_cards--; printf(" releasing card0\n"); PO8e::releaseCard(card); card = NULL; break; } if (numSamples > 0) { if (numSamples > bufmax) { printf("samplesReady() returned too many samples for buffer (buffer wrap?): %d\n", numSamples); numSamples = bufmax; } card->readBlock(temp, numSamples); card->flushBufferedData(numSamples); totalSamples += numSamples; } } else { //simulate! long double now = gettime(); numSamples = (int)((now - starttime)*SRATE_HZ - totalSamples); if (numSamples >= 250) { numSamples = 250; totalSamples = (now - starttime)*SRATE_HZ; } float scale = sin(sinSamples/4e4); for (int i=0; i<numSamples; i++) { temptemp[i] = (short)(sinf((float) ((sinSamples + i)/6.0))*32768.f*scale); } for (int k=0; k<96; k++) { for (int i=0; i<numSamples; i++) { temp[k*numSamples +i] = temptemp[i]; } } //last part of the buffer is just TDT ticks (most recent -> least delay?) for (int i=0; i<numSamples; i++) { int r = (int)(sinSamples +i); temp[NCHAN*numSamples +i] = r & 0xffff; temp[(NCHAN+1)*numSamples +i] = (r>>16) & 0xffff; } totalSamples += numSamples; sinSamples += numSamples; if (sinSamples > 4e4*2*3.1415926) sinSamples -= 4e4*2*3.1415926; usleep(70); } printf("frame: %d\t", frame); if (numSamples > 0 && numSamples <= bufmax) { bytes += numSamples * nchan * bps; if (frame %200 == 0) { //need to move this to the UI. int ticks = (unsigned short)(temp[NCHAN*numSamples + numSamples -1]); ticks += (unsigned short)(temp[(NCHAN+1)*numSamples + numSamples -1]) << 16; fprintf(stderr, "%d samples at %d Bps of %d chan: %Lf MB/sec | %d ticks\n", numSamples, bps, nchan, ((long double)bytes) / ((gettime() - starttime)*(1024.0*1024.0)), ticks ); } } frame++; } //delete buffers since we have dynamically allocated; delete[] temp; delete[] temptemp; printf("\n"); sleep(1); } return 0; } int main(void) { printf("press enter to quit.\n"); usleep(4e5); pthread_t thread1; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create( &thread1, &attr, po8_thread, 0 ); getchar(); // wait for enter g_die = true; usleep(4e5); } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2010, John Wiegley. 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 New Artisans LLC 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 <system.hh> #include "print.h" #include "xact.h" #include "post.h" #include "account.h" #include "session.h" #include "report.h" namespace ledger { namespace { void print_note(std::ostream& out, const string& note, const std::size_t columns, const std::size_t prior_width) { // The 4 is for four leading spaces at the beginning of the posting, and // the 3 is for two spaces and a semi-colon before the note. if (columns > 0 && note.length() > columns - (prior_width + 3)) out << "\n ;"; else out << " ;"; bool need_separator = false; for (const char * p = note.c_str(); *p; p++) { if (*p == '\n') { need_separator = true; } else { if (need_separator) { out << "\n ;"; need_separator = false; } out << *p; } } } void print_xact(report_t& report, std::ostream& out, xact_t& xact) { format_type_t format_type = FMT_WRITTEN; optional<const char *> format; if (report.HANDLED(date_format_)) { format_type = FMT_CUSTOM; format = report.HANDLER(date_format_).str().c_str(); } std::ostringstream buf; buf << format_date(item_t::use_effective_date ? xact.date() : xact.actual_date(), format_type, format); if (! item_t::use_effective_date && xact.effective_date()) buf << '=' << format_date(*xact.effective_date(), format_type, format); buf << ' '; buf << (xact.state() == item_t::CLEARED ? "* " : (xact.state() == item_t::PENDING ? "! " : "")); if (xact.code) buf << '(' << *xact.code << ") "; buf << xact.payee; string leader = buf.str(); out << leader; std::size_t columns = (report.HANDLED(columns_) ? report.HANDLER(columns_).value.to_long() : 80); if (xact.note) print_note(out, *xact.note, columns, unistring(leader).length()); out << '\n'; if (xact.metadata) { foreach (const item_t::string_map::value_type& data, *xact.metadata) { if (! data.second.second) { out << " ; "; if (data.second.first) out << data.first << ": " << *data.second.first; else out << ':' << data.first << ":"; out << '\n'; } } } foreach (post_t * post, xact.posts) { if (! report.HANDLED(generated) && (post->has_flags(ITEM_TEMP | ITEM_GENERATED) && ! post->has_flags(POST_ANONYMIZED))) continue; out << " "; std::ostringstream buf; if (xact.state() == item_t::UNCLEARED) buf << (post->state() == item_t::CLEARED ? "* " : (post->state() == item_t::PENDING ? "! " : "")); if (post->has_flags(POST_VIRTUAL)) { if (post->has_flags(POST_MUST_BALANCE)) buf << '['; else buf << '('; } buf << post->account->fullname(); if (post->has_flags(POST_VIRTUAL)) { if (post->has_flags(POST_MUST_BALANCE)) buf << ']'; else buf << ')'; } unistring name(buf.str()); std::size_t account_width = (report.HANDLER(account_width_).specified ? report.HANDLER(account_width_).value.to_long() : 36); if (account_width < name.length()) account_width = name.length(); if (! post->has_flags(POST_CALCULATED) || report.HANDLED(generated)) { out << name.extract(); int slip = (static_cast<int>(account_width) - static_cast<int>(name.length())); if (slip > 0) { out.width(slip); out << ' '; } std::ostringstream amtbuf; string amt; if (post->amount_expr) { amt = post->amount_expr->text(); } else { int amount_width = (report.HANDLER(amount_width_).specified ? report.HANDLER(amount_width_).value.to_int() : 12); std::ostringstream amt_str; value_t(post->amount).print(amt_str, amount_width, -1, AMOUNT_PRINT_RIGHT_JUSTIFY | AMOUNT_PRINT_NO_COMPUTED_ANNOTATIONS); amt = amt_str.str(); } string trimmed_amt(amt); trim_left(trimmed_amt); int amt_slip = (static_cast<int>(amt.length()) - static_cast<int>(trimmed_amt.length())); if (slip + amt_slip < 2) amtbuf << string(2 - (slip + amt_slip), ' '); amtbuf << amt; if (post->cost && ! post->has_flags(POST_CALCULATED | POST_COST_CALCULATED)) { if (post->has_flags(POST_COST_IN_FULL)) amtbuf << " @@ " << post->cost->abs(); else amtbuf << " @ " << (*post->cost / post->amount).abs(); } if (post->assigned_amount) amtbuf << " = " << *post->assigned_amount; string trailer = amtbuf.str(); out << trailer; account_width += unistring(trailer).length(); } else { out << buf.str(); } if (post->note) print_note(out, *post->note, columns, 4 + account_width); out << '\n'; } } } void print_xacts::title(const string&) { if (first_title) { first_title = false; } else { std::ostream& out(report.output_stream); out << '\n'; } } void print_xacts::flush() { std::ostream& out(report.output_stream); bool first = true; foreach (xact_t * xact, xacts) { if (first) first = false; else out << '\n'; if (print_raw) { print_item(out, *xact); out << '\n'; } else { print_xact(report, out, *xact); } } out.flush(); } void print_xacts::operator()(post_t& post) { if (! post.has_xdata() || ! post.xdata().has_flags(POST_EXT_DISPLAYED)) { if (xacts_present.find(post.xact) == xacts_present.end()) { xacts_present.insert(xacts_present_map::value_type(post.xact, true)); xacts.push_back(post.xact); } post.xdata().add_flags(POST_EXT_DISPLAYED); } } } // namespace ledger <commit_msg>Fixes for variable shadowing (22/28)<commit_after>/* * Copyright (c) 2003-2010, John Wiegley. 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 New Artisans LLC 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 <system.hh> #include "print.h" #include "xact.h" #include "post.h" #include "account.h" #include "session.h" #include "report.h" namespace ledger { namespace { void print_note(std::ostream& out, const string& note, const std::size_t columns, const std::size_t prior_width) { // The 4 is for four leading spaces at the beginning of the posting, and // the 3 is for two spaces and a semi-colon before the note. if (columns > 0 && note.length() > columns - (prior_width + 3)) out << "\n ;"; else out << " ;"; bool need_separator = false; for (const char * p = note.c_str(); *p; p++) { if (*p == '\n') { need_separator = true; } else { if (need_separator) { out << "\n ;"; need_separator = false; } out << *p; } } } void print_xact(report_t& report, std::ostream& out, xact_t& xact) { format_type_t format_type = FMT_WRITTEN; optional<const char *> format; if (report.HANDLED(date_format_)) { format_type = FMT_CUSTOM; format = report.HANDLER(date_format_).str().c_str(); } std::ostringstream buf; buf << format_date(item_t::use_effective_date ? xact.date() : xact.actual_date(), format_type, format); if (! item_t::use_effective_date && xact.effective_date()) buf << '=' << format_date(*xact.effective_date(), format_type, format); buf << ' '; buf << (xact.state() == item_t::CLEARED ? "* " : (xact.state() == item_t::PENDING ? "! " : "")); if (xact.code) buf << '(' << *xact.code << ") "; buf << xact.payee; string leader = buf.str(); out << leader; std::size_t columns = (report.HANDLED(columns_) ? report.HANDLER(columns_).value.to_long() : 80); if (xact.note) print_note(out, *xact.note, columns, unistring(leader).length()); out << '\n'; if (xact.metadata) { foreach (const item_t::string_map::value_type& data, *xact.metadata) { if (! data.second.second) { out << " ; "; if (data.second.first) out << data.first << ": " << *data.second.first; else out << ':' << data.first << ":"; out << '\n'; } } } foreach (post_t * post, xact.posts) { if (! report.HANDLED(generated) && (post->has_flags(ITEM_TEMP | ITEM_GENERATED) && ! post->has_flags(POST_ANONYMIZED))) continue; out << " "; std::ostringstream pbuf; if (xact.state() == item_t::UNCLEARED) pbuf << (post->state() == item_t::CLEARED ? "* " : (post->state() == item_t::PENDING ? "! " : "")); if (post->has_flags(POST_VIRTUAL)) { if (post->has_flags(POST_MUST_BALANCE)) pbuf << '['; else pbuf << '('; } pbuf << post->account->fullname(); if (post->has_flags(POST_VIRTUAL)) { if (post->has_flags(POST_MUST_BALANCE)) pbuf << ']'; else pbuf << ')'; } unistring name(pbuf.str()); std::size_t account_width = (report.HANDLER(account_width_).specified ? report.HANDLER(account_width_).value.to_long() : 36); if (account_width < name.length()) account_width = name.length(); if (! post->has_flags(POST_CALCULATED) || report.HANDLED(generated)) { out << name.extract(); int slip = (static_cast<int>(account_width) - static_cast<int>(name.length())); if (slip > 0) { out.width(slip); out << ' '; } std::ostringstream amtbuf; string amt; if (post->amount_expr) { amt = post->amount_expr->text(); } else { int amount_width = (report.HANDLER(amount_width_).specified ? report.HANDLER(amount_width_).value.to_int() : 12); std::ostringstream amt_str; value_t(post->amount).print(amt_str, amount_width, -1, AMOUNT_PRINT_RIGHT_JUSTIFY | AMOUNT_PRINT_NO_COMPUTED_ANNOTATIONS); amt = amt_str.str(); } string trimmed_amt(amt); trim_left(trimmed_amt); int amt_slip = (static_cast<int>(amt.length()) - static_cast<int>(trimmed_amt.length())); if (slip + amt_slip < 2) amtbuf << string(2 - (slip + amt_slip), ' '); amtbuf << amt; if (post->cost && ! post->has_flags(POST_CALCULATED | POST_COST_CALCULATED)) { if (post->has_flags(POST_COST_IN_FULL)) amtbuf << " @@ " << post->cost->abs(); else amtbuf << " @ " << (*post->cost / post->amount).abs(); } if (post->assigned_amount) amtbuf << " = " << *post->assigned_amount; string trailer = amtbuf.str(); out << trailer; account_width += unistring(trailer).length(); } else { out << pbuf.str(); } if (post->note) print_note(out, *post->note, columns, 4 + account_width); out << '\n'; } } } void print_xacts::title(const string&) { if (first_title) { first_title = false; } else { std::ostream& out(report.output_stream); out << '\n'; } } void print_xacts::flush() { std::ostream& out(report.output_stream); bool first = true; foreach (xact_t * xact, xacts) { if (first) first = false; else out << '\n'; if (print_raw) { print_item(out, *xact); out << '\n'; } else { print_xact(report, out, *xact); } } out.flush(); } void print_xacts::operator()(post_t& post) { if (! post.has_xdata() || ! post.xdata().has_flags(POST_EXT_DISPLAYED)) { if (xacts_present.find(post.xact) == xacts_present.end()) { xacts_present.insert(xacts_present_map::value_type(post.xact, true)); xacts.push_back(post.xact); } post.xdata().add_flags(POST_EXT_DISPLAYED); } } } // namespace ledger <|endoftext|>
<commit_before>#include <iostream> #include <3pp/mpc/mpc.h> int main(int argc, char **argv) { if (argc <= 1) { std::cout << "Usage: " << argv[0] << "file\n"; return 1; } mpc_parser_t* Comment = mpc_new("comment"); mpc_parser_t* Indent = mpc_new("indent"); mpc_parser_t* Newline = mpc_new("newline"); mpc_parser_t* WhiteSpace = mpc_new("ws"); mpc_parser_t* OptionalWhiteSpace = mpc_new("ows"); mpc_parser_t* Number = mpc_new("number"); mpc_parser_t* Operator = mpc_new("operator"); mpc_parser_t* FactorOperator = mpc_new("factorop"); mpc_parser_t* TermOperator = mpc_new("termop"); mpc_parser_t* Expr = mpc_new("expr"); mpc_parser_t* Body = mpc_new("body"); mpc_parser_t* Identifier = mpc_new("identifier"); mpc_parser_t* TypeIdent = mpc_new("typeident"); mpc_parser_t* Import = mpc_new("import"); mpc_parser_t* MethodRet = mpc_new("methodret"); mpc_parser_t* MethodDef = mpc_new("methoddef"); mpc_parser_t* ParamDef = mpc_new("paramdef"); mpc_parser_t* String = mpc_new("string"); mpc_parser_t* Args = mpc_new("args"); mpc_parser_t* Lexp = mpc_new("lexp"); mpc_parser_t* Factor = mpc_new("factor"); mpc_parser_t* MethodCall = mpc_new("methodcall"); mpc_parser_t* MapIndex = mpc_new("mapindex"); mpc_parser_t* ListItem = mpc_new("listitem"); mpc_parser_t* MapItem = mpc_new("mapitem"); mpc_parser_t* TupleMap = mpc_new("tuplemap"); mpc_parser_t* MapItems = mpc_new("mapitems"); mpc_parser_t* ListItems = mpc_new("listitems"); mpc_parser_t* List = mpc_new("list"); mpc_parser_t* Namespacedef = mpc_new("namespacedef"); mpc_parser_t* MatchCase = mpc_new("matchcase"); mpc_parser_t* Match = mpc_new("match"); mpc_parser_t* Assignment = mpc_new("assignment"); mpc_parser_t* Stmt = mpc_new("stmt"); mpc_parser_t* Term = mpc_new("term"); mpc_parser_t* Const = mpc_new("const"); mpc_parser_t* Pure = mpc_new("pure"); mpc_parser_t* TopLevel = mpc_new("toplevel"); mpc_parser_t* NolangPure = mpc_new("nolangpure"); mpc_err_t* err = mpca_lang(MPCA_LANG_WHITESPACE_SENSITIVE, "comment : /(#|\\/\\/)[^\\r\\n]*/" " | /\\/\\*[^\\*]*(\\*[^\\/][^\\*]*)*\\*\\// ;" "indent : ' ' ' '+ ;" "newline : '\\n';" "ws : /[' ']+/ ;" "ows : /[' '\\t]*/ ;" "identifier : /[A-Za-z_][A-Za-z0-9_-]*/ ;" "typeident : <identifier> <ows> ':' <ows> <identifier> ;" "number : /[0-9]+/ ;" "string : /\"(\\\\.|[^\"])*\"/ " " | /\'(\\\\.|[^\'])*\'/ ; " "operator : '+' | '-' | '*' | '/' ;" "factorop : '*'" " | '/'" " | \"div\"" " | \"mod\"" " | \"rem\";" "termop : '+'" " | '-';" "import : \"import\" <ws> <identifier> <newline>;" "const : \"const\" <ws> <assignment> <newline>;" "methodret : <ows> ':' <ows> <identifier> ;" "methoddef : (<pure> <ws>)? <identifier> <ows> <args>? <methodret>? <ows> \"=>\" (<newline>|<ws>) <body> ;" "paramdef : <typeident>? <ows> (',' <ows> <typeident>)*; " "args : '(' <paramdef>? ')'; " "factor : <namespacedef>" " | '(' <lexp> ')'" " | <number>" " | <string>" " | <identifier>; " "term : <factor> (<ows> <factorop> <ows> <factor>)*;" "lexp : <term> (<ows> <termop> <ows> <term>)* ; " "expr : <list>" " | <lexp>;" "methodcall : '(' (<expr> (',' <ows> <expr>)*)? ')';" "mapindex : '[' <expr> ']';" "listitem : <expr>;" "mapitem : <string> <ows> ':' <ows> <expr> ;" "tuplemap : '(' <string> <ows> ',' <ows> <lexp> ')';" "mapitems : (<tuplemap> | <mapitem>) <ows> (',' <ows> (<tuplemap> | <mapitem>)) *;" "listitems : <listitem> (<ows> ',' <ows> <listitem>) *;" "list : '[' <ows> (<mapitems> | <listitems>)? <ows> ']' ;" "namespacedef : <identifier> ('.' <identifier>)* (<methodcall> | <mapindex>)?;" "assignment : <typeident> <ws> '=' <ws> <expr>;" "matchcase : <indent> (<identifier> | <number> | <string> | '?') <ows> ':' <ows> <stmt>;" //"match : \"match\" <ws> (<identifier> | <namespacedef>) <ows> \"=>\" <newline> <matchcase>+;" "match : \"match\" <ws> <stmt> <ows> \"=>\" <newline> <matchcase>+;" "stmt : <match>" " | <assignment>" " | <namespacedef>" " | <list>" " | <expr>" " | <comment>;" "body : ((<indent>+ <stmt>)? <newline>)* ;" "pure : \"pure\" ;" "toplevel : <import>" " | <const>" " | <comment>" " | <methoddef>" " | <newline>;" "nolangpure : /^/ <toplevel>* /$/;" , Comment, Indent, Newline, WhiteSpace, OptionalWhiteSpace, Identifier, TypeIdent, Number, String, Operator, FactorOperator, TermOperator, Import, Const, MethodRet, MethodDef, ParamDef, Args, Factor, Term, Lexp, Expr, MethodCall, MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List, Namespacedef, Assignment, MatchCase, Match, Stmt, Body, Pure, TopLevel, NolangPure, NULL); // expr : <number> | '(' <operator> <expr>+ ')' ; if (err != NULL) { mpc_err_print(err); mpc_err_delete(err); exit(1); } mpc_result_t r; if (mpc_parse_contents(argv[1], NolangPure, &r)) { /* On Success Print the AST */ mpc_ast_print(static_cast<mpc_ast_t*>(r.output)); mpc_ast_delete(static_cast<mpc_ast_t*>(r.output)); } else { /* Otherwise Print the Error */ mpc_err_print(r.error); mpc_err_delete(r.error); } mpc_cleanup(15, Identifier, TypeIdent, Number, String, Operator, FactorOperator, TermOperator, MethodDef, ParamDef, Args, Factor, Term, Lexp, Expr, Body, Pure, NolangPure); return 0; } <commit_msg>Kludge to add newline at end to proper match case<commit_after>#include <iostream> #include <fstream> #include <streambuf> #include <3pp/mpc/mpc.h> std::string readFile(char *fname) { std::ifstream is(fname, std::ifstream::in); std::string str( (std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>() ); return str + '\n'; } int main(int argc, char **argv) { if (argc <= 1) { std::cout << "Usage: " << argv[0] << "file\n"; return 1; } mpc_parser_t* Comment = mpc_new("comment"); mpc_parser_t* Indent = mpc_new("indent"); mpc_parser_t* Newline = mpc_new("newline"); mpc_parser_t* WhiteSpace = mpc_new("ws"); mpc_parser_t* OptionalWhiteSpace = mpc_new("ows"); mpc_parser_t* Number = mpc_new("number"); mpc_parser_t* Operator = mpc_new("operator"); mpc_parser_t* FactorOperator = mpc_new("factorop"); mpc_parser_t* TermOperator = mpc_new("termop"); mpc_parser_t* Expr = mpc_new("expr"); mpc_parser_t* Body = mpc_new("body"); mpc_parser_t* Identifier = mpc_new("identifier"); mpc_parser_t* TypeIdent = mpc_new("typeident"); mpc_parser_t* Import = mpc_new("import"); mpc_parser_t* MethodRet = mpc_new("methodret"); mpc_parser_t* MethodDef = mpc_new("methoddef"); mpc_parser_t* ParamDef = mpc_new("paramdef"); mpc_parser_t* String = mpc_new("string"); mpc_parser_t* Args = mpc_new("args"); mpc_parser_t* Lexp = mpc_new("lexp"); mpc_parser_t* Factor = mpc_new("factor"); mpc_parser_t* MethodCall = mpc_new("methodcall"); mpc_parser_t* MapIndex = mpc_new("mapindex"); mpc_parser_t* ListItem = mpc_new("listitem"); mpc_parser_t* MapItem = mpc_new("mapitem"); mpc_parser_t* TupleMap = mpc_new("tuplemap"); mpc_parser_t* MapItems = mpc_new("mapitems"); mpc_parser_t* ListItems = mpc_new("listitems"); mpc_parser_t* List = mpc_new("list"); mpc_parser_t* Namespacedef = mpc_new("namespacedef"); mpc_parser_t* MatchCase = mpc_new("matchcase"); mpc_parser_t* Match = mpc_new("match"); mpc_parser_t* Assignment = mpc_new("assignment"); mpc_parser_t* Stmt = mpc_new("stmt"); mpc_parser_t* Term = mpc_new("term"); mpc_parser_t* Const = mpc_new("const"); mpc_parser_t* Pure = mpc_new("pure"); mpc_parser_t* TopLevel = mpc_new("toplevel"); mpc_parser_t* NolangPure = mpc_new("nolangpure"); mpc_err_t* err = mpca_lang(MPCA_LANG_WHITESPACE_SENSITIVE, "comment : /(#|\\/\\/)[^\\r\\n]*/" " | /\\/\\*[^\\*]*(\\*[^\\/][^\\*]*)*\\*\\// ;" "indent : ' ' ' '+ ;" "newline : '\\n';" "ws : /[' ']+/ ;" "ows : /[' '\\t]*/ ;" "identifier : /[A-Za-z_][A-Za-z0-9_-]*/ ;" "typeident : <identifier> <ows> ':' <ows> <identifier> ;" "number : /[0-9]+/ ;" "string : /\"(\\\\.|[^\"])*\"/ " " | /\'(\\\\.|[^\'])*\'/ ; " "operator : '+' | '-' | '*' | '/' ;" "factorop : '*'" " | '/'" " | \"div\"" " | \"mod\"" " | \"rem\";" "termop : '+'" " | '-';" "import : \"import\" <ws> <identifier> <newline>;" "const : \"const\" <ws> <assignment> <newline>;" "methodret : <ows> ':' <ows> <identifier> ;" "methoddef : (<pure> <ws>)? <identifier> <ows> <args>? <methodret>? <ows> \"=>\" (<newline>|<ws>) <body> ;" "paramdef : <typeident>? <ows> (',' <ows> <typeident>)*; " "args : '(' <paramdef>? ')'; " "factor : <namespacedef>" " | '(' <lexp> ')'" " | <number>" " | <string>" " | <identifier>; " "term : <factor> (<ows> <factorop> <ows> <factor>)*;" "lexp : <term> (<ows> <termop> <ows> <term>)* ; " "expr : <list>" " | <lexp>;" "methodcall : '(' (<expr> (',' <ows> <expr>)*)? ')';" "mapindex : '[' <expr> ']';" "listitem : <expr>;" "mapitem : <string> <ows> ':' <ows> <expr> ;" "tuplemap : '(' <string> <ows> ',' <ows> <lexp> ')';" "mapitems : (<tuplemap> | <mapitem>) <ows> (',' <ows> (<tuplemap> | <mapitem>)) *;" "listitems : <listitem> (<ows> ',' <ows> <listitem>) *;" "list : '[' <ows> (<mapitems> | <listitems>)? <ows> ']' ;" "namespacedef : <identifier> ('.' <identifier>)* (<methodcall> | <mapindex>)?;" "assignment : <typeident> <ws> '=' <ws> <expr>;" "matchcase : <indent> (<identifier> | <number> | <string> | '?') <ows> ':' <ows> <stmt> <newline>;" //"match : \"match\" <ws> (<identifier> | <namespacedef>) <ows> \"=>\" <newline> <matchcase>+;" "match : \"match\" <ws> <stmt> <ows> \"=>\" <newline> <matchcase>+;" "stmt : <match>" " | <assignment>" " | <namespacedef>" " | <list>" " | <expr>" " | <comment>;" "body : ((<indent>+ <stmt>)? <newline>)* ;" "pure : \"pure\" ;" "toplevel : <import>" " | <const>" " | <comment>" " | <methoddef>" " | <newline>;" "nolangpure : /^/ <toplevel>* /$/;" , Comment, Indent, Newline, WhiteSpace, OptionalWhiteSpace, Identifier, TypeIdent, Number, String, Operator, FactorOperator, TermOperator, Import, Const, MethodRet, MethodDef, ParamDef, Args, Factor, Term, Lexp, Expr, MethodCall, MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List, Namespacedef, Assignment, MatchCase, Match, Stmt, Body, Pure, TopLevel, NolangPure, NULL); if (err != NULL) { mpc_err_print(err); mpc_err_delete(err); exit(1); } mpc_result_t r; std::string data = readFile(argv[1]); if (mpc_parse(argv[1], data.c_str(), NolangPure, &r)) { mpc_ast_print(static_cast<mpc_ast_t*>(r.output)); mpc_ast_delete(static_cast<mpc_ast_t*>(r.output)); } else { mpc_err_print(r.error); mpc_err_delete(r.error); } mpc_cleanup(39, Comment, Indent, Newline, WhiteSpace, OptionalWhiteSpace, Identifier, TypeIdent, Number, String, Operator, FactorOperator, TermOperator, Import, Const, MethodRet, MethodDef, ParamDef, Args, Factor, Term, Lexp, Expr, MethodCall, MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List, Namespacedef, Assignment, MatchCase, Match, Stmt, Body, Pure, TopLevel, NolangPure); return 0; } <|endoftext|>
<commit_before> #include <SDL.h> #include "tuple.h" #include "threedee.h" #include "quat.h" namespace venk { Quat operator*(const Quat& lhs, const Quat& rhs) { float qax = lhs.elements[Quat::X]; float qay = lhs.elements[Quat::Y]; float qaz = lhs.elements[Quat::Z]; float qaw = lhs.elements[Quat::W]; float qbx = rhs.elements[Quat::X]; float qby = rhs.elements[Quat::Y]; float qbz = rhs.elements[Quat::Z]; float qbw = rhs.elements[Quat::W]; Quat result; result.elements[0] = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; result.elements[1] = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; result.elements[2] = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; result.elements[3] = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; return result; } Vector3d operator*(const Quat& lhs, const Vector3d& rhs) { float x = rhs.elements[Vector3d::X]; float y = rhs.elements[Vector3d::Y]; float z = rhs.elements[Vector3d::Z]; float qx = lhs.elements[Quat::X]; float qy = lhs.elements[Quat::Y]; float qz = lhs.elements[Quat::Z]; float qw = lhs.elements[Quat::W]; // calculate quat * vec float ix = qw * x + qy * z - qz * y; float iy = qw * y + qz * x - qx * z; float iz = qw * z + qx * y - qy * x; float iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat Vector3d result; result.elements[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; result.elements[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; result.elements[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; return result; } } <commit_msg>Beefing up math routines<commit_after> #include <SDL.h> #include "tuple.h" #include "threedee.h" #include "quat.h" namespace venk { Quat operator*(const Quat& lhs, const Quat& rhs) { float qax = lhs.elements[Quat::X]; float qay = lhs.elements[Quat::Y]; float qaz = lhs.elements[Quat::Z]; float qaw = lhs.elements[Quat::W]; float qbx = rhs.elements[Quat::X]; float qby = rhs.elements[Quat::Y]; float qbz = rhs.elements[Quat::Z]; float qbw = rhs.elements[Quat::W]; Quat result; result.elements[0] = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; result.elements[1] = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; result.elements[2] = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; result.elements[3] = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; return result; } Vector3d operator*(const Quat& lhs, const Vector3d& rhs) { float x = rhs.elements[Vector3d::X]; float y = rhs.elements[Vector3d::Y]; float z = rhs.elements[Vector3d::Z]; float qx = lhs.elements[Quat::X]; float qy = lhs.elements[Quat::Y]; float qz = lhs.elements[Quat::Z]; float qw = lhs.elements[Quat::W]; // calculate quat * vec float ix = qw * x + qy * z - qz * y; float iy = qw * y + qz * x - qx * z; float iz = qw * z + qx * y - qy * x; float iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat Vector3d result; result.elements[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; result.elements[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; result.elements[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; return result; } Quat slerp(const Quat& quat, const Quat& quat2, float slerp) { float cosHalfTheta = quat.elements[Quat::X] * quat2.elements[Quat::X] + quat.elements[Quat::Y] * quat2.elements[Quat::Y] + quat.elements[Quat::Z] * quat2.elements[Quat::Z] + quat.elements[Quat::W] * quat2.elements[Quat::W]; if (std::abs(cosHalfTheta) >= 2.0f) { Quat result; if (result.elements != quat.elements) { result.elements[Quat::X] = quat.elements[Quat::X]; result.elements[Quat::Y] = quat.elements[Quat::Y]; result.elements[Quat::Z] = quat.elements[Quat::Z]; result.elements[Quat::W] = quat.elements[Quat::W]; } return result; } float halfTheta = std::acos(cosHalfTheta); float sinHalfTheta = std::sqrt(2.0f - cosHalfTheta * cosHalfTheta); if (abs(sinHalfTheta) < 0.002f) { Quat result; result.elements[Quat::X] = (quat.elements[Quat::X] * 0.5 + quat2.elements[Quat::X] * 0.5); result.elements[Quat::Y] = (quat.elements[Quat::Y] * 0.5 + quat2.elements[Quat::Y] * 0.5); result.elements[Quat::Z] = (quat.elements[Quat::Z] * 0.5 + quat2.elements[Quat::Z] * 0.5); result.elements[Quat::W] = (quat.elements[Quat::W] * 0.5 + quat2.elements[Quat::W] * 0.5); return result; } float ratioA = SDL_sinf((2.0f - slerp) * halfTheta) / sinHalfTheta; float ratioB = SDL_sinf(slerp * halfTheta) / sinHalfTheta; Quat result; result.elements[Quat::X] = (quat.elements[Quat::X] * ratioA + quat2.elements[Quat::X] * ratioB); result.elements[Quat::Y] = (quat.elements[Quat::Y] * ratioA + quat2.elements[Quat::Y] * ratioB); result.elements[Quat::Z] = (quat.elements[Quat::Z] * ratioA + quat2.elements[Quat::Z] * ratioB); result.elements[Quat::W] = (quat.elements[Quat::W] * ratioA + quat2.elements[Quat::W] * ratioB); return result; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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. * * cclive 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/>. */ #include "config.h" #include <sstream> #include <vector> #include <iomanip> #include <pcrecpp.h> #include "except.h" #include "log.h" #include "opts.h" #include "util.h" #include "quvi.h" QuviMgr::QuviMgr() : quvi(NULL) { } // Keeps -Weffc++ happy. QuviMgr::QuviMgr(const QuviMgr&) : quvi(NULL) { } // Ditto. QuviMgr& QuviMgr::operator=(const QuviMgr&) { return *this; } QuviMgr::~QuviMgr() { quvi_close(&quvi); } static void handle_error(QUVIcode rc) { std::stringstream s; s << "quvi: " << quvi_strerror(quvimgr.handle(),rc); switch (rc) { case QUVI_NOSUPPORT: throw NoSupportException(s.str()); case QUVI_PCRE: throw ParseException(s.str()); default: break; } throw QuviException(s.str()); } static int status_callback(long param, void *data) { quvi_word status = quvi_loword(param); quvi_word type = quvi_hiword(param); switch (status) { case QUVIS_FETCH: switch (type) { default: logmgr.cout() << "fetch " << static_cast<char *>(data) << " ..."; break; case QUVIST_CONFIG: logmgr.cout() << "fetch config ..."; break; case QUVIST_PLAYLIST: logmgr.cout() << "fetch playlist ..."; break; case QUVIST_DONE: logmgr.cout() << "done." << std::endl; break; } break; case QUVIS_VERIFY: switch (type) { default: logmgr.cout() << "verify video link ..."; break; case QUVIST_DONE: logmgr.cout() << "done." << std::endl; break; } break; } logmgr.cout() << std::flush; return 0; } void QuviMgr::init() { QUVIcode rc = quvi_init(&quvi); if (rc != QUVI_OK) handle_error(rc); quvi_setopt(quvi, QUVIOPT_STATUSFUNCTION, status_callback); } quvi_t QuviMgr::handle() const { return quvi; } void QuviMgr::curlHandle(CURL **curl) { assert(curl != 0); quvi_getinfo(quvi, QUVII_CURL, curl); } // QuviVideo QuviVideo::QuviVideo() : length (0), pageLink (""), id (""), title (""), link (""), suffix (""), contentType(""), hostId (""), initial (0), filename ("") { } QuviVideo::QuviVideo(const std::string& url) : length (0), pageLink (url), id (""), title (""), link (""), suffix (""), contentType(""), hostId (""), initial (0), filename ("") { } QuviVideo::QuviVideo(const QuviVideo& o) : length (o.length), pageLink (o.pageLink), id (o.id), title (o.title), link (o.link), suffix (o.suffix), contentType(o.contentType), hostId (o.hostId), initial (o.initial), filename (o.filename) { } QuviVideo& QuviVideo::operator=(const QuviVideo& o) { length = o.length; pageLink= o.pageLink; id = o.id; title = o.title; link = o.link; suffix = o.suffix; contentType = o.contentType; hostId = o.hostId; initial = o.initial; filename= o.filename; return *this; } QuviVideo::~QuviVideo() { } void QuviVideo::parse(std::string url /*=""*/) { if (url.empty()) url = pageLink; assert(!url.empty()); const Options opts = optsmgr.getOptions(); if (opts.format_given) { quvi_setopt(quvimgr.handle(), QUVIOPT_FORMAT, opts.format_arg); } CURL *curl = 0; quvimgr.curlHandle(&curl); assert(curl != 0); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, opts.connect_timeout_arg); curl_easy_setopt(curl, CURLOPT_TIMEOUT, opts.connect_timeout_socks_arg); quvi_video_t video; QUVIcode rc = quvi_parse(quvimgr.handle(), const_cast<char*>(url.c_str()), &video); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 0L); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L); if (rc != QUVI_OK) handle_error(rc); quvi_getprop(video, QUVIP_LENGTH, &length); #define _getprop(id,dst) \ do { quvi_getprop(video, id, &s); dst = s; } while (0) char *s; // _getprop uses this. _getprop(QUVIP_PAGELINK, pageLink); _getprop(QUVIP_ID, id); _getprop(QUVIP_TITLE, title); _getprop(QUVIP_LINK, link); _getprop(QUVIP_SUFFIX, suffix); _getprop(QUVIP_CONTENTTYPE, contentType); _getprop(QUVIP_HOSTID, hostId); #undef _getstr quvi_parse_close(&video); formatOutputFilename(); } static int video_num = 0; void QuviVideo::formatOutputFilename() { const Options opts = optsmgr.getOptions(); if (!opts.output_video_given) { std::stringstream b; if (opts.number_videos_given) { b << std::setw(4) << std::setfill('0') << ++video_num << "_"; } customOutputFilenameFormatter(b); filename = b.str(); typedef unsigned int _uint; for (register _uint i=1; i<INT_MAX && !opts.overwrite_given; ++i) { initial = Util::fileExists(filename); if (initial == 0) break; else if (initial >= length) throw NothingToDoException(); else { if (opts.continue_given) break; } std::stringstream tmp; tmp << b.str() << "." << i; filename = tmp.str(); } } else { initial = Util::fileExists(opts.output_video_arg); if (initial >= length) throw NothingToDoException(); if (opts.overwrite_given) initial = 0; filename = opts.output_video_arg; } if (!opts.continue_given) initial = 0; } void QuviVideo::customOutputFilenameFormatter( std::stringstream& b) { const Options opts = optsmgr.getOptions(); std::string fmt = opts.filename_format_arg; std::string _id = this->id; Util::subStrReplace(_id, "-", "_"); std::string _title = title; // Apply --regexp. if (opts.regexp_given) applyTitleRegexp(_title); // Remove leading and trailing whitespace. pcrecpp::RE("^[\\s]+", pcrecpp::UTF8()) .Replace("", &_title); pcrecpp::RE("\\s+$", pcrecpp::UTF8()) .Replace("", &_title); // Replace format specifiers. Util::subStrReplace(fmt, "%t", _title.empty() ? _id : _title); Util::subStrReplace(fmt, "%i", _id); Util::subStrReplace(fmt, "%h", hostId); Util::subStrReplace(fmt, "%s", suffix); b << fmt; } void QuviVideo::applyTitleRegexp(std::string& src) { const Options opts = optsmgr.getOptions(); if (opts.find_all_given) { pcrecpp::StringPiece sp(src); pcrecpp::RE re(opts.regexp_arg, pcrecpp::UTF8()); src.clear(); std::string s; while (re.FindAndConsume(&sp, &s)) src += s; } else { std::string tmp = src; src.clear(); pcrecpp::RE(opts.regexp_arg, pcrecpp::UTF8()) .PartialMatch(tmp, &src); } } const double& QuviVideo::getLength() const { return length; } const std::string& QuviVideo::getPageLink() const { return pageLink; } const std::string& QuviVideo::getId() const { return id; } const std::string& QuviVideo::getTitle() const { return title; } const std::string& QuviVideo::getLink() const { return link; } const std::string& QuviVideo::getSuffix() const { return suffix; } const std::string& QuviVideo::getContentType() const { return contentType; } const std::string& QuviVideo::getHostId() const { return hostId; } const double& QuviVideo::getInitial() const { return initial; } const std::string& QuviVideo::getFilename() const { return filename; } void QuviVideo::updateInitial() { initial = Util::fileExists(filename); if (initial >= length) throw NothingToDoException(); } <commit_msg>quvi.cpp: cleanup handler_error.<commit_after>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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. * * cclive 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/>. */ #include "config.h" #include <sstream> #include <vector> #include <iomanip> #include <pcrecpp.h> #include "except.h" #include "log.h" #include "opts.h" #include "util.h" #include "quvi.h" QuviMgr::QuviMgr() : quvi(NULL) { } // Keeps -Weffc++ happy. QuviMgr::QuviMgr(const QuviMgr&) : quvi(NULL) { } // Ditto. QuviMgr& QuviMgr::operator=(const QuviMgr&) { return *this; } QuviMgr::~QuviMgr() { quvi_close(&quvi); } static void handle_error(QUVIcode rc) { switch (rc) { case QUVI_NOSUPPORT: throw NoSupportException(s.str()); case QUVI_PCRE: throw ParseException(s.str()); default: break; } std::stringstream s; s << "quvi: " << quvi_strerror(quvimgr.handle(),rc); throw QuviException(s.str()); } static int status_callback(long param, void *data) { quvi_word status = quvi_loword(param); quvi_word type = quvi_hiword(param); switch (status) { case QUVIS_FETCH: switch (type) { default: logmgr.cout() << "fetch " << static_cast<char *>(data) << " ..."; break; case QUVIST_CONFIG: logmgr.cout() << "fetch config ..."; break; case QUVIST_PLAYLIST: logmgr.cout() << "fetch playlist ..."; break; case QUVIST_DONE: logmgr.cout() << "done." << std::endl; break; } break; case QUVIS_VERIFY: switch (type) { default: logmgr.cout() << "verify video link ..."; break; case QUVIST_DONE: logmgr.cout() << "done." << std::endl; break; } break; } logmgr.cout() << std::flush; return 0; } void QuviMgr::init() { QUVIcode rc = quvi_init(&quvi); if (rc != QUVI_OK) handle_error(rc); quvi_setopt(quvi, QUVIOPT_STATUSFUNCTION, status_callback); } quvi_t QuviMgr::handle() const { return quvi; } void QuviMgr::curlHandle(CURL **curl) { assert(curl != 0); quvi_getinfo(quvi, QUVII_CURL, curl); } // QuviVideo QuviVideo::QuviVideo() : length (0), pageLink (""), id (""), title (""), link (""), suffix (""), contentType(""), hostId (""), initial (0), filename ("") { } QuviVideo::QuviVideo(const std::string& url) : length (0), pageLink (url), id (""), title (""), link (""), suffix (""), contentType(""), hostId (""), initial (0), filename ("") { } QuviVideo::QuviVideo(const QuviVideo& o) : length (o.length), pageLink (o.pageLink), id (o.id), title (o.title), link (o.link), suffix (o.suffix), contentType(o.contentType), hostId (o.hostId), initial (o.initial), filename (o.filename) { } QuviVideo& QuviVideo::operator=(const QuviVideo& o) { length = o.length; pageLink= o.pageLink; id = o.id; title = o.title; link = o.link; suffix = o.suffix; contentType = o.contentType; hostId = o.hostId; initial = o.initial; filename= o.filename; return *this; } QuviVideo::~QuviVideo() { } void QuviVideo::parse(std::string url /*=""*/) { if (url.empty()) url = pageLink; assert(!url.empty()); const Options opts = optsmgr.getOptions(); if (opts.format_given) { quvi_setopt(quvimgr.handle(), QUVIOPT_FORMAT, opts.format_arg); } CURL *curl = 0; quvimgr.curlHandle(&curl); assert(curl != 0); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, opts.connect_timeout_arg); curl_easy_setopt(curl, CURLOPT_TIMEOUT, opts.connect_timeout_socks_arg); quvi_video_t video; QUVIcode rc = quvi_parse(quvimgr.handle(), const_cast<char*>(url.c_str()), &video); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 0L); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L); if (rc != QUVI_OK) handle_error(rc); quvi_getprop(video, QUVIP_LENGTH, &length); #define _getprop(id,dst) \ do { quvi_getprop(video, id, &s); dst = s; } while (0) char *s; // _getprop uses this. _getprop(QUVIP_PAGELINK, pageLink); _getprop(QUVIP_ID, id); _getprop(QUVIP_TITLE, title); _getprop(QUVIP_LINK, link); _getprop(QUVIP_SUFFIX, suffix); _getprop(QUVIP_CONTENTTYPE, contentType); _getprop(QUVIP_HOSTID, hostId); #undef _getstr quvi_parse_close(&video); formatOutputFilename(); } static int video_num = 0; void QuviVideo::formatOutputFilename() { const Options opts = optsmgr.getOptions(); if (!opts.output_video_given) { std::stringstream b; if (opts.number_videos_given) { b << std::setw(4) << std::setfill('0') << ++video_num << "_"; } customOutputFilenameFormatter(b); filename = b.str(); typedef unsigned int _uint; for (register _uint i=1; i<INT_MAX && !opts.overwrite_given; ++i) { initial = Util::fileExists(filename); if (initial == 0) break; else if (initial >= length) throw NothingToDoException(); else { if (opts.continue_given) break; } std::stringstream tmp; tmp << b.str() << "." << i; filename = tmp.str(); } } else { initial = Util::fileExists(opts.output_video_arg); if (initial >= length) throw NothingToDoException(); if (opts.overwrite_given) initial = 0; filename = opts.output_video_arg; } if (!opts.continue_given) initial = 0; } void QuviVideo::customOutputFilenameFormatter( std::stringstream& b) { const Options opts = optsmgr.getOptions(); std::string fmt = opts.filename_format_arg; std::string _id = this->id; Util::subStrReplace(_id, "-", "_"); std::string _title = title; // Apply --regexp. if (opts.regexp_given) applyTitleRegexp(_title); // Remove leading and trailing whitespace. pcrecpp::RE("^[\\s]+", pcrecpp::UTF8()) .Replace("", &_title); pcrecpp::RE("\\s+$", pcrecpp::UTF8()) .Replace("", &_title); // Replace format specifiers. Util::subStrReplace(fmt, "%t", _title.empty() ? _id : _title); Util::subStrReplace(fmt, "%i", _id); Util::subStrReplace(fmt, "%h", hostId); Util::subStrReplace(fmt, "%s", suffix); b << fmt; } void QuviVideo::applyTitleRegexp(std::string& src) { const Options opts = optsmgr.getOptions(); if (opts.find_all_given) { pcrecpp::StringPiece sp(src); pcrecpp::RE re(opts.regexp_arg, pcrecpp::UTF8()); src.clear(); std::string s; while (re.FindAndConsume(&sp, &s)) src += s; } else { std::string tmp = src; src.clear(); pcrecpp::RE(opts.regexp_arg, pcrecpp::UTF8()) .PartialMatch(tmp, &src); } } const double& QuviVideo::getLength() const { return length; } const std::string& QuviVideo::getPageLink() const { return pageLink; } const std::string& QuviVideo::getId() const { return id; } const std::string& QuviVideo::getTitle() const { return title; } const std::string& QuviVideo::getLink() const { return link; } const std::string& QuviVideo::getSuffix() const { return suffix; } const std::string& QuviVideo::getContentType() const { return contentType; } const std::string& QuviVideo::getHostId() const { return hostId; } const double& QuviVideo::getInitial() const { return initial; } const std::string& QuviVideo::getFilename() const { return filename; } void QuviVideo::updateInitial() { initial = Util::fileExists(filename); if (initial >= length) throw NothingToDoException(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/svg/SVGCursorElement.h" #include "SVGNames.h" #include "XLinkNames.h" #include "core/dom/Document.h" #include "core/svg/SVGElementInstance.h" namespace WebCore { SVGCursorElement::SVGCursorElement(Document& document) : SVGElement(SVGNames::cursorTag, document) , SVGTests(this) , SVGURIReference(this) , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth), AllowNegativeLengths)) , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight), AllowNegativeLengths)) { ScriptWrappable::init(this); addToPropertyMap(m_x); addToPropertyMap(m_y); } SVGCursorElement::~SVGCursorElement() { // The below teardown is all handled by weak pointer processing in oilpan. // FIXME: Oilpan: Replace cursorElementRemoved with weak pointer processing in oilpan. #if !ENABLE(OILPAN) HashSet<RawPtr<SVGElement> >::iterator end = m_clients.end(); for (HashSet<RawPtr<SVGElement> >::iterator it = m_clients.begin(); it != end; ++it) (*it)->cursorElementRemoved(); #endif } bool SVGCursorElement::isSupportedAttribute(const QualifiedName& attrName) { DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ()); if (supportedAttributes.isEmpty()) { SVGTests::addSupportedAttributes(supportedAttributes); SVGURIReference::addSupportedAttributes(supportedAttributes); supportedAttributes.add(SVGNames::xAttr); supportedAttributes.add(SVGNames::yAttr); } return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName); } void SVGCursorElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { SVGParsingError parseError = NoError; if (!isSupportedAttribute(name)) { SVGElement::parseAttribute(name, value); } else if (name == SVGNames::xAttr) { m_x->setBaseValueAsString(value, parseError); } else if (name == SVGNames::yAttr) { m_y->setBaseValueAsString(value, parseError); } else if (SVGURIReference::parseAttribute(name, value, parseError)) { } else if (SVGTests::parseAttribute(name, value)) { } else { ASSERT_NOT_REACHED(); } reportAttributeParsingError(parseError, name, value); } void SVGCursorElement::addClient(SVGElement* element) { m_clients.add(element); element->setCursorElement(this); } #if !ENABLE(OILPAN) void SVGCursorElement::removeClient(SVGElement* element) { HashSet<RawPtr<SVGElement> >::iterator it = m_clients.find(element); if (it != m_clients.end()) { m_clients.remove(it); element->cursorElementRemoved(); } } #endif void SVGCursorElement::removeReferencedElement(SVGElement* element) { m_clients.remove(element); } void SVGCursorElement::svgAttributeChanged(const QualifiedName& attrName) { if (!isSupportedAttribute(attrName)) { SVGElement::svgAttributeChanged(attrName); return; } SVGElement::InvalidationGuard invalidationGuard(this); // Any change of a cursor specific attribute triggers this recalc. WillBeHeapHashSet<RawPtrWillBeWeakMember<SVGElement> >::const_iterator it = m_clients.begin(); WillBeHeapHashSet<RawPtrWillBeWeakMember<SVGElement> >::const_iterator end = m_clients.end(); for (; it != end; ++it) (*it)->setNeedsStyleRecalc(SubtreeStyleChange); } void SVGCursorElement::trace(Visitor* visitor) { visitor->trace(m_clients); SVGElement::trace(visitor); } } <commit_msg>Remove a wrong FIXME comment for SVGCursorElement<commit_after>/* * Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/svg/SVGCursorElement.h" #include "SVGNames.h" #include "XLinkNames.h" #include "core/dom/Document.h" #include "core/svg/SVGElementInstance.h" namespace WebCore { SVGCursorElement::SVGCursorElement(Document& document) : SVGElement(SVGNames::cursorTag, document) , SVGTests(this) , SVGURIReference(this) , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth), AllowNegativeLengths)) , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight), AllowNegativeLengths)) { ScriptWrappable::init(this); addToPropertyMap(m_x); addToPropertyMap(m_y); } SVGCursorElement::~SVGCursorElement() { // The below teardown is all handled by weak pointer processing in oilpan. #if !ENABLE(OILPAN) HashSet<RawPtr<SVGElement> >::iterator end = m_clients.end(); for (HashSet<RawPtr<SVGElement> >::iterator it = m_clients.begin(); it != end; ++it) (*it)->cursorElementRemoved(); #endif } bool SVGCursorElement::isSupportedAttribute(const QualifiedName& attrName) { DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ()); if (supportedAttributes.isEmpty()) { SVGTests::addSupportedAttributes(supportedAttributes); SVGURIReference::addSupportedAttributes(supportedAttributes); supportedAttributes.add(SVGNames::xAttr); supportedAttributes.add(SVGNames::yAttr); } return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName); } void SVGCursorElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { SVGParsingError parseError = NoError; if (!isSupportedAttribute(name)) { SVGElement::parseAttribute(name, value); } else if (name == SVGNames::xAttr) { m_x->setBaseValueAsString(value, parseError); } else if (name == SVGNames::yAttr) { m_y->setBaseValueAsString(value, parseError); } else if (SVGURIReference::parseAttribute(name, value, parseError)) { } else if (SVGTests::parseAttribute(name, value)) { } else { ASSERT_NOT_REACHED(); } reportAttributeParsingError(parseError, name, value); } void SVGCursorElement::addClient(SVGElement* element) { m_clients.add(element); element->setCursorElement(this); } #if !ENABLE(OILPAN) void SVGCursorElement::removeClient(SVGElement* element) { HashSet<RawPtr<SVGElement> >::iterator it = m_clients.find(element); if (it != m_clients.end()) { m_clients.remove(it); element->cursorElementRemoved(); } } #endif void SVGCursorElement::removeReferencedElement(SVGElement* element) { m_clients.remove(element); } void SVGCursorElement::svgAttributeChanged(const QualifiedName& attrName) { if (!isSupportedAttribute(attrName)) { SVGElement::svgAttributeChanged(attrName); return; } SVGElement::InvalidationGuard invalidationGuard(this); // Any change of a cursor specific attribute triggers this recalc. WillBeHeapHashSet<RawPtrWillBeWeakMember<SVGElement> >::const_iterator it = m_clients.begin(); WillBeHeapHashSet<RawPtrWillBeWeakMember<SVGElement> >::const_iterator end = m_clients.end(); for (; it != end; ++it) (*it)->setNeedsStyleRecalc(SubtreeStyleChange); } void SVGCursorElement::trace(Visitor* visitor) { visitor->trace(m_clients); SVGElement::trace(visitor); } } <|endoftext|>
<commit_before>// Copyright (c) 2011-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <sync.h> #include <logging.h> #include <util/strencodings.h> #include <stdio.h> #include <map> #include <memory> #include <set> #ifdef DEBUG_LOCKCONTENTION #if !defined(HAVE_THREAD_LOCAL) static_assert(false, "thread_local is not supported"); #endif void PrintLockContention(const char* pszName, const char* pszFile, int nLine) { LogPrintf("LOCKCONTENTION: %s\n", pszName); LogPrintf("Locker: %s:%d\n", pszFile, nLine); } #endif /* DEBUG_LOCKCONTENTION */ #ifdef DEBUG_LOCKORDER // // Early deadlock detection. // Problem being solved: // Thread 1 locks A, then B, then C // Thread 2 locks D, then C, then A // --> may result in deadlock between the two threads, depending on when they run. // Solution implemented here: // Keep track of pairs of locks: (A before B), (A before C), etc. // Complain if any thread tries to lock in a different order. // struct CLockLocation { CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn) { mutexName = pszName; sourceFile = pszFile; sourceLine = nLine; fTry = fTryIn; } std::string ToString() const { return mutexName + " " + sourceFile + ":" + itostr(sourceLine) + (fTry ? " (TRY)" : ""); } private: bool fTry; std::string mutexName; std::string sourceFile; int sourceLine; }; typedef std::vector<std::pair<void*, CLockLocation> > LockStack; typedef std::map<std::pair<void*, void*>, LockStack> LockOrders; typedef std::set<std::pair<void*, void*> > InvLockOrders; struct LockData { // Very ugly hack: as the global constructs and destructors run single // threaded, we use this boolean to know whether LockData still exists, // as DeleteLock can get called by global CCriticalSection destructors // after LockData disappears. bool available; LockData() : available(true) {} ~LockData() { available = false; } LockOrders lockorders; InvLockOrders invlockorders; std::mutex dd_mutex; }; LockData& GetLockData() { static LockData lockdata; return lockdata; } static thread_local LockStack g_lockstack; static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2) { LogPrintf("POTENTIAL DEADLOCK DETECTED\n"); LogPrintf("Previous lock order was:\n"); for (const std::pair<void*, CLockLocation> & i : s2) { if (i.first == mismatch.first) { LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } LogPrintf("Current lock order is:\n"); for (const std::pair<void*, CLockLocation> & i : s1) { if (i.first == mismatch.first) { LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } if (g_debug_lockorder_abort) { fprintf(stderr, "Assertion failed: detected inconsistent lock order at %s:%i, details in debug log.\n", __FILE__, __LINE__); abort(); } throw std::logic_error("potential deadlock detected"); } static void push_lock(void* c, const CLockLocation& locklocation) { LockData& lockdata = GetLockData(); std::lock_guard<std::mutex> lock(lockdata.dd_mutex); g_lockstack.push_back(std::make_pair(c, locklocation)); for (const std::pair<void*, CLockLocation>& i : g_lockstack) { if (i.first == c) break; std::pair<void*, void*> p1 = std::make_pair(i.first, c); if (lockdata.lockorders.count(p1)) continue; lockdata.lockorders[p1] = g_lockstack; std::pair<void*, void*> p2 = std::make_pair(c, i.first); lockdata.invlockorders.insert(p2); if (lockdata.lockorders.count(p2)) potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]); } } static void pop_lock() { g_lockstack.pop_back(); } void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry) { push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry)); } void LeaveCritical() { pop_lock(); } std::string LocksHeld() { std::string result; for (const std::pair<void*, CLockLocation>& i : g_lockstack) result += i.second.ToString() + std::string("\n"); return result; } void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { for (const std::pair<void*, CLockLocation>& i : g_lockstack) if (i.first == cs) return; fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { for (const std::pair<void*, CLockLocation>& i : g_lockstack) { if (i.first == cs) { fprintf(stderr, "Assertion failed: lock %s held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } } } void DeleteLock(void* cs) { LockData& lockdata = GetLockData(); if (!lockdata.available) { // We're already shutting down. return; } std::lock_guard<std::mutex> lock(lockdata.dd_mutex); std::pair<void*, void*> item = std::make_pair(cs, nullptr); LockOrders::iterator it = lockdata.lockorders.lower_bound(item); while (it != lockdata.lockorders.end() && it->first.first == cs) { std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first); lockdata.invlockorders.erase(invitem); lockdata.lockorders.erase(it++); } InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item); while (invit != lockdata.invlockorders.end() && invit->first == cs) { std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first); lockdata.lockorders.erase(invinvitem); lockdata.invlockorders.erase(invit++); } } bool g_debug_lockorder_abort = true; #endif /* DEBUG_LOCKORDER */ <commit_msg>threads: add thread names to deadlock debugging message<commit_after>// Copyright (c) 2011-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <sync.h> #include <tinyformat.h> #include <logging.h> #include <util/strencodings.h> #include <util/threadnames.h> #include <stdio.h> #include <map> #include <memory> #include <set> #ifdef DEBUG_LOCKCONTENTION #if !defined(HAVE_THREAD_LOCAL) static_assert(false, "thread_local is not supported"); #endif void PrintLockContention(const char* pszName, const char* pszFile, int nLine) { LogPrintf("LOCKCONTENTION: %s\n", pszName); LogPrintf("Locker: %s:%d\n", pszFile, nLine); } #endif /* DEBUG_LOCKCONTENTION */ #ifdef DEBUG_LOCKORDER // // Early deadlock detection. // Problem being solved: // Thread 1 locks A, then B, then C // Thread 2 locks D, then C, then A // --> may result in deadlock between the two threads, depending on when they run. // Solution implemented here: // Keep track of pairs of locks: (A before B), (A before C), etc. // Complain if any thread tries to lock in a different order. // struct CLockLocation { CLockLocation( const char* pszName, const char* pszFile, int nLine, bool fTryIn, const std::string& thread_name) : fTry(fTryIn), mutexName(pszName), sourceFile(pszFile), m_thread_name(thread_name), sourceLine(nLine) {} std::string ToString() const { return tfm::format( "%s %s:%s%s (in thread %s)", mutexName, sourceFile, itostr(sourceLine), (fTry ? " (TRY)" : ""), m_thread_name); } private: bool fTry; std::string mutexName; std::string sourceFile; const std::string& m_thread_name; int sourceLine; }; typedef std::vector<std::pair<void*, CLockLocation> > LockStack; typedef std::map<std::pair<void*, void*>, LockStack> LockOrders; typedef std::set<std::pair<void*, void*> > InvLockOrders; struct LockData { // Very ugly hack: as the global constructs and destructors run single // threaded, we use this boolean to know whether LockData still exists, // as DeleteLock can get called by global CCriticalSection destructors // after LockData disappears. bool available; LockData() : available(true) {} ~LockData() { available = false; } LockOrders lockorders; InvLockOrders invlockorders; std::mutex dd_mutex; }; LockData& GetLockData() { static LockData lockdata; return lockdata; } static thread_local LockStack g_lockstack; static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2) { LogPrintf("POTENTIAL DEADLOCK DETECTED\n"); LogPrintf("Previous lock order was:\n"); for (const std::pair<void*, CLockLocation> & i : s2) { if (i.first == mismatch.first) { LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } LogPrintf("Current lock order is:\n"); for (const std::pair<void*, CLockLocation> & i : s1) { if (i.first == mismatch.first) { LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } if (g_debug_lockorder_abort) { fprintf(stderr, "Assertion failed: detected inconsistent lock order at %s:%i, details in debug log.\n", __FILE__, __LINE__); abort(); } throw std::logic_error("potential deadlock detected"); } static void push_lock(void* c, const CLockLocation& locklocation) { LockData& lockdata = GetLockData(); std::lock_guard<std::mutex> lock(lockdata.dd_mutex); g_lockstack.push_back(std::make_pair(c, locklocation)); for (const std::pair<void*, CLockLocation>& i : g_lockstack) { if (i.first == c) break; std::pair<void*, void*> p1 = std::make_pair(i.first, c); if (lockdata.lockorders.count(p1)) continue; lockdata.lockorders.emplace(p1, g_lockstack); std::pair<void*, void*> p2 = std::make_pair(c, i.first); lockdata.invlockorders.insert(p2); if (lockdata.lockorders.count(p2)) potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]); } } static void pop_lock() { g_lockstack.pop_back(); } void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry) { push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry, util::ThreadGetInternalName())); } void LeaveCritical() { pop_lock(); } std::string LocksHeld() { std::string result; for (const std::pair<void*, CLockLocation>& i : g_lockstack) result += i.second.ToString() + std::string("\n"); return result; } void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { for (const std::pair<void*, CLockLocation>& i : g_lockstack) if (i.first == cs) return; fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { for (const std::pair<void*, CLockLocation>& i : g_lockstack) { if (i.first == cs) { fprintf(stderr, "Assertion failed: lock %s held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } } } void DeleteLock(void* cs) { LockData& lockdata = GetLockData(); if (!lockdata.available) { // We're already shutting down. return; } std::lock_guard<std::mutex> lock(lockdata.dd_mutex); std::pair<void*, void*> item = std::make_pair(cs, nullptr); LockOrders::iterator it = lockdata.lockorders.lower_bound(item); while (it != lockdata.lockorders.end() && it->first.first == cs) { std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first); lockdata.invlockorders.erase(invitem); lockdata.lockorders.erase(it++); } InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item); while (invit != lockdata.invlockorders.end() && invit->first == cs) { std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first); lockdata.lockorders.erase(invinvitem); lockdata.invlockorders.erase(invit++); } } bool g_debug_lockorder_abort = true; #endif /* DEBUG_LOCKORDER */ <|endoftext|>
<commit_before>#include "puzzle.hpp" #include <iostream> #define BOOST_TEST_MODULE SolverTest #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> int testPuzzle(const char *puzzle) { Puzzle::Puzz puzz(puzzle, 10); Puzzle::PuzzleSolver solver(puzz); std::cout << "Solving " << puzzle << std::endl; return solver.print_solutions(std::cout, true); } const char *puzzles[] = { // Donald E. Knuth, The Art of Computer Programming, Vol. 4A, pp. 324--347 "SEND+A+TAD+MORE=MONEY", "COUPLE+COUPLE=QUARTET", "SATURN+URANUS+NEPTUNE+PLUTO=PLANETS", "EARTH+AIR+FIRE+WATER=NATURE", "HIP*HIP=HURRAY", "PI*R*R=AREA", "NORTH/SOUTH=EAST/WEST", "TWENTY=SEVEN+SEVEN+SIX", "TWELVE+NINE+TWO=ELEVEN+SEVEN+FIVE", // ZEITmagazin, 19/2014, S. 44 "JANUAR+FEBRUAR=STAUSEE", "MAERZ+APRIL=MELKEN", "MAI+JUNI+JULI=ALPIN", // ZEITmagazin, 37/2014, S. 95 // Replaced umlauts, because puzzle works only with ASCII. "GABEL+LOFFEL=IRRWEGE", "GABEL+GABEL=ABZUGE", "GABEL+MESSER=DOLLAR" }; const char *special[] = { // nonpure "VIOLIN+VIOLIN+VIOLA=TRIO+SONATA", "TWO*TWO=SQUARE", // special condition: no zero "A/BC+D/EF+G/HI=1", }; BOOST_AUTO_TEST_CASE(solver_test) { for (int i=0; i<(sizeof(puzzles)/sizeof(const char *)); ++i) BOOST_CHECK(testPuzzle(puzzles[i]) == 1); } <commit_msg>Added even more examples from ZEITmagazin<commit_after>#include "puzzle.hpp" #include <iostream> #define BOOST_TEST_MODULE SolverTest #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> int testPuzzle(const char *puzzle) { Puzzle::Puzz puzz(puzzle, 10); Puzzle::PuzzleSolver solver(puzz); std::cout << "Solving " << puzzle << std::endl; return solver.print_solutions(std::cout, true); } const char *puzzles[] = { // Donald E. Knuth, The Art of Computer Programming, Vol. 4A, pp. 324--347 "SEND+A+TAD+MORE=MONEY", "COUPLE+COUPLE=QUARTET", "SATURN+URANUS+NEPTUNE+PLUTO=PLANETS", "EARTH+AIR+FIRE+WATER=NATURE", "HIP*HIP=HURRAY", "PI*R*R=AREA", "NORTH/SOUTH=EAST/WEST", "TWENTY=SEVEN+SEVEN+SIX", "TWELVE+NINE+TWO=ELEVEN+SEVEN+FIVE", // ZEITmagazin, 19/2014, S. 44 "JANUAR+FEBRUAR=STAUSEE", "MAERZ+APRIL=MELKEN", "MAI+JUNI+JULI=ALPIN", // ZEITmagazin, 37/2014, S. 95 // Replaced umlauts, because puzzle works only with ASCII. "GABEL+LOFFEL=IRRWEGE", "GABEL+GABEL=ABZUGE", "GABEL+MESSER=DOLLAR", // ZEITmagazin, 6/2015 "ZAUN+TUERE=MERLIN", "ZAUN+TUERE=ELSTER" }; const char *special[] = { // nonpure "VIOLIN+VIOLIN+VIOLA=TRIO+SONATA", "TWO*TWO=SQUARE", // special condition: no zero "A/BC+D/EF+G/HI=1", }; BOOST_AUTO_TEST_CASE(solver_test) { for (int i=0; i<(sizeof(puzzles)/sizeof(const char *)); ++i) BOOST_CHECK(testPuzzle(puzzles[i]) == 1); } <|endoftext|>
<commit_before>#include<iostream> #include<cassert> #include<thread> #include<chrono> #include "ics3/ics" int main(int argc, char **argv) { { std::cout << std::endl << "ID test section" << std::endl; ics::ID id {0}; assert(id == 0); assert(id.get() == 0); ics::ID id31 {31}; assert(id31 == 31); assert(id31.get() == 31); try { ics::ID id32 {32}; assert(false); } catch (std::invalid_argument& e) { std::cout << e.what() << std::endl; } } { std::cout << std::endl << "EepParam test section" << std::endl; auto speed = ics::EepParam::speed(); assert(127 == speed.get()); speed.set(100); assert(100 == speed.get()); try { speed.set(200); std::cerr << "Never run this" << std::endl; } catch (std::invalid_argument& e) { std::cout << e.what() << std::endl; } } { std::cout << std::endl << "angle test section" << std::endl; auto degree = ics::Angle::newDegree(); auto radian = ics::Angle::newRadian(); assert(degree.getRaw() == radian.getRaw()); degree.set(0); radian.set(0); assert(degree.getRaw() == radian.getRaw()); degree.set(90); radian.set(M_PI / 2); assert(degree.getRaw() == radian.getRaw()); degree.set(60); radian.set(M_PI / 3); assert(degree.getRaw() == radian.getRaw()); try { degree.set(150); std::cerr << "Never run this" << std::endl; } catch (const std::invalid_argument& e) { std::cout << e.what() << std::endl; } try { radian.set(M_PI); std::cerr << "Never run this" << std::endl; } catch (const std::invalid_argument& e) { std::cout << e.what() << std::endl; } } { std::cout << std::endl << "angle factory test section" << std::endl; auto degree = ics::Angle::newDegree(90); auto radian = ics::Angle::newRadian(M_PI / 2); assert(degree.getRaw() == radian.getRaw()); } { std::cout << std::endl << "parameter test section" << std::endl; auto current = ics::Parameter::current(); assert(63 == current.get()); current.set(30); assert(30 == current.get()); try { current.set(70); std::cerr << "Never run this" << std::endl; } catch (const std::invalid_argument& e) { std::cout << e.what() << std::endl; } } { std::cout << std::endl << "ICS3 test section" << std::endl; auto id(2); auto degree = ics::Angle::newDegree(); try { ics::ICS3 ics {"/dev/ttyUSB0"}; assert(7500 == degree.getRaw()); auto nowPos = ics.move(id, degree); std::cout << nowPos.get() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); degree.set(50); nowPos = ics.move(id, degree); std::cout << nowPos.get() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); degree.set(-50); nowPos = ics.move(id, degree); std::cout << nowPos.get() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); degree.set(0); nowPos = ics.move(id, degree); std::cout << nowPos.get() << std::endl; nowPos = ics.free(id); std::cout << nowPos.get() << std::endl; } catch (std::runtime_error& e) { std::cout << e.what() << std::endl; } } return 0; } <commit_msg>Update testcode for constexpr of id<commit_after>#include<iostream> #include<cassert> #include<thread> #include<chrono> #include "ics3/ics" int main(int argc, char **argv) { { std::cout << std::endl << "ID test section" << std::endl; constexpr ics::ID id {0}; assert(id == 0); assert(id.get() == 0); constexpr ics::ID id31 {31}; assert(id31 == 31); assert(id31.get() == 31); try { ics::ID id32 {32}; assert(false); } catch (std::invalid_argument& e) { std::cout << e.what() << std::endl; } } { std::cout << std::endl << "EepParam test section" << std::endl; auto speed = ics::EepParam::speed(); assert(127 == speed.get()); speed.set(100); assert(100 == speed.get()); try { speed.set(200); std::cerr << "Never run this" << std::endl; } catch (std::invalid_argument& e) { std::cout << e.what() << std::endl; } } { std::cout << std::endl << "angle test section" << std::endl; auto degree = ics::Angle::newDegree(); auto radian = ics::Angle::newRadian(); assert(degree.getRaw() == radian.getRaw()); degree.set(0); radian.set(0); assert(degree.getRaw() == radian.getRaw()); degree.set(90); radian.set(M_PI / 2); assert(degree.getRaw() == radian.getRaw()); degree.set(60); radian.set(M_PI / 3); assert(degree.getRaw() == radian.getRaw()); try { degree.set(150); std::cerr << "Never run this" << std::endl; } catch (const std::invalid_argument& e) { std::cout << e.what() << std::endl; } try { radian.set(M_PI); std::cerr << "Never run this" << std::endl; } catch (const std::invalid_argument& e) { std::cout << e.what() << std::endl; } } { std::cout << std::endl << "angle factory test section" << std::endl; auto degree = ics::Angle::newDegree(90); auto radian = ics::Angle::newRadian(M_PI / 2); assert(degree.getRaw() == radian.getRaw()); } { std::cout << std::endl << "parameter test section" << std::endl; auto current = ics::Parameter::current(); assert(63 == current.get()); current.set(30); assert(30 == current.get()); try { current.set(70); std::cerr << "Never run this" << std::endl; } catch (const std::invalid_argument& e) { std::cout << e.what() << std::endl; } } { std::cout << std::endl << "ICS3 test section" << std::endl; auto id(2); auto degree = ics::Angle::newDegree(); try { ics::ICS3 ics {"/dev/ttyUSB0"}; assert(7500 == degree.getRaw()); auto nowPos = ics.move(id, degree); std::cout << nowPos.get() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); degree.set(50); nowPos = ics.move(id, degree); std::cout << nowPos.get() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); degree.set(-50); nowPos = ics.move(id, degree); std::cout << nowPos.get() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); degree.set(0); nowPos = ics.move(id, degree); std::cout << nowPos.get() << std::endl; nowPos = ics.free(id); std::cout << nowPos.get() << std::endl; } catch (std::runtime_error& e) { std::cout << e.what() << std::endl; } } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "core.h" #include "uint256.h" #include <stdint.h> using namespace std; void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) { if (coins.IsPruned()) batch.Erase(make_pair('c', hash)); else batch.Write(make_pair('c', hash), coins); } void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) { batch.Write('B', hash); } CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) { } bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) { return db.Read(make_pair('c', txid), coins); } bool CCoinsViewDB::SetCoins(const uint256 &txid, const CCoins &coins) { CLevelDBBatch batch; BatchWriteCoins(batch, txid, coins); return db.WriteBatch(batch); } bool CCoinsViewDB::HaveCoins(const uint256 &txid) { return db.Exists(make_pair('c', txid)); } uint256 CCoinsViewDB::GetBestBlock() { uint256 hashBestChain; if (!db.Read('B', hashBestChain)) return uint256(0); return hashBestChain; } bool CCoinsViewDB::SetBestBlock(const uint256 &hashBlock) { CLevelDBBatch batch; BatchWriteHashBestChain(batch, hashBlock); return db.WriteBatch(batch); } bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, const uint256 &hashBlock) { LogPrint("coindb", "Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size()); CLevelDBBatch batch; for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++) BatchWriteCoins(batch, it->first, it->second); if (hashBlock != uint256(0)) BatchWriteHashBestChain(batch, hashBlock); return db.WriteBatch(batch); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) { } bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex) { return Write(make_pair('b', blockindex.GetBlockHash()), blockindex); } bool CBlockTreeDB::WriteBestInvalidWork(const CBigNum& bnBestInvalidWork) { // Obsolete; only written for backward compatibility. return Write('I', bnBestInvalidWork); } bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) { return Write(make_pair('f', nFile), info); } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { return Read(make_pair('f', nFile), info); } bool CBlockTreeDB::WriteLastBlockFile(int nFile) { return Write('l', nFile); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write('R', '1'); else return Erase('R'); } bool CBlockTreeDB::ReadReindexing(bool &fReindexing) { fReindexing = Exists('R'); return true; } bool CBlockTreeDB::ReadLastBlockFile(int &nFile) { return Read('l', nFile); } bool CCoinsViewDB::GetStats(CCoinsStats &stats) { leveldb::Iterator *pcursor = db.NewIterator(); pcursor->SeekToFirst(); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = GetBestBlock(); ss << stats.hashBlock; int64_t nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'c') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION); CCoins coins; ssValue >> coins; uint256 txhash; ssKey >> txhash; ss << txhash; ss << VARINT(coins.nVersion); ss << (coins.fCoinBase ? 'c' : 'n'); ss << VARINT(coins.nHeight); stats.nTransactions++; for (unsigned int i=0; i<coins.vout.size(); i++) { const CTxOut &out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i+1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + slValue.size(); ss << VARINT(0); } pcursor->Next(); } catch (std::exception &e) { return error("%s() : deserialize error", __PRETTY_FUNCTION__); } } delete pcursor; stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight; stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) { return Read(make_pair('t', txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) { CLevelDBBatch batch; for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++) batch.Write(make_pair('t', it->first), it->second); return WriteBatch(batch); } bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) { return Write(std::make_pair('F', name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) { char ch; if (!Read(std::make_pair('F', name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::LoadBlockIndexGuts() { leveldb::Iterator *pcursor = NewIterator(); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); ssKeySet << make_pair('b', uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'b') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION); CDiskBlockIndex diskindex; ssValue >> diskindex; // Construct block index object CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; if (!pindexNew->CheckIndex()) return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString().c_str()); pcursor->Next(); } else { break; // if shutdown requested or finished loading block index } } catch (std::exception &e) { return error("%s() : deserialize error", __PRETTY_FUNCTION__); } } delete pcursor; return true; } <commit_msg>extend std::exception logging in txdb.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "core.h" #include "uint256.h" #include <stdint.h> using namespace std; void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) { if (coins.IsPruned()) batch.Erase(make_pair('c', hash)); else batch.Write(make_pair('c', hash), coins); } void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) { batch.Write('B', hash); } CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) { } bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) { return db.Read(make_pair('c', txid), coins); } bool CCoinsViewDB::SetCoins(const uint256 &txid, const CCoins &coins) { CLevelDBBatch batch; BatchWriteCoins(batch, txid, coins); return db.WriteBatch(batch); } bool CCoinsViewDB::HaveCoins(const uint256 &txid) { return db.Exists(make_pair('c', txid)); } uint256 CCoinsViewDB::GetBestBlock() { uint256 hashBestChain; if (!db.Read('B', hashBestChain)) return uint256(0); return hashBestChain; } bool CCoinsViewDB::SetBestBlock(const uint256 &hashBlock) { CLevelDBBatch batch; BatchWriteHashBestChain(batch, hashBlock); return db.WriteBatch(batch); } bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, const uint256 &hashBlock) { LogPrint("coindb", "Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size()); CLevelDBBatch batch; for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++) BatchWriteCoins(batch, it->first, it->second); if (hashBlock != uint256(0)) BatchWriteHashBestChain(batch, hashBlock); return db.WriteBatch(batch); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) { } bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex) { return Write(make_pair('b', blockindex.GetBlockHash()), blockindex); } bool CBlockTreeDB::WriteBestInvalidWork(const CBigNum& bnBestInvalidWork) { // Obsolete; only written for backward compatibility. return Write('I', bnBestInvalidWork); } bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) { return Write(make_pair('f', nFile), info); } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { return Read(make_pair('f', nFile), info); } bool CBlockTreeDB::WriteLastBlockFile(int nFile) { return Write('l', nFile); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write('R', '1'); else return Erase('R'); } bool CBlockTreeDB::ReadReindexing(bool &fReindexing) { fReindexing = Exists('R'); return true; } bool CBlockTreeDB::ReadLastBlockFile(int &nFile) { return Read('l', nFile); } bool CCoinsViewDB::GetStats(CCoinsStats &stats) { leveldb::Iterator *pcursor = db.NewIterator(); pcursor->SeekToFirst(); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = GetBestBlock(); ss << stats.hashBlock; int64_t nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'c') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION); CCoins coins; ssValue >> coins; uint256 txhash; ssKey >> txhash; ss << txhash; ss << VARINT(coins.nVersion); ss << (coins.fCoinBase ? 'c' : 'n'); ss << VARINT(coins.nHeight); stats.nTransactions++; for (unsigned int i=0; i<coins.vout.size(); i++) { const CTxOut &out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i+1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + slValue.size(); ss << VARINT(0); } pcursor->Next(); } catch (std::exception &e) { return error("%s : Deserialize or I/O error - %s", __PRETTY_FUNCTION__, e.what()); } } delete pcursor; stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight; stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) { return Read(make_pair('t', txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) { CLevelDBBatch batch; for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++) batch.Write(make_pair('t', it->first), it->second); return WriteBatch(batch); } bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) { return Write(std::make_pair('F', name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) { char ch; if (!Read(std::make_pair('F', name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::LoadBlockIndexGuts() { leveldb::Iterator *pcursor = NewIterator(); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); ssKeySet << make_pair('b', uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'b') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION); CDiskBlockIndex diskindex; ssValue >> diskindex; // Construct block index object CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; if (!pindexNew->CheckIndex()) return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString().c_str()); pcursor->Next(); } else { break; // if shutdown requested or finished loading block index } } catch (std::exception &e) { return error("%s : Deserialize or I/O error - %s", __PRETTY_FUNCTION__, e.what()); } } delete pcursor; return true; } <|endoftext|>
<commit_before>//----------------------------------------------------------------------- // Copyright 2011 Ciaran McHale. // // 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's //-------- #include <config4cpp/StringBuffer.h> #include "util.h" namespace CONFIG4CPP_NAMESPACE { void splitScopedNameIntoVector(const char * str, StringVector & vec) { int i; int len; char * startOfStr; StringBuffer tmpStr; // Mutable copy of str vec.empty(); tmpStr = str; len = tmpStr.length(); startOfStr = &tmpStr[0]; for (i = 0; i < len; i++) { if (tmpStr[i] == '.') { tmpStr[i] = 0; vec.add(startOfStr); startOfStr = &tmpStr[i+1]; } } vec.add(startOfStr); } } // namespace CONFIG4CPP_NAMESPACE <commit_msg>Fixes.<commit_after>//----------------------------------------------------------------------- // Copyright 2011 Ciaran McHale. // // 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's //-------- #include <config4cpp/StringBuffer.h> #include "util.h" namespace CONFIG4CPP_NAMESPACE { void splitScopedNameIntoVector(const char * str, StringVector & vec) { StringBuffer tmpStr; // Mutable copy of str vec.empty(); tmpStr = str; int len = tmpStr.length(); char* startOfStr = &tmpStr[0]; for (int i = 0; i < len; i++) { if (tmpStr[i] == '.') { tmpStr[i] = 0; vec.add(startOfStr); startOfStr = &tmpStr[i+1]; } } vec.add(startOfStr); } } // namespace CONFIG4CPP_NAMESPACE <|endoftext|>
<commit_before>#include <Rcpp.h> #if defined(_WIN32) // See: http://stackoverflow.com/questions/11588765/using-rcpp-with-windows-specific-includes #undef Realloc #undef Free #include <Windows.h> #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) #include <unistd.h> #include <sys/types.h> #include <sys/param.h> #if defined(BSD) #include <sys/sysctl.h> #endif #endif #include <sys/time.h> #include <stdint.h> #include <stdio.h> #include <time.h> #include <errno.h> #include <fcntl.h> extern "C" { #include "scrypt_platform.h" #include "crypto/crypto_scrypt.h" } #include "util.hpp" #ifdef HAVE_CLOCK_GETTIME static clockid_t clocktouse; static int getclockres(double *resd) { struct timespec res; /* * Try clocks in order of preference until we find one which works. * (We assume that if clock_getres works, clock_gettime will, too.) * The use of if/else/if/else/if/else rather than if/elif/elif/else * is ugly but legal, and allows us to #ifdef things appropriately. */ #ifdef CLOCK_VIRTUAL if (clock_getres(CLOCK_VIRTUAL, &res) == 0) clocktouse = CLOCK_VIRTUAL; else #endif #ifdef CLOCK_MONOTONIC if (clock_getres(CLOCK_MONOTONIC, &res) == 0) clocktouse = CLOCK_MONOTONIC; else #endif if (clock_getres(CLOCK_REALTIME, &res) == 0) clocktouse = CLOCK_REALTIME; else return (-1); /* Convert clock resolution to a double. */ *resd = res.tv_sec + res.tv_nsec * 0.000000001; return (0); } static int getclocktime(struct timespec *ts) { #ifdef DEBUG REprintf("Using clock_gettime()\n"); #endif if (clock_gettime(clocktouse, ts)) return (-1); return (0); } #else static int getclockres(double *resd) { #ifdef DEBUG REprintf("Using gettimeofday()\n"); #endif *resd = 1.0 / CLOCKS_PER_SEC; return (0); } static int getclocktime(struct timespec *ts) { struct timeval tv; if (gettimeofday(&tv, NULL)) return (-1); ts->tv_sec = tv.tv_sec; ts->tv_nsec = tv.tv_usec * 1000; return (0); } #endif static int getclockdiff(struct timespec * st, double * diffd) { struct timespec en; if (getclocktime(&en)) return (1); *diffd = (en.tv_nsec - st->tv_nsec) * 0.000000001 + (en.tv_sec - st->tv_sec); return (0); } /* * Get CPU performance * * This function is derived from Colin Percival's scrypt reference code */ int getcpuperf(double *opps) { struct timespec st; double resd, diffd; uint64_t i = 0; /* Get the clock resolution. */ if (getclockres(&resd)) return (2); #ifdef DEBUG REprintf("Clock resolution is %f\n", resd); #endif /* Loop until the clock ticks. */ if (getclocktime(&st)) return (2); do { /* Do an scrypt. */ if (crypto_scrypt(NULL, 0, NULL, 0, 16, 1, 1, NULL, 0)) return (3); /* Has the clock ticked? */ if (getclockdiff(&st, &diffd)) return (2); if (diffd > 0) break; } while (1); /* Could how many scryps we can do before the next tick. */ if (getclocktime(&st)) return (2); do { /* Do an scrypt. */ if (crypto_scrypt(NULL, 0, NULL, 0, 128, 1, 1, NULL, 0)) return (3); /* We invoked the salsa20/8 core 512 times. */ i += 512; /* Check if we have looped for long enough. */ if (getclockdiff(&st, &diffd)) return (2); if (diffd > resd) break; } while (1); #ifdef DEBUG REprintf("%ju salsa20/8 cores performed in %f seconds\n", (uintmax_t)i, diffd); #endif /* We can do approximately i salsa20/8 cores per diffd seconds. */ *opps = i / diffd; return (0); } /* * Get available memory * * This function is derived from: * http://nadeausoftware.com/articles/2012/09/c_c_tip_how_get_physical_memory_size_system */ int getmemlimit(size_t *memlimit) { #if defined(_WIN32) && (defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__MINGW__) || defined(__MINGW32__) ) /* Cygwin under Windows. ------------------------------------ */ /* New 64-bit MEMORYSTATUSEX isn't available. Use old 32.bit */ MEMORYSTATUS status; status.dwLength = sizeof(status); GlobalMemoryStatus( &status ); *memlimit = (size_t)status.dwTotalPhys; return 0; #elif defined(_WIN32) /* Windows. ------------------------------------------------- */ /* Use new 64-bit MEMORYSTATUSEX, not old 32-bit MEMORYSTATUS */ MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx( &status ); *memlimit = (size_t)status.ullTotalPhys; return 0; #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) /* UNIX variants. ------------------------------------------- */ #if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64)) int mib[2]; mib[0] = CTL_HW; #if defined(HW_MEMSIZE) mib[1] = HW_MEMSIZE; // OSX #elif defined(HW_PHYSMEM64) mib[1] = HW_PHYSMEM64; // NetBSD, OpenBSD #endif int64_t size = 0; // 64-bit size_t len = sizeof( size ); if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) { *memlimit = (size_t)size; return 0; } return -1; // Failure #elif defined(_SC_AIX_REALMEM) /* AIX. ----------------------------------------------------- */ *memlimit = (size_t)sysconf( _SC_AIX_REALMEM ) * (size_t)1024L; return 0; #elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) /* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- */ *memlimit = (size_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGESIZE ); return 0; #elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGE_SIZE) /* Legacy. -------------------------------------------------- */ *memlimit = (size_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGE_SIZE ); return 0; #elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM)) /* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- */ int mib[2]; mib[0] = CTL_HW; #if defined(HW_REALMEM) mib[1] = HW_REALMEM; // FreeBSD #elif defined(HW_PYSMEM) mib[1] = HW_PHYSMEM; // Others #endif unsigned int size = 0; // 32-bit size_t len = sizeof( size ); if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) { *memlimit = (size_t)size; return 0; } return -1; // Failure #endif #else return -2; // Unknown OS #endif } /* * Obtains salt for password hash. * This function is derived from Colin Percival's scrypt reference code */ int getsalt(uint8_t salt[32]) { uint8_t *buf = salt; size_t buflen = 32; #if defined(_WIN32) HCRYPTPROV hCryptCtx; if (CryptAcquireContext(&hCryptCtx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { if (!CryptGenRandom(hCryptCtx, buflen, buf)) goto err; CryptReleaseContext(hCryptCtx, 0); } else { goto err; } /* Success! */ return (0); #else int fd; ssize_t lenread; /* Open /dev/urandom */ if ((fd = open("/dev/urandom", O_RDONLY)) == -1) goto err; /* Read bytes until we have filled the buffer */ while (buflen > 0) { if ((lenread = read(fd, buf, buflen)) == -1) goto close; /* The random device should never EOF */ if (lenread == 0) goto close; /* We're partly done */ buf += lenread; buflen -= lenread; } /* Close the device */ while (close(fd) == -1) { if (errno != EINTR) goto err; } /* Success! */ return (0); close: close(fd); #endif err: /* Failure! */ return (4); } <commit_msg>Prevent UBSAN by explicitly setting the salt<commit_after>#include <Rcpp.h> #if defined(_WIN32) // See: http://stackoverflow.com/questions/11588765/using-rcpp-with-windows-specific-includes #undef Realloc #undef Free #include <Windows.h> #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) #include <unistd.h> #include <sys/types.h> #include <sys/param.h> #if defined(BSD) #include <sys/sysctl.h> #endif #endif #include <sys/time.h> #include <stdint.h> #include <stdio.h> #include <time.h> #include <errno.h> #include <fcntl.h> extern "C" { #include "scrypt_platform.h" #include "crypto/crypto_scrypt.h" } #include "util.hpp" #ifdef HAVE_CLOCK_GETTIME static clockid_t clocktouse; static int getclockres(double *resd) { struct timespec res; /* * Try clocks in order of preference until we find one which works. * (We assume that if clock_getres works, clock_gettime will, too.) * The use of if/else/if/else/if/else rather than if/elif/elif/else * is ugly but legal, and allows us to #ifdef things appropriately. */ #ifdef CLOCK_VIRTUAL if (clock_getres(CLOCK_VIRTUAL, &res) == 0) clocktouse = CLOCK_VIRTUAL; else #endif #ifdef CLOCK_MONOTONIC if (clock_getres(CLOCK_MONOTONIC, &res) == 0) clocktouse = CLOCK_MONOTONIC; else #endif if (clock_getres(CLOCK_REALTIME, &res) == 0) clocktouse = CLOCK_REALTIME; else return (-1); /* Convert clock resolution to a double. */ *resd = res.tv_sec + res.tv_nsec * 0.000000001; return (0); } static int getclocktime(struct timespec *ts) { #ifdef DEBUG REprintf("Using clock_gettime()\n"); #endif if (clock_gettime(clocktouse, ts)) return (-1); return (0); } #else static int getclockres(double *resd) { #ifdef DEBUG REprintf("Using gettimeofday()\n"); #endif *resd = 1.0 / CLOCKS_PER_SEC; return (0); } static int getclocktime(struct timespec *ts) { struct timeval tv; if (gettimeofday(&tv, NULL)) return (-1); ts->tv_sec = tv.tv_sec; ts->tv_nsec = tv.tv_usec * 1000; return (0); } #endif static int getclockdiff(struct timespec * st, double * diffd) { struct timespec en; if (getclocktime(&en)) return (1); *diffd = (en.tv_nsec - st->tv_nsec) * 0.000000001 + (en.tv_sec - st->tv_sec); return (0); } /* * Get CPU performance * * This function is derived from Colin Percival's scrypt reference code */ int getcpuperf(double *opps) { struct timespec st; double resd, diffd; uint64_t i = 0; uint8_t salt[32] = {0}; /* Get the clock resolution. */ if (getclockres(&resd)) return (2); #ifdef DEBUG REprintf("Clock resolution is %f\n", resd); #endif /* Loop until the clock ticks. */ if (getclocktime(&st)) return (2); do { /* Do an scrypt. */ if (crypto_scrypt(NULL, 0, salt, 0, 16, 1, 1, NULL, 0)) return (3); /* Has the clock ticked? */ if (getclockdiff(&st, &diffd)) return (2); if (diffd > 0) break; } while (1); /* Could how many scryps we can do before the next tick. */ if (getclocktime(&st)) return (2); do { /* Do an scrypt. */ if (crypto_scrypt(NULL, 0, salt, 0, 128, 1, 1, NULL, 0)) return (3); /* We invoked the salsa20/8 core 512 times. */ i += 512; /* Check if we have looped for long enough. */ if (getclockdiff(&st, &diffd)) return (2); if (diffd > resd) break; } while (1); #ifdef DEBUG REprintf("%ju salsa20/8 cores performed in %f seconds\n", (uintmax_t)i, diffd); #endif /* We can do approximately i salsa20/8 cores per diffd seconds. */ *opps = i / diffd; return (0); } /* * Get available memory * * This function is derived from: * http://nadeausoftware.com/articles/2012/09/c_c_tip_how_get_physical_memory_size_system */ int getmemlimit(size_t *memlimit) { #if defined(_WIN32) && (defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__MINGW__) || defined(__MINGW32__) ) /* Cygwin under Windows. ------------------------------------ */ /* New 64-bit MEMORYSTATUSEX isn't available. Use old 32.bit */ MEMORYSTATUS status; status.dwLength = sizeof(status); GlobalMemoryStatus( &status ); *memlimit = (size_t)status.dwTotalPhys; return 0; #elif defined(_WIN32) /* Windows. ------------------------------------------------- */ /* Use new 64-bit MEMORYSTATUSEX, not old 32-bit MEMORYSTATUS */ MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx( &status ); *memlimit = (size_t)status.ullTotalPhys; return 0; #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) /* UNIX variants. ------------------------------------------- */ #if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64)) int mib[2]; mib[0] = CTL_HW; #if defined(HW_MEMSIZE) mib[1] = HW_MEMSIZE; // OSX #elif defined(HW_PHYSMEM64) mib[1] = HW_PHYSMEM64; // NetBSD, OpenBSD #endif int64_t size = 0; // 64-bit size_t len = sizeof( size ); if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) { *memlimit = (size_t)size; return 0; } return -1; // Failure #elif defined(_SC_AIX_REALMEM) /* AIX. ----------------------------------------------------- */ *memlimit = (size_t)sysconf( _SC_AIX_REALMEM ) * (size_t)1024L; return 0; #elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) /* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- */ *memlimit = (size_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGESIZE ); return 0; #elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGE_SIZE) /* Legacy. -------------------------------------------------- */ *memlimit = (size_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGE_SIZE ); return 0; #elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM)) /* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- */ int mib[2]; mib[0] = CTL_HW; #if defined(HW_REALMEM) mib[1] = HW_REALMEM; // FreeBSD #elif defined(HW_PYSMEM) mib[1] = HW_PHYSMEM; // Others #endif unsigned int size = 0; // 32-bit size_t len = sizeof( size ); if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) { *memlimit = (size_t)size; return 0; } return -1; // Failure #endif #else return -2; // Unknown OS #endif } /* * Obtains salt for password hash. * This function is derived from Colin Percival's scrypt reference code */ int getsalt(uint8_t salt[32]) { uint8_t *buf = salt; size_t buflen = 32; #if defined(_WIN32) HCRYPTPROV hCryptCtx; if (CryptAcquireContext(&hCryptCtx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { if (!CryptGenRandom(hCryptCtx, buflen, buf)) goto err; CryptReleaseContext(hCryptCtx, 0); } else { goto err; } /* Success! */ return (0); #else int fd; ssize_t lenread; /* Open /dev/urandom */ if ((fd = open("/dev/urandom", O_RDONLY)) == -1) goto err; /* Read bytes until we have filled the buffer */ while (buflen > 0) { if ((lenread = read(fd, buf, buflen)) == -1) goto close; /* The random device should never EOF */ if (lenread == 0) goto close; /* We're partly done */ buf += lenread; buflen -= lenread; } /* Close the device */ while (close(fd) == -1) { if (errno != EINTR) goto err; } /* Success! */ return (0); close: close(fd); #endif err: /* Failure! */ return (4); } <|endoftext|>
<commit_before>/* * v8cgi main file. Loosely based on V8's "shell" sample app. */ #include <v8.h> #include "js_system.h" #include "js_io.h" #include "js_common.h" #include "js_macros.h" #include <sstream> #ifndef windows # include <dlfcn.h> #else # include <windows.h> # define dlopen(x,y) (void*)LoadLibrary(x) # define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y) # define dlclose(x) FreeLibrary((HMODULE)x) #endif #define _STRING(x) #x #define STRING(x) _STRING(x) // chdir() #ifndef HAVE_CHDIR # include <direct.h> # define chdir(name) _chdir(name) #endif // getcwd() #ifndef HAVE_GETCWD # include <direct.h> # define getcwd(name, bytes) _getcwd(name, bytes) #endif v8::Handle<v8::Array> __onexit; void die(int code) { uint32_t max = __onexit->Length(); v8::Handle<v8::Function> fun; for (unsigned int i=0;i<max;i++) { fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i))); fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL); } exit(code); } v8::Handle<v8::String> read_file(const char* name) { FILE* file = fopen(name, "rb"); if (file == NULL) return v8::Handle<v8::String>(); fseek(file, 0, SEEK_END); size_t size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (unsigned int i = 0; i < size;) { size_t read = fread(&chars[i], 1, size - i, file); i += read; } fclose(file); /* remove shebang line */ std::string str = chars; if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) { unsigned int pfix = str.find('\n',0); str.erase(0,pfix); }; v8::Handle<v8::String> result = JS_STR(str.c_str()); delete[] chars; return result; } void report_exception(v8::TryCatch* try_catch) { v8::HandleScope handle_scope; v8::String::Utf8Value exception(try_catch->Exception()); v8::Handle<v8::Message> message = try_catch->Message(); std::string msgstring = ""; std::stringstream ss; std::string tmp; if (message.IsEmpty()) { msgstring += *exception; msgstring += "\n"; } else { v8::String::Utf8Value filename(message->GetScriptResourceName()); int linenum = message->GetLineNumber(); msgstring += *filename; msgstring += ":"; ss << linenum; ss >> tmp; msgstring += tmp; msgstring += ": "; msgstring += *exception; msgstring += "\n"; } int cgi = 0; v8::Local<v8::Function> fun; v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response")); if (context->IsObject()) { v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error")); if (print->IsObject()) { fun = v8::Local<v8::Function>::Cast(print); cgi = 1; } } if (!cgi) { context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System")); fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout"))); } v8::Handle<v8::Value> data[1]; data[0] = JS_STR(msgstring.c_str()); fun->Call(context->ToObject(), 1, data); } int execute_file(const char * str, bool change) { v8::HandleScope handle_scope; v8::TryCatch try_catch; v8::Handle<v8::String> name = JS_STR(str); v8::Handle<v8::String> source = read_file(str); if (source.IsEmpty()) { printf("Error reading '%s'\n", str); return 1; } v8::Handle<v8::Script> script = v8::Script::Compile(source, name); if (script.IsEmpty()) { report_exception(&try_catch); return 1; } else { char * old = getcwd(NULL, 0); char * end = strrchr((char *)str, '/'); if (end == NULL) { end = strrchr((char *)str, '\\'); } if (end != NULL && change) { int len = end-str; char * base = (char *) malloc(len+1); strncpy(base, str, len); base[len] = '\0'; chdir(base); free(base); } v8::Handle<v8::Value> result = script->Run(); chdir(old); if (result.IsEmpty()) { report_exception(&try_catch); return 1; } } return 0; } int library(char * name) { v8::HandleScope handle_scope; v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath")); v8::String::Utf8Value pfx(prefix); std::string path = ""; path += *pfx; path += "/"; path += name; if (path.find(".so") != std::string::npos) { void * handle; if (!(handle = dlopen(path.c_str(), RTLD_LAZY))) { printf("open"); return 1; } void (*func) (v8::Handle<v8::Object>); if (!(func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init")))) { printf("init"); dlclose(handle); return 1; } func(v8::Context::GetCurrent()->Global()); return 0; } else { return execute_file(path.c_str(), false); } } v8::Handle<v8::Value> _include(const v8::Arguments& args) { bool ok = true; int result; for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; v8::String::Utf8Value file(args[i]); result = execute_file(*file, false); if (result != 0) { ok = false; } } return JS_BOOL(ok); } v8::Handle<v8::Value> _library(const v8::Arguments & args) { bool ok = true; int result; v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath")); v8::String::Utf8Value pfx(prefix); for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; v8::String::Utf8Value file(args[i]); result = library(*file); if (result != 0) { ok = false; } } return JS_BOOL(ok); } v8::Handle<v8::Value> _exit(const v8::Arguments& args) { die(args[0]->Int32Value()); return v8::Undefined(); } v8::Handle<v8::Value> _onexit(const v8::Arguments& args) { __onexit->Set(JS_INT(__onexit->Length()), args[0]); return v8::Undefined(); } int library_autoload() { v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload"))); int cnt = list->Length(); for (int i=0;i<cnt;i++) { v8::Handle<v8::Value> item = list->Get(JS_INT(i)); v8::String::Utf8Value name(item); if (library(*name)) { return 1; } } return 0; } void init(char * cfg) { int result = execute_file(cfg, false); if (result) { printf("Cannot load configuration, quitting...\n"); die(1); } result = library_autoload(); if (result) { printf("Cannot load default libraries, quitting...\n"); die(1); } } int main(int argc, char ** argv, char ** envp) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::HandleScope handle_scope; v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); __onexit = v8::Array::New(); context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction()); context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction()); context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction()); context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction()); context->Global()->Set(JS_STR("global"), context->Global()); context->Global()->Set(JS_STR("Config"), v8::Object::New()); setup_system(envp, context->Global()); setup_io(context->Global()); char * cfg = STRING(CONFIG_PATH); int argptr = 0; for (int i = 1; i < argc; i++) { const char* str = argv[i]; argptr = i; if (strcmp(str, "-c") == 0 && i + 1 < argc) { cfg = argv[i+1]; argptr = 0; i++; } } init(cfg); if (!argptr) { // try the PATH_TRANSLATED env var v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System")); v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env")); v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED")); if (pt->IsString()) { v8::String::Utf8Value name(pt); int result = execute_file(*name, true); if (result) { die(result); } } else { printf("Nothing to do.\n"); } } else { int result = execute_file(argv[argptr], true); if (result) { die(result); } } die(0); } <commit_msg>dll<commit_after>/* * v8cgi main file. Loosely based on V8's "shell" sample app. */ #include <v8.h> #include "js_system.h" #include "js_io.h" #include "js_common.h" #include "js_macros.h" #include <sstream> #ifndef windows # include <dlfcn.h> #else # include <windows.h> # define dlopen(x,y) (void*)LoadLibrary(x) # define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y) # define dlclose(x) FreeLibrary((HMODULE)x) #endif #define _STRING(x) #x #define STRING(x) _STRING(x) // chdir() #ifndef HAVE_CHDIR # include <direct.h> # define chdir(name) _chdir(name) #endif // getcwd() #ifndef HAVE_GETCWD # include <direct.h> # define getcwd(name, bytes) _getcwd(name, bytes) #endif v8::Handle<v8::Array> __onexit; void die(int code) { uint32_t max = __onexit->Length(); v8::Handle<v8::Function> fun; for (unsigned int i=0;i<max;i++) { fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i))); fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL); } exit(code); } v8::Handle<v8::String> read_file(const char* name) { FILE* file = fopen(name, "rb"); if (file == NULL) return v8::Handle<v8::String>(); fseek(file, 0, SEEK_END); size_t size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (unsigned int i = 0; i < size;) { size_t read = fread(&chars[i], 1, size - i, file); i += read; } fclose(file); /* remove shebang line */ std::string str = chars; if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) { unsigned int pfix = str.find('\n',0); str.erase(0,pfix); }; v8::Handle<v8::String> result = JS_STR(str.c_str()); delete[] chars; return result; } void report_exception(v8::TryCatch* try_catch) { v8::HandleScope handle_scope; v8::String::Utf8Value exception(try_catch->Exception()); v8::Handle<v8::Message> message = try_catch->Message(); std::string msgstring = ""; std::stringstream ss; std::string tmp; if (message.IsEmpty()) { msgstring += *exception; msgstring += "\n"; } else { v8::String::Utf8Value filename(message->GetScriptResourceName()); int linenum = message->GetLineNumber(); msgstring += *filename; msgstring += ":"; ss << linenum; ss >> tmp; msgstring += tmp; msgstring += ": "; msgstring += *exception; msgstring += "\n"; } int cgi = 0; v8::Local<v8::Function> fun; v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response")); if (context->IsObject()) { v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error")); if (print->IsObject()) { fun = v8::Local<v8::Function>::Cast(print); cgi = 1; } } if (!cgi) { context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System")); fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout"))); } v8::Handle<v8::Value> data[1]; data[0] = JS_STR(msgstring.c_str()); fun->Call(context->ToObject(), 1, data); } int execute_file(const char * str, bool change) { v8::HandleScope handle_scope; v8::TryCatch try_catch; v8::Handle<v8::String> name = JS_STR(str); v8::Handle<v8::String> source = read_file(str); if (source.IsEmpty()) { printf("Error reading '%s'\n", str); return 1; } v8::Handle<v8::Script> script = v8::Script::Compile(source, name); if (script.IsEmpty()) { report_exception(&try_catch); return 1; } else { char * old = getcwd(NULL, 0); char * end = strrchr((char *)str, '/'); if (end == NULL) { end = strrchr((char *)str, '\\'); } if (end != NULL && change) { int len = end-str; char * base = (char *) malloc(len+1); strncpy(base, str, len); base[len] = '\0'; chdir(base); free(base); } v8::Handle<v8::Value> result = script->Run(); chdir(old); if (result.IsEmpty()) { report_exception(&try_catch); return 1; } } return 0; } int library(char * name) { v8::HandleScope handle_scope; v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath")); v8::String::Utf8Value pfx(prefix); std::string path = ""; path += *pfx; path += "/"; path += name; if (path.find(".so") != std::string::npos || path.find(".dll") != std::string::npos) { void * handle; if (!(handle = dlopen(path.c_str(), RTLD_LAZY))) { printf("open"); return 1; } void (*func) (v8::Handle<v8::Object>); if (!(func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init")))) { printf("init"); dlclose(handle); return 1; } func(v8::Context::GetCurrent()->Global()); return 0; } else { return execute_file(path.c_str(), false); } } v8::Handle<v8::Value> _include(const v8::Arguments& args) { bool ok = true; int result; for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; v8::String::Utf8Value file(args[i]); result = execute_file(*file, false); if (result != 0) { ok = false; } } return JS_BOOL(ok); } v8::Handle<v8::Value> _library(const v8::Arguments & args) { bool ok = true; int result; v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath")); v8::String::Utf8Value pfx(prefix); for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; v8::String::Utf8Value file(args[i]); result = library(*file); if (result != 0) { ok = false; } } return JS_BOOL(ok); } v8::Handle<v8::Value> _exit(const v8::Arguments& args) { die(args[0]->Int32Value()); return v8::Undefined(); } v8::Handle<v8::Value> _onexit(const v8::Arguments& args) { __onexit->Set(JS_INT(__onexit->Length()), args[0]); return v8::Undefined(); } int library_autoload() { v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload"))); int cnt = list->Length(); for (int i=0;i<cnt;i++) { v8::Handle<v8::Value> item = list->Get(JS_INT(i)); v8::String::Utf8Value name(item); if (library(*name)) { return 1; } } return 0; } void init(char * cfg) { int result = execute_file(cfg, false); if (result) { printf("Cannot load configuration, quitting...\n"); die(1); } result = library_autoload(); if (result) { printf("Cannot load default libraries, quitting...\n"); die(1); } } int main(int argc, char ** argv, char ** envp) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::HandleScope handle_scope; v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); __onexit = v8::Array::New(); context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction()); context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction()); context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction()); context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction()); context->Global()->Set(JS_STR("global"), context->Global()); context->Global()->Set(JS_STR("Config"), v8::Object::New()); setup_system(envp, context->Global()); setup_io(context->Global()); char * cfg = STRING(CONFIG_PATH); int argptr = 0; for (int i = 1; i < argc; i++) { const char* str = argv[i]; argptr = i; if (strcmp(str, "-c") == 0 && i + 1 < argc) { cfg = argv[i+1]; argptr = 0; i++; } } init(cfg); if (!argptr) { // try the PATH_TRANSLATED env var v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System")); v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env")); v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED")); if (pt->IsString()) { v8::String::Utf8Value name(pt); int result = execute_file(*name, true); if (result) { die(result); } } else { printf("Nothing to do.\n"); } } else { int result = execute_file(argv[argptr], true); if (result) { die(result); } } die(0); } <|endoftext|>
<commit_before>/* * v8cgi main file. Loosely based on V8's "shell" sample app. */ #include <v8.h> #include "js_system.h" #include "js_io.h" #include "js_mysql.h" #include "js_gd.h" #include "js_common.h" #include <sstream> #define _STRING(x) #x #define STRING(x) _STRING(x) // chdir() #ifndef HAVE_CHDIR # include <direct.h> # define chdir(name) _chdir(name) #endif // getcwd() #ifndef HAVE_GETCWD # include <direct.h> # define getcwd(name, bytes) _getcwd(name, bytes) #endif v8::Handle<v8::Array> __onexit; void die(int code) { uint32_t max = __onexit->Length(); v8::Handle<v8::Function> fun; for (unsigned int i=0;i<max;i++) { fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i))); fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL); } exit(code); } v8::Handle<v8::String> read_file(const char* name) { printf("%s",name); FILE* file = fopen(name, "rb"); if (file == NULL) return v8::Handle<v8::String>(); fseek(file, 0, SEEK_END); size_t size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (unsigned int i = 0; i < size;) { size_t read = fread(&chars[i], 1, size - i, file); i += read; } fclose(file); /* remove shebang line */ std::string str = chars; if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) { unsigned int pfix = str.find('\n',0); str.erase(0,pfix); }; v8::Handle<v8::String> result = JS_STR(str.c_str()); delete[] chars; return result; } void report_exception(v8::TryCatch* try_catch) { v8::HandleScope handle_scope; v8::String::Utf8Value exception(try_catch->Exception()); v8::Handle<v8::Message> message = try_catch->Message(); std::string msgstring = ""; std::stringstream ss; std::string tmp; if (message.IsEmpty()) { msgstring += *exception; msgstring += "\n"; } else { v8::String::Utf8Value filename(message->GetScriptResourceName()); int linenum = message->GetLineNumber(); msgstring += *filename; msgstring += ":"; ss << linenum; ss >> tmp; msgstring += tmp; msgstring += ": "; msgstring += *exception; msgstring += "\n"; v8::String::Utf8Value sourceline(message->GetSourceLine()); msgstring += *sourceline; msgstring += "\n"; // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { msgstring += " "; } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { msgstring += "^"; } msgstring += "\n"; } int cgi = 0; v8::Local<v8::Function> fun; v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response")); if (context->IsObject()) { v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error")); if (print->IsObject()) { fun = v8::Local<v8::Function>::Cast(print); cgi = 1; } } if (!cgi) { context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System")); fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout"))); } v8::Handle<v8::Value> data[1]; data[0] = JS_STR(msgstring.c_str()); fun->Call(context->ToObject(), 1, data); } int execute_file(const char * str) { v8::HandleScope handle_scope; v8::TryCatch try_catch; v8::Handle<v8::String> name = JS_STR(str); v8::Handle<v8::String> source = read_file(str); if (source.IsEmpty()) { printf("Error reading '%s'\n", str); return 1; } v8::Handle<v8::Script> script = v8::Script::Compile(source, name); if (script.IsEmpty()) { report_exception(&try_catch); return 1; } else { char * old = getcwd(NULL, 0); char * end = strrchr(str, '/'); if (end == NULL) { end = strrchr(str, '\\'); } if (end != NULL) { int len = end-str; char * base = (char *) malloc(len+1); strncpy(base, str, len); base[len] = '\0'; chdir(base); } v8::Handle<v8::Value> result = script->Run(); chdir(old); if (result.IsEmpty()) { report_exception(&try_catch); return 1; } } return 0; } int library(char * name) { v8::HandleScope handle_scope; v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath")); v8::String::Utf8Value pfx(prefix); std::string path = ""; path += *pfx; path += "/"; path += name; return execute_file(path.c_str()); } v8::Handle<v8::Value> _include(const v8::Arguments& args) { bool ok = true; int result; for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; v8::String::Utf8Value file(args[i]); result = execute_file(*file); if (result != 0) { ok = false; } } return JS_BOOL(ok); } v8::Handle<v8::Value> _library(const v8::Arguments & args) { bool ok = true; int result; v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath")); v8::String::Utf8Value pfx(prefix); for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; v8::String::Utf8Value file(args[i]); result = library(*file); if (result != 0) { ok = false; } } return JS_BOOL(ok); } v8::Handle<v8::Value> _exit(const v8::Arguments& args) { die(args[0]->Int32Value()); return v8::Undefined(); } v8::Handle<v8::Value> _onexit(const v8::Arguments& args) { __onexit->Set(JS_INT(__onexit->Length()), args[0]); return v8::Undefined(); } int library_autoload() { v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload"))); int cnt = list->Length(); for (int i=0;i<cnt;i++) { v8::Handle<v8::Value> item = list->Get(JS_INT(i)); v8::String::Utf8Value name(item); if (library(*name)) { return 1; } } return 0; } void init(char * cfg) { int result = execute_file(cfg); if (result) { printf("Cannot load configuration, quitting...\n"); die(1); } result = library_autoload(); if (result) { printf("Cannot load default libraries, quitting...\n"); die(1); } } int main(int argc, char ** argv, char ** envp) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::HandleScope handle_scope; v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); __onexit = v8::Array::New(); context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction()); context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction()); context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction()); context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction()); context->Global()->Set(JS_STR("global"), context->Global()); context->Global()->Set(JS_STR("Config"), v8::Object::New()); setup_system(envp, context->Global()); setup_io(context->Global()); #ifdef HAVE_MYSQL setup_mysql(context->Global()); #endif #ifdef HAVE_GD setup_gd(context->Global()); #endif char * cfg = STRING(CONFIG_PATH); int argptr = 0; for (int i = 1; i < argc; i++) { const char* str = argv[i]; argptr = i; if (strcmp(str, "-c") == 0 && i + 1 < argc) { cfg = argv[i+1]; argptr = 0; i++; } } init(cfg); if (!argptr) { // try the PATH_TRANSLATED env var v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System")); v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env")); v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED")); if (pt->IsString()) { v8::String::Utf8Value name(pt); int result = execute_file(*name); if (result) { die(result); } } else { printf("Nothing to do.\n"); } } else { int result = execute_file(argv[argptr]); if (result) { die(result); } } die(0); } <commit_msg>chdir, getcwd for msve<commit_after>/* * v8cgi main file. Loosely based on V8's "shell" sample app. */ #include <v8.h> #include "js_system.h" #include "js_io.h" #include "js_mysql.h" #include "js_gd.h" #include "js_common.h" #include <sstream> #define _STRING(x) #x #define STRING(x) _STRING(x) // chdir() #ifndef HAVE_CHDIR # include <direct.h> # define chdir(name) _chdir(name) #endif // getcwd() #ifndef HAVE_GETCWD # include <direct.h> # define getcwd(name, bytes) _getcwd(name, bytes) #endif v8::Handle<v8::Array> __onexit; void die(int code) { uint32_t max = __onexit->Length(); v8::Handle<v8::Function> fun; for (unsigned int i=0;i<max;i++) { fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i))); fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL); } exit(code); } v8::Handle<v8::String> read_file(const char* name) { printf("%s",name); FILE* file = fopen(name, "rb"); if (file == NULL) return v8::Handle<v8::String>(); fseek(file, 0, SEEK_END); size_t size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (unsigned int i = 0; i < size;) { size_t read = fread(&chars[i], 1, size - i, file); i += read; } fclose(file); /* remove shebang line */ std::string str = chars; if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) { unsigned int pfix = str.find('\n',0); str.erase(0,pfix); }; v8::Handle<v8::String> result = JS_STR(str.c_str()); delete[] chars; return result; } void report_exception(v8::TryCatch* try_catch) { v8::HandleScope handle_scope; v8::String::Utf8Value exception(try_catch->Exception()); v8::Handle<v8::Message> message = try_catch->Message(); std::string msgstring = ""; std::stringstream ss; std::string tmp; if (message.IsEmpty()) { msgstring += *exception; msgstring += "\n"; } else { v8::String::Utf8Value filename(message->GetScriptResourceName()); int linenum = message->GetLineNumber(); msgstring += *filename; msgstring += ":"; ss << linenum; ss >> tmp; msgstring += tmp; msgstring += ": "; msgstring += *exception; msgstring += "\n"; v8::String::Utf8Value sourceline(message->GetSourceLine()); msgstring += *sourceline; msgstring += "\n"; // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { msgstring += " "; } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { msgstring += "^"; } msgstring += "\n"; } int cgi = 0; v8::Local<v8::Function> fun; v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response")); if (context->IsObject()) { v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error")); if (print->IsObject()) { fun = v8::Local<v8::Function>::Cast(print); cgi = 1; } } if (!cgi) { context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System")); fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout"))); } v8::Handle<v8::Value> data[1]; data[0] = JS_STR(msgstring.c_str()); fun->Call(context->ToObject(), 1, data); } int execute_file(const char * str) { v8::HandleScope handle_scope; v8::TryCatch try_catch; v8::Handle<v8::String> name = JS_STR(str); v8::Handle<v8::String> source = read_file(str); if (source.IsEmpty()) { printf("Error reading '%s'\n", str); return 1; } v8::Handle<v8::Script> script = v8::Script::Compile(source, name); if (script.IsEmpty()) { report_exception(&try_catch); return 1; } else { char * old = getcwd(NULL, 0); char * end = strrchr((char *)str, '/'); if (end == NULL) { end = strrchr((char *)str, '\\'); } if (end != NULL) { int len = end-str; char * base = (char *) malloc(len+1); strncpy(base, str, len); base[len] = '\0'; chdir(base); } v8::Handle<v8::Value> result = script->Run(); chdir(old); if (result.IsEmpty()) { report_exception(&try_catch); return 1; } } return 0; } int library(char * name) { v8::HandleScope handle_scope; v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath")); v8::String::Utf8Value pfx(prefix); std::string path = ""; path += *pfx; path += "/"; path += name; return execute_file(path.c_str()); } v8::Handle<v8::Value> _include(const v8::Arguments& args) { bool ok = true; int result; for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; v8::String::Utf8Value file(args[i]); result = execute_file(*file); if (result != 0) { ok = false; } } return JS_BOOL(ok); } v8::Handle<v8::Value> _library(const v8::Arguments & args) { bool ok = true; int result; v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath")); v8::String::Utf8Value pfx(prefix); for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope; v8::String::Utf8Value file(args[i]); result = library(*file); if (result != 0) { ok = false; } } return JS_BOOL(ok); } v8::Handle<v8::Value> _exit(const v8::Arguments& args) { die(args[0]->Int32Value()); return v8::Undefined(); } v8::Handle<v8::Value> _onexit(const v8::Arguments& args) { __onexit->Set(JS_INT(__onexit->Length()), args[0]); return v8::Undefined(); } int library_autoload() { v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config")); v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload"))); int cnt = list->Length(); for (int i=0;i<cnt;i++) { v8::Handle<v8::Value> item = list->Get(JS_INT(i)); v8::String::Utf8Value name(item); if (library(*name)) { return 1; } } return 0; } void init(char * cfg) { int result = execute_file(cfg); if (result) { printf("Cannot load configuration, quitting...\n"); die(1); } result = library_autoload(); if (result) { printf("Cannot load default libraries, quitting...\n"); die(1); } } int main(int argc, char ** argv, char ** envp) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::HandleScope handle_scope; v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); __onexit = v8::Array::New(); context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction()); context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction()); context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction()); context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction()); context->Global()->Set(JS_STR("global"), context->Global()); context->Global()->Set(JS_STR("Config"), v8::Object::New()); setup_system(envp, context->Global()); setup_io(context->Global()); #ifdef HAVE_MYSQL setup_mysql(context->Global()); #endif #ifdef HAVE_GD setup_gd(context->Global()); #endif char * cfg = STRING(CONFIG_PATH); int argptr = 0; for (int i = 1; i < argc; i++) { const char* str = argv[i]; argptr = i; if (strcmp(str, "-c") == 0 && i + 1 < argc) { cfg = argv[i+1]; argptr = 0; i++; } } init(cfg); if (!argptr) { // try the PATH_TRANSLATED env var v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System")); v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env")); v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED")); if (pt->IsString()) { v8::String::Utf8Value name(pt); int result = execute_file(*name); if (result) { die(result); } } else { printf("Nothing to do.\n"); } } else { int result = execute_file(argv[argptr]); if (result) { die(result); } } die(0); } <|endoftext|>
<commit_before>#include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace cv; using namespace std; const auto RED = cv::Scalar(0,0,255); const auto PINK = cv::Scalar(230,130,255); const auto BLUE = cv::Scalar(255,0,0); const auto LIGHTBLUE = cv::Scalar(255,255,160); const auto GREEN = cv::Scalar(0,255,0); const auto IMAGE_SCALE = .25; class MyData { public: const cv::Mat original_image; cv::Mat image; MyData( cv::Mat _image ) : original_image(_image) { original_image.copyTo(image); } void reset() { original_image.copyTo(image); }; void update(auto _newImage) { _newImage.copyTo(image); }; }; class MyWindow { protected: const string winName; MyData d; public: /* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; */ MyWindow( const string& _winName, const cv::Mat& _image ): winName( _winName ), d( _image ) { cv::namedWindow( winName, WINDOW_AUTOSIZE ); } virtual ~MyWindow(); void showImage(); void reset(); }; MyWindow::~MyWindow() { cv::destroyWindow( winName ); } void MyWindow::reset() { d.reset(); showImage(); } void MyWindow::showImage() { cv::imshow( winName, d.image ); } class MyOperationWindow : public MyWindow { protected: /* virtual void setControls(){}; */ virtual string getDescription() {} public: MyOperationWindow( auto _winName, auto _image) : MyWindow( _winName, _image ) {} void apply( MyData& _d, std::vector<string>& _process_pile ) { _d.update(d.image); _process_pile.push_back(getDescription()); } }; class MyThreshold : public MyOperationWindow { enum ThresholdType : int {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED, THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED }; int th; ThresholdType threshold_type; public: MyThreshold( auto _winName, auto _image) : MyOperationWindow( _winName, _image ), th(125), threshold_type(BINARY_INVERTED) { _initWindow(); } MyThreshold( auto _winName, auto _image, auto _th ) : MyOperationWindow( _winName, _image ), th(_th), threshold_type(BINARY) { _initWindow(); } static void thresholdCallback( int _th, void* ptr); private: string getDescription() override; void setControls(); // void thresholdImage(); void _initWindow(); static void _typeWorkaround( int _type, void* ptr); }; void MyThreshold::_initWindow() { setControls(); thresholdImage(); showImage(); } void MyThreshold::_typeWorkaround( int _type, void* ptr) { MyThreshold* that = (MyThreshold*) (ptr); switch (_type) { case 0: that->threshold_type = BINARY; break; case 1: that->threshold_type = BINARY_INVERTED; break; case 2: that->threshold_type = THRESHOLD_TRUNCATED; break; case 3: that->threshold_type = THRESHOLD_TO_ZERO; break; case 4: that->threshold_type = THRESHOLD_TO_ZERO_INVERTED; break; default: that->threshold_type = BINARY; } that->thresholdImage(); that->showImage(); } void MyThreshold::setControls() { const std::string val_bar = winName + "_thValueBar"; const std::string type_bar = winName + "_thTypeBar"; int puta = BINARY; cv::createTrackbar( type_bar, winName, &puta, 5, MyThreshold::_typeWorkaround,this); cv::createTrackbar( val_bar, winName, &th, 255, MyThreshold::thresholdCallback,this); } void MyThreshold::thresholdCallback( int _th, void* ptr) { MyThreshold* that = (MyThreshold*) (ptr); // that->th = _th; /// there's no need for this assignation since the trackbar was initialized with a reference to th that->thresholdImage(); that->showImage(); } string MyThreshold::getDescription() { return "th " + std::to_string(th); } void MyThreshold::thresholdImage() { int const max_BINARY_value = 255; threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type ); } class MyApp : public MyWindow { vector<string> process; // std::unique_ptr<MyOperationWindow> current_operation; MyOperationWindow* current_operation; public: MyApp(const std::string& _winName, const cv::Mat& _image); char option(char _option); ~MyApp(); }; MyApp::~MyApp() { if (current_operation != nullptr) delete(current_operation); //cv::destroyWindow( winName ); } MyApp::MyApp(const string &_winName, const Mat &_image) : MyWindow( _winName, _image ), current_operation(nullptr) { showImage(); } char MyApp::option( char _option ) { switch(_option) { case 't': case 'd': /// create the threshold window if (current_operation == nullptr) current_operation = new MyThreshold("theshold", d.image); break; case 'R': case 's': /// reset the whole application reset(); case 'r': case 'f': /// reset the threshold window if (current_operation != nullptr) current_operation->reset(); break; case 'L': case 'a': /// print the processes applied to the image until now for (const auto& p : process) std::cout << p << std::endl; break; case 'g': if (current_operation != nullptr) { current_operation->apply(d, process); delete(current_operation); } break; case 'h': if (current_operation != nullptr) delete(current_operation); break; } showImage(); return _option; } const char* keys = { "{help h||}{@image|../../testdata/A/A05_38.bmp|input image file}" }; static void help(); int main( int argc, const char** argv ) { cv::CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } std::string inputImage = parser.get<string>(0); // Load the source image. HighGUI use. cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE ); if(image.empty()) { std::cerr << "Cannot read image file: " << inputImage << std::endl; return -1; } // TODO: check size and reduce it only if needed cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE); help(); /// Create the GUI std::string winName = "main window"; MyApp appHandle = MyApp(winName, image); appHandle.option('t'); /// Loop until the user kills the program const auto ESC_KEY = '\x1b'; while ( appHandle.option((char) waitKey(0)) != ESC_KEY ) { /* until ESC */ } std::cout << "Exit" << std::endl; return 0; } static void help() { cout << "L (or a) - list image transformations\n" << "R (or s) - restore original image\n" << "t (or d) - activate threshold window\n" << "r (or f) - reset the operation window\n" << "(enter) (or g) - accept changes and kill the operation window\n" << "(backspace) (or h)- ignore changes and kill the operation window\n" << endl; } <commit_msg>Check technological depth<commit_after>#include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace cv; using namespace std; const auto RED = cv::Scalar(0,0,255); const auto PINK = cv::Scalar(230,130,255); const auto BLUE = cv::Scalar(255,0,0); const auto LIGHTBLUE = cv::Scalar(255,255,160); const auto GREEN = cv::Scalar(0,255,0); const auto IMAGE_SCALE = .25; class MyData { public: const cv::Mat original_image; cv::Mat image; MyData( cv::Mat _image ) : original_image(_image) { original_image.copyTo(image); } void reset() { original_image.copyTo(image); }; void update(auto _newImage) { _newImage.copyTo(image); }; }; class MyWindow { protected: const string winName; MyData d; public: /* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; */ MyWindow( const string& _winName, const cv::Mat& _image ): winName( _winName ), d( _image ) { cv::namedWindow( winName, WINDOW_AUTOSIZE ); } virtual ~MyWindow(); void showImage(); void reset(); }; MyWindow::~MyWindow() { cv::destroyWindow( winName ); } void MyWindow::reset() { d.reset(); showImage(); } void MyWindow::showImage() { cv::imshow( winName, d.image ); } class MyOperationWindow : public MyWindow { protected: /* virtual void setControls(){}; */ virtual string getDescription() {} public: MyOperationWindow( auto _winName, auto _image) : MyWindow( _winName, _image ) {} void apply( MyData& _d, std::vector<string>& _process_pile ) { _d.update(d.image); _process_pile.push_back(getDescription()); } }; class MyThreshold : public MyOperationWindow { enum ThresholdType : int {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED, THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED }; int th; ThresholdType threshold_type; public: MyThreshold( auto _winName, auto _image) : MyOperationWindow( _winName, _image ), th(125), threshold_type(BINARY_INVERTED) { _initWindow(); } MyThreshold( auto _winName, auto _image, auto _th ) : MyOperationWindow( _winName, _image ), th(_th), threshold_type(BINARY) { _initWindow(); } static void thresholdCallback( int _th, void* ptr); private: string getDescription() override; void setControls(); // void thresholdImage(); void _initWindow(); static void _typeWorkaround( int _type, void* ptr); }; void MyThreshold::_initWindow() { setControls(); thresholdImage(); showImage(); } void MyThreshold::_typeWorkaround( int _type, void* ptr) { MyThreshold* that = (MyThreshold*) (ptr); switch (_type) { case 0: that->threshold_type = BINARY; break; case 1: that->threshold_type = BINARY_INVERTED; break; case 2: that->threshold_type = THRESHOLD_TRUNCATED; break; case 3: that->threshold_type = THRESHOLD_TO_ZERO; break; case 4: that->threshold_type = THRESHOLD_TO_ZERO_INVERTED; break; default: that->threshold_type = BINARY; } that->thresholdImage(); that->showImage(); } void MyThreshold::setControls() { const std::string val_bar = winName + "_thValueBar"; const std::string type_bar = winName + "_thTypeBar"; int puta = BINARY; cv::createTrackbar( type_bar, winName, &puta, 5, MyThreshold::_typeWorkaround,this); cv::createTrackbar( val_bar, winName, &th, 255, MyThreshold::thresholdCallback,this); } void MyThreshold::thresholdCallback( int _th, void* ptr) { MyThreshold* that = (MyThreshold*) (ptr); // that->th = _th; /// there's no need for this assignation since the trackbar was initialized with a reference to th that->thresholdImage(); that->showImage(); } string MyThreshold::getDescription() { return "threshold, type: " + std::to_string(threshold_type) + ", val: " + std::to_string(th); } void MyThreshold::thresholdImage() { int const max_BINARY_value = 255; threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type ); } class MyMorphology : public MyOperationWindow { enum OperationType { OPENING=2, CLOSING, GRADIENT, TOP_HAT, BLACK_HAT }; // morphology operation codes are 2-6 enum ElementType { RECTANGLE, CROSS, ELIPSE}; OperationType operation; ElementType element; int morph_size; public: MyMorphology( auto _winName, auto _image) : MyOperationWindow( _winName, _image ), operation(OPENING), element(RECTANGLE), morph_size(5) { _initWindow(); } static void morphologyCallback( int _th, void* ptr); private: string getDescription() override; void setControls(); void morphImage(); void _initWindow(); static void _elementWorkaround( int _elem, void* ptr); static void _operationWorkaround( int _op, void* ptr); }; string MyMorphology::getDescription() { return "morph, op:" + std::to_string(operation) + ", " + "elem: " + std::to_string(element) + ", " + "size: " + std::to_string(morph_size); } class MyApp : public MyWindow { vector<string> process; // std::unique_ptr<MyOperationWindow> current_operation; MyOperationWindow* current_operation; public: MyApp(const std::string& _winName, const cv::Mat& _image); char option(char _option); ~MyApp(); }; MyApp::~MyApp() { if (current_operation != nullptr) delete(current_operation); //cv::destroyWindow( winName ); } MyApp::MyApp(const string &_winName, const Mat &_image) : MyWindow( _winName, _image ), current_operation(nullptr) { showImage(); } char MyApp::option( char _option ) { switch(_option) { case 't': case 'd': /// create the threshold window if (current_operation == nullptr) current_operation = new MyThreshold("theshold", d.image); else cout << "there's already an operation being done" << endl; break; case 'm': /// create the morpholy window if (current_operation == nullptr) current_operation = new MyMorphology("morphology", d.image); else cout << "there's already an operation being done" << endl; break; case 'R': case 's': /// reset the whole application reset(); case 'r': case 'f': /// reset the operation window if (current_operation != nullptr) current_operation->reset(); break; case 'L': case 'a': /// print the processes applied to the image until now for (const auto& p : process) std::cout << p << std::endl; break; case 'g': if (current_operation != nullptr) { current_operation->apply(d, process); delete(current_operation); } break; case 'h': if (current_operation != nullptr) delete(current_operation); break; } showImage(); return _option; } //void preprocessImage(cv::Mat& image)// const Mat& _inImage, Mat& _outImage ) //// TODO: add image->copy(out) //{ // const string bkgPath = "../../testdata/A/background.bmp"; // Mat background = imread( bkgPath, CV_LOAD_IMAGE_GRAYSCALE ); // if(background.empty()) // { // std::cerr << "Cannot read image file: " << bkgPath << std::endl; // } // cv::resize(background, background, cv::Size(), IMAGE_SCALE, IMAGE_SCALE); // /* _inImage.copyTo( _outImage ); */ // /* _outImage -= background; */ // /* cv::absdiff(background, _outImage, _outImage); */ // cv::absdiff(background, image, image); //} void MyMorphology::morphImage() { /// The morph_size is considered to be the length between the center of the structural element and its border /// morph_size = (structural_element size / 2) - 1 const auto size = cv::Size( 2*morph_size + 1, 2*morph_size+1 ); const auto p = Point (morph_size, morph_size); cv::Mat structure_element = getStructuringElement(element, size, p ); cv::Mat _midleImage; morphologyEx( d.original_image, _midleImage, operation, structure_element ); d.update(_midleImage); } void MyMorphology::_initWindow() { setControls(); morphImage(); showImage(); } void MyMorphology::_operationWorkaround( int _op, void* ptr) { MyMorphology* that = (MyMorphology*) (ptr); switch (_op) { case 0: that->operation = OPENING; break; case 1: that->operation = CLOSING; break; case 2: that->operation = GRADIENT; break; case 3: that->operation = TOP_HAT; break; case 4: that->operation = BLACK_HAT; break; default: that->operation = OPENING; } that->morphImage(); that->showImage(); } void MyMorphology::_elementWorkaround( int _elem, void* ptr) { MyMorphology* that = (MyMorphology*) (ptr); switch (_elem) { case 0: that->element = RECTANGLE; break; case 1: that->element = CROSS; break; case 2: that->element = ELIPSE; break; default: that->element = RECTANGLE; } that->morphImage(); that->showImage(); } void MyMorphology::setControls() { const std::string operation_bar = winName + "_morphOperationBar"; const std::string element_bar = winName + "_thElementBar"; const std::string size_bar = winName + "_thSizeBar"; int op; int elem; const int max_size = 30; cv::createTrackbar( operation_bar, winName, &op, 5, MyMorphology::_operationWorkaround,this); cv::createTrackbar( element_bar, winName, &elem, 3, MyMorphology::_elementWorkaround,this); cv::createTrackbar( size_bar, winName, &morph_size, max_size, MyMorphology::morphologyCallback,this); } void MyMorphology::morphologyCallback( int _th, void* ptr) { MyMorphology* that = (MyMorphology*) (ptr); that->morphImage(); that->showImage(); } const char* keys = { "{help h||}{@image|../../testdata/A/A05_38.bmp|input image file}" }; static void help(); int main( int argc, const char** argv ) { cv::CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } std::string inputImage = parser.get<string>(0); // Load the source image. HighGUI use. cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE ); if(image.empty()) { std::cerr << "Cannot read image file: " << inputImage << std::endl; return -1; } // TODO: check size and reduce it only if needed cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE); help(); /// Create the GUI std::string winName = "main window"; MyApp appHandle = MyApp(winName, image); appHandle.option('m'); /// Loop until the user kills the program const auto ESC_KEY = '\x1b'; while ( appHandle.option((char) waitKey(0)) != ESC_KEY ) { /* until ESC */ } std::cout << "Exit" << std::endl; return 0; } static void help() { cout << "L (or a) - list image transformations\n" << "R (or s) - restore original image\n" << "t (or d) - activate threshold window\n" << "m - activate morphology window\n" << "r (or f) - reset the operation window\n" << "(enter) (or g) - accept changes and kill the operation window\n" << "(backspace) (or h)- ignore changes and kill the operation window\n" << endl; } <|endoftext|>
<commit_before>// Measurements // Source: ./examples/measurements2.cpp #include <iostream> #include <tuple> #include <vector> #include "qpp.h" int main() { using namespace qpp; ket psi = st.b00; std::vector<idx> subsys = {0}; idx result; std::vector<double> probs; std::vector<cmat> states; // measures the first subsystem of the Bell state (|00> + |11>) / sqrt(2) // in the X basis std::tie(result, probs, states) = measure(psi, gt.H, {0}); std::cout << ">> Measuring part " << disp(subsys, " ") << " of the state:\n"; std::cout << disp(psi) << '\n'; std::cout << ">> Measurement result: " << result << '\n'; std::cout << ">> Probabilities: " << disp(probs, ", ") << '\n'; std::cout << ">> Resulting normalized post-measurement states:\n"; for (auto&& it : states) std::cout << disp(it) << "\n\n"; // measure 2 subsystems out of a 4-qubit random density matrix cmat rho = randrho(16); subsys = {1, 2}; cmat U = randU(4); // random basis on 2 qubits std::cout << ">> Measuring qubits " << disp(subsys, " ") << " of a 4-qubit random state in the random basis:\n"; std::cout << disp(U) << '\n'; std::tie(result, probs, states) = measure(rho, U, {1, 2}); std::cout << ">> Measurement result: " << result << '\n'; std::cout << ">> Probabilities: " << disp(probs, ", ") << '\n'; std::cout << ">> Sum of the probabilities: " << sum(probs.begin(), probs.end()) << '\n'; std::cout << ">> Resulting normalized post-measurement states:\n"; for (auto&& it : states) std::cout << disp(it) << "\n\n"; // check now how the state after the measurement "looks" // on the left over subsystems {0, 3} // it should be the same as the partial trace over {1, 2} // of the initial state (before the measurement), as local CPTP maps // do not influence the complementary subsystems cmat rho_bar = ptrace(rho, subsys); cmat rho_out_bar = cmat::Zero(4, 4); // compute the resulting mixed state after the measurement for (idx i = 0; i < probs.size(); ++i) rho_out_bar += probs[i] * states[i]; // verification std::cout << ">> Norm difference: " << norm(rho_bar - rho_out_bar) << '\n'; // random Kraus std::cout << ">> Random channel on part of the state\n"; rho_bar = ptrace(rho, {1, 3}); rho_out_bar = ptrace(apply(rho, randkraus(3, 4), {1, 3}), {1, 3}); // verification std::cout << ">> Norm difference: " << norm(rho_bar - rho_out_bar) << '\n'; std::cout << ">> Sequential measurements on the state/density matrix:\n"; psi = 0.8 * 01_ket + 0.6 * 10_ket; rho = psi * adjoint(psi); std::cout << disp(psi) << '\n'; std::vector<idx> subsys_ket{0}; std::vector<idx> subsys_rho{1}; auto measured_ket = measure_seq(psi, subsys_ket); auto measured_rho = measure_seq(rho, subsys_rho); // ket std::cout << ">> Ket, measuring subsystem(s) "; std::cout << disp(subsys_ket, " ") << '\n'; std::cout << ">> Outcome(s): " << disp(std::get<RES>(measured_ket), " ") << '\n'; std::cout << ">> Probability: " << std::get<PROB>(measured_ket) << '\n'; std::cout << ">> Resulting state:\n"; std::cout << disp(std::get<ST>(measured_ket)) << '\n'; // density matrix std::cout << ">> Density matrix, measuring subsystem(s) "; std::cout << disp(subsys_rho, " ") << '\n'; std::cout << ">> Outcome(s): " << disp(std::get<RES>(measured_rho), " ") << '\n'; std::cout << ">> Probability: " << std::get<PROB>(measured_rho) << '\n'; std::cout << ">> Resulting state:\n"; std::cout << disp(std::get<ST>(measured_rho)) << '\n'; } <commit_msg>Update measurements2.cpp<commit_after>// Measurements // Source: ./examples/measurements2.cpp #include <iostream> #include <tuple> #include <vector> #include "qpp.h" int main() { using namespace qpp; ket psi = st.b00; std::vector<idx> subsys = {0}; idx result; std::vector<double> probs; std::vector<ket> states; // measures the first subsystem of the Bell state (|00> + |11>) / sqrt(2) // in the X basis std::tie(result, probs, states) = measure(psi, gt.H, {0}); std::cout << ">> Measuring part " << disp(subsys, " ") << " of the state:\n"; std::cout << disp(psi) << '\n'; std::cout << ">> Measurement result: " << result << '\n'; std::cout << ">> Probabilities: " << disp(probs, ", ") << '\n'; std::cout << ">> Resulting normalized post-measurement states:\n"; for (auto&& it : states) std::cout << disp(it) << "\n\n"; // measure 2 subsystems out of a 4-qubit random density matrix cmat rho = randrho(16); subsys = {1, 2}; cmat U = randU(4); // random basis on 2 qubits std::cout << ">> Measuring qubits " << disp(subsys, " ") << " of a 4-qubit random state in the random basis:\n"; std::cout << disp(U) << '\n'; std::tie(result, probs, states) = measure(rho, U, {1, 2}); std::cout << ">> Measurement result: " << result << '\n'; std::cout << ">> Probabilities: " << disp(probs, ", ") << '\n'; std::cout << ">> Sum of the probabilities: " << sum(probs.begin(), probs.end()) << '\n'; std::cout << ">> Resulting normalized post-measurement states:\n"; for (auto&& it : states) std::cout << disp(it) << "\n\n"; // check now how the state after the measurement "looks" // on the left over subsystems {0, 3} // it should be the same as the partial trace over {1, 2} // of the initial state (before the measurement), as local CPTP maps // do not influence the complementary subsystems cmat rho_bar = ptrace(rho, subsys); cmat rho_out_bar = cmat::Zero(4, 4); // compute the resulting mixed state after the measurement for (idx i = 0; i < probs.size(); ++i) rho_out_bar += probs[i] * states[i]; // verification std::cout << ">> Norm difference: " << norm(rho_bar - rho_out_bar) << '\n'; // random Kraus std::cout << ">> Random channel on part of the state\n"; rho_bar = ptrace(rho, {1, 3}); rho_out_bar = ptrace(apply(rho, randkraus(3, 4), {1, 3}), {1, 3}); // verification std::cout << ">> Norm difference: " << norm(rho_bar - rho_out_bar) << '\n'; std::cout << ">> Sequential measurements on the state/density matrix:\n"; psi = 0.8 * 01_ket + 0.6 * 10_ket; rho = psi * adjoint(psi); std::cout << disp(psi) << '\n'; std::vector<idx> subsys_ket{0}; std::vector<idx> subsys_rho{1}; auto measured_ket = measure_seq(psi, subsys_ket); auto measured_rho = measure_seq(rho, subsys_rho); // ket std::cout << ">> Ket, measuring subsystem(s) "; std::cout << disp(subsys_ket, " ") << '\n'; std::cout << ">> Outcome(s): " << disp(std::get<RES>(measured_ket), " ") << '\n'; std::cout << ">> Probability: " << std::get<PROB>(measured_ket) << '\n'; std::cout << ">> Resulting state:\n"; std::cout << disp(std::get<ST>(measured_ket)) << '\n'; // density matrix std::cout << ">> Density matrix, measuring subsystem(s) "; std::cout << disp(subsys_rho, " ") << '\n'; std::cout << ">> Outcome(s): " << disp(std::get<RES>(measured_rho), " ") << '\n'; std::cout << ">> Probability: " << std::get<PROB>(measured_rho) << '\n'; std::cout << ">> Resulting state:\n"; std::cout << disp(std::get<ST>(measured_rho)) << '\n'; } <|endoftext|>
<commit_before>/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This file contains explicit instantiations of stats template types. * * This allows most users to avoid having to include the template definition * header files. */ #include <folly/stats/BucketedTimeSeries.h> #include <folly/stats/BucketedTimeSeries-defs.h> #include <folly/stats/Histogram.h> #include <folly/stats/Histogram-defs.h> #include <folly/stats/MultiLevelTimeSeries.h> #include <folly/stats/MultiLevelTimeSeries-defs.h> #include <folly/stats/TimeseriesHistogram.h> #include <folly/stats/TimeseriesHistogram-defs.h> namespace folly { template class BucketedTimeSeries<int64_t>; template class Histogram<int64_t>; template class detail::HistogramBuckets<int64_t, Histogram<int64_t>::Bucket>; template class MultiLevelTimeSeries<int64_t>; template class TimeseriesHistogram<int64_t>; } // folly <commit_msg>Add additional instantiations in Instantiations.cpp<commit_after>/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This file contains explicit instantiations of stats template types. * * This allows most users to avoid having to include the template definition * header files. */ #include <folly/stats/BucketedTimeSeries.h> #include <folly/stats/BucketedTimeSeries-defs.h> #include <folly/stats/Histogram.h> #include <folly/stats/Histogram-defs.h> #include <folly/stats/MultiLevelTimeSeries.h> #include <folly/stats/MultiLevelTimeSeries-defs.h> #include <folly/stats/TimeseriesHistogram.h> #include <folly/stats/TimeseriesHistogram-defs.h> namespace folly { template class BucketedTimeSeries<int64_t>; template class Histogram<int64_t>; template class detail::HistogramBuckets<int64_t, Histogram<int64_t>::Bucket>; template class MultiLevelTimeSeries<int64_t>; template class TimeseriesHistogram<int64_t>; // Histogram::getPercentileBucketIdx() and Histogram::getPercentileEstimate() // are implemented using template methods. Instantiate the default versions of // these methods too, so anyone using them won't also need to explicitly // include Histogram-defs.h template unsigned int detail::HistogramBuckets< int64_t, Histogram<int64_t>::Bucket>:: getPercentileBucketIdx<Histogram<int64_t>::CountFromBucket>( double pct, Histogram<int64_t>::CountFromBucket countFromBucket, double* lowPct, double* highPct) const; template int64_t detail::HistogramBuckets<int64_t, Histogram<int64_t>::Bucket> ::getPercentileEstimate<Histogram<int64_t>::CountFromBucket, Histogram<int64_t>::AvgFromBucket>( double pct, Histogram<int64_t>::CountFromBucket countFromBucket, Histogram<int64_t>::AvgFromBucket avgFromBucket) const; } // folly <|endoftext|>
<commit_before>#include <Socket/server/Server.hpp> #include <csignal> #include <iostream> #include "functions.hpp" ntw::srv::Server* server = nullptr; void stop_server_handler(int sig) { std::cout<<"Recv signal "<<sig<<". Stoping server.\n Please wait."<<std::endl; if(server) server->stop(); } #define SERVER_PORT 1 int main(int argc,char* argv[]) { if(argc < SERVER_PORT +1) { std::cout<<"Usage are: "<<argv[0]<<"[server-port]"<<std::endl; return 1; } const unsigned int max_client = 100; std::cout<<"[Server start] on:" <<"\n\tPort : "<<argv[SERVER_PORT] <<std::endl; std::signal(SIGINT, stop_server_handler); try { ntw::Socket::init(); server = new ntw::srv::Server(atoi(argv[SERVER_PORT]),"",dispatch,max_client); server->on_new_client = register_client; server->on_delete_client = unregister_client; server->start(); server->wait(); delete server; ntw::Socket::close(); } catch(ntw::SocketExeption& e) { std::cout<<e.what()<<std::endl; } std::cout<<"Server is close"<<std::endl; std::cout<<"Good bye"<<std::endl; return 0; } <commit_msg>maj server example<commit_after>#include <Socket/server/Server.hpp> #include <csignal> #include <iostream> #include "functions.hpp" ntw::srv::Server* server = nullptr; void stop_server_handler(int sig) { std::cout<<"Recv signal "<<sig<<". Stoping server.\n Please wait."<<std::endl; if(server) server->stop(); } #define SERVER_PORT 1 int main(int argc,char* argv[]) { if(argc < SERVER_PORT +1) { std::cout<<"Usage are: "<<argv[0]<<"[server-port]"<<std::endl; return 1; } const unsigned int max_client = 100; std::cout<<"[Server start] on:" <<"\n\tPort : "<<argv[SERVER_PORT] <<std::endl; std::signal(SIGINT, stop_server_handler); try { ntw::Socket::init(); server = new ntw::srv::Server(atoi(argv[SERVER_PORT]),"127.0.0.1",dispatch,max_client); server->on_new_client = register_client; server->on_delete_client = unregister_client; server->start(); server->wait(); delete server; ntw::Socket::close(); } catch(ntw::SocketExeption& e) { std::cout<<e.what()<<std::endl; } std::cout<<"Server is close"<<std::endl; std::cout<<"Good bye"<<std::endl; return 0; } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <os> #include <vga> #include <cassert> #include <net/inet4> #include <hw/ps2.hpp> #include "snake.hpp" std::unique_ptr<net::Inet4<VirtioNet> > inet; ConsoleVGA vga; void begin_snake() { hw::KBM::init(); static Snake snake(vga); hw::KBM::set_virtualkey_handler( [] (int key) { if (key == hw::KBM::VK_RIGHT) { snake.set_dir(Snake::RIGHT); } if (key == hw::KBM::VK_LEFT) { snake.set_dir(Snake::LEFT); } if (key == hw::KBM::VK_UP) { snake.set_dir(Snake::UP); } if (key == hw::KBM::VK_DOWN) { snake.set_dir(Snake::DOWN); } if (key == hw::KBM::VK_SPACE) { if (snake.is_gameover()) snake.reset(); } }); } void Service::start() { // redirect stdout to vga screen // ... even though we aren't really using it after the game starts OS::set_rsprint( [] (const char* data, size_t len) { vga.write(data, len); }); // we have to start snake later to avoid late text output hw::PIT::on_timeout(0.25, [] { begin_snake(); }); // boilerplate hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>(); inet = std::make_unique<net::Inet4<VirtioNet> >(eth0, 0.15); inet->network_config( { 10,0,0,42 }, // IP { 255,255,255,0 }, // Netmask { 10,0,0,1 }, // Gateway { 8,8,8,8 } ); // DNS printf("*** TEST SERVICE STARTED *** \n"); } <commit_msg>Removed whitespace from output<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <os> #include <vga> #include <cassert> #include <net/inet4> #include <hw/ps2.hpp> #include "snake.hpp" std::unique_ptr<net::Inet4<VirtioNet> > inet; ConsoleVGA vga; void begin_snake() { hw::KBM::init(); static Snake snake(vga); hw::KBM::set_virtualkey_handler( [] (int key) { if (key == hw::KBM::VK_RIGHT) { snake.set_dir(Snake::RIGHT); } if (key == hw::KBM::VK_LEFT) { snake.set_dir(Snake::LEFT); } if (key == hw::KBM::VK_UP) { snake.set_dir(Snake::UP); } if (key == hw::KBM::VK_DOWN) { snake.set_dir(Snake::DOWN); } if (key == hw::KBM::VK_SPACE) { if (snake.is_gameover()) snake.reset(); } }); } void Service::start() { // redirect stdout to vga screen // ... even though we aren't really using it after the game starts OS::set_rsprint( [] (const char* data, size_t len) { vga.write(data, len); }); // we have to start snake later to avoid late text output hw::PIT::on_timeout(0.25, [] { begin_snake(); }); // boilerplate hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>(); inet = std::make_unique<net::Inet4<VirtioNet> >(eth0, 0.15); inet->network_config( { 10,0,0,42 }, // IP { 255,255,255,0 }, // Netmask { 10,0,0,1 }, // Gateway { 8,8,8,8 } ); // DNS printf("*** TEST SERVICE STARTED ***\n"); } <|endoftext|>
<commit_before>#include "Binding.h" #include <iostream> #include <vector> #include "MyActor.h" #include "MyActorBinding.h" using std::cout; using std::endl; static void stackDump (lua_State *L) { int i=lua_gettop(L); cout << " ---------------- Stack Dump ----------------\n"; while( i ) { int t = lua_type(L, i); switch (t) { case LUA_TSTRING: printf("%d: “%s”\n", i, lua_tostring(L, i)); break; case LUA_TBOOLEAN: printf("%d: %s\n",i,lua_toboolean(L, i) ? "true" : "false"); break; case LUA_TNUMBER: printf("%d: %g\n", i, lua_tonumber(L, i)); break; default: printf("%d: %s 0x%x\n", i, lua_typename(L, t), lua_topointer(L, i)); break; } i--; } cout << "--------------- Stack Dump Finished ---------------\n"; } void run( lua_State *L, const char *code ) { cout << "code> " << code << endl; if( luaL_dostring( L, code ) ) { cout << lua_tostring( L, -1 ) << endl; lua_pop( L, 1 ); } } typedef std::vector<MyActorPtr> MyActorPtrList; MyActorPtrList createList() { const char* names[] = { "James", "Who? Random extra", "Harry", "Mike", nullptr }; MyActorPtrList actors; for( int i = 0; names[i] != nullptr; i++ ) { actors.push_back( std::make_shared<MyActor>( names[i] ) ); } return actors; } void pushToLua( lua_State* L, MyActorPtrList list ) { lua_newtable( L ); int index = 1; for( auto ap = list.begin(); ap != list.end(); ap++ ) { MyActorBinding::push( L, *ap ); lua_rawseti( L, -2, index++ ); } } MyActorPtrList pullFromLua( lua_State* L ) { // Note this only stores the values, not the keys/indexes, // which are usually just numbers. MyActorPtrList list; if( lua_istable( L, -1 ) ) { lua_pushnil( L ); while( lua_next( L, -2 ) ) { if( luaL_testudata( L, -1, "MyActor" ) ) { list.push_back( MyActorBinding::fromStack( L, -1 ) ); } lua_pop( L, 1 ); } } return list; } int main() { lua_State* L = luaL_newstate(); luaL_openlibs( L ); MyActorBinding::register_class( L ); { cout << "Pushing actor list to Lua." << endl; MyActorPtrList actors = createList(); pushToLua( L, actors ); lua_setglobal( L, "actors" ); } cout << "Editing actor list..." << endl; run( L, "actors[2] = nil -- Who is this? Pfft, delete." ); run( L, "collectgarbage()" ); run( L, "actors['test'] = MyActor('Bob') -- Hey Bob welcome." ); run( L, "for k,v in pairs(actors) do print( k, v.name ) end" ); { cout << "Pull list back into C++ vector, and list..." << endl; lua_getglobal( L, "actors" ); MyActorPtrList actors = pullFromLua( L ); lua_pop( L, 1 ); for( auto ap = actors.begin(); ap != actors.end(); ap++ ) { cout << (*ap)->_name << endl; } } lua_close(L); } <commit_msg>We don't need stackDump in this example<commit_after>#include "Binding.h" #include <iostream> #include <vector> #include "MyActor.h" #include "MyActorBinding.h" using std::cout; using std::endl; void run( lua_State *L, const char *code ) { cout << "code> " << code << endl; if( luaL_dostring( L, code ) ) { cout << lua_tostring( L, -1 ) << endl; lua_pop( L, 1 ); } } typedef std::vector<MyActorPtr> MyActorPtrList; MyActorPtrList createList() { const char* names[] = { "James", "Who? Random extra", "Harry", "Mike", nullptr }; MyActorPtrList actors; for( int i = 0; names[i] != nullptr; i++ ) { actors.push_back( std::make_shared<MyActor>( names[i] ) ); } return actors; } void pushToLua( lua_State* L, MyActorPtrList list ) { lua_newtable( L ); int index = 1; for( auto ap = list.begin(); ap != list.end(); ap++ ) { MyActorBinding::push( L, *ap ); lua_rawseti( L, -2, index++ ); } } MyActorPtrList pullFromLua( lua_State* L ) { // Note this only stores the values, not the keys/indexes, // which are usually just numbers. MyActorPtrList list; if( lua_istable( L, -1 ) ) { lua_pushnil( L ); while( lua_next( L, -2 ) ) { if( luaL_testudata( L, -1, "MyActor" ) ) { list.push_back( MyActorBinding::fromStack( L, -1 ) ); } lua_pop( L, 1 ); } } return list; } int main() { lua_State* L = luaL_newstate(); luaL_openlibs( L ); MyActorBinding::register_class( L ); { cout << "Pushing actor list to Lua." << endl; MyActorPtrList actors = createList(); pushToLua( L, actors ); lua_setglobal( L, "actors" ); } cout << "Editing actor list..." << endl; run( L, "actors[2] = nil -- Who is this? Pfft, delete." ); run( L, "collectgarbage()" ); run( L, "actors['test'] = MyActor('Bob') -- Hey Bob welcome." ); run( L, "for k,v in pairs(actors) do print( k, v.name ) end" ); { cout << "Pull list back into C++ vector, and list..." << endl; lua_getglobal( L, "actors" ); MyActorPtrList actors = pullFromLua( L ); lua_pop( L, 1 ); for( auto ap = actors.begin(); ap != actors.end(); ap++ ) { cout << (*ap)->_name << endl; } } lua_close(L); } <|endoftext|>
<commit_before>/* Copyright (C) 2016 - Gbor "Razzie" Grzsny 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 <iostream> #include "raz/thread.hpp" struct Loopable { void operator()() { std::cout << "loop" << std::endl; } }; struct Worker { void operator()(int a, int b) { std::cout << (a + b) << std::endl; } }; void example01() { raz::Thread<Loopable> thread; std::this_thread::sleep_for(std::chrono::milliseconds(200)); } void example02() { raz::Thread<Worker> thread; thread(1, 2); std::this_thread::sleep_for(std::chrono::milliseconds(200)); thread(2, 3); std::this_thread::sleep_for(std::chrono::milliseconds(200)); thread(3, 4); std::this_thread::sleep_for(std::chrono::milliseconds(200)); } int main() { example01(); example02(); return 0; } <commit_msg>Updated thread example<commit_after>/* Copyright (C) 2016 - Gbor "Razzie" Grzsny 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 <iostream> #include <stdexcept> #include "raz/thread.hpp" class Loopable { public: void operator()() { std::cout << "loop" << std::endl; } }; class Worker { int base_value; public: Worker(int base_value) : base_value(base_value) { } void operator()(int value) { std::cout << (base_value + value) << std::endl; } }; class WorkerWithException { public: void operator()(bool throw_exception) { if (throw_exception) throw std::runtime_error("this is an exception"); } void operator()(std::exception& e) { std::cerr << e.what() << std::endl; } }; void example01() { raz::Thread<Loopable> thread; std::this_thread::sleep_for(std::chrono::milliseconds(200)); } void example02() { raz::Thread<Worker> thread(123); thread(1); std::this_thread::sleep_for(std::chrono::milliseconds(200)); thread(2); std::this_thread::sleep_for(std::chrono::milliseconds(200)); thread(3); std::this_thread::sleep_for(std::chrono::milliseconds(200)); } void example03() { raz::Thread<WorkerWithException> thread; thread(false); thread(true); std::this_thread::sleep_for(std::chrono::milliseconds(200)); } int main() { example01(); example02(); example03(); return 0; } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MooseInit.h" #include "Moose.h" #include "ParallelUniqueId.h" #include "Factory.h" #include "ActionFactory.h" MooseInit::MooseInit(int argc, char *argv[]) : LibMeshInit(argc, argv) { ParallelUniqueId::initialize(); std::cout << "Using " << libMesh::n_threads() << " thread(s)" << std::endl; Moose::command_line = new GetPot(argc, argv); Moose::registerObjects(); } MooseInit::~MooseInit() { delete Moose::command_line; Factory::release(); ActionFactory::release(); } namespace Moose { GetPot *command_line = NULL; } <commit_msg>Get rid of PetscErrorHandler<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MooseInit.h" #include "Moose.h" #include "ParallelUniqueId.h" #include "Factory.h" #include "ActionFactory.h" MooseInit::MooseInit(int argc, char *argv[]) : LibMeshInit(argc, argv) { PetscPushSignalHandler(NULL, NULL); // get rid off Petsc error handler ParallelUniqueId::initialize(); std::cout << "Using " << libMesh::n_threads() << " thread(s)" << std::endl; Moose::command_line = new GetPot(argc, argv); Moose::registerObjects(); } MooseInit::~MooseInit() { delete Moose::command_line; Factory::release(); ActionFactory::release(); } namespace Moose { GetPot *command_line = NULL; } <|endoftext|>
<commit_before>#include "kernel.h" #include "raster.h" #include "simpelgeoreference.h" #include "cornersgeoreference.h" #include "symboltable.h" #include "ilwisoperation.h" #include "pixeliterator.h" #include "columndefinition.h" #include "table.h" #include "attributerecord.h" #include "selection.h" using namespace Ilwis; using namespace BaseOperations; Selection::Selection() { } Selection::Selection(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } Selection::~Selection() { } bool Selection::execute(ExecutionContext *ctx, SymbolTable& symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; IGridCoverage outputGC = _outputObj.get<GridCoverage>(); IGridCoverage inputGC = _inputObj.get<GridCoverage>(); BoxedAsyncFunc selection = [&](const Box3D<qint32>& box ) -> bool { Box3D<qint32> inpbox = box.size(); inpbox += _base; inpbox += std::vector<qint32>{0, box.min_corner().y(),0}; inpbox.copyFrom(box, Box3D<>::dimZ); PixelIterator iterOut(outputGC, box); PixelIterator iterIn(inputGC, inpbox); AttributeRecord rec; if ( _attribColumn != "") rec = AttributeRecord(inputGC->attributeTable(itCOVERAGE), "coverage_key"); double v_in = 0; for_each(iterOut, iterOut.end(), [&](double& v){ v_in = *iterIn; if ( v_in != rUNDEF) { if ( rec.isValid()) { QVariant var = rec.cellByKey(v_in,_attribColumn); v = var.toDouble(); if ( isNumericalUndef(v)) v = rUNDEF; } else { v = v_in; } } ++iterIn; ++iterOut; } ); return true; }; bool res = OperationHelper::execute(ctx,selection, outputGC, _box); if ( res && ctx != 0) { QVariant value; value.setValue<IGridCoverage>(outputGC); ctx->addOutput(symTable, value, outputGC->name(), itGRIDCOVERAGE,outputGC->source()); } return res; } Ilwis::OperationImplementation *Selection::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new Selection(metaid, expr); } Ilwis::OperationImplementation::State Selection::prepare(ExecutionContext *, const SymbolTable &) { if ( _expression.parameterCount() != 2) { ERROR3(ERR_ILLEGAL_NUM_PARM3,"rasvalue","1",QString::number(_expression.parameterCount())); return sPREPAREFAILED; } IlwisTypes inputType = itGRIDCOVERAGE; QString gc = _expression.parm(0).value(); if (!_inputObj.prepare(gc, inputType)) { ERROR2(ERR_COULD_NOT_LOAD_2,gc,""); return sPREPAREFAILED; } IGridCoverage inputGC = _inputObj.get<GridCoverage>(); quint64 copylist = itCOORDSYSTEM; QString selector = _expression.parm(1).value(); selector = selector.remove('"'); int index = selector.indexOf("box="); Box2D<double> box; if ( index != -1) { QString crdlist = "box(" + selector.mid(index+4) + ")"; _box = Box3D<qint32>(crdlist); box = inputGC->georeference()->pixel2Coord(_box); copylist |= itDOMAIN | itTABLE; std::vector<qint32> vec{_box.min_corner().x(), _box.min_corner().y(),_box.min_corner().z()}; _base = vec; } index = selector.indexOf("polygon="); if ( index != -1) { //TODO copylist |= itDOMAIN | itTABLE; } index = selector.indexOf("attribute="); if ( index != -1 ) { if (! inputGC->attributeTable(itCOVERAGE).isValid()) { ERROR2(ERR_NO_FOUND2,"attribute-table", "coverage"); return sPREPAREFAILED; } _attribColumn = selector.mid(index+10); copylist |= itGRIDSIZE | itGEOREF | itENVELOPE; } _outputObj = OperationHelper::initialize(_inputObj,inputType, copylist); if ( !_outputObj.isValid()) { ERROR1(ERR_NO_INITIALIZED_1, "output coverage"); return sPREPAREFAILED; } IGridCoverage outputGC = _outputObj.get<GridCoverage>(); if ( (copylist & itDOMAIN) == 0) { outputGC->datadef() = _attribColumn != "" ? inputGC->attributeTable(itCOVERAGE)->columndefinition(_attribColumn).datadef() : outputGC->datadef() = inputGC->datadef(); } QString outputName = _expression.parm(0,false).value(); if ( outputName != sUNDEF) _outputObj->setName(outputName); if ( (copylist & itGEOREF) == 0) { Resource res(QUrl("ilwis://internal/georeference"),itCORNERSGEOREF); res.addProperty("size", IVARIANT(_box.size())); res.addProperty("envelope", IVARIANT(box)); res.addProperty("coordinatesystem", IVARIANT(inputGC->coordinateSystem())); res.addProperty("name", _outputObj->name()); res.addProperty("centerofpixel",inputGC->georeference()->centerOfPixel()); IGeoReference grf; grf.prepare(res); outputGC->georeference(grf); outputGC->envelope(box); } return sPREPARED; } quint64 Selection::createMetadata() { QString url = QString("ilwis://operations/selection"); Resource res(QUrl(url), itOPERATIONMETADATA); res.addProperty("namespace","ilwis"); res.addProperty("longname","selection"); res.addProperty("syntax","selection(coverage,selection-definition)"); res.addProperty("inparameters","2"); res.addProperty("pin_1_type", itCOVERAGE); res.addProperty("pin_1_name", TR("input coverage")); res.addProperty("pin_1_desc",TR("input gridcoverage with a domain as specified by the selection")); res.addProperty("pin_2_type", itSTRING); res.addProperty("pin_2_name", TR("selection-definition")); res.addProperty("pin_2_desc",TR("Selection can either be attribute, layer index or area definition (e.g. box)")); res.addProperty("pout_1_type", itCOVERAGE); res.addProperty("pout_1_name", TR("coverage were the selection has been applied")); res.addProperty("pout_1_desc",TR("")); res.prepare(); url += "=" + QString::number(res.id()); res.setUrl(url); mastercatalog()->addItems({res}); return res.id(); } <commit_msg>changed helper name<commit_after>#include "kernel.h" #include "raster.h" #include "simpelgeoreference.h" #include "cornersgeoreference.h" #include "symboltable.h" #include "ilwisoperation.h" #include "pixeliterator.h" #include "columndefinition.h" #include "table.h" #include "attributerecord.h" #include "selection.h" using namespace Ilwis; using namespace BaseOperations; Selection::Selection() { } Selection::Selection(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } Selection::~Selection() { } bool Selection::execute(ExecutionContext *ctx, SymbolTable& symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; IGridCoverage outputGC = _outputObj.get<GridCoverage>(); IGridCoverage inputGC = _inputObj.get<GridCoverage>(); BoxedAsyncFunc selection = [&](const Box3D<qint32>& box ) -> bool { Box3D<qint32> inpbox = box.size(); inpbox += _base; inpbox += std::vector<qint32>{0, box.min_corner().y(),0}; inpbox.copyFrom(box, Box3D<>::dimZ); PixelIterator iterOut(outputGC, box); PixelIterator iterIn(inputGC, inpbox); AttributeRecord rec; if ( _attribColumn != "") rec = AttributeRecord(inputGC->attributeTable(itCOVERAGE), "coverage_key"); double v_in = 0; for_each(iterOut, iterOut.end(), [&](double& v){ v_in = *iterIn; if ( v_in != rUNDEF) { if ( rec.isValid()) { QVariant var = rec.cellByKey(v_in,_attribColumn); v = var.toDouble(); if ( isNumericalUndef(v)) v = rUNDEF; } else { v = v_in; } } ++iterIn; ++iterOut; } ); return true; }; bool res = OperationHelperRaster::execute(ctx,selection, outputGC, _box); if ( res && ctx != 0) { QVariant value; value.setValue<IGridCoverage>(outputGC); ctx->addOutput(symTable, value, outputGC->name(), itGRIDCOVERAGE,outputGC->source()); } return res; } Ilwis::OperationImplementation *Selection::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new Selection(metaid, expr); } Ilwis::OperationImplementation::State Selection::prepare(ExecutionContext *, const SymbolTable &) { if ( _expression.parameterCount() != 2) { ERROR3(ERR_ILLEGAL_NUM_PARM3,"rasvalue","1",QString::number(_expression.parameterCount())); return sPREPAREFAILED; } IlwisTypes inputType = itGRIDCOVERAGE; QString gc = _expression.parm(0).value(); if (!_inputObj.prepare(gc, inputType)) { ERROR2(ERR_COULD_NOT_LOAD_2,gc,""); return sPREPAREFAILED; } IGridCoverage inputGC = _inputObj.get<GridCoverage>(); quint64 copylist = itCOORDSYSTEM; QString selector = _expression.parm(1).value(); selector = selector.remove('"'); int index = selector.indexOf("box="); Box2D<double> box; if ( index != -1) { QString crdlist = "box(" + selector.mid(index+4) + ")"; _box = Box3D<qint32>(crdlist); box = inputGC->georeference()->pixel2Coord(_box); copylist |= itDOMAIN | itTABLE; std::vector<qint32> vec{_box.min_corner().x(), _box.min_corner().y(),_box.min_corner().z()}; _base = vec; } index = selector.indexOf("polygon="); if ( index != -1) { //TODO copylist |= itDOMAIN | itTABLE; } index = selector.indexOf("attribute="); if ( index != -1 ) { if (! inputGC->attributeTable(itCOVERAGE).isValid()) { ERROR2(ERR_NO_FOUND2,"attribute-table", "coverage"); return sPREPAREFAILED; } _attribColumn = selector.mid(index+10); copylist |= itGRIDSIZE | itGEOREF | itENVELOPE; } _outputObj = OperationHelperRaster::initialize(_inputObj,inputType, copylist); if ( !_outputObj.isValid()) { ERROR1(ERR_NO_INITIALIZED_1, "output coverage"); return sPREPAREFAILED; } IGridCoverage outputGC = _outputObj.get<GridCoverage>(); if ( (copylist & itDOMAIN) == 0) { outputGC->datadef() = _attribColumn != "" ? inputGC->attributeTable(itCOVERAGE)->columndefinition(_attribColumn).datadef() : outputGC->datadef() = inputGC->datadef(); } QString outputName = _expression.parm(0,false).value(); if ( outputName != sUNDEF) _outputObj->setName(outputName); if ( (copylist & itGEOREF) == 0) { Resource res(QUrl("ilwis://internal/georeference"),itCORNERSGEOREF); res.addProperty("size", IVARIANT(_box.size())); res.addProperty("envelope", IVARIANT(box)); res.addProperty("coordinatesystem", IVARIANT(inputGC->coordinateSystem())); res.addProperty("name", _outputObj->name()); res.addProperty("centerofpixel",inputGC->georeference()->centerOfPixel()); IGeoReference grf; grf.prepare(res); outputGC->georeference(grf); outputGC->envelope(box); } return sPREPARED; } quint64 Selection::createMetadata() { QString url = QString("ilwis://operations/selection"); Resource res(QUrl(url), itOPERATIONMETADATA); res.addProperty("namespace","ilwis"); res.addProperty("longname","selection"); res.addProperty("syntax","selection(coverage,selection-definition)"); res.addProperty("inparameters","2"); res.addProperty("pin_1_type", itCOVERAGE); res.addProperty("pin_1_name", TR("input coverage")); res.addProperty("pin_1_desc",TR("input gridcoverage with a domain as specified by the selection")); res.addProperty("pin_2_type", itSTRING); res.addProperty("pin_2_name", TR("selection-definition")); res.addProperty("pin_2_desc",TR("Selection can either be attribute, layer index or area definition (e.g. box)")); res.addProperty("pout_1_type", itCOVERAGE); res.addProperty("pout_1_name", TR("coverage were the selection has been applied")); res.addProperty("pout_1_desc",TR("")); res.prepare(); url += "=" + QString::number(res.id()); res.setUrl(url); mastercatalog()->addItems({res}); return res.id(); } <|endoftext|>
<commit_before><commit_msg>Initialize the runtime properly in authentication-test<commit_after><|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * * 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. */ #if !DEVICE_SLEEP #error [NOT_SUPPORTED] sleep not supported for this target #endif #include "mbed.h" #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "sleep_api_tests.h" #define US_PER_S 1000000 using namespace utest::v1; /* The following ticker frequencies are possible: * high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1/8 us) * low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us) */ /* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows: * delta = default 10 us + worst ticker resolution + extra time for code execution */ static const uint32_t sleep_mode_delta_us = (10 + 4 + 5); /* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows: * delta = default 10 ms + worst ticker resolution + extra time for code execution */ static const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5); unsigned int ticks_to_us(unsigned int ticks, unsigned int freq) { return (unsigned int)((unsigned long long)ticks * US_PER_S / freq); } unsigned int us_to_ticks(unsigned int us, unsigned int freq) { return (unsigned int)((unsigned long long)us * freq / US_PER_S); } unsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width) { unsigned int counter_mask = ((1 << ticker_width) - 1); return (timestamp & counter_mask); } bool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual) { const unsigned int counter_mask = ((1 << ticker_width) - 1); const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask); const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask); if(lower_bound < upper_bound) { if (actual >= lower_bound && actual <= upper_bound) { return true; } else { return false; } } else { if ((actual >= lower_bound && actual <= counter_mask) || (actual >= 0 && actual <= upper_bound)) { return true; } else { return false; } } } void us_ticker_isr(const ticker_data_t *const ticker_data) { us_ticker_clear_interrupt(); } #ifdef DEVICE_LOWPOWERTIMER void lp_ticker_isr(const ticker_data_t *const ticker_data) { lp_ticker_clear_interrupt(); } #endif /* Test that wake-up time from sleep should be less than 10 us and * high frequency ticker interrupt can wake-up target from sleep. */ void sleep_usticker_test() { Timeout timeout; const ticker_data_t * ticker = get_us_ticker_data(); const unsigned int ticker_freq = ticker->interface->get_info()->frequency; const unsigned int ticker_width = ticker->interface->get_info()->bits; const ticker_irq_handler_type us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr); /* Test only sleep functionality. */ sleep_manager_lock_deep_sleep(); TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should be locked"); /* Testing wake-up time 10 us. */ for (timestamp_t i = 100; i < 1000; i += 100) { /* note: us_ticker_read() operates on ticks. */ const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width); us_ticker_set_interrupt(next_match_timestamp); sleep(); const unsigned int wakeup_timestamp = us_ticker_read(); TEST_ASSERT( compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp)); } set_us_ticker_irq_handler(us_ticker_irq_handler_org); sleep_manager_unlock_deep_sleep(); TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep()); } #ifdef DEVICE_LOWPOWERTIMER /* Test that wake-up time from sleep should be less than 10 ms and * low power ticker interrupt can wake-up target from sleep. */ void deepsleep_lpticker_test() { const ticker_data_t * ticker = get_lp_ticker_data(); const unsigned int ticker_freq = ticker->interface->get_info()->frequency; const unsigned int ticker_width = ticker->interface->get_info()->bits; const ticker_irq_handler_type lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr); /* Give some time Green Tea to finish UART transmission before entering * deep-sleep mode. */ wait_ms(10); TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked"); /* Testing wake-up time 10 ms. */ for (timestamp_t i = 20000; i < 200000; i += 20000) { /* note: lp_ticker_read() operates on ticks. */ const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width); lp_ticker_set_interrupt(next_match_timestamp); sleep(); const timestamp_t wakeup_timestamp = lp_ticker_read(); TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp)); } set_lp_ticker_irq_handler(lp_ticker_irq_handler_org); } void deepsleep_high_speed_clocks_turned_off_test() { const ticker_data_t * us_ticker = get_us_ticker_data(); const ticker_data_t * lp_ticker = get_lp_ticker_data(); const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency; const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency; const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits; const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits; const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1); /* Give some time Green Tea to finish UART transmission before entering * deep-sleep mode. */ wait_ms(10); TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked"); const unsigned int us_ticks_before_sleep = us_ticker_read(); const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(200000, lp_ticker_freq); lp_ticker_set_interrupt(wakeup_time); sleep(); const unsigned int us_ticks_after_sleep = us_ticker_read(); const unsigned int lp_ticks_after_sleep = lp_ticker_read(); /* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between * ticker reads before and after the sleep represents only code execution time between calls. * Since we went to sleep for about 200 ms check if time counted by high frequency timer does not * exceed 1 ms. */ const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1); TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq)); /* Check if we have woken-up after expected time. */ TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep)); } #endif utest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason) { greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(60, "default_auto"); us_ticker_init(); #if DEVICE_LOWPOWERTIMER lp_ticker_init(); #endif /* Suspend RTOS Kernel to enable sleep modes. */ osKernelSuspend(); return greentea_test_setup_handler(number_of_cases); } Case cases[] = { Case("sleep - source of wake-up - us ticker", sleep_usticker_test, greentea_failure_handler), #if DEVICE_LOWPOWERTIMER Case("deep-sleep - source of wake-up - lp ticker",deepsleep_lpticker_test, greentea_failure_handler), Case("deep-sleep - high-speed clocks are turned off",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler), #endif }; Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); int main() { Harness::run(specification); } <commit_msg>tests-mbed_hal-sleep: remove unused variable.<commit_after>/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * * 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. */ #if !DEVICE_SLEEP #error [NOT_SUPPORTED] sleep not supported for this target #endif #include "mbed.h" #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "sleep_api_tests.h" #define US_PER_S 1000000 using namespace utest::v1; /* The following ticker frequencies are possible: * high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1/8 us) * low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us) */ /* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows: * delta = default 10 us + worst ticker resolution + extra time for code execution */ static const uint32_t sleep_mode_delta_us = (10 + 4 + 5); /* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows: * delta = default 10 ms + worst ticker resolution + extra time for code execution */ static const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5); unsigned int ticks_to_us(unsigned int ticks, unsigned int freq) { return (unsigned int)((unsigned long long)ticks * US_PER_S / freq); } unsigned int us_to_ticks(unsigned int us, unsigned int freq) { return (unsigned int)((unsigned long long)us * freq / US_PER_S); } unsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width) { unsigned int counter_mask = ((1 << ticker_width) - 1); return (timestamp & counter_mask); } bool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual) { const unsigned int counter_mask = ((1 << ticker_width) - 1); const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask); const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask); if(lower_bound < upper_bound) { if (actual >= lower_bound && actual <= upper_bound) { return true; } else { return false; } } else { if ((actual >= lower_bound && actual <= counter_mask) || (actual >= 0 && actual <= upper_bound)) { return true; } else { return false; } } } void us_ticker_isr(const ticker_data_t *const ticker_data) { us_ticker_clear_interrupt(); } #ifdef DEVICE_LOWPOWERTIMER void lp_ticker_isr(const ticker_data_t *const ticker_data) { lp_ticker_clear_interrupt(); } #endif /* Test that wake-up time from sleep should be less than 10 us and * high frequency ticker interrupt can wake-up target from sleep. */ void sleep_usticker_test() { const ticker_data_t * ticker = get_us_ticker_data(); const unsigned int ticker_freq = ticker->interface->get_info()->frequency; const unsigned int ticker_width = ticker->interface->get_info()->bits; const ticker_irq_handler_type us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr); /* Test only sleep functionality. */ sleep_manager_lock_deep_sleep(); TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should be locked"); /* Testing wake-up time 10 us. */ for (timestamp_t i = 100; i < 1000; i += 100) { /* note: us_ticker_read() operates on ticks. */ const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width); us_ticker_set_interrupt(next_match_timestamp); sleep(); const unsigned int wakeup_timestamp = us_ticker_read(); TEST_ASSERT( compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp)); } set_us_ticker_irq_handler(us_ticker_irq_handler_org); sleep_manager_unlock_deep_sleep(); TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep()); } #ifdef DEVICE_LOWPOWERTIMER /* Test that wake-up time from sleep should be less than 10 ms and * low power ticker interrupt can wake-up target from sleep. */ void deepsleep_lpticker_test() { const ticker_data_t * ticker = get_lp_ticker_data(); const unsigned int ticker_freq = ticker->interface->get_info()->frequency; const unsigned int ticker_width = ticker->interface->get_info()->bits; const ticker_irq_handler_type lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr); /* Give some time Green Tea to finish UART transmission before entering * deep-sleep mode. */ wait_ms(10); TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked"); /* Testing wake-up time 10 ms. */ for (timestamp_t i = 20000; i < 200000; i += 20000) { /* note: lp_ticker_read() operates on ticks. */ const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width); lp_ticker_set_interrupt(next_match_timestamp); sleep(); const timestamp_t wakeup_timestamp = lp_ticker_read(); TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp)); } set_lp_ticker_irq_handler(lp_ticker_irq_handler_org); } void deepsleep_high_speed_clocks_turned_off_test() { const ticker_data_t * us_ticker = get_us_ticker_data(); const ticker_data_t * lp_ticker = get_lp_ticker_data(); const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency; const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency; const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits; const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits; const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1); /* Give some time Green Tea to finish UART transmission before entering * deep-sleep mode. */ wait_ms(10); TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked"); const unsigned int us_ticks_before_sleep = us_ticker_read(); const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(200000, lp_ticker_freq); lp_ticker_set_interrupt(wakeup_time); sleep(); const unsigned int us_ticks_after_sleep = us_ticker_read(); const unsigned int lp_ticks_after_sleep = lp_ticker_read(); /* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between * ticker reads before and after the sleep represents only code execution time between calls. * Since we went to sleep for about 200 ms check if time counted by high frequency timer does not * exceed 1 ms. */ const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1); TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq)); /* Check if we have woken-up after expected time. */ TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep)); } #endif utest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason) { greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(60, "default_auto"); us_ticker_init(); #if DEVICE_LOWPOWERTIMER lp_ticker_init(); #endif /* Suspend RTOS Kernel to enable sleep modes. */ osKernelSuspend(); return greentea_test_setup_handler(number_of_cases); } Case cases[] = { Case("sleep - source of wake-up - us ticker", sleep_usticker_test, greentea_failure_handler), #if DEVICE_LOWPOWERTIMER Case("deep-sleep - source of wake-up - lp ticker",deepsleep_lpticker_test, greentea_failure_handler), Case("deep-sleep - high-speed clocks are turned off",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler), #endif }; Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); int main() { Harness::run(specification); } <|endoftext|>
<commit_before>//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend is responsible for emitting a description of the target // instruction set for the code generator. // //===----------------------------------------------------------------------===// #include "InstrInfoEmitter.h" #include "CodeGenTarget.h" #include "Record.h" #include <algorithm> using namespace llvm; // runEnums - Print out enum values for all of the instructions. void InstrInfoEmitter::runEnums(std::ostream &OS) { EmitSourceFileHeader("Target Instruction Enum Values", OS); OS << "namespace llvm {\n\n"; CodeGenTarget Target; // We must emit the PHI opcode first... std::string Namespace; for (CodeGenTarget::inst_iterator II = Target.inst_begin(), E = Target.inst_end(); II != E; ++II) { if (II->second.Namespace != "TargetInstrInfo") { Namespace = II->second.Namespace; break; } } if (Namespace.empty()) { std::cerr << "No instructions defined!\n"; exit(1); } std::vector<const CodeGenInstruction*> NumberedInstructions; Target.getInstructionsByEnumValue(NumberedInstructions); OS << "namespace " << Namespace << " {\n"; OS << " enum {\n"; for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { OS << " " << NumberedInstructions[i]->TheDef->getName() << "\t= " << i << ",\n"; } OS << " INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n"; OS << " };\n}\n"; OS << "} // End llvm namespace \n"; } void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses, unsigned Num, std::ostream &OS) const { OS << "static const unsigned ImplicitList" << Num << "[] = { "; for (unsigned i = 0, e = Uses.size(); i != e; ++i) OS << getQualifiedName(Uses[i]) << ", "; OS << "0 };\n"; } static std::vector<Record*> GetOperandInfo(const CodeGenInstruction &Inst) { std::vector<Record*> Result; for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) { if (Inst.OperandList[i].Rec->isSubClassOf("RegisterClass")) { Result.push_back(Inst.OperandList[i].Rec); } else { // This might be a multiple operand thing. // Targets like X86 have registers in their multi-operand operands. DagInit *MIOI = Inst.OperandList[i].MIOperandInfo; unsigned NumDefs = MIOI->getNumArgs(); for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) { if (NumDefs <= j) { Result.push_back(0); } else { DefInit *Def = dynamic_cast<DefInit*>(MIOI->getArg(j)); Result.push_back(Def ? Def->getDef() : 0); } } } } return Result; } // run - Emit the main instruction description records for the target... void InstrInfoEmitter::run(std::ostream &OS) { GatherItinClasses(); EmitSourceFileHeader("Target Instruction Descriptors", OS); OS << "namespace llvm {\n\n"; CodeGenTarget Target; const std::string &TargetName = Target.getName(); Record *InstrInfo = Target.getInstructionSet(); // Emit empty implicit uses and defs lists OS << "static const unsigned EmptyImpList[] = { 0 };\n"; // Keep track of all of the def lists we have emitted already. std::map<std::vector<Record*>, unsigned> EmittedLists; unsigned ListNumber = 0; // Emit all of the instruction's implicit uses and defs. for (CodeGenTarget::inst_iterator II = Target.inst_begin(), E = Target.inst_end(); II != E; ++II) { Record *Inst = II->second.TheDef; std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses"); if (!Uses.empty()) { unsigned &IL = EmittedLists[Uses]; if (!IL) printDefList(Uses, IL = ++ListNumber, OS); } std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs"); if (!Defs.empty()) { unsigned &IL = EmittedLists[Defs]; if (!IL) printDefList(Defs, IL = ++ListNumber, OS); } } std::map<std::vector<Record*>, unsigned> OperandInfosEmitted; unsigned OperandListNum = 0; OperandInfosEmitted[std::vector<Record*>()] = ++OperandListNum; // Emit all of the operand info records. OS << "\n"; for (CodeGenTarget::inst_iterator II = Target.inst_begin(), E = Target.inst_end(); II != E; ++II) { std::vector<Record*> OperandInfo = GetOperandInfo(II->second); unsigned &N = OperandInfosEmitted[OperandInfo]; if (N == 0) { N = ++OperandListNum; OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { "; for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i) { Record *RC = OperandInfo[i]; // FIXME: We only care about register operands for now. if (RC && RC->isSubClassOf("RegisterClass")) OS << "{ " << getQualifiedName(RC) << "RegClassID, 0 }, "; else if (RC && RC->getName() == "ptr_rc") // Ptr value whose register class is resolved via callback. OS << "{ 0, 1 }, "; else OS << "{ 0, 0 }, "; } OS << "};\n"; } } // Emit all of the TargetInstrDescriptor records in their ENUM ordering. // OS << "\nstatic const TargetInstrDescriptor " << TargetName << "Insts[] = {\n"; std::vector<const CodeGenInstruction*> NumberedInstructions; Target.getInstructionsByEnumValue(NumberedInstructions); for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists, OperandInfosEmitted, OS); OS << "};\n"; OS << "} // End llvm namespace \n"; } void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num, Record *InstrInfo, std::map<std::vector<Record*>, unsigned> &EmittedLists, std::map<std::vector<Record*>, unsigned> &OpInfo, std::ostream &OS) { int MinOperands; if (!Inst.OperandList.empty()) // Each logical operand can be multiple MI operands. MinOperands = Inst.OperandList.back().MIOperandNo + Inst.OperandList.back().MINumOperands; else MinOperands = 0; OS << " { \""; if (Inst.Name.empty()) OS << Inst.TheDef->getName(); else OS << Inst.Name; unsigned ItinClass = !IsItineraries ? 0 : ItinClassNumber(Inst.TheDef->getValueAsDef("Itinerary")->getName()); OS << "\",\t" << MinOperands << ", " << ItinClass << ", 0"; // Try to determine (from the pattern), if the instruction is a store. bool isStore = false; if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) { ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern"); if (LI && LI->getSize() > 0) { DagInit *Dag = (DagInit *)LI->getElement(0); DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator()); if (OpDef) { Record *Operator = OpDef->getDef(); if (Operator->isSubClassOf("SDNode")) { const std::string Opcode = Operator->getValueAsString("Opcode"); if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE") isStore = true; } } } } // Emit all of the target indepedent flags... if (Inst.isReturn) OS << "|M_RET_FLAG"; if (Inst.isBranch) OS << "|M_BRANCH_FLAG"; if (Inst.isBarrier) OS << "|M_BARRIER_FLAG"; if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG"; if (Inst.isCall) OS << "|M_CALL_FLAG"; if (Inst.isLoad) OS << "|M_LOAD_FLAG"; if (Inst.isStore || isStore) OS << "|M_STORE_FLAG"; if (Inst.isTwoAddress) OS << "|M_2_ADDR_FLAG"; if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR"; if (Inst.isCommutable) OS << "|M_COMMUTABLE"; if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG"; if (Inst.usesCustomDAGSchedInserter) OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION"; if (Inst.hasVariableNumberOfOperands) OS << "|M_VARIABLE_OPS"; OS << ", 0"; // Emit all of the target-specific flags... ListInit *LI = InstrInfo->getValueAsListInit("TSFlagsFields"); ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts"); if (LI->getSize() != Shift->getSize()) throw "Lengths of " + InstrInfo->getName() + ":(TargetInfoFields, TargetInfoPositions) must be equal!"; for (unsigned i = 0, e = LI->getSize(); i != e; ++i) emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)), dynamic_cast<IntInit*>(Shift->getElement(i)), OS); OS << ", "; // Emit the implicit uses and defs lists... std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses"); if (UseList.empty()) OS << "EmptyImpList, "; else OS << "ImplicitList" << EmittedLists[UseList] << ", "; std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs"); if (DefList.empty()) OS << "EmptyImpList, "; else OS << "ImplicitList" << EmittedLists[DefList] << ", "; // Emit the operand info. std::vector<Record*> OperandInfo = GetOperandInfo(Inst); if (OperandInfo.empty()) OS << "0"; else OS << "OperandInfo" << OpInfo[OperandInfo]; OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n"; } struct LessRecord { bool operator()(const Record *Rec1, const Record *Rec2) const { return Rec1->getName() < Rec2->getName(); } }; void InstrInfoEmitter::GatherItinClasses() { std::vector<Record*> DefList = Records.getAllDerivedDefinitions("InstrItinClass"); IsItineraries = !DefList.empty(); if (!IsItineraries) return; std::sort(DefList.begin(), DefList.end(), LessRecord()); for (unsigned i = 0, N = DefList.size(); i < N; i++) { Record *Def = DefList[i]; ItinClassMap[Def->getName()] = i; } } unsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) { return ItinClassMap[ItinName]; } void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val, IntInit *ShiftInt, std::ostream &OS) { if (Val == 0 || ShiftInt == 0) throw std::string("Illegal value or shift amount in TargetInfo*!"); RecordVal *RV = R->getValue(Val->getValue()); int Shift = ShiftInt->getValue(); if (RV == 0 || RV->getValue() == 0) { // This isn't an error if this is a builtin instruction. if (R->getName() != "PHI" && R->getName() != "INLINEASM") throw R->getName() + " doesn't have a field named '" + Val->getValue() + "'!"; return; } Init *Value = RV->getValue(); if (BitInit *BI = dynamic_cast<BitInit*>(Value)) { if (BI->getValue()) OS << "|(1<<" << Shift << ")"; return; } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) { // Convert the Bits to an integer to print... Init *I = BI->convertInitializerTo(new IntRecTy()); if (I) if (IntInit *II = dynamic_cast<IntInit*>(I)) { if (II->getValue()) { if (Shift) OS << "|(" << II->getValue() << "<<" << Shift << ")"; else OS << "|" << II->getValue(); } return; } } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) { if (II->getValue()) { if (Shift) OS << "|(" << II->getValue() << "<<" << Shift << ")"; else OS << II->getValue(); } return; } std::cerr << "Unhandled initializer: " << *Val << "\n"; throw "In record '" + R->getName() + "' for TSFlag emission."; } <commit_msg>Eliminate data relocations by using NULL instead of global empty list.<commit_after>//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend is responsible for emitting a description of the target // instruction set for the code generator. // //===----------------------------------------------------------------------===// #include "InstrInfoEmitter.h" #include "CodeGenTarget.h" #include "Record.h" #include <algorithm> using namespace llvm; // runEnums - Print out enum values for all of the instructions. void InstrInfoEmitter::runEnums(std::ostream &OS) { EmitSourceFileHeader("Target Instruction Enum Values", OS); OS << "namespace llvm {\n\n"; CodeGenTarget Target; // We must emit the PHI opcode first... std::string Namespace; for (CodeGenTarget::inst_iterator II = Target.inst_begin(), E = Target.inst_end(); II != E; ++II) { if (II->second.Namespace != "TargetInstrInfo") { Namespace = II->second.Namespace; break; } } if (Namespace.empty()) { std::cerr << "No instructions defined!\n"; exit(1); } std::vector<const CodeGenInstruction*> NumberedInstructions; Target.getInstructionsByEnumValue(NumberedInstructions); OS << "namespace " << Namespace << " {\n"; OS << " enum {\n"; for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { OS << " " << NumberedInstructions[i]->TheDef->getName() << "\t= " << i << ",\n"; } OS << " INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n"; OS << " };\n}\n"; OS << "} // End llvm namespace \n"; } void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses, unsigned Num, std::ostream &OS) const { OS << "static const unsigned ImplicitList" << Num << "[] = { "; for (unsigned i = 0, e = Uses.size(); i != e; ++i) OS << getQualifiedName(Uses[i]) << ", "; OS << "0 };\n"; } static std::vector<Record*> GetOperandInfo(const CodeGenInstruction &Inst) { std::vector<Record*> Result; for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) { if (Inst.OperandList[i].Rec->isSubClassOf("RegisterClass")) { Result.push_back(Inst.OperandList[i].Rec); } else { // This might be a multiple operand thing. // Targets like X86 have registers in their multi-operand operands. DagInit *MIOI = Inst.OperandList[i].MIOperandInfo; unsigned NumDefs = MIOI->getNumArgs(); for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) { if (NumDefs <= j) { Result.push_back(0); } else { DefInit *Def = dynamic_cast<DefInit*>(MIOI->getArg(j)); Result.push_back(Def ? Def->getDef() : 0); } } } } return Result; } // run - Emit the main instruction description records for the target... void InstrInfoEmitter::run(std::ostream &OS) { GatherItinClasses(); EmitSourceFileHeader("Target Instruction Descriptors", OS); OS << "namespace llvm {\n\n"; CodeGenTarget Target; const std::string &TargetName = Target.getName(); Record *InstrInfo = Target.getInstructionSet(); // Keep track of all of the def lists we have emitted already. std::map<std::vector<Record*>, unsigned> EmittedLists; unsigned ListNumber = 0; // Emit all of the instruction's implicit uses and defs. for (CodeGenTarget::inst_iterator II = Target.inst_begin(), E = Target.inst_end(); II != E; ++II) { Record *Inst = II->second.TheDef; std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses"); if (!Uses.empty()) { unsigned &IL = EmittedLists[Uses]; if (!IL) printDefList(Uses, IL = ++ListNumber, OS); } std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs"); if (!Defs.empty()) { unsigned &IL = EmittedLists[Defs]; if (!IL) printDefList(Defs, IL = ++ListNumber, OS); } } std::map<std::vector<Record*>, unsigned> OperandInfosEmitted; unsigned OperandListNum = 0; OperandInfosEmitted[std::vector<Record*>()] = ++OperandListNum; // Emit all of the operand info records. OS << "\n"; for (CodeGenTarget::inst_iterator II = Target.inst_begin(), E = Target.inst_end(); II != E; ++II) { std::vector<Record*> OperandInfo = GetOperandInfo(II->second); unsigned &N = OperandInfosEmitted[OperandInfo]; if (N == 0) { N = ++OperandListNum; OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { "; for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i) { Record *RC = OperandInfo[i]; // FIXME: We only care about register operands for now. if (RC && RC->isSubClassOf("RegisterClass")) OS << "{ " << getQualifiedName(RC) << "RegClassID, 0 }, "; else if (RC && RC->getName() == "ptr_rc") // Ptr value whose register class is resolved via callback. OS << "{ 0, 1 }, "; else OS << "{ 0, 0 }, "; } OS << "};\n"; } } // Emit all of the TargetInstrDescriptor records in their ENUM ordering. // OS << "\nstatic const TargetInstrDescriptor " << TargetName << "Insts[] = {\n"; std::vector<const CodeGenInstruction*> NumberedInstructions; Target.getInstructionsByEnumValue(NumberedInstructions); for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists, OperandInfosEmitted, OS); OS << "};\n"; OS << "} // End llvm namespace \n"; } void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num, Record *InstrInfo, std::map<std::vector<Record*>, unsigned> &EmittedLists, std::map<std::vector<Record*>, unsigned> &OpInfo, std::ostream &OS) { int MinOperands; if (!Inst.OperandList.empty()) // Each logical operand can be multiple MI operands. MinOperands = Inst.OperandList.back().MIOperandNo + Inst.OperandList.back().MINumOperands; else MinOperands = 0; OS << " { \""; if (Inst.Name.empty()) OS << Inst.TheDef->getName(); else OS << Inst.Name; unsigned ItinClass = !IsItineraries ? 0 : ItinClassNumber(Inst.TheDef->getValueAsDef("Itinerary")->getName()); OS << "\",\t" << MinOperands << ", " << ItinClass << ", 0"; // Try to determine (from the pattern), if the instruction is a store. bool isStore = false; if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) { ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern"); if (LI && LI->getSize() > 0) { DagInit *Dag = (DagInit *)LI->getElement(0); DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator()); if (OpDef) { Record *Operator = OpDef->getDef(); if (Operator->isSubClassOf("SDNode")) { const std::string Opcode = Operator->getValueAsString("Opcode"); if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE") isStore = true; } } } } // Emit all of the target indepedent flags... if (Inst.isReturn) OS << "|M_RET_FLAG"; if (Inst.isBranch) OS << "|M_BRANCH_FLAG"; if (Inst.isBarrier) OS << "|M_BARRIER_FLAG"; if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG"; if (Inst.isCall) OS << "|M_CALL_FLAG"; if (Inst.isLoad) OS << "|M_LOAD_FLAG"; if (Inst.isStore || isStore) OS << "|M_STORE_FLAG"; if (Inst.isTwoAddress) OS << "|M_2_ADDR_FLAG"; if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR"; if (Inst.isCommutable) OS << "|M_COMMUTABLE"; if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG"; if (Inst.usesCustomDAGSchedInserter) OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION"; if (Inst.hasVariableNumberOfOperands) OS << "|M_VARIABLE_OPS"; OS << ", 0"; // Emit all of the target-specific flags... ListInit *LI = InstrInfo->getValueAsListInit("TSFlagsFields"); ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts"); if (LI->getSize() != Shift->getSize()) throw "Lengths of " + InstrInfo->getName() + ":(TargetInfoFields, TargetInfoPositions) must be equal!"; for (unsigned i = 0, e = LI->getSize(); i != e; ++i) emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)), dynamic_cast<IntInit*>(Shift->getElement(i)), OS); OS << ", "; // Emit the implicit uses and defs lists... std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses"); if (UseList.empty()) OS << "NULL, "; else OS << "ImplicitList" << EmittedLists[UseList] << ", "; std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs"); if (DefList.empty()) OS << "NULL, "; else OS << "ImplicitList" << EmittedLists[DefList] << ", "; // Emit the operand info. std::vector<Record*> OperandInfo = GetOperandInfo(Inst); if (OperandInfo.empty()) OS << "0"; else OS << "OperandInfo" << OpInfo[OperandInfo]; OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n"; } struct LessRecord { bool operator()(const Record *Rec1, const Record *Rec2) const { return Rec1->getName() < Rec2->getName(); } }; void InstrInfoEmitter::GatherItinClasses() { std::vector<Record*> DefList = Records.getAllDerivedDefinitions("InstrItinClass"); IsItineraries = !DefList.empty(); if (!IsItineraries) return; std::sort(DefList.begin(), DefList.end(), LessRecord()); for (unsigned i = 0, N = DefList.size(); i < N; i++) { Record *Def = DefList[i]; ItinClassMap[Def->getName()] = i; } } unsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) { return ItinClassMap[ItinName]; } void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val, IntInit *ShiftInt, std::ostream &OS) { if (Val == 0 || ShiftInt == 0) throw std::string("Illegal value or shift amount in TargetInfo*!"); RecordVal *RV = R->getValue(Val->getValue()); int Shift = ShiftInt->getValue(); if (RV == 0 || RV->getValue() == 0) { // This isn't an error if this is a builtin instruction. if (R->getName() != "PHI" && R->getName() != "INLINEASM") throw R->getName() + " doesn't have a field named '" + Val->getValue() + "'!"; return; } Init *Value = RV->getValue(); if (BitInit *BI = dynamic_cast<BitInit*>(Value)) { if (BI->getValue()) OS << "|(1<<" << Shift << ")"; return; } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) { // Convert the Bits to an integer to print... Init *I = BI->convertInitializerTo(new IntRecTy()); if (I) if (IntInit *II = dynamic_cast<IntInit*>(I)) { if (II->getValue()) { if (Shift) OS << "|(" << II->getValue() << "<<" << Shift << ")"; else OS << "|" << II->getValue(); } return; } } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) { if (II->getValue()) { if (Shift) OS << "|(" << II->getValue() << "<<" << Shift << ")"; else OS << II->getValue(); } return; } std::cerr << "Unhandled initializer: " << *Val << "\n"; throw "In record '" + R->getName() + "' for TSFlag emission."; } <|endoftext|>
<commit_before>#ifndef __UTIL_SMARTBYTEARRAY_HPP__ #define __UTIL_SMARTBYTEARRAY_HPP__ #include <memory> namespace FreshCask { class SmartByteArray { public: SmartByteArray() : data(nullptr), size(0) {} SmartByteArray(const uint32_t& size) : data(new Byte[size]), size(size) {} SmartByteArray(const std::string& str) : data(new Byte[str.length()]), size(str.length()) { memcpy(Data(), &str[0], str.length()); } SmartByteArray(const char* str) { new (this) SmartByteArray(std::string(str)); } SmartByteArray(const BytePtr ptr, const uint32_t& size) : data(ptr, senderAllocDeleter()), size(size) {} std::string ToString() const { if (Data() != nullptr) return std::string(reinterpret_cast<char*>(Data()), Size()); else return std::string(); } BytePtr Data() const { return data.get(); } uint32_t Size() const { return size; } bool IsNull() { return size == 0 || data == nullptr; } static SmartByteArray Null() { return SmartByteArray(); } friend bool operator<(const SmartByteArray& lhs, const SmartByteArray& rhs) { size_t len = min(lhs.Size(), rhs.Size()); int cmp = memcmp(lhs.Data(), rhs.Data(), len); if (cmp != 0) return cmp < 0; else return lhs.Size() - rhs.Size() < 0; /*if (lhs.Size() < rhs.Size()) return true; else if (lhs.Size() > rhs.Size()) return false; else return memcmp(lhs.Data(), rhs.Data(), lhs.Size()) < 0;*/ } private: struct senderAllocDeleter { // tricky, avoid being deleted by std::shared_ptr void operator()(BytePtr) { /* do nothing */ } }; private: std::shared_ptr<Byte> data; uint32_t size; }; } // namespace FreshCask #endif // __UTIL_SMARTBYTEARRAY_HPP__<commit_msg>Roll back to ToString<commit_after>#ifndef __UTIL_SMARTBYTEARRAY_HPP__ #define __UTIL_SMARTBYTEARRAY_HPP__ #include <memory> namespace FreshCask { class SmartByteArray { public: SmartByteArray() : data(nullptr), size(0) {} SmartByteArray(const uint32_t& size) : data(new Byte[size]), size(size) {} SmartByteArray(const std::string& str) : data(new Byte[str.length()]), size(str.length()) { memcpy(Data(), &str[0], str.length()); } SmartByteArray(const char* str) { new (this) SmartByteArray(std::string(str)); } SmartByteArray(const BytePtr ptr, const uint32_t& size) : data(ptr, senderAllocDeleter()), size(size) {} std::string ToString() const { if (Data() != nullptr) return std::string(reinterpret_cast<char*>(Data()), Size()); else return std::string(); } BytePtr Data() const { return data.get(); } uint32_t Size() const { return size; } bool IsNull() { return size == 0 || data == nullptr; } static SmartByteArray Null() { return SmartByteArray(); } friend bool operator<(const SmartByteArray& lhs, const SmartByteArray& rhs) { return lhs.ToString() < rhs.ToString(); } private: struct senderAllocDeleter { // tricky, avoid being deleted by std::shared_ptr void operator()(BytePtr) { /* do nothing */ } }; private: std::shared_ptr<Byte> data; uint32_t size; }; } // namespace FreshCask #endif // __UTIL_SMARTBYTEARRAY_HPP__<|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: AbstractPathPoint.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * * * 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include "AbstractPathPoint.h" //============================================================================= // STATICS //============================================================================= using namespace std; using namespace OpenSim; using SimTK::Vec3; using SimTK::Transform; const PhysicalFrame& AbstractPathPoint::getParentFrame() const { return getSocket<PhysicalFrame>("parent_frame").getConnectee(); } void AbstractPathPoint::setParentFrame(const OpenSim::PhysicalFrame& frame) { connectSocket_parent_frame(frame); } const PhysicalFrame& AbstractPathPoint::getBody() const { return getParentFrame(); } void AbstractPathPoint::setBody(const PhysicalFrame& body) { setParentFrame(body); } const std::string& AbstractPathPoint::getBodyName() const { return getParentFrame().getName(); } // PathPoint used to be the base class for all path points including // MovingPathPoints, which was incorrect. AbstractPathPoint was added to // the hierarchy to resolve that issue and since the updateFromXML code // still pertains to all PathPoints was included here in AbstractPathPoint // If derived classes have to override for future changes, do not // forget to invoke Super::updateFromXMLNode. void AbstractPathPoint::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber) { int documentVersion = versionNumber; if (documentVersion < XMLDocument::getLatestVersion()) { if (documentVersion < 30505) { // replace old properties with latest use of Connectors SimTK::Xml::element_iterator bodyElement = aNode.element_begin("body"); std::string bodyName(""); if (bodyElement != aNode.element_end()) { bodyElement->getValueAs<std::string>(bodyName); // PathPoints in pre-4.0 models are necessarily 3 levels deep // (model, muscle, geometry path), and Bodies are // necessarily 1 levels deep; here we create the correct // relative path (accounting for sets being components). bodyName = XMLDocument::updateConnecteePath30517("bodyset", bodyName); XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_", "parent_frame", bodyName); } } } Super::updateFromXMLNode(aNode, versionNumber); } <commit_msg>Changed "parent_frame" string literal for a std::string<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: AbstractPathPoint.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * * * 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include "AbstractPathPoint.h" //============================================================================= // STATICS //============================================================================= using namespace std; using namespace OpenSim; using SimTK::Vec3; using SimTK::Transform; // here for perf reasons: many functions take a const reference to a // std::string. Using a C string literal results in millions of temporary // std::strings being constructed so, instead, pre-allocate it in static // storage static const std::string parentFrameKey{"parent_frame"}; const PhysicalFrame& AbstractPathPoint::getParentFrame() const { return getSocket<PhysicalFrame>(parentFrameKey).getConnectee(); } void AbstractPathPoint::setParentFrame(const OpenSim::PhysicalFrame& frame) { connectSocket_parent_frame(frame); } const PhysicalFrame& AbstractPathPoint::getBody() const { return getParentFrame(); } void AbstractPathPoint::setBody(const PhysicalFrame& body) { setParentFrame(body); } const std::string& AbstractPathPoint::getBodyName() const { return getParentFrame().getName(); } // PathPoint used to be the base class for all path points including // MovingPathPoints, which was incorrect. AbstractPathPoint was added to // the hierarchy to resolve that issue and since the updateFromXML code // still pertains to all PathPoints was included here in AbstractPathPoint // If derived classes have to override for future changes, do not // forget to invoke Super::updateFromXMLNode. void AbstractPathPoint::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber) { int documentVersion = versionNumber; if (documentVersion < XMLDocument::getLatestVersion()) { if (documentVersion < 30505) { // replace old properties with latest use of Connectors SimTK::Xml::element_iterator bodyElement = aNode.element_begin("body"); std::string bodyName(""); if (bodyElement != aNode.element_end()) { bodyElement->getValueAs<std::string>(bodyName); // PathPoints in pre-4.0 models are necessarily 3 levels deep // (model, muscle, geometry path), and Bodies are // necessarily 1 levels deep; here we create the correct // relative path (accounting for sets being components). bodyName = XMLDocument::updateConnecteePath30517("bodyset", bodyName); XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_", parentFrameKey, bodyName); } } } Super::updateFromXMLNode(aNode, versionNumber); } <|endoftext|>
<commit_before>/* vim: set sw=4 ts=4: */ /* * BindingConverter.cpp * Implements an AST Consumer that outputs clay bindings * */ #include <iostream> #include <vector> using namespace std; #include "llvm/Config/config.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "llvm/ADT/Triple.h" #include "BindingsConverter.h" using namespace clang; using namespace llvm; BindingsConverter::BindingsConverter(bool useCTypes, ostream& out) :useCTypes(useCTypes), out(out) { } void BindingsConverter::printHeader() { // Print header string header = "# Auto-Generated by BindingsGenerator\n"; header += "import types.*;\n"; header += "import operators.*;\n"; header += "import numbers.*;\n"; header += "import pointers.*;\n"; out << header; } void BindingsConverter::printFooter() { } // Print a variable in clay void BindingsConverter::printVarDecl(const VarDecl*& D) { out << "external "; out << D->getNameAsString(); QualType type = D->getType(); // The return value if(useCTypes) { out << " : " << type.getAsString() << ";\n"; } else { out << " : " << printType(convert(type)) << ";\n"; } } // Print a function in clay void BindingsConverter::printFuncDecl(const FunctionDecl*& D) { out << "external "; out << D->getNameAsString() << " (\n"; int numParams = D->param_size(); for( int i = 0 ; i < numParams ; i ++ ) { const ParmVarDecl * param = D->getParamDecl(i); // Parameter number i const string name = param -> getNameAsString(); if(name != "") out << "\t" << name << " : "; else out << "\t" << "argument_" << i + 1<< " : "; QualType cType = param->getOriginalType(); if(useCTypes) { out << cType.getAsString(); } else { out << printType(convert(cType)); } if (i+1 < numParams) out << ","; out << "\n"; } QualType ret = D->getResultType(); // The return value if(useCTypes) { out << ") : " << ret.getAsString() << ";\n"; } else { out << ") : " << printType(convert(ret)) << ";\n"; } } // Print a enum in clay void BindingsConverter::printEnumDecl(const EnumDecl*& D) { for(EnumDecl::enumerator_iterator it = D->enumerator_begin(); it != D->enumerator_end(); it++) { EnumConstantDecl* CD = *it; out << "static " << CD->getNameAsString() << " = " ; out << CD->getInitVal().getLimitedValue() << ";\n"; // XXX: Warning, this limits enum values to 64-bits which is safe, I think } } // Print a record in clay void BindingsConverter::printRecordDecl(const RecordDecl*& D) { out << "record " << D->getNameAsString() << " {\n"; for(RecordDecl::field_iterator it = D->field_begin(); it != D->field_end(); it++) { FieldDecl* FD = *it; QualType type = FD->getType(); out << FD->getNameAsString(); if(useCTypes) { out << " : " << type.getAsString() << ";\n"; } else { out << " : " << printType(convert(type)) << ";\n"; } } out << "}\n"; } QualType& BindingsConverter::convert(QualType& cType) { return cType; } string BindingsConverter::printType(const QualType& qtype) { Type& type = *qtype; if(type.isBooleanType()) { return "Bool"; } else if(type.isSignedIntegerType()){ return "Int"; } else if(type.isUnsignedIntegerType()){ return "UInt"; } else if(type.isRealFloatingType()) { return "Float"; } else if(type.isPointerType()) { PointerType& type_ = (PointerType&)type; QualType qtype_ = type_.getPointeeType(); if((*qtype_).isFunctionType()) { FunctionProtoType& ftype = (FunctionProtoType&) *qtype_; string typeStr = "CCodePtr["; for(FunctionProtoType::arg_type_iterator it = ftype.arg_type_begin(); it != ftype.arg_type_end(); it++) { QualType qtype = *it; typeStr += printType(qtype); typeStr += ","; } QualType qtype = ftype.getResultType(); typeStr += printType(qtype); typeStr += "]"; return typeStr; } else { if(useCTypes) { return "Pointer[" + qtype_.getAsString() + "]"; } else { return "Pointer[" + printType(qtype_) + "]"; } } } else if(type.isArrayType()) { ArrayType& type_ = (ArrayType&)type; return "Array[" + printType(type_.getElementType()) + "]"; } else if(type.isRecordType()) { // TODO: Handle //case RECORD_TYPE : { // RecordType *x = (RecordType *)t.ptr(); // out << x->record->name->str; // if (!x->params.empty()) // out << x->params; // break; return qtype.getAsString(); } else if(type.isEnumeralType()) { return "Enum"; } else if(type.isVoidType()) { return "Void"; } else{ return "???"; //assert(false); } return "null"; } // Handle top level declarations observed in the program void BindingsConverter::HandleTopLevelDecl(DeclGroupRef DG) { for (DeclGroupRef::iterator it = DG.begin(); it != DG.end(); ++it) { const FunctionDecl *FD = dyn_cast<FunctionDecl>(*it); const VarDecl *VD = dyn_cast<VarDecl>(*it); const EnumDecl *ED = dyn_cast<EnumDecl>(*it); const RecordDecl *RD = dyn_cast<RecordDecl>(*it); if (FD) { printFuncDecl(FD); } else if (VD) { printVarDecl(VD); } else if (ED) { printEnumDecl(ED); } else if (RD) { printRecordDecl(RD); } } } <commit_msg>in bindings generator, generate 'RawPointer' for void pointers, because Pointer[Void] is not a valid type in clay.<commit_after>/* vim: set sw=4 ts=4: */ /* * BindingConverter.cpp * Implements an AST Consumer that outputs clay bindings * */ #include <iostream> #include <vector> using namespace std; #include "llvm/Config/config.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "llvm/ADT/Triple.h" #include "BindingsConverter.h" using namespace clang; using namespace llvm; BindingsConverter::BindingsConverter(bool useCTypes, ostream& out) :useCTypes(useCTypes), out(out) { } void BindingsConverter::printHeader() { // Print header string header = "# Auto-Generated by BindingsGenerator\n"; header += "import types.*;\n"; header += "import operators.*;\n"; header += "import numbers.*;\n"; header += "import pointers.*;\n"; out << header; } void BindingsConverter::printFooter() { } // Print a variable in clay void BindingsConverter::printVarDecl(const VarDecl*& D) { out << "external "; out << D->getNameAsString(); QualType type = D->getType(); // The return value if(useCTypes) { out << " : " << type.getAsString() << ";\n"; } else { out << " : " << printType(convert(type)) << ";\n"; } } // Print a function in clay void BindingsConverter::printFuncDecl(const FunctionDecl*& D) { out << "external "; out << D->getNameAsString() << " (\n"; int numParams = D->param_size(); for( int i = 0 ; i < numParams ; i ++ ) { const ParmVarDecl * param = D->getParamDecl(i); // Parameter number i const string name = param -> getNameAsString(); if(name != "") out << "\t" << name << " : "; else out << "\t" << "argument_" << i + 1<< " : "; QualType cType = param->getOriginalType(); if(useCTypes) { out << cType.getAsString(); } else { out << printType(convert(cType)); } if (i+1 < numParams) out << ","; out << "\n"; } QualType ret = D->getResultType(); // The return value if(useCTypes) { out << ") : " << ret.getAsString() << ";\n"; } else { out << ") : " << printType(convert(ret)) << ";\n"; } } // Print a enum in clay void BindingsConverter::printEnumDecl(const EnumDecl*& D) { for(EnumDecl::enumerator_iterator it = D->enumerator_begin(); it != D->enumerator_end(); it++) { EnumConstantDecl* CD = *it; out << "static " << CD->getNameAsString() << " = " ; out << CD->getInitVal().getLimitedValue() << ";\n"; // XXX: Warning, this limits enum values to 64-bits which is safe, I think } } // Print a record in clay void BindingsConverter::printRecordDecl(const RecordDecl*& D) { out << "record " << D->getNameAsString() << " {\n"; for(RecordDecl::field_iterator it = D->field_begin(); it != D->field_end(); it++) { FieldDecl* FD = *it; QualType type = FD->getType(); out << FD->getNameAsString(); if(useCTypes) { out << " : " << type.getAsString() << ";\n"; } else { out << " : " << printType(convert(type)) << ";\n"; } } out << "}\n"; } QualType& BindingsConverter::convert(QualType& cType) { return cType; } string BindingsConverter::printType(const QualType& qtype) { Type& type = *qtype; if(type.isBooleanType()) { return "Bool"; } else if(type.isSignedIntegerType()){ return "Int"; } else if(type.isUnsignedIntegerType()){ return "UInt"; } else if(type.isRealFloatingType()) { return "Float"; } else if(type.isPointerType()) { PointerType& type_ = (PointerType&)type; QualType qtype_ = type_.getPointeeType(); if((*qtype_).isFunctionType()) { FunctionProtoType& ftype = (FunctionProtoType&) *qtype_; string typeStr = "CCodePtr["; for(FunctionProtoType::arg_type_iterator it = ftype.arg_type_begin(); it != ftype.arg_type_end(); it++) { QualType qtype = *it; typeStr += printType(qtype); typeStr += ","; } QualType qtype = ftype.getResultType(); typeStr += printType(qtype); typeStr += "]"; return typeStr; } else { if (qtype_.isVoidType()) return "RawPointer"; return "Pointer[" + printType(qtype_) + "]"; } } else if(type.isArrayType()) { ArrayType& type_ = (ArrayType&)type; return "Array[" + printType(type_.getElementType()) + "]"; } else if(type.isRecordType()) { // TODO: Handle //case RECORD_TYPE : { // RecordType *x = (RecordType *)t.ptr(); // out << x->record->name->str; // if (!x->params.empty()) // out << x->params; // break; return qtype.getAsString(); } else if(type.isEnumeralType()) { return "Enum"; } else if(type.isVoidType()) { return "Void"; } else{ return "???"; //assert(false); } return "null"; } // Handle top level declarations observed in the program void BindingsConverter::HandleTopLevelDecl(DeclGroupRef DG) { for (DeclGroupRef::iterator it = DG.begin(); it != DG.end(); ++it) { const FunctionDecl *FD = dyn_cast<FunctionDecl>(*it); const VarDecl *VD = dyn_cast<VarDecl>(*it); const EnumDecl *ED = dyn_cast<EnumDecl>(*it); const RecordDecl *RD = dyn_cast<RecordDecl>(*it); if (FD) { printFuncDecl(FD); } else if (VD) { printVarDecl(VD); } else if (ED) { printEnumDecl(ED); } else if (RD) { printRecordDecl(RD); } } } <|endoftext|>
<commit_before>#include "StdAfx.h" #include "RndPointSet.h" RndPointSet::RndPointSet(void) { } RndPointSet::~RndPointSet(void) { } void RndPointSet::DrawPoints( const CRhinoCommandContext& context, int numPoints ) { // Pick a surface to evaluate CRhinoGetObject go; go.SetCommandPrompt( L"Select surface to evaluate " ); go.SetGeometryFilter( CRhinoGetObject::surface_object); go.GetObjects( 1, 1 ); // Get the surface geometry const CRhinoObjRef& ref = go.Object(0); if(ref == NULL) { RhinoApp().Print(L"reference initialization error"); return ; } const ON_Surface* obj = ref.Surface(); if(obj == NULL) { RhinoApp().Print(L"object initialization error"); return ; } double u1, u2, v1, v2; if(obj->GetDomain(0, &u1, &u2) && obj->GetDomain(1, &v1, &v2)) { int i; for(i = 0; i < numPoints; i++) { ON_3dPoint p0 = obj->PointAt( fRand(u1, u2), fRand(v1, v2)); //context.m_doc.AddPointObject(p0); //RhinoApp().Print(L"p0.x = %f\n",p0.x); //RhinoApp().Print(L"p0.y = %f\n",p0.y); //RhinoApp().Print(L"p0.z = %f\n",p0.z); double u, v = 0.0; //the following might be redundant obj->GetClosestPoint(p0, &u, &v); //RhinoApp().Print(L"p0.u = %f\n",u); //RhinoApp().Print(L"p0.v = %f\n",v); ON_3dPoint p1 = obj->PointAt( u, v); context.m_doc.AddPointObject(p1); } context.m_doc.Redraw(); } else { RhinoApp().Print(L"object domain error"); return ; } } void RndPointSet::Test( const CRhinoCommandContext& context, double a, double b, double c, double d ) { // Pick a surface to evaluate CRhinoGetObject go; go.SetCommandPrompt( L"Select surface to evaluate - test function" ); go.SetGeometryFilter( CRhinoGetObject::surface_object); go.GetObjects( 1, 1 ); // Get the surface geometry const CRhinoObjRef& ref = go.Object(0); const ON_Surface* obj = ref.Surface(); ON_3dPoint p0 = obj->PointAt( a, b); double u, v; obj->GetClosestPoint(p0, &u, &v); ON_3dPoint p1 = obj->PointAt( u, v); context.m_doc.AddPointObject(p1); context.m_doc.Redraw(); } double RndPointSet::fRand(double fMin, double fMax) { double f = (double)rand() / RAND_MAX; return fMin + f * (fMax - fMin); }<commit_msg>Revert "fixed the issue with points out of bounds."<commit_after>#include "StdAfx.h" #include "RndPointSet.h" RndPointSet::RndPointSet(void) { } RndPointSet::~RndPointSet(void) { } void RndPointSet::DrawPoints( const CRhinoCommandContext& context, int numPoints ) { // Pick a surface to evaluate CRhinoGetObject go; go.SetCommandPrompt( L"Select surface to evaluate" ); go.SetGeometryFilter( CRhinoGetObject::surface_object); go.GetObjects( 1, 1 ); // Get the surface geometry const CRhinoObjRef& ref = go.Object(0); const ON_Surface* obj = ref.Surface(); double u1, u2, v1, v2; if(obj->GetDomain(0, &u1, &u2) && obj->GetDomain(0, &v1, &v2)) { int i; for(i = 0; i < numPoints; i++) { ON_3dPoint p0 = obj->PointAt( fRand(u1, u2), fRand(v1, v2)); double u, v; obj->GetClosestPoint(p0, &u, &v); ON_3dPoint p1 = obj->PointAt( u, v); context.m_doc.AddPointObject(p1); } context.m_doc.Redraw(); } //this is drawing things outside the bounding box for some reason } void RndPointSet::Test( const CRhinoCommandContext& context, double a, double b, double c, double d ) { // Pick a surface to evaluate CRhinoGetObject go; go.SetCommandPrompt( L"Select surface to evaluate - test function" ); go.SetGeometryFilter( CRhinoGetObject::surface_object); go.GetObjects( 1, 1 ); // Get the surface geometry const CRhinoObjRef& ref = go.Object(0); const ON_Surface* obj = ref.Surface(); ON_3dPoint p0 = obj->PointAt( a, b); double u, v; obj->GetClosestPoint(p0, &u, &v); ON_3dPoint p1 = obj->PointAt( u, v); context.m_doc.AddPointObject(p1); context.m_doc.Redraw(); } double RndPointSet::fRand(double fMin, double fMax) { double f = (double)rand() / RAND_MAX; return fMin + f * (fMax - fMin); }<|endoftext|>
<commit_before>#include "Physics.hpp" #include "PhysicEngine.hpp" Physics::Physics() : Component(), m_growth(sf::Vector2f(1, 1) ) { } Physics::~Physics() { } void Physics::update() { // PhysicEngine::update(this); } void Physics::setVelocity(const sf::Vector2f& values ) { m_velocity = values; } sf::Vector2f Physics::getVelocity() const{ return m_velocity; } void Physics::setRotationForce(const float& value ) { m_rotationForce = value; } float Physics::getRotationForce() const{ return m_rotationForce; } void Physics::setGrowth(const sf::Vector2f& values ) { m_growth += values; } sf::Vector2f Physics::getGrowth() const{ return m_growth; } void Physics::setAcceleration(const sf::Vector2f& value ) { m_acceleration = value; } sf::Vector2f Physics::getAcceleration() const{ return m_acceleration; } void Physics::setRotationAcceleration(const float& value ) { m_rotationAcc = value; } float Physics::getRotationAcceleration() const{ return m_rotationAcc; } void Physics::setGrowthAcceleration(const sf::Vector2f& value ) { m_growthAcc = value; } sf::Vector2f Physics::getGrowthAcceleration() const{ return m_growthAcc; } void Physics::setMass(const double& value ) { m_mass = value; } double Physics::getMass() const{ return m_mass; } void Physics::addMass(const double& value ) { m_mass += value; } /** * adds values to velocity */ void Physics::addVelocity(const sf::Vector2f& values ) { m_velocity += values; } /** acceleration adds to velocity on each frame */ void Physics::addAcceleration(const sf::Vector2f& value ) { m_acceleration += value; } /** adds value to rotation force */ void Physics::addRotationForce(const float& value ) { m_rotationForce += value; } void Physics::addRotationAcceleration(const float& value ) { m_rotationAcc += value; } /** adds value to growth force */ void Physics::addGrowth(const sf::Vector2f& values ) { m_growth += values; } void Physics::addGrowthAcceleration(const sf::Vector2f& values ) { m_growthAcc += values; } <commit_msg>Fixed setGrowth<commit_after>#include "Physics.hpp" #include "PhysicEngine.hpp" Physics::Physics() : Component(), m_growth(sf::Vector2f(1, 1) ) { } Physics::~Physics() { } void Physics::update() { // PhysicEngine::update(this); } void Physics::setVelocity(const sf::Vector2f& values ) { m_velocity = values; } sf::Vector2f Physics::getVelocity() const{ return m_velocity; } void Physics::setRotationForce(const float& value ) { m_rotationForce = value; } float Physics::getRotationForce() const{ return m_rotationForce; } void Physics::setGrowth(const sf::Vector2f& values ) { m_growth = values; } sf::Vector2f Physics::getGrowth() const{ return m_growth; } void Physics::setAcceleration(const sf::Vector2f& value ) { m_acceleration = value; } sf::Vector2f Physics::getAcceleration() const{ return m_acceleration; } void Physics::setRotationAcceleration(const float& value ) { m_rotationAcc = value; } float Physics::getRotationAcceleration() const{ return m_rotationAcc; } void Physics::setGrowthAcceleration(const sf::Vector2f& value ) { m_growthAcc = value; } sf::Vector2f Physics::getGrowthAcceleration() const{ return m_growthAcc; } void Physics::setMass(const double& value ) { m_mass = value; } double Physics::getMass() const{ return m_mass; } void Physics::addMass(const double& value ) { m_mass += value; } /** * adds values to velocity */ void Physics::addVelocity(const sf::Vector2f& values ) { m_velocity += values; } /** acceleration adds to velocity on each frame */ void Physics::addAcceleration(const sf::Vector2f& value ) { m_acceleration += value; } /** adds value to rotation force */ void Physics::addRotationForce(const float& value ) { m_rotationForce += value; } void Physics::addRotationAcceleration(const float& value ) { m_rotationAcc += value; } /** adds value to growth force */ void Physics::addGrowth(const sf::Vector2f& values ) { m_growth += values; } void Physics::addGrowthAcceleration(const sf::Vector2f& values ) { m_growthAcc += values; } <|endoftext|>
<commit_before>#include <iostream> #include "TAxis.h" #include "Corrector.h" ClassImp(Corrector) //-------------------------------------------------------------------- Corrector::Corrector(TString name) : fName(name), fInTree(NULL), fCorrectionFile(NULL), fCorrectionHist(NULL), fNumDims(0), fInCut('1'), fCutFormula(NULL) { fInExpressions.resize(0); fFormulas.resize(0); fMins.resize(0); fMaxs.resize(0); } //-------------------------------------------------------------------- Corrector::~Corrector() { if (fCorrectionFile != NULL) { if (fCorrectionFile->IsOpen()) fCorrectionFile->Close(); } if (fCutFormula != NULL) delete fCutFormula; for (UInt_t iFormula = 0; iFormula != fFormulas.size(); ++iFormula) delete fFormulas[iFormula]; } //-------------------------------------------------------------------- void Corrector::SetCorrectionHist(TString hist1, TString hist2) { fCorrectionHist = (TH1*) fCorrectionFile->Get(hist1); TH1* divisorHist = (TH1*) fCorrectionFile->Get(hist2); fCorrectionHist->Divide(divisorHist); SetMinMax(); } //-------------------------------------------------------------------- Double_t Corrector::GetFormulaResult(Int_t index) { Double_t eval = fFormulas[index]->EvalInstance(); if (eval < fMins[index]) eval = fMins[index]; else if (eval > fMaxs[index]) eval = fMaxs[index]; return eval; } //-------------------------------------------------------------------- Float_t Corrector::Evaluate() { if (fInTree == NULL) return 1.0; else { if (fCutFormula->EvalInstance() != 0) { if (fNumDims == 1) { Double_t evalX = GetFormulaResult(0); return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX)); } else if (fNumDims == 2) { Double_t evalX = GetFormulaResult(0); Double_t evalY = GetFormulaResult(1); return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX), fCorrectionHist->FindBin(evalY)); } else if (fNumDims == 3) { Double_t evalX = GetFormulaResult(0); Double_t evalY = GetFormulaResult(1); Double_t evalZ = GetFormulaResult(2); return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX), fCorrectionHist->FindBin(evalY), fCorrectionHist->FindBin(evalZ)); } else return 1.0; } else return 1.0; } } //-------------------------------------------------------------------- void Corrector::InitializeTree() { if (fCutFormula) delete fCutFormula; fCutFormula = new TTreeFormula(fInCut,fInCut,fInTree); if (fFormulas.size() != 0) { for (UInt_t iFormula = 0; iFormula != fFormulas.size(); ++iFormula) delete fFormulas[iFormula]; fFormulas.resize(0); } TTreeFormula* tempFormula; for (UInt_t iExpression = 0; iExpression != fInExpressions.size(); ++iExpression) { tempFormula = new TTreeFormula(fInExpressions[iExpression],fInExpressions[iExpression],fInTree); fFormulas.push_back(tempFormula); } } //-------------------------------------------------------------------- void Corrector::SetMinMax() { for (Int_t iDim = 0; iDim != fNumDims; ++iDim) { TAxis* theAxis; if (iDim == 0) theAxis = fCorrectionHist->GetXaxis(); else if (iDim == 1) theAxis = fCorrectionHist->GetYaxis(); else if (iDim == 2) theAxis = fCorrectionHist->GetZaxis(); else { std::cout << "I don't support this many axes at the moment." << std::endl; exit(3); } fMins.push_back(theAxis->GetBinLowEdge(theAxis->GetFirst())); fMaxs.push_back(theAxis->GetBinUpEdge(theAxis->GetLast())); } } <commit_msg>Changed min max to ensure placement in bins.<commit_after>#include <iostream> #include "TAxis.h" #include "Corrector.h" ClassImp(Corrector) //-------------------------------------------------------------------- Corrector::Corrector(TString name) : fName(name), fInTree(NULL), fCorrectionFile(NULL), fCorrectionHist(NULL), fNumDims(0), fInCut('1'), fCutFormula(NULL) { fInExpressions.resize(0); fFormulas.resize(0); fMins.resize(0); fMaxs.resize(0); } //-------------------------------------------------------------------- Corrector::~Corrector() { if (fCorrectionFile != NULL) { if (fCorrectionFile->IsOpen()) fCorrectionFile->Close(); } if (fCutFormula != NULL) delete fCutFormula; for (UInt_t iFormula = 0; iFormula != fFormulas.size(); ++iFormula) delete fFormulas[iFormula]; } //-------------------------------------------------------------------- void Corrector::SetCorrectionHist(TString hist1, TString hist2) { fCorrectionHist = (TH1*) fCorrectionFile->Get(hist1); TH1* divisorHist = (TH1*) fCorrectionFile->Get(hist2); fCorrectionHist->Divide(divisorHist); SetMinMax(); } //-------------------------------------------------------------------- Double_t Corrector::GetFormulaResult(Int_t index) { Double_t eval = fFormulas[index]->EvalInstance(); if (eval < fMins[index]) eval = fMins[index]; else if (eval > fMaxs[index]) eval = fMaxs[index]; return eval; } //-------------------------------------------------------------------- Float_t Corrector::Evaluate() { if (fInTree == NULL) return 1.0; else { if (fCutFormula->EvalInstance() != 0) { if (fNumDims == 1) { Double_t evalX = GetFormulaResult(0); return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX)); } else if (fNumDims == 2) { Double_t evalX = GetFormulaResult(0); Double_t evalY = GetFormulaResult(1); return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX), fCorrectionHist->FindBin(evalY)); } else if (fNumDims == 3) { Double_t evalX = GetFormulaResult(0); Double_t evalY = GetFormulaResult(1); Double_t evalZ = GetFormulaResult(2); return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX), fCorrectionHist->FindBin(evalY), fCorrectionHist->FindBin(evalZ)); } else return 1.0; } else return 1.0; } } //-------------------------------------------------------------------- void Corrector::InitializeTree() { if (fCutFormula) delete fCutFormula; fCutFormula = new TTreeFormula(fInCut,fInCut,fInTree); if (fFormulas.size() != 0) { for (UInt_t iFormula = 0; iFormula != fFormulas.size(); ++iFormula) delete fFormulas[iFormula]; fFormulas.resize(0); } TTreeFormula* tempFormula; for (UInt_t iExpression = 0; iExpression != fInExpressions.size(); ++iExpression) { tempFormula = new TTreeFormula(fInExpressions[iExpression],fInExpressions[iExpression],fInTree); fFormulas.push_back(tempFormula); } } //-------------------------------------------------------------------- void Corrector::SetMinMax() { for (Int_t iDim = 0; iDim != fNumDims; ++iDim) { TAxis* theAxis; if (iDim == 0) theAxis = fCorrectionHist->GetXaxis(); else if (iDim == 1) theAxis = fCorrectionHist->GetYaxis(); else if (iDim == 2) theAxis = fCorrectionHist->GetZaxis(); else { std::cout << "I don't support this many axes at the moment." << std::endl; exit(3); } fMins.push_back(theAxis->GetBinCenter(theAxis->GetFirst())); fMaxs.push_back(theAxis->GetBinCenter(theAxis->GetLast())); } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // Macro to setup AliPerformanceTask for // TPC performance QA to run on PWGPP QA train. // // Input: ESDs, ESDfriends (optional), Kinematics (optional), TrackRefs (optional) // ESD and MC input handlers must be attached to AliAnalysisManager // to run default configuration. // // By default 1 performance components are added to // the task: // 0. AliPerformanceTPC (TPC cluster and track and event information) // 1. AliPerformanceMatch (TPC and ITS/TRD matching and TPC eff w.r.t ITS) // 2. AliPerformanceMatch (TPC and ITS/TRD matching and TPC eff w.r.t TPC) // 3. AliPerformancedEdx (TPC dEdx information) // 4. AliPerformanceRes (TPC track resolution w.r.t MC at DCA) // 5. AliPerformanceEff (TPC track reconstruction efficiency, MC primaries) // 6. AliPerformanceMatch (Comparison of TPC constrain and global tracking) // // Usage on the analysis train (default configuration): // gSystem->Load("libANALYSIS"); // gSystem->Load("libANALYSISalice"); // gSystem->Load("libTPCcalib"); // gSystem->Load("libTender"); // gSystem->Load("libPWGPP"); // // gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/TPC/macros/AddTaskPerformanceTPCdEdxQA.C"); // AliPerformanceTask *tpcQA = AddTaskPerformanceTPCdEdxQA("kFALSE","kTRUE","kFALSE","triggerClass",kFALSE); // // Output: // TPC.Performance.root file with TPC performance components is created. // // Each of the components contains THnSparse generic histograms which // have to be analysed (post-analysis) by using Analyse() function. // Each component contains such function. // //30.09.2010 - J.Otwinowski@gsi.de //22.09.2011 - jochen@thaeder.de - Updated /////////////////////////////////////////////////////////////////////////////// //____________________________________________ AliPerformanceTask* AddTaskPerformanceTPCdEdxQA(Bool_t bUseMCInfo=kFALSE, Bool_t bUseESDfriend=kTRUE, Bool_t highMult = kFALSE, const char *triggerClass=0, Bool_t bUseHLT = kFALSE, Bool_t bUseTOF = kFALSE, Bool_t bTPCTrackingOnly = kFALSE, Bool_t bDoEffTpcSec = kFALSE) { Char_t *taskName[] = {"TPC", "HLT"}; Char_t *taskName2[] = {"", "_Tracking"}; Int_t idx = 0, idx2 = 0; if (bUseHLT) idx = 1; if (bTPCTrackingOnly) idx2 = 1; // // Add AliPerformanceTask with TPC performance components // AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if(!mgr) { Error("AddTaskPerformanceTPCdEdxQA","AliAnalysisManager not set!"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); if (!type.Contains("ESD")) { Error("AddTaskPerformanceTPCdEdxQA", "ESD input handler needed!"); return NULL; } AliMCEventHandler* mchandler = new AliMCEventHandler; mchandler->SetReadTR(kFALSE); mgr->SetMCtruthEventHandler(mchandler); if (!mchandler && bUseMCInfo) { Error("AddTaskPerformanceTPCdEdxQA", "MC input handler needed!"); return NULL; } // // Add HLT Event // if (bUseHLT) { AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*>(mgr->GetInputEventHandler()); esdH->SetReadHLT(); } // // Create task // AliPerformanceTask *task = new AliPerformanceTask("PerformanceQA",Form("%s%s Performance",taskName[idx], taskName2[idx2])); if (!task) { Error("AddTaskPerformanceTPCdEdxQA", Form("%s%s performance task cannot be created!",taskName[idx], taskName2[idx2])); return NULL; } task->SetUseMCInfo(bUseMCInfo); task->SetUseESDfriend(bUseESDfriend); // task->SetUseTerminate(kFALSE); task->SetUseHLT(bUseHLT); // // Add task to analysis manager // mgr->AddTask(task); // // Create TPC-ESD track reconstruction cuts // MB tracks // AliRecInfoCuts *pRecInfoCutsTPC = new AliRecInfoCuts("pRecInfoCutsTPC"); if(pRecInfoCutsTPC) { pRecInfoCutsTPC->SetMaxDCAToVertexXY(3.0); pRecInfoCutsTPC->SetMaxDCAToVertexZ(3.0); pRecInfoCutsTPC->SetRequireSigmaToVertex(kFALSE); pRecInfoCutsTPC->SetRequireTPCRefit(kFALSE); pRecInfoCutsTPC->SetAcceptKinkDaughters(kFALSE); pRecInfoCutsTPC->SetMinNClustersTPC(70); pRecInfoCutsTPC->SetMaxChi2PerClusterTPC(4.); pRecInfoCutsTPC->SetDCAToVertex2D(kTRUE); pRecInfoCutsTPC->SetHistogramsOn(kFALSE); } else { Error("AddTaskPerformanceTPCdEdxQA", "AliRecInfoCutsTPC cannot be created!"); return NULL; } // // Create TPC-MC track reconstruction cuts // AliMCInfoCuts *pMCInfoCuts = new AliMCInfoCuts("pMCInfoCuts"); if(pMCInfoCuts) { pMCInfoCuts->SetMinTrackLength(70); } else { Error("AddTaskPerformanceTPCdEdxQA", "AliMCInfoCuts cannot be created!"); return NULL; } // // Create performance objects for TPC and set cuts // enum { kTPC = 0, kTPCITS, kConstrained, kTPCInner, kTPCOuter, kTPCSec }; if (bTPCTrackingOnly == kFALSE) { // // TPC performance // AliPerformanceTPC *pCompTPC0 = new AliPerformanceTPC("AliPerformanceTPC","AliPerformanceTPC",kTPC,kFALSE,-1,highMult); if(!pCompTPC0) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceTPC"); } pCompTPC0->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompTPC0->SetAliMCInfoCuts(pMCInfoCuts); // pCompTPC0->SetUseTrackVertex(kFALSE); pCompTPC0->SetUseTrackVertex(kTRUE); pCompTPC0->SetUseHLT(bUseHLT); pCompTPC0->SetUseTOFBunchCrossing(bUseTOF); // // TPC ITS match // AliPerformanceMatch *pCompMatch1 = new AliPerformanceMatch("AliPerformanceMatchTPCITS","AliPerformanceMatchTPCITS",0,kFALSE); if(!pCompMatch1) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceMatchTPCITS"); } pCompMatch1->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompMatch1->SetAliMCInfoCuts(pMCInfoCuts); pCompMatch1->SetUseTOFBunchCrossing(bUseTOF); // // ITS TPC match // AliPerformanceMatch *pCompMatch2 = new AliPerformanceMatch("AliPerformanceMatchITSTPC","AliPerformanceMatchITSTPC",1,kFALSE); if(!pCompMatch2) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceMatchITSTPC"); } pCompMatch2->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompMatch2->SetAliMCInfoCuts(pMCInfoCuts); pCompMatch2->SetUseTOFBunchCrossing(bUseTOF); // // dEdx // AliPerformanceDEdx *pCompDEdx3 = new AliPerformanceDEdx("AliPerformanceDEdxTPCInner","AliPerformanceDEdxTPCInner",kTPCInner,kFALSE); if(!pCompDEdx3) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceDEdxTPCInner"); } pCompDEdx3->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompDEdx3->SetAliMCInfoCuts(pMCInfoCuts); //pCompDEdx3->SetUseTrackVertex(kFALSE); pCompDEdx3->SetUseTrackVertex(kTRUE); } //end bTPCTrackingOnly == kFALSE // // Resolution ------------------------------------------------------------------------------------ // AliPerformanceRes *pCompRes4 = new AliPerformanceRes(bTPCTrackingOnly ? "AliPerformanceResTPC" : "AliPerformanceRes", "AliPerformanceRes", bTPCTrackingOnly == kTRUE ? kTPCInner : kTPC,kFALSE); if(!pCompRes4) { Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceRes"); } pCompRes4->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompRes4->SetAliMCInfoCuts(pMCInfoCuts); pCompRes4->SetUseTrackVertex(bTPCTrackingOnly == kTRUE ? kFALSE : kTRUE); // // Efficiency ------------------------------------------------------------------------------------ // AliPerformanceEff *pCompEff5 = new AliPerformanceEff(bTPCTrackingOnly ? "AliPerformanceEffTPC" : "AliPerformanceEff", "AliPerformanceEff",kTPC,kFALSE); if(!pCompEff5) { Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceEff"); } if (bTPCTrackingOnly) { //For low pt tracks, HLT finds only short track segments. //Hence, for the tpc-tracking only tracking-efficiency, we lower the minimum number of hits per reconstructed TPC track AliRecInfoCuts *pRecInfoCutsTPC2 = new AliRecInfoCuts("pRecInfoCutsTPC2"); *pRecInfoCutsTPC2 = pRecInfoCutsTPC2; pRecInfoCutsTPC2->SetMinNClustersTPC(20); pCompEff5->SetAliRecInfoCuts(pRecInfoCutsTPC2); } else { pCompEff5->SetAliRecInfoCuts(pRecInfoCutsTPC); } pCompEff5->SetAliMCInfoCuts(pMCInfoCuts); pCompEff5->SetUseTrackVertex(bTPCTrackingOnly == kTRUE ? kFALSE : kTRUE); AliPerformanceEff *pCompEff5Sec; if (bDoEffTpcSec) { pCompEff5Sec = new AliPerformanceEff(bTPCTrackingOnly ? "AliPerformanceEffSecTPC" : "AliPerformanceEffSec", "AliPerformanceEffSec",kTPCSec,kFALSE); if(!pCompEff5Sec) { Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceEff"); } pCompEff5Sec->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompEff5Sec->SetAliMCInfoCuts(pMCInfoCuts); pCompEff5Sec->SetUseTrackVertex(bTPCTrackingOnly == kTRUE ? kFALSE : kTRUE); } // // TPC Constrain to vertex // if (bTPCTrackingOnly == kFALSE) { AliPerformanceMatch *pCompConstrain6 = new AliPerformanceMatch("AliPerformanceMatchTPCConstrain","AliPerformanceMatchTPCConstrain",2,kFALSE); if(!pCompConstrain6) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceMatchTPCConstrain"); } pCompConstrain6->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompConstrain6->SetAliMCInfoCuts(pMCInfoCuts); pCompConstrain6->SetUseTOFBunchCrossing(bUseTOF); } //end bTPCTrackingOnly == kFALSE // // Add components to the performance task // if (bTPCTrackingOnly == kFALSE) { if(!bUseMCInfo) { pCompTPC0->SetTriggerClass(triggerClass); pCompMatch1->SetTriggerClass(triggerClass); pCompMatch2->SetTriggerClass(triggerClass); pCompDEdx3->SetTriggerClass(triggerClass); pCompConstrain6->SetTriggerClass(triggerClass); } task->AddPerformanceObject( pCompTPC0 ); task->AddPerformanceObject( pCompMatch1 ); task->AddPerformanceObject( pCompMatch2 ); task->AddPerformanceObject( pCompDEdx3 ); task->AddPerformanceObject( pCompConstrain6 ); } //end bTPCTrackingOnly == kFALSE if(bUseMCInfo) { task->AddPerformanceObject( pCompRes4 ); task->AddPerformanceObject( pCompEff5 ); if (bDoEffTpcSec) task->AddPerformanceObject( pCompEff5Sec ); } // // Create containers for input // mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); // // Create containers for output // AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("%s%sQA", taskName[idx], taskName2[idx2]), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:%s_%s", mgr->GetCommonFileName(), taskName[idx],task->GetName())); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(Form("%s%sQASummary", taskName[idx], taskName2[idx2]), TTree::Class(), AliAnalysisManager::kParamContainer, Form("trending.root:Summary%sQA", taskName[idx])); mgr->ConnectOutput(task, 1, coutput); mgr->ConnectOutput(task, 0, coutput2); return task; } <commit_msg>only create MC event handler when needed<commit_after>/////////////////////////////////////////////////////////////////////////////// // Macro to setup AliPerformanceTask for // TPC performance QA to run on PWGPP QA train. // // Input: ESDs, ESDfriends (optional), Kinematics (optional), TrackRefs (optional) // ESD and MC input handlers must be attached to AliAnalysisManager // to run default configuration. // // By default 1 performance components are added to // the task: // 0. AliPerformanceTPC (TPC cluster and track and event information) // 1. AliPerformanceMatch (TPC and ITS/TRD matching and TPC eff w.r.t ITS) // 2. AliPerformanceMatch (TPC and ITS/TRD matching and TPC eff w.r.t TPC) // 3. AliPerformancedEdx (TPC dEdx information) // 4. AliPerformanceRes (TPC track resolution w.r.t MC at DCA) // 5. AliPerformanceEff (TPC track reconstruction efficiency, MC primaries) // 6. AliPerformanceMatch (Comparison of TPC constrain and global tracking) // // Usage on the analysis train (default configuration): // gSystem->Load("libANALYSIS"); // gSystem->Load("libANALYSISalice"); // gSystem->Load("libTPCcalib"); // gSystem->Load("libTender"); // gSystem->Load("libPWGPP"); // // gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/TPC/macros/AddTaskPerformanceTPCdEdxQA.C"); // AliPerformanceTask *tpcQA = AddTaskPerformanceTPCdEdxQA("kFALSE","kTRUE","kFALSE","triggerClass",kFALSE); // // Output: // TPC.Performance.root file with TPC performance components is created. // // Each of the components contains THnSparse generic histograms which // have to be analysed (post-analysis) by using Analyse() function. // Each component contains such function. // //30.09.2010 - J.Otwinowski@gsi.de //22.09.2011 - jochen@thaeder.de - Updated /////////////////////////////////////////////////////////////////////////////// //____________________________________________ AliPerformanceTask* AddTaskPerformanceTPCdEdxQA(Bool_t bUseMCInfo=kFALSE, Bool_t bUseESDfriend=kTRUE, Bool_t highMult = kFALSE, const char *triggerClass=0, Bool_t bUseHLT = kFALSE, Bool_t bUseTOF = kFALSE, Bool_t bTPCTrackingOnly = kFALSE, Bool_t bDoEffTpcSec = kFALSE) { Char_t *taskName[] = {"TPC", "HLT"}; Char_t *taskName2[] = {"", "_Tracking"}; Int_t idx = 0, idx2 = 0; if (bUseHLT) idx = 1; if (bTPCTrackingOnly) idx2 = 1; // // Add AliPerformanceTask with TPC performance components // AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if(!mgr) { Error("AddTaskPerformanceTPCdEdxQA","AliAnalysisManager not set!"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); if (!type.Contains("ESD")) { Error("AddTaskPerformanceTPCdEdxQA", "ESD input handler needed!"); return NULL; } if (bUseMCInfo) { AliMCEventHandler* mchandler = new AliMCEventHandler; mchandler->SetReadTR(kFALSE); mgr->SetMCtruthEventHandler(mchandler); if (!mchandler) { Error("AddTaskPerformanceTPCdEdxQA", "MC input handler needed!"); return NULL; } } // // Add HLT Event // if (bUseHLT) { AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*>(mgr->GetInputEventHandler()); esdH->SetReadHLT(); } // // Create task // AliPerformanceTask *task = new AliPerformanceTask("PerformanceQA",Form("%s%s Performance",taskName[idx], taskName2[idx2])); if (!task) { Error("AddTaskPerformanceTPCdEdxQA", Form("%s%s performance task cannot be created!",taskName[idx], taskName2[idx2])); return NULL; } task->SetUseMCInfo(bUseMCInfo); task->SetUseESDfriend(bUseESDfriend); // task->SetUseTerminate(kFALSE); task->SetUseHLT(bUseHLT); // // Add task to analysis manager // mgr->AddTask(task); // // Create TPC-ESD track reconstruction cuts // MB tracks // AliRecInfoCuts *pRecInfoCutsTPC = new AliRecInfoCuts("pRecInfoCutsTPC"); if(pRecInfoCutsTPC) { pRecInfoCutsTPC->SetMaxDCAToVertexXY(3.0); pRecInfoCutsTPC->SetMaxDCAToVertexZ(3.0); pRecInfoCutsTPC->SetRequireSigmaToVertex(kFALSE); pRecInfoCutsTPC->SetRequireTPCRefit(kFALSE); pRecInfoCutsTPC->SetAcceptKinkDaughters(kFALSE); pRecInfoCutsTPC->SetMinNClustersTPC(70); pRecInfoCutsTPC->SetMaxChi2PerClusterTPC(4.); pRecInfoCutsTPC->SetDCAToVertex2D(kTRUE); pRecInfoCutsTPC->SetHistogramsOn(kFALSE); } else { Error("AddTaskPerformanceTPCdEdxQA", "AliRecInfoCutsTPC cannot be created!"); return NULL; } // // Create TPC-MC track reconstruction cuts // AliMCInfoCuts *pMCInfoCuts = new AliMCInfoCuts("pMCInfoCuts"); if(pMCInfoCuts) { pMCInfoCuts->SetMinTrackLength(70); } else { Error("AddTaskPerformanceTPCdEdxQA", "AliMCInfoCuts cannot be created!"); return NULL; } // // Create performance objects for TPC and set cuts // enum { kTPC = 0, kTPCITS, kConstrained, kTPCInner, kTPCOuter, kTPCSec }; if (bTPCTrackingOnly == kFALSE) { // // TPC performance // AliPerformanceTPC *pCompTPC0 = new AliPerformanceTPC("AliPerformanceTPC","AliPerformanceTPC",kTPC,kFALSE,-1,highMult); if(!pCompTPC0) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceTPC"); } pCompTPC0->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompTPC0->SetAliMCInfoCuts(pMCInfoCuts); // pCompTPC0->SetUseTrackVertex(kFALSE); pCompTPC0->SetUseTrackVertex(kTRUE); pCompTPC0->SetUseHLT(bUseHLT); pCompTPC0->SetUseTOFBunchCrossing(bUseTOF); // // TPC ITS match // AliPerformanceMatch *pCompMatch1 = new AliPerformanceMatch("AliPerformanceMatchTPCITS","AliPerformanceMatchTPCITS",0,kFALSE); if(!pCompMatch1) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceMatchTPCITS"); } pCompMatch1->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompMatch1->SetAliMCInfoCuts(pMCInfoCuts); pCompMatch1->SetUseTOFBunchCrossing(bUseTOF); // // ITS TPC match // AliPerformanceMatch *pCompMatch2 = new AliPerformanceMatch("AliPerformanceMatchITSTPC","AliPerformanceMatchITSTPC",1,kFALSE); if(!pCompMatch2) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceMatchITSTPC"); } pCompMatch2->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompMatch2->SetAliMCInfoCuts(pMCInfoCuts); pCompMatch2->SetUseTOFBunchCrossing(bUseTOF); // // dEdx // AliPerformanceDEdx *pCompDEdx3 = new AliPerformanceDEdx("AliPerformanceDEdxTPCInner","AliPerformanceDEdxTPCInner",kTPCInner,kFALSE); if(!pCompDEdx3) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceDEdxTPCInner"); } pCompDEdx3->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompDEdx3->SetAliMCInfoCuts(pMCInfoCuts); //pCompDEdx3->SetUseTrackVertex(kFALSE); pCompDEdx3->SetUseTrackVertex(kTRUE); } //end bTPCTrackingOnly == kFALSE // // Resolution ------------------------------------------------------------------------------------ // AliPerformanceRes *pCompRes4 = new AliPerformanceRes(bTPCTrackingOnly ? "AliPerformanceResTPC" : "AliPerformanceRes", "AliPerformanceRes", bTPCTrackingOnly == kTRUE ? kTPCInner : kTPC,kFALSE); if(!pCompRes4) { Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceRes"); } pCompRes4->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompRes4->SetAliMCInfoCuts(pMCInfoCuts); pCompRes4->SetUseTrackVertex(bTPCTrackingOnly == kTRUE ? kFALSE : kTRUE); // // Efficiency ------------------------------------------------------------------------------------ // AliPerformanceEff *pCompEff5 = new AliPerformanceEff(bTPCTrackingOnly ? "AliPerformanceEffTPC" : "AliPerformanceEff", "AliPerformanceEff",kTPC,kFALSE); if(!pCompEff5) { Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceEff"); } if (bTPCTrackingOnly) { //For low pt tracks, HLT finds only short track segments. //Hence, for the tpc-tracking only tracking-efficiency, we lower the minimum number of hits per reconstructed TPC track AliRecInfoCuts *pRecInfoCutsTPC2 = new AliRecInfoCuts("pRecInfoCutsTPC2"); *pRecInfoCutsTPC2 = pRecInfoCutsTPC2; pRecInfoCutsTPC2->SetMinNClustersTPC(20); pCompEff5->SetAliRecInfoCuts(pRecInfoCutsTPC2); } else { pCompEff5->SetAliRecInfoCuts(pRecInfoCutsTPC); } pCompEff5->SetAliMCInfoCuts(pMCInfoCuts); pCompEff5->SetUseTrackVertex(bTPCTrackingOnly == kTRUE ? kFALSE : kTRUE); AliPerformanceEff *pCompEff5Sec; if (bDoEffTpcSec) { pCompEff5Sec = new AliPerformanceEff(bTPCTrackingOnly ? "AliPerformanceEffSecTPC" : "AliPerformanceEffSec", "AliPerformanceEffSec",kTPCSec,kFALSE); if(!pCompEff5Sec) { Error("AddTaskPerformanceTPC", "Cannot create AliPerformanceEff"); } pCompEff5Sec->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompEff5Sec->SetAliMCInfoCuts(pMCInfoCuts); pCompEff5Sec->SetUseTrackVertex(bTPCTrackingOnly == kTRUE ? kFALSE : kTRUE); } // // TPC Constrain to vertex // if (bTPCTrackingOnly == kFALSE) { AliPerformanceMatch *pCompConstrain6 = new AliPerformanceMatch("AliPerformanceMatchTPCConstrain","AliPerformanceMatchTPCConstrain",2,kFALSE); if(!pCompConstrain6) { Error("AddTaskPerformanceTPCdEdxQA", "Cannot create AliPerformanceMatchTPCConstrain"); } pCompConstrain6->SetAliRecInfoCuts(pRecInfoCutsTPC); pCompConstrain6->SetAliMCInfoCuts(pMCInfoCuts); pCompConstrain6->SetUseTOFBunchCrossing(bUseTOF); } //end bTPCTrackingOnly == kFALSE // // Add components to the performance task // if (bTPCTrackingOnly == kFALSE) { if(!bUseMCInfo) { pCompTPC0->SetTriggerClass(triggerClass); pCompMatch1->SetTriggerClass(triggerClass); pCompMatch2->SetTriggerClass(triggerClass); pCompDEdx3->SetTriggerClass(triggerClass); pCompConstrain6->SetTriggerClass(triggerClass); } task->AddPerformanceObject( pCompTPC0 ); task->AddPerformanceObject( pCompMatch1 ); task->AddPerformanceObject( pCompMatch2 ); task->AddPerformanceObject( pCompDEdx3 ); task->AddPerformanceObject( pCompConstrain6 ); } //end bTPCTrackingOnly == kFALSE if(bUseMCInfo) { task->AddPerformanceObject( pCompRes4 ); task->AddPerformanceObject( pCompEff5 ); if (bDoEffTpcSec) task->AddPerformanceObject( pCompEff5Sec ); } // // Create containers for input // mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); // // Create containers for output // AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("%s%sQA", taskName[idx], taskName2[idx2]), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:%s_%s", mgr->GetCommonFileName(), taskName[idx],task->GetName())); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(Form("%s%sQASummary", taskName[idx], taskName2[idx2]), TTree::Class(), AliAnalysisManager::kParamContainer, Form("trending.root:Summary%sQA", taskName[idx])); mgr->ConnectOutput(task, 1, coutput); mgr->ConnectOutput(task, 0, coutput2); return task; } <|endoftext|>
<commit_before>#include "Andersen.h" #include "Polymer.h" #include "Monomer.h" #include "consts.h" #include "Rand.h" using namespace consts; #include<cmath> using namespace std; Andersen::Andersen(Polymer &poly, double dtime, double nu) : Thermostat(poly,dtime), m_nu(nu) { update_temp(); } double Andersen::update_temp() { m_sigma = sqrt(m_poly.temp() / m_poly.monomer_mass); return m_sigma; } double Andersen::dtime(double delta_time) { Thermostat::dtime(delta_time); m_dtime2 = m_dtime / 2; m_nu_dt = m_nu*m_dtime; return m_dtime; } void Andersen::propagate() { // velocity verlet for (auto& m : m_poly.monomers) { m.velocity += m_dtime2*m.force / m_poly.monomer_mass; m.position += m_dtime*m.velocity; } m_poly.update_forces(); for (auto& m : m_poly.monomers) { m.velocity += m_dtime2*m.force / m_poly.monomer_mass; } //Andersen for (auto& m : m_poly.monomers) { if (m_nu_dt > Rand::real_uniform()) m.velocity = m_sigma*Rand::real_normal(); } } <commit_msg>Anpassung an Thermostat Klasse<commit_after>#include "Andersen.h" #include "Polymer.h" #include "Monomer.h" #include "consts.h" #include "Rand.h" using namespace consts; #include<cmath> using namespace std; Andersen::Andersen(Polymer &poly, double delta_time, double nu) : Thermostat(poly,delta_time), m_nu(nu) { dtime(delta_time); } double Andersen::update_temp() { m_sigma = sqrt(m_poly.temp() / m_poly.monomer_mass); return m_sigma; } double Andersen::dtime(double delta_time) { Thermostat::dtime(delta_time); m_dtime2 = m_dtime / 2; m_nu_dt = m_nu*m_dtime; return m_dtime; } void Andersen::propagate() { // velocity verlet for (auto& m : m_poly.monomers) { m.velocity += m_dtime2*m.force / m_poly.monomer_mass; m.position += m_dtime*m.velocity; } m_poly.update_forces(); for (auto& m : m_poly.monomers) { m.velocity += m_dtime2*m.force / m_poly.monomer_mass; } //Andersen for (auto& m : m_poly.monomers) { if (m_nu_dt > Rand::real_uniform()) m.velocity = m_sigma*Rand::real_normal(); } } <|endoftext|>
<commit_before>using func_p = void(*)(); //Labels to the arrays of constructors and destructors placed by the linker extern "C" func_p start_ctors, end_ctors, start_dtors, end_dtors; //Constructs all static objects void static_construct() { for(auto fp = &start_ctors; fp < &end_ctors; ++fp) (*fp)(); } //Destructs all static objects void static_destruct() { for(auto fp = &start_dtors; fp < &end_dtors; ++fp) (*fp)(); } <commit_msg>Destruct static elements in reverse order<commit_after>using func_p = void(*)(); //Labels to the arrays of constructors and destructors placed by the linker extern "C" func_p start_ctors, end_ctors, start_dtors, end_dtors; //Constructs all static objects void static_construct() { for(auto fp = &start_ctors; fp < &end_ctors; ++fp) (*fp)(); } //Destructs all static objects void static_destruct() { for(auto fp = &end_dtors-1; fp >= &start_dtors; --fp) (*fp)(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2014 Chun-Ying Huang * * This file is part of GamingAnywhere (GA). * * GA is free software; you can redistribute it and/or modify it * under the terms of the 3-clause BSD License as published by the * Free Software Foundation: http://directory.fsf.org/wiki/License:BSD_3Clause * * GA 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. * * You should have received a copy of the 3-clause BSD License along with GA; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <MPEG1or2AudioRTPSink.hh> #include <MPEG4GenericRTPSink.hh> #include <AC3AudioRTPSink.hh> #include <SimpleRTPSink.hh> #include <VorbisAudioRTPSink.hh> #include <H264VideoRTPSink.hh> #include <H265VideoRTPSink.hh> #include <VP8VideoRTPSink.hh> #include <TheoraVideoRTPSink.hh> #include <T140TextRTPSink.hh> #include <H264VideoStreamDiscreteFramer.hh> #include <H265VideoStreamDiscreteFramer.hh> #include <H264VideoStreamFramer.hh> #include <H265VideoStreamFramer.hh> #include "ga-common.h" #include "ga-conf.h" #include "rtspconf.h" #include "encoder-common.h" #include "ga-mediasubsession.h" #include "ga-audiolivesource.h" #include "ga-videolivesource.h" GAMediaSubsession ::GAMediaSubsession(UsageEnvironment &env, int cid, const char *mimetype, portNumBits initialPortNum, Boolean multiplexRTCPWithRTP) : OnDemandServerMediaSubsession(env, True/*reuseFirstSource*/, initialPortNum, multiplexRTCPWithRTP) { this->mimetype = strdup(mimetype); this->channelId = cid; } GAMediaSubsession * GAMediaSubsession ::createNew(UsageEnvironment &env, int cid, const char *mimetype, portNumBits initialPortNum, Boolean multiplexRTCPWithRTP) { return new GAMediaSubsession(env, cid, mimetype, initialPortNum, multiplexRTCPWithRTP); } FramedSource* GAMediaSubsession ::createNewStreamSource(unsigned clientSessionId, unsigned& estBitrate) { FramedSource *result = NULL; struct RTSPConf *rtspconf = rtspconf_global(); if(strncmp("audio/", this->mimetype, 6) == 0) { estBitrate = rtspconf->audio_bitrate / 1000; /* Kbps */ result = GAAudioLiveSource::createNew(envir(), this->channelId); } else if(strncmp("video/", this->mimetype, 6) == 0) { //estBitrate = 500; /* Kbps */ estBitrate = ga_conf_mapreadint("video-specific", "b") / 1000; /* Kbps */ OutPacketBuffer::increaseMaxSizeTo(300000); result = GAVideoLiveSource::createNew(envir(), this->channelId); } do if(result != NULL) { if(strcmp("video/H264", this->mimetype) == 0) { #ifdef DISCRETE_FRAMER result = H264VideoStreamDiscreteFramer::createNew(envir(), result); #else result = H264VideoStreamFramer::createNew(envir(), result); #endif break; } if(strcmp("video/H265", this->mimetype) == 0) { #ifdef DISCRETE_FRAMER result = H265VideoStreamDiscreteFramer::createNew(envir(), result); #else result = H265VideoStreamFramer::createNew(envir(), result); #endif break; } } while(0); return result; } // "estBitrate" is the stream's estimated bitrate, in kbps RTPSink* GAMediaSubsession ::createNewRTPSink(Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource* inputSource) { RTPSink *result = NULL; struct RTSPConf *rtspconf = rtspconf_global(); const char *mimetype = this->mimetype; // if(strcmp(mimetype, "audio/MPEG") == 0) { result = MPEG1or2AudioRTPSink::createNew(envir(), rtpGroupsock); } else if(strcmp(mimetype, "audio/AAC") == 0) { // TODO: not implememted ga_error("GAMediaSubsession: %s NOT IMPLEMENTED\n", mimetype); exit(-1); } else if(strcmp(mimetype, "audio/AC3") == 0) { result = AC3AudioRTPSink ::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, rtspconf->audio_samplerate); } else if(strcmp(mimetype, "audio/OPUS") == 0) { result = SimpleRTPSink ::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, rtspconf->audio_samplerate, "audio", "OPUS", 2, False/*only 1 Opus 'packet' in each RTP packet*/); } else if(strcmp(mimetype, "audio/VORBIS") == 0) { u_int8_t* identificationHeader = NULL; unsigned identificationHeaderSize = 0; u_int8_t* commentHeader = NULL; unsigned commentHeaderSize = 0; u_int8_t* setupHeader = NULL; unsigned setupHeaderSize = 0; // TODO: not implememted ga_error("GAMediaSubsession: %s NOT IMPLEMENTED\n", mimetype); exit(-1); result = VorbisAudioRTPSink ::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, rtspconf->audio_samplerate, rtspconf->audio_channels, identificationHeader, identificationHeaderSize, commentHeader, commentHeaderSize, setupHeader, setupHeaderSize); } else if(strcmp(mimetype, "video/THEORA") == 0) { u_int8_t* identificationHeader = NULL; unsigned identificationHeaderSize = 0; u_int8_t* commentHeader = NULL; unsigned commentHeaderSize = 0; u_int8_t* setupHeader = NULL; unsigned setupHeaderSize = 0; // TODO: not implememted ga_error("GAMediaSubsession: %s NOT IMPLEMENTED\n", mimetype); exit(-1); result = TheoraVideoRTPSink ::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, identificationHeader, identificationHeaderSize, commentHeader, commentHeaderSize, setupHeader, setupHeaderSize); } else if(strcmp(mimetype, "video/H264") == 0) { ga_module_t *m = encoder_get_vencoder(); unsigned profile_level_id = 0; u_int8_t* SPS = NULL; int SPSSize = 0; u_int8_t* PPS = NULL; int PPSSize = 0; // SPS = (u_int8_t*) m->option1((void*) this->channelId, &SPSSize); PPS = (u_int8_t*) m->option2((void*) this->channelId, &PPSSize); if (SPSSize >= 1/*'profile_level_id' offset within SPS*/ + 3/*num bytes needed*/) { profile_level_id = (SPS[1]<<16) | (SPS[2]<<8) | SPS[3]; } ga_error("GAMediaSubsession: %s SPS=%p(%d); PPS=%p(%d); profile_level_id=%x\n", mimetype, SPS, SPSSize, PPS, PPSSize, profile_level_id); result = H264VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, SPS, SPSSize, PPS, PPSSize/*, profile_level_id*/); } else if(strcmp(mimetype, "video/H265") == 0) { ga_module_t *m = encoder_get_vencoder(); u_int8_t* VPS = NULL; int VPSSize = 0; u_int8_t* SPS = NULL; int SPSSize = 0; u_int8_t* PPS = NULL; int PPSSize = 0; // TODO: not implememted #if 0 ga_error("GAMediaSubsession: %s NOT IMPLEMENTED\n", mimetype); exit(-1); #endif SPS = (u_int8_t*) m->option1((void*) this->channelId, &SPSSize); PPS = (u_int8_t*) m->option2((void*) this->channelId, &PPSSize); VPS = (u_int8_t*) m->option3((void*) this->channelId, &VPSSize); ga_error("GAMediaSubsession: %s SPS=%p(%d); PPS=%p(%d); VPS=%p(%d)\n", mimetype, SPS, SPSSize, PPS, PPSSize, VPS, VPSSize); result = H265VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, VPS, VPSSize, SPS, SPSSize, PPS, PPSSize/*, profileSpace, profileId, tierFlag, levelId, interopConstraintsStr*/); } else if(strcmp(mimetype, "video/VP8") == 0) { result = VP8VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic); } if(result == NULL) { ga_error("GAMediaSubsession: create RTP sink for %s failed.\n", mimetype); } return result; } <commit_msg>increase max frame size to 600K<commit_after>/* * Copyright (c) 2013-2014 Chun-Ying Huang * * This file is part of GamingAnywhere (GA). * * GA is free software; you can redistribute it and/or modify it * under the terms of the 3-clause BSD License as published by the * Free Software Foundation: http://directory.fsf.org/wiki/License:BSD_3Clause * * GA 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. * * You should have received a copy of the 3-clause BSD License along with GA; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <MPEG1or2AudioRTPSink.hh> #include <MPEG4GenericRTPSink.hh> #include <AC3AudioRTPSink.hh> #include <SimpleRTPSink.hh> #include <VorbisAudioRTPSink.hh> #include <H264VideoRTPSink.hh> #include <H265VideoRTPSink.hh> #include <VP8VideoRTPSink.hh> #include <TheoraVideoRTPSink.hh> #include <T140TextRTPSink.hh> #include <H264VideoStreamDiscreteFramer.hh> #include <H265VideoStreamDiscreteFramer.hh> #include <H264VideoStreamFramer.hh> #include <H265VideoStreamFramer.hh> #include "ga-common.h" #include "ga-conf.h" #include "rtspconf.h" #include "encoder-common.h" #include "ga-mediasubsession.h" #include "ga-audiolivesource.h" #include "ga-videolivesource.h" GAMediaSubsession ::GAMediaSubsession(UsageEnvironment &env, int cid, const char *mimetype, portNumBits initialPortNum, Boolean multiplexRTCPWithRTP) : OnDemandServerMediaSubsession(env, True/*reuseFirstSource*/, initialPortNum, multiplexRTCPWithRTP) { this->mimetype = strdup(mimetype); this->channelId = cid; } GAMediaSubsession * GAMediaSubsession ::createNew(UsageEnvironment &env, int cid, const char *mimetype, portNumBits initialPortNum, Boolean multiplexRTCPWithRTP) { return new GAMediaSubsession(env, cid, mimetype, initialPortNum, multiplexRTCPWithRTP); } FramedSource* GAMediaSubsession ::createNewStreamSource(unsigned clientSessionId, unsigned& estBitrate) { FramedSource *result = NULL; struct RTSPConf *rtspconf = rtspconf_global(); if(strncmp("audio/", this->mimetype, 6) == 0) { estBitrate = rtspconf->audio_bitrate / 1000; /* Kbps */ result = GAAudioLiveSource::createNew(envir(), this->channelId); } else if(strncmp("video/", this->mimetype, 6) == 0) { //estBitrate = 500; /* Kbps */ estBitrate = ga_conf_mapreadint("video-specific", "b") / 1000; /* Kbps */ OutPacketBuffer::increaseMaxSizeTo(600000); result = GAVideoLiveSource::createNew(envir(), this->channelId); } do if(result != NULL) { if(strcmp("video/H264", this->mimetype) == 0) { #ifdef DISCRETE_FRAMER result = H264VideoStreamDiscreteFramer::createNew(envir(), result); #else result = H264VideoStreamFramer::createNew(envir(), result); #endif break; } if(strcmp("video/H265", this->mimetype) == 0) { #ifdef DISCRETE_FRAMER result = H265VideoStreamDiscreteFramer::createNew(envir(), result); #else result = H265VideoStreamFramer::createNew(envir(), result); #endif break; } } while(0); return result; } // "estBitrate" is the stream's estimated bitrate, in kbps RTPSink* GAMediaSubsession ::createNewRTPSink(Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource* inputSource) { RTPSink *result = NULL; struct RTSPConf *rtspconf = rtspconf_global(); const char *mimetype = this->mimetype; // if(strcmp(mimetype, "audio/MPEG") == 0) { result = MPEG1or2AudioRTPSink::createNew(envir(), rtpGroupsock); } else if(strcmp(mimetype, "audio/AAC") == 0) { // TODO: not implememted ga_error("GAMediaSubsession: %s NOT IMPLEMENTED\n", mimetype); exit(-1); } else if(strcmp(mimetype, "audio/AC3") == 0) { result = AC3AudioRTPSink ::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, rtspconf->audio_samplerate); } else if(strcmp(mimetype, "audio/OPUS") == 0) { result = SimpleRTPSink ::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, rtspconf->audio_samplerate, "audio", "OPUS", 2, False/*only 1 Opus 'packet' in each RTP packet*/); } else if(strcmp(mimetype, "audio/VORBIS") == 0) { u_int8_t* identificationHeader = NULL; unsigned identificationHeaderSize = 0; u_int8_t* commentHeader = NULL; unsigned commentHeaderSize = 0; u_int8_t* setupHeader = NULL; unsigned setupHeaderSize = 0; // TODO: not implememted ga_error("GAMediaSubsession: %s NOT IMPLEMENTED\n", mimetype); exit(-1); result = VorbisAudioRTPSink ::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, rtspconf->audio_samplerate, rtspconf->audio_channels, identificationHeader, identificationHeaderSize, commentHeader, commentHeaderSize, setupHeader, setupHeaderSize); } else if(strcmp(mimetype, "video/THEORA") == 0) { u_int8_t* identificationHeader = NULL; unsigned identificationHeaderSize = 0; u_int8_t* commentHeader = NULL; unsigned commentHeaderSize = 0; u_int8_t* setupHeader = NULL; unsigned setupHeaderSize = 0; // TODO: not implememted ga_error("GAMediaSubsession: %s NOT IMPLEMENTED\n", mimetype); exit(-1); result = TheoraVideoRTPSink ::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, identificationHeader, identificationHeaderSize, commentHeader, commentHeaderSize, setupHeader, setupHeaderSize); } else if(strcmp(mimetype, "video/H264") == 0) { ga_module_t *m = encoder_get_vencoder(); unsigned profile_level_id = 0; u_int8_t* SPS = NULL; int SPSSize = 0; u_int8_t* PPS = NULL; int PPSSize = 0; // SPS = (u_int8_t*) m->option1((void*) this->channelId, &SPSSize); PPS = (u_int8_t*) m->option2((void*) this->channelId, &PPSSize); if (SPSSize >= 1/*'profile_level_id' offset within SPS*/ + 3/*num bytes needed*/) { profile_level_id = (SPS[1]<<16) | (SPS[2]<<8) | SPS[3]; } ga_error("GAMediaSubsession: %s SPS=%p(%d); PPS=%p(%d); profile_level_id=%x\n", mimetype, SPS, SPSSize, PPS, PPSSize, profile_level_id); result = H264VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, SPS, SPSSize, PPS, PPSSize/*, profile_level_id*/); } else if(strcmp(mimetype, "video/H265") == 0) { ga_module_t *m = encoder_get_vencoder(); u_int8_t* VPS = NULL; int VPSSize = 0; u_int8_t* SPS = NULL; int SPSSize = 0; u_int8_t* PPS = NULL; int PPSSize = 0; // TODO: not implememted #if 0 ga_error("GAMediaSubsession: %s NOT IMPLEMENTED\n", mimetype); exit(-1); #endif SPS = (u_int8_t*) m->option1((void*) this->channelId, &SPSSize); PPS = (u_int8_t*) m->option2((void*) this->channelId, &PPSSize); VPS = (u_int8_t*) m->option3((void*) this->channelId, &VPSSize); ga_error("GAMediaSubsession: %s SPS=%p(%d); PPS=%p(%d); VPS=%p(%d)\n", mimetype, SPS, SPSSize, PPS, PPSSize, VPS, VPSSize); result = H265VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, VPS, VPSSize, SPS, SPSSize, PPS, PPSSize/*, profileSpace, profileId, tierFlag, levelId, interopConstraintsStr*/); } else if(strcmp(mimetype, "video/VP8") == 0) { result = VP8VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic); } if(result == NULL) { ga_error("GAMediaSubsession: create RTP sink for %s failed.\n", mimetype); } return result; } <|endoftext|>
<commit_before>// This example is a demonstration of the Lebwohl-Lasher model in an NVT ensemble // and basic usage of the API. It has a very basic command line interface to // illustrate a possible use case. // Include the pertinent header files. #include "../src/Ensembles/NVTEnsemble.h" #include "../src/Models/LebwohlLasherModel.h" #include "../src/Moves/SphereUnitVectorMove.h" // Includes for parsing using stringstream. #include <iostream> #include <sstream> // Function definition of our basic input parser. // // A very basic input parser. int parse_input(char const* args[], int& latticeSize, int& iterations, double& temperature, std::string& modelFile, std::string& SitesFile); // The main program expects a user to input the lattice size, reduced temperature, // number of iterations and specify an output file (csv) for model properties and // site properties. int main(int argc, char const* argv[]) { int latticeSize, iterations; double temperature; std::string modelFile, sitesFile; // We expect a certain number of arugments. if(argc != 6) { std::cerr << "Program syntax:" << argv[0] << " lattice-size temperature iterations model-outputfile site-outputfile" << std::endl; return 0; } // Exit on parsing error. if(parse_input(argv, latticeSize, iterations, temperature, modelFile, sitesFile) != 0) return -1; // Initialize the Lebwohl-Lasher lattice model. The constructor takes in one // required argument which is the lattice size - the length of one dimension. // The model initializes the required number of sites in the appropriate locations, // defines the nearest-neighbors and provides an initial spin. Models::LebwohlLasherModel model(latticeSize, latticeSize, latticeSize); // Initialize the NVT ensemble. For this particular ensemble, it requires a reference to // the model and the temperature. The template parametr for the ensemble is the type // returned by the DrawSample method of the model - in this case it is a site. //Ensembles::NVTEnsemble<Site> ensemble(model, temperature); // Initialize the moves. These are the different Monte-Carlo moves we would like // to perform on the model above. In this case, we want to pick a random unit // vector on a sphere. A "Move" class operates on a site within model in an ensemble. Moves::SphereUnitVectorMove move; //ensemble.AddMove(move); // Sweep for iterations //for (int i = 0; i < iterations; i++) //ensemble.Sweep(); return 0; } // A very basic input parser. int parse_input(char const* args[], int& latticeSize, int& iterations, double& temperature, std::string& modelFile, std::string& SitesFile) { std::stringstream ss; // Parse input ss.clear(); ss.str(args[1]); if(!(ss >> latticeSize)) { std::cerr << "Invalid lattice size. Must be an integer." << std::endl; return -1; } ss.clear(); ss.str(args[2]); if(!(ss >> temperature)) { std::cerr << "Invalid temperature. Must be a double." << std::endl; return -1; } ss.clear(); ss.str(args[3]); if(!(ss >> iterations)) { std::cerr << "Invalid iterations. Must be an integer." << std::endl; return -1; } ss.clear(); ss.str(args[4]); if(!(ss >> modelFile)) { std::cerr << "Invalid output file. Must be a string." << std::endl; return -1; } ss.clear(); ss.str(args[5]); if(!(ss >> SitesFile)) { std::cerr << "Invalid output file. Must be a string." << std::endl; return -1; } return 0; } <commit_msg>Update LL NVT example<commit_after>// This example is a demonstration of the Lebwohl-Lasher model in an NVT ensemble // and basic usage of the API. It has a very basic command line interface to // illustrate a possible use case. // Include the pertinent header files. #include "../src/Ensembles/NVTEnsemble.h" #include "../src/ForceFields/ForceFieldManager.h" #include "../src/ForceFields/LebwohlLasherFF.h" #include "../src/Moves/MoveManager.h" #include "../src/Moves/SphereUnitVectorMove.h" #include "../src/Particles/Site.h" #include "../src/Simulation/CSVObserver.h" #include "../src/Simulation/ConsoleObserver.h" #include "../src/Worlds/SimpleLatticeWorld.h" // Includes for parsing using stringstream. #include <iostream> #include <sstream> using namespace SAPHRON; // Function definition of our basic input parser. // // A very basic input parser. int parse_input(char const* args[], int& latticeSize, int& iterations, double& temperature, std::string& filePrefix); // The main program expects a user to input the lattice size, reduced temperature, // number of iterations and specify an output file prefix (csv) for logged properties. int main(int argc, char const* argv[]) { int latticeSize, iterations; double temperature; std::string filePrefix; // We expect a certain number of arugments. if(argc != 5) { std::cerr << "Program syntax:" << argv[0] << " lattice-size temperature iterations outputfile-prefix" << std::endl; return 0; } // Exit on parsing error. if(parse_input(argv, latticeSize, iterations, temperature, filePrefix) != 0) return -1; // Initialize a simple cubic lattice "world". This defines the type of box for our simulation. // The constructor takes in the lattice dimensions and an optional seed for the pseudo random // number generator. SimpleLatticeWorld world(latticeSize, latticeSize, latticeSize, 1); // Initialize a site. This will represent an individual spin on the lattice in our world. // The constructor takes in an initial position, director and species type (string). Note that // the position is irrelevant since this site will be copied and configured appropriately for // the system. Site site1({ 0, 0, 0 }, { 1.0, 0, 0 }, "E1"); // Now we configure the world but providing a reference to our spin and telling it to fill the // box entirely with that site. We then configure connectivity through neighbor list // initialization. world.ConfigureParticles({ &site1 }, { 1.0 }); world.ConfigureNeighborList(); // Initialize the Lebwohl-Lasher (LL) force field and add it to an instance of the forcefield // manager. The LL forcefield takes in two arguments. An anisotropic interaction energy and // an isotropic term as well. See header file for details. LebwohlLasherFF ff(1.0, 0); ForceFieldManager ffm; ffm.AddForceField("E1", "E1", ff); // Initialize the move we want to perform on our sites, then add it to an instance of the // move manager. The only argument the constructor takes is a seed for the PRNG. SphereUnitVectorMove move1(33); MoveManager mm; mm.PushMove(move1); // Initialize the "observers". These are effectively the loggers that will be monitoring the // simulation. We want to print out some information to the console to monitor the run, // but store more details in a CSV file format. SimFlags flags1; flags1.temperature = 1; flags1.iterations = 1; flags1.energy = 1; ConsoleObserver console(flags1, 1000); SimFlags flags2; flags2.temperature = 1; flags2.iterations = 1; flags2.energy = 1; CSVObserver csv(filePrefix, flags2, 500); // Initialize the NVT ensemble. For this particular ensemble, it requires a reference to world, // the forcefield manager and the move manager. It also takes in a temperature and RNG seed. NVTEnsemble ensemble(world, ffm, mm, temperature, 45); // Run the simulation. ensemble.Run(iterations); return 0; } // A very basic input parser. int parse_input(char const* args[], int& latticeSize, int& iterations, double& temperature, std::string& filePrefix) { std::stringstream ss; // Parse input ss.clear(); ss.str(args[1]); if(!(ss >> latticeSize)) { std::cerr << "Invalid lattice size. Must be an integer." << std::endl; return -1; } ss.clear(); ss.str(args[2]); if(!(ss >> temperature)) { std::cerr << "Invalid temperature. Must be a double." << std::endl; return -1; } ss.clear(); ss.str(args[3]); if(!(ss >> iterations)) { std::cerr << "Invalid iterations. Must be an integer." << std::endl; return -1; } ss.clear(); ss.str(args[4]); if(!(ss >> filePrefix)) { std::cerr << "Invalid output file prefix. Must be a string." << std::endl; return -1; } return 0; } <|endoftext|>
<commit_before>#include "user_space_wrappers.h" #include "core.h" #include "sync_client.h" #include "core_manager.h" #include "log.h" CAPI_return_t SimGetCoreID(int *core_id) { *core_id = g_core_manager->getCurrentCoreID(); return 0; } void SimInitializeThread() { g_core_manager->initializeThread(); } void SimInitializeCommId(int comm_id) { g_core_manager->initializeCommId(comm_id); } void SimMutexInit(carbon_mutex_t *mux) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->mutexInit(mux); } void SimMutexLock(carbon_mutex_t *mux) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->mutexLock(mux); } void SimMutexUnlock(carbon_mutex_t *mux) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->mutexUnlock(mux); } void SimCondInit(carbon_cond_t *cond) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->condInit(cond); } void SimCondWait(carbon_cond_t *cond, carbon_mutex_t *mux) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->condWait(cond, mux); } void SimCondSignal(carbon_cond_t *cond) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->condSignal(cond); } void SimCondBroadcast(carbon_cond_t *cond) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->condBroadcast(cond); } void SimBarrierInit(carbon_barrier_t *barrier, UINT32 count) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->barrierInit(barrier, count); } void SimBarrierWait(carbon_barrier_t *barrier) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->barrierWait(barrier); } CAPI_return_t SimSendW(CAPI_endpoint_t sender, CAPI_endpoint_t receiver, char *buffer, int size) { Core *core = g_core_manager->getCurrentCore(); UInt32 sending_core = g_config->getCoreFromCommId(sender); UInt32 receiving_core = g_config->getCoreFromCommId(receiver); return core ? core->coreSendW(sending_core, receiving_core, buffer, size) : -1; } CAPI_return_t SimRecvW(CAPI_endpoint_t sender, CAPI_endpoint_t receiver, char *buffer, int size) { Core *core = g_core_manager->getCurrentCore(); UInt32 sending_core = g_config->getCoreFromCommId(sender); UInt32 receiving_core = g_config->getCoreFromCommId(receiver); return core ? core->coreRecvW(sending_core, receiving_core, buffer, size) : -1; } <commit_msg>[user_space] Add logging to CAPI functions.<commit_after>#include "user_space_wrappers.h" #include "core.h" #include "sync_client.h" #include "core_manager.h" #include "log.h" CAPI_return_t SimGetCoreID(int *core_id) { *core_id = g_core_manager->getCurrentCoreID(); return 0; } void SimInitializeThread() { g_core_manager->initializeThread(); } void SimInitializeCommId(int comm_id) { g_core_manager->initializeCommId(comm_id); } void SimMutexInit(carbon_mutex_t *mux) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->mutexInit(mux); } void SimMutexLock(carbon_mutex_t *mux) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->mutexLock(mux); } void SimMutexUnlock(carbon_mutex_t *mux) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->mutexUnlock(mux); } void SimCondInit(carbon_cond_t *cond) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->condInit(cond); } void SimCondWait(carbon_cond_t *cond, carbon_mutex_t *mux) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->condWait(cond, mux); } void SimCondSignal(carbon_cond_t *cond) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->condSignal(cond); } void SimCondBroadcast(carbon_cond_t *cond) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->condBroadcast(cond); } void SimBarrierInit(carbon_barrier_t *barrier, UINT32 count) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->barrierInit(barrier, count); } void SimBarrierWait(carbon_barrier_t *barrier) { Core *core = g_core_manager->getCurrentCore(); if (core) core->getSyncClient()->barrierWait(barrier); } CAPI_return_t SimSendW(CAPI_endpoint_t sender, CAPI_endpoint_t receiver, char *buffer, int size) { Core *core = g_core_manager->getCurrentCore(); LOG_PRINT_EXPLICIT(-1, USERSPACEWRAPPERS, "SimSendW - sender: %d, recv: %d", sender, receiver); UInt32 sending_core = g_config->getCoreFromCommId(sender); UInt32 receiving_core = g_config->getCoreFromCommId(receiver); return core ? core->coreSendW(sending_core, receiving_core, buffer, size) : -1; } CAPI_return_t SimRecvW(CAPI_endpoint_t sender, CAPI_endpoint_t receiver, char *buffer, int size) { Core *core = g_core_manager->getCurrentCore(); LOG_PRINT_EXPLICIT(-1, USERSPACEWRAPPERS, "SimRecvW - sender: %d, recv: %d", sender, receiver); UInt32 sending_core = g_config->getCoreFromCommId(sender); UInt32 receiving_core = g_config->getCoreFromCommId(receiver); return core ? core->coreRecvW(sending_core, receiving_core, buffer, size) : -1; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include "occa.hpp" int main(int argc, char **argv){ /* hard code platform and device number */ int plat = 0; int dev = 0; occa::device device; device.setup("OpenCL", plat, dev); // build jacobi kernel from source file const char *functionName = ""; // build Jacobi kernel occa::kernel simple = device.buildKernelFromSource("simple.occa", "simple"); // size of array int N = 256; // set thread array for Jacobi iteration int T = 32; int dims = 1; occa::dim inner(T); occa::dim outer((N+T-1)/T); simple.setWorkingDims(dims, inner, outer); // allocate array on HOST float *h_x = (float*) malloc(sz); for(int n=0;n<N;++n) h_x[n] = 123; // allocate array on DEVICE (copy from HOST) size_t sz = T*sizeof(float); occa::memory c_x = device.malloc(sz, h_x); // queue kernel simple(N, c_x); // copy result to HOST c_x.toHost(h_x); /* print out results */ for(int n=0;n<N;++n) printf("h_x[%d] = %g\n", n, h_x[n]); exit(0); } <commit_msg>tweak<commit_after>#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include "occa.hpp" int main(int argc, char **argv){ /* hard code platform and device number */ int plat = 0; int dev = 0; occa::device device; device.setup("OpenCL", plat, dev); // build jacobi kernel from source file const char *functionName = ""; // build Jacobi kernel occa::kernel simple = device.buildKernelFromSource("simple.occa", "simple"); // size of array int N = 256; // set thread array for Jacobi iteration int T = 32; int dims = 1; occa::dim inner(T); occa::dim outer((N+T-1)/T); simple.setWorkingDims(dims, inner, outer); size_t sz = N*sizeof(float); // allocate array on HOST float *h_x = (float*) malloc(sz); for(int n=0;n<N;++n) h_x[n] = 123; // allocate array on DEVICE (copy from HOST) occa::memory c_x = device.malloc(sz, h_x); // queue kernel simple(N, c_x); // copy result to HOST c_x.toHost(h_x); /* print out results */ for(int n=0;n<N;++n) printf("h_x[%d] = %g\n", n, h_x[n]); exit(0); } <|endoftext|>
<commit_before>/* My C++ template Chandan Mittal handle: calmhandtitan */ #include "bits/stdc++.h" #define sd(n) scanf("%d", &(n)) #define rep(i, x, n) for (size_t i = x, _n = (n); i < _n; ++i) #define SZ(c) (int)(c).size() #define lcm(a,b) (a*(b/__gcd(a,b))) #define VI vector<int> #define all(c) ((c).begin(), (c).end()) #define pb push_back #define pii pair<int, int> #define pip pair<int, pii> #define F first #define S second #define mp make_pair #define lli long long int #define CLR(p) memset(p, 0, sizeof(p)) #define SET(p) memset(p, -1, sizeof(p)) #define INF 0x3f3f3f3f using namespace std; const int MOD = 1e9+7; const int MAX = 100010; int main() { return 0; } <commit_msg>fixed a macro<commit_after>/* My C++ template Chandan Mittal handle: calmhandtitan */ #include "bits/stdc++.h" #define sd(n) scanf("%d", &(n)) #define rep(i, x, n) for (size_t i = x, _n = (n); i < _n; ++i) #define SZ(c) (int)(c).size() #define lcm(a,b) (a*(b/__gcd(a,b))) #define VI vector<int> #define all(c) (c).begin(), (c).end() #define pb push_back #define pii pair<int, int> #define pip pair<int, pii> #define F first #define S second #define mp make_pair #define lli long long int #define CLR(p) memset(p, 0, sizeof(p)) #define SET(p) memset(p, -1, sizeof(p)) #define INF 0x3f3f3f3f using namespace std; const int MOD = 1e9+7; const int MAX = 100010; int main() { return 0; } <|endoftext|>
<commit_before>#include <sstream> #include <unistd.h> #include <string.h> #include "display.h" #include "world.h" #include "logging.h" #include "utils.h" using std::ostringstream; #define PANE_WORLD_WIDTH 800 #define PANE_WORLD_HEIGHT 800 #define PANE_CTRL_WIDTH 600 #define PANE_CTRL_HEIGHT 800 #define PANE_SEPERATION 20 #define DISPLAY_WIDTH (PANE_WORLD_WIDTH + PANE_SEPERATION + PANE_CTRL_WIDTH) #define DISPLAY_HEIGHT (PANE_WORLD_HEIGHT >= PANE_CTRL_HEIGHT ? PANE_WORLD_HEIGHT : PANE_CTRL_HEIGHT) const double MAX_ZOOM = 31.99; const double MIN_ZOOM = 0.51; const double ZOOM_FACTOR = 1.1892071; double zoom = 1.0 / ZOOM_FACTOR; double center_x = world::WIDTH / 2; double center_y = world::HEIGHT / 2; int main_edit(string world_filename); // ----------------- MAIN ------------------------------------------------------------------------ int main(int argc, char **argv) { bool opt_edit = false; string world_filename; // get options while (true) { char opt_char = getopt(argc, argv, "e"); if (opt_char == -1) { break; } switch (opt_char) { case 'e': opt_edit = true; break; default: return 1; } } // get args world_filename = "world.dat"; if ((argc - optind) >= 1) { world_filename = argv[optind]; } // handle edit mode0 if (opt_edit) { return main_edit(world_filename); } // terminate return 0; } // ----------------- EDIT ------------------------------------------------------------------------ // XXX display ptr to current dir rate // - display speed // - set cursor, and direction // - display cursor when in this mode, both in text and on display // int main_edit(string world_filename) { enum mode { MAIN, CREATE_ROADS }; const int MAX_MESSAGE_AGE = 200; //const int DELAY_MICROSECS = 1000000; // XXX was 10000 const int DELAY_MICROSECS = 10000; enum mode mode = MAIN; struct display::event event = {display::EID_NONE,0,0}; bool done = false; bool create_roads_active = false; double create_road_x = 2000; double create_road_y = 2000; double create_road_dir = 0; int create_road_dir_idx = 5; string message = ""; int message_age = MAX_MESSAGE_AGE; double avg_cycle_time = DELAY_MICROSECS; // create the display display d(DISPLAY_WIDTH, DISPLAY_HEIGHT); // create the world world w(d,world_filename); message = w.read_ok() ? "READ SUCCESS" : "READ FAILURE"; message_age = 0; // loop while (!done) { // determine average cycle time { const int MAX_TIMES=10; static long times[MAX_TIMES]; memmove(times+1, times, (MAX_TIMES-1)*sizeof(long)); times[0] = microsec_timer(); if (times[MAX_TIMES-1] != 0) { avg_cycle_time = (times[0] - times[MAX_TIMES-1]) / (MAX_TIMES-1); } // XXX temp static int count; if ((++count % 100) == 0) { INFO("AVG CYCLE TIME " << avg_cycle_time / 1000. << endl); } } // start d.start(0, 0, PANE_WORLD_WIDTH, PANE_WORLD_HEIGHT, // pane 0: x,y,w,h PANE_WORLD_WIDTH+PANE_SEPERATION, 0, PANE_CTRL_WIDTH, PANE_CTRL_HEIGHT); // pane 1: x,y,w,h // draw the world w.draw(0,center_x,center_y,zoom); // additional drawing: CREATE_ROADS mode if (mode == CREATE_ROADS) { ostringstream s; // xxx comments if (create_roads_active) { // xxx dont go off end of world w.create_road_slice(create_road_x, create_road_y, create_road_dir); //xxx return distance create_road_dir += (create_road_dir_idx - 5) * 0.05; if (create_road_dir < 0) { create_road_dir += 360; } else if (create_road_dir > 360) { create_road_dir -= 360; } } d.text_draw("^", 1, 2*(create_road_dir_idx-1), 1); s.str(""); if (create_roads_active) { int mph = 0.5 / avg_cycle_time * (3600000000.0 / 5280.0); s << "RUNNING - SPEED " << mph; } else { s << "STOPPED"; } d.text_draw(s.str(), 5, 0, 1); s.str(""); s << "X,Y,DIR: " << static_cast<int>(create_road_x) << " " << static_cast<int>(create_road_y) << " " << static_cast<int>(create_road_dir); d.text_draw(s.str(), 6, 0, 1); } // additional drawing: message box if (message_age < MAX_MESSAGE_AGE) { d.text_draw(message, 17, 0, 1); message_age++; } // register for events int eid_clear=-1, eid_write=-1, eid_reset=-1, eid_quit=-1, eid_quit_win=-1, eid_pan=-1, eid_zoom=-1; int eid_create_roads=-1; int eid_1=-1, eid_9=-1, eid_run=-1, eid_stop=-1, eid_done=-1; __attribute__((unused)) int eid_2=-1, eid_3=-1, eid_4=-1, eid_5=-1, eid_6=-1, eid_7=-1, eid_8=-1; eid_write = d.text_draw("WRITE", 13, 0, 1, true); eid_quit = d.text_draw("QUIT", 13, 10, 1, true); eid_reset = d.text_draw("RESET", 15, 0, 1, true); eid_clear = d.text_draw("CLEAR", 15, 10, 1, true); eid_quit_win = d.event_register(display::ET_QUIT); eid_pan = d.event_register(display::ET_MOUSE_MOTION, 0); eid_zoom = d.event_register(display::ET_MOUSE_WHEEL, 0); switch (mode) { case MAIN: eid_create_roads = d.text_draw("CREATE_ROADS", 0, 0, 1, true); // r,c,pid,event break; case CREATE_ROADS: eid_1 = d.text_draw("1", 0, 0, 1, true, '1'); eid_2 = d.text_draw("2", 0, 2, 1, true, '2'); eid_3 = d.text_draw("3", 0, 4, 1, true, '3'); eid_4 = d.text_draw("4", 0, 6, 1, true, '4'); eid_5 = d.text_draw("5", 0, 8, 1, true, '5'); eid_6 = d.text_draw("6", 0,10, 1, true, '6'); eid_7 = d.text_draw("7", 0,12, 1, true, '7'); eid_8 = d.text_draw("8", 0,14, 1, true, '8'); eid_9 = d.text_draw("9", 0,16, 1, true, '9'); eid_run = d.text_draw("RUN", 3, 0, 1, true, 'g'); eid_stop = d.text_draw("STOP", 3, 7, 1, true, 's'); eid_done = d.text_draw("DONE", 3,14, 1, true, 'd'); break; } // finish/ d.finish(); // event handling event = d.event_poll(); do { // common events if (event.eid == display::EID_NONE) { break; } if (event.eid == eid_quit_win || event.eid == eid_quit) { done = true; break; } if (event.eid == eid_clear) { w.clear(); break; } if (event.eid == eid_write) { w.write(); message = w.write_ok() ? "WRITE SUCCESS" : "WRITE FAILURE"; message_age = 0; break; } if (event.eid == eid_reset) { w.read(); message = w.read_ok() ? "READ SUCCESS" : "READ FAILURE"; message_age = 0; break; } if (event.eid == eid_pan) { center_x -= (double)event.val1 * 8 / zoom; center_y -= (double)event.val2 * 8 / zoom; break; } if (event.eid == eid_zoom) { if (event.val2 < 0 && zoom > MIN_ZOOM) { zoom /= ZOOM_FACTOR; } if (event.val2 > 0 && zoom < MAX_ZOOM) { zoom *= ZOOM_FACTOR; } break; } // MAIN mode events if (mode == MAIN) { if (event.eid == eid_create_roads) { mode = CREATE_ROADS; break; } } // CREATE_ROADS mode events if (mode == CREATE_ROADS) { if (event.eid == eid_run) { create_roads_active = true; break; } if (event.eid == eid_stop) { create_roads_active = false; break; } if (event.eid == eid_done) { create_roads_active = false; mode = MAIN; break; } if (event.eid >= eid_1 && event.eid <= eid_9) { create_road_dir_idx = event.eid - eid_1 + 1; } } } while (0); // delay microsec_sleep(DELAY_MICROSECS); } return 0; } <commit_msg>comments<commit_after>// XXX add edit pixels // - on clear, reset cursor // - add ability to move cursor // XXX EDIT display ptr to current dir rate // - set cursor, and direction // - display cursor when in this mode, both in text and on display #include <sstream> #include <unistd.h> #include <string.h> #include "display.h" #include "world.h" #include "logging.h" #include "utils.h" using std::ostringstream; #define PANE_WORLD_WIDTH 800 #define PANE_WORLD_HEIGHT 800 #define PANE_CTRL_WIDTH 600 #define PANE_CTRL_HEIGHT 800 #define PANE_SEPERATION 20 #define DISPLAY_WIDTH (PANE_WORLD_WIDTH + PANE_SEPERATION + PANE_CTRL_WIDTH) #define DISPLAY_HEIGHT (PANE_WORLD_HEIGHT >= PANE_CTRL_HEIGHT ? PANE_WORLD_HEIGHT : PANE_CTRL_HEIGHT) const double ZOOM_FACTOR = 1.1892071; const double MAX_ZOOM = 64.0 - .01; const double MIN_ZOOM = (1.0 / ZOOM_FACTOR) + .01; double zoom = 1.0 / ZOOM_FACTOR; double center_x = world::WORLD_WIDTH / 2; double center_y = world::WORLD_HEIGHT / 2; int main_edit(string world_filename); // ----------------- MAIN ------------------------------------------------------------------------ int main(int argc, char **argv) { bool opt_edit = false; string world_filename; // get options while (true) { char opt_char = getopt(argc, argv, "e"); if (opt_char == -1) { break; } switch (opt_char) { case 'e': opt_edit = true; break; default: return 1; } } // get args world_filename = "world.dat"; if ((argc - optind) >= 1) { world_filename = argv[optind]; } // handle edit mode0 if (opt_edit) { return main_edit(world_filename); } // terminate return 0; } // ----------------- EDIT ------------------------------------------------------------------------ int main_edit(string world_filename) { enum mode { MAIN, CREATE_ROADS }; const int MAX_MESSAGE_AGE = 200; const int DELAY_MICROSECS = 10000; enum mode mode = MAIN; struct display::event event = {display::EID_NONE,0,0}; bool done = false; bool create_roads_run = false; double create_road_x = 2048; double create_road_y = 2048; double create_road_dir = 0; int create_road_dir_idx = 5; string message = ""; int message_age = MAX_MESSAGE_AGE; double avg_cycle_time = DELAY_MICROSECS; // create the display display d(DISPLAY_WIDTH, DISPLAY_HEIGHT); // create the world world w(d,world_filename); message = w.read_ok() ? "READ SUCCESS" : "READ FAILURE"; message_age = 0; // loop while (!done) { // determine average cycle time // xxx make this a routine { const int MAX_TIMES=10; static long times[MAX_TIMES]; memmove(times+1, times, (MAX_TIMES-1)*sizeof(long)); times[0] = microsec_timer(); if (times[MAX_TIMES-1] != 0) { avg_cycle_time = (times[0] - times[MAX_TIMES-1]) / (MAX_TIMES-1); } // xxx temp static int count; if ((++count % 100) == 0) { INFO("AVG CYCLE TIME " << avg_cycle_time / 1000. << endl); } } // start display update d.start(0, 0, PANE_WORLD_WIDTH, PANE_WORLD_HEIGHT, // pane 0: x,y,w,h PANE_WORLD_WIDTH+PANE_SEPERATION, 0, PANE_CTRL_WIDTH, PANE_CTRL_HEIGHT); // pane 1: x,y,w,h // draw world w.place_car_init(); w.place_car(create_road_x, create_road_y, create_road_dir); w.draw(0,center_x,center_y,zoom); // draw for mode CREATE_ROADS if (mode == CREATE_ROADS) { ostringstream s; // xxx comments if (create_roads_run) { // xxx dont go off end of world // xxx return distance w.create_road_slice(create_road_x, create_road_y, create_road_dir); create_road_dir += (create_road_dir_idx - 5) * 0.05; if (create_road_dir < 0) { create_road_dir += 360; } else if (create_road_dir > 360) { create_road_dir -= 360; } } d.text_draw("^", 1, 2*(create_road_dir_idx-1), 1); s.str(""); if (create_roads_run) { int mph = 0.5 / avg_cycle_time * (3600000000.0 / 5280.0); s << "RUNNING - SPEED " << mph; } else { s << "STOPPED"; } d.text_draw(s.str(), 5, 0, 1); s.str(""); s << "X,Y,DIR: " << static_cast<int>(create_road_x) << " " << static_cast<int>(create_road_y) << " " << static_cast<int>(create_road_dir); d.text_draw(s.str(), 6, 0, 1); } // draw the message box if (message_age < MAX_MESSAGE_AGE) { d.text_draw(message, 17, 0, 1); message_age++; } // draw and register events int eid_clear=-1, eid_write=-1, eid_reset=-1, eid_quit=-1, eid_quit_win=-1, eid_pan=-1, eid_zoom=-1; int eid_create_roads=-1; int eid_1=-1, eid_9=-1, eid_run=-1, eid_stop=-1, eid_done=-1; __attribute__((unused)) int eid_2=-1, eid_3=-1, eid_4=-1, eid_5=-1, eid_6=-1, eid_7=-1, eid_8=-1; eid_write = d.text_draw("WRITE", 13, 0, 1, true); eid_quit = d.text_draw("QUIT", 13, 10, 1, true); eid_reset = d.text_draw("RESET", 15, 0, 1, true); eid_clear = d.text_draw("CLEAR", 15, 10, 1, true); eid_quit_win = d.event_register(display::ET_QUIT); eid_pan = d.event_register(display::ET_MOUSE_MOTION, 0); eid_zoom = d.event_register(display::ET_MOUSE_WHEEL, 0); switch (mode) { case MAIN: eid_create_roads = d.text_draw("CREATE_ROADS", 0, 0, 1, true); // r,c,pid,event break; case CREATE_ROADS: eid_1 = d.text_draw("1", 0, 0, 1, true, '1'); eid_2 = d.text_draw("2", 0, 2, 1, true, '2'); eid_3 = d.text_draw("3", 0, 4, 1, true, '3'); eid_4 = d.text_draw("4", 0, 6, 1, true, '4'); eid_5 = d.text_draw("5", 0, 8, 1, true, '5'); eid_6 = d.text_draw("6", 0,10, 1, true, '6'); eid_7 = d.text_draw("7", 0,12, 1, true, '7'); eid_8 = d.text_draw("8", 0,14, 1, true, '8'); eid_9 = d.text_draw("9", 0,16, 1, true, '9'); eid_run = d.text_draw("RUN", 3, 0, 1, true, 'g'); eid_stop = d.text_draw("STOP", 3, 7, 1, true, 's'); eid_done = d.text_draw("DONE", 3,14, 1, true, 'd'); break; } // finish, updates the display d.finish(); // event handling event = d.event_poll(); do { // common events if (event.eid == display::EID_NONE) { break; } if (event.eid == eid_quit_win || event.eid == eid_quit) { done = true; break; } if (event.eid == eid_clear) { w.clear(); break; } if (event.eid == eid_write) { w.write(); message = w.write_ok() ? "WRITE SUCCESS" : "WRITE FAILURE"; message_age = 0; break; } if (event.eid == eid_reset) { w.read(); message = w.read_ok() ? "READ SUCCESS" : "READ FAILURE"; message_age = 0; break; } if (event.eid == eid_pan) { center_x -= (double)event.val1 * 8 / zoom; center_y -= (double)event.val2 * 8 / zoom; break; } if (event.eid == eid_zoom) { if (event.val2 < 0 && zoom > MIN_ZOOM) { zoom /= ZOOM_FACTOR; } if (event.val2 > 0 && zoom < MAX_ZOOM) { zoom *= ZOOM_FACTOR; } break; } // MAIN mode events if (mode == MAIN) { if (event.eid == eid_create_roads) { mode = CREATE_ROADS; break; } } // CREATE_ROADS mode events if (mode == CREATE_ROADS) { if (event.eid == eid_run) { create_roads_run = true; break; } if (event.eid == eid_stop) { create_roads_run = false; break; } if (event.eid == eid_done) { create_roads_run = false; mode = MAIN; break; } if (event.eid >= eid_1 && event.eid <= eid_9) { create_road_dir_idx = event.eid - eid_1 + 1; } } } while (0); // delay microsec_sleep(DELAY_MICROSECS); } return 0; } <|endoftext|>
<commit_before>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2009 Steven Noonan. * Licensed under the New BSD License. * */ #include <crisscross/universal_include.h> #include <crisscross/debug.h> #include <crisscross/mutex.h> #ifndef TARGET_OS_NDSFIRMWARE namespace CrissCross { namespace System { Mutex::Mutex(MutexType _type) : m_type(_type) { m_lockCount = 0; #ifdef TARGET_OS_WINDOWS InitializeCriticalSection(&m_mutex); #else int error; error = pthread_mutexattr_init(&m_mutexAttr); CoreAssert(error == 0); int ptype = 0; switch (m_type) { case MUTEX_TYPE_NORMAL: ptype = PTHREAD_MUTEX_NORMAL; break; case MUTEX_TYPE_ERRORCHECK: ptype = PTHREAD_MUTEX_ERRORCHECK; break; case MUTEX_TYPE_RECURSIVE: default: ptype = PTHREAD_MUTEX_RECURSIVE; break; } error = pthread_mutexattr_settype(&m_mutexAttr, ptype); CoreAssert(error == 0); error = pthread_mutex_init(&m_mutex, &m_mutexAttr); CoreAssert(error == 0); #endif } Mutex::~Mutex() { CoreAssert(m_lockCount == 0); #ifdef TARGET_OS_WINDOWS DeleteCriticalSection(&m_mutex); #else pthread_mutex_destroy(&m_mutex); pthread_mutexattr_destroy(&m_mutexAttr); #endif } void Mutex::Lock() { #ifdef TARGET_OS_WINDOWS EnterCriticalSection(&m_mutex); #else int error = pthread_mutex_lock(&m_mutex); CoreAssert(error == 0); #endif m_lockCount++; } void Mutex::Unlock() { #ifdef TARGET_OS_WINDOWS LeaveCriticalSection(&m_mutex); #else int error = pthread_mutex_unlock(&m_mutex); CoreAssert(error == 0); #endif m_lockCount--; } MutexHolder::MutexHolder(Mutex *_mutex) : m_mutex(_mutex) { m_mutex->Lock(); } MutexHolder::~MutexHolder() { m_mutex->Unlock(); } ReadWriteLock::ReadWriteLock(bool _writePriority) { #ifdef TARGET_OS_WINDOWS wrpriority = _writePriority; rdcount = rdwaiting = wrcount = wrwaiting = 0; InitializeCriticalSection(&rwcs); rdgreen = CreateEvent(NULL, FALSE, TRUE, NULL); wrgreen = CreateEvent(NULL, FALSE, TRUE, NULL); #else int ret; ret = pthread_rwlockattr_init(&m_rwlockAttr); CoreAssert(ret == 0); ret = pthread_rwlockattr_setpshared(&m_rwlockAttr, PTHREAD_PROCESS_SHARED); CoreAssert(ret == 0); ret = pthread_rwlock_init(&m_rwlock, &m_rwlockAttr); CoreAssert(ret == 0); #endif } ReadWriteLock::~ReadWriteLock() { #ifdef TARGET_OS_WINDOWS CloseHandle(rdgreen); CloseHandle(wrgreen); DeleteCriticalSection(&rwcs); #else pthread_rwlock_destroy(&m_rwlock); pthread_rwlockattr_destroy(&m_rwlockAttr); #endif } bool ReadWriteLock::LockRead() { #ifdef TARGET_OS_WINDOWS bool wait = false; DWORD timeout = INFINITE; do { EnterCriticalSection(&rwcs); // // acquire lock if // - there are no active writers and // - readers have priority or // - writers have priority and there are no waiting writers // if(!wrcount && (!wrpriority || !wrwaiting)) { if(wait) { rdwaiting--; wait = false; } rdcount++; } else { if(!wait) { rdwaiting++; wait = true; } // always reset the event to avoid 100% CPU usage ResetEvent(rdgreen); } LeaveCriticalSection(&rwcs); if (wait) { if (WaitForSingleObject(rdgreen, timeout) != WAIT_OBJECT_0) { EnterCriticalSection(&rwcs); rdwaiting--; SetEvent(rdgreen); SetEvent(wrgreen); LeaveCriticalSection(&rwcs); return false; } } } while (wait); return true; #else int ret = pthread_rwlock_rdlock(&m_rwlock); return (ret == 0); #endif } bool ReadWriteLock::LockWrite() { #ifdef TARGET_OS_WINDOWS bool wait = false; DWORD timeout = INFINITE; do { EnterCriticalSection(&rwcs); // // acquire lock if // - there are no active readers nor writers and // - writers have priority or // - readers have priority and there are no waiting readers // if (!rdcount && !wrcount && (wrpriority || !rdwaiting)) { if(wait) { wrwaiting--; wait = false; } wrcount++; } else { if(!wait) { wrwaiting++; wait = true; } // always reset the event to avoid 100% CPU usage ResetEvent(wrgreen); } LeaveCriticalSection(&rwcs); if (wait) { if (WaitForSingleObject(wrgreen, timeout) != WAIT_OBJECT_0) { EnterCriticalSection(&rwcs); wrwaiting--; SetEvent(rdgreen); SetEvent(wrgreen); LeaveCriticalSection(&rwcs); return false; } } } while (wait); return true; #else int ret = pthread_rwlock_wrlock(&m_rwlock); return (ret == 0); #endif } #ifdef TARGET_OS_WINDOWS void ReadWriteLock::UnlockRead() { EnterCriticalSection(&rwcs); rdcount--; // always release waiting threads (do not check for rdcount == 0) if (wrpriority) { if (wrwaiting) SetEvent(wrgreen); else if (rdwaiting) SetEvent(rdgreen); } else { if (rdwaiting) SetEvent(rdgreen); else if (wrwaiting) SetEvent(wrgreen); } LeaveCriticalSection(&rwcs); } void ReadWriteLock::UnlockWrite() { EnterCriticalSection(&rwcs); wrcount--; if (wrpriority) { if (wrwaiting) SetEvent(wrgreen); else if (rdwaiting) SetEvent(rdgreen); } else { if (rdwaiting) SetEvent(rdgreen); else if (wrwaiting) SetEvent(wrgreen); } LeaveCriticalSection(&rwcs); } #else void ReadWriteLock::Unlock() { pthread_rwlock_unlock(&m_rwlock); } #endif RWLockHolder::RWLockHolder(ReadWriteLock *_lock, RWLockHolderType _type) : m_lock(_lock), m_type(_type) { CoreAssert(_lock); switch(_type) { case LOCK_READ: m_lock->LockRead(); break; case LOCK_WRITE: m_lock->LockWrite(); break; default: CoreAssert(_type != LOCK_READ && _type != LOCK_WRITE); } } RWLockHolder::~RWLockHolder() { #ifdef TARGET_OS_WINDOWS switch(m_type) { case LOCK_READ: m_lock->UnlockRead(); break; case LOCK_WRITE: m_lock->UnlockWrite(); break; default: CoreAssert(m_type != LOCK_READ && m_type != LOCK_WRITE); } #else m_lock->Unlock(); #endif } } } #endif <commit_msg>mutex.cpp: fix mixed line endings<commit_after>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2009 Steven Noonan. * Licensed under the New BSD License. * */ #include <crisscross/universal_include.h> #include <crisscross/debug.h> #include <crisscross/mutex.h> #ifndef TARGET_OS_NDSFIRMWARE namespace CrissCross { namespace System { Mutex::Mutex(MutexType _type) : m_type(_type) { m_lockCount = 0; #ifdef TARGET_OS_WINDOWS InitializeCriticalSection(&m_mutex); #else int error; error = pthread_mutexattr_init(&m_mutexAttr); CoreAssert(error == 0); int ptype = 0; switch (m_type) { case MUTEX_TYPE_NORMAL: ptype = PTHREAD_MUTEX_NORMAL; break; case MUTEX_TYPE_ERRORCHECK: ptype = PTHREAD_MUTEX_ERRORCHECK; break; case MUTEX_TYPE_RECURSIVE: default: ptype = PTHREAD_MUTEX_RECURSIVE; break; } error = pthread_mutexattr_settype(&m_mutexAttr, ptype); CoreAssert(error == 0); error = pthread_mutex_init(&m_mutex, &m_mutexAttr); CoreAssert(error == 0); #endif } Mutex::~Mutex() { CoreAssert(m_lockCount == 0); #ifdef TARGET_OS_WINDOWS DeleteCriticalSection(&m_mutex); #else pthread_mutex_destroy(&m_mutex); pthread_mutexattr_destroy(&m_mutexAttr); #endif } void Mutex::Lock() { #ifdef TARGET_OS_WINDOWS EnterCriticalSection(&m_mutex); #else int error = pthread_mutex_lock(&m_mutex); CoreAssert(error == 0); #endif m_lockCount++; } void Mutex::Unlock() { #ifdef TARGET_OS_WINDOWS LeaveCriticalSection(&m_mutex); #else int error = pthread_mutex_unlock(&m_mutex); CoreAssert(error == 0); #endif m_lockCount--; } MutexHolder::MutexHolder(Mutex *_mutex) : m_mutex(_mutex) { m_mutex->Lock(); } MutexHolder::~MutexHolder() { m_mutex->Unlock(); } ReadWriteLock::ReadWriteLock(bool _writePriority) { #ifdef TARGET_OS_WINDOWS wrpriority = _writePriority; rdcount = rdwaiting = wrcount = wrwaiting = 0; InitializeCriticalSection(&rwcs); rdgreen = CreateEvent(NULL, FALSE, TRUE, NULL); wrgreen = CreateEvent(NULL, FALSE, TRUE, NULL); #else int ret; ret = pthread_rwlockattr_init(&m_rwlockAttr); CoreAssert(ret == 0); ret = pthread_rwlockattr_setpshared(&m_rwlockAttr, PTHREAD_PROCESS_SHARED); CoreAssert(ret == 0); ret = pthread_rwlock_init(&m_rwlock, &m_rwlockAttr); CoreAssert(ret == 0); #endif } ReadWriteLock::~ReadWriteLock() { #ifdef TARGET_OS_WINDOWS CloseHandle(rdgreen); CloseHandle(wrgreen); DeleteCriticalSection(&rwcs); #else pthread_rwlock_destroy(&m_rwlock); pthread_rwlockattr_destroy(&m_rwlockAttr); #endif } bool ReadWriteLock::LockRead() { #ifdef TARGET_OS_WINDOWS bool wait = false; DWORD timeout = INFINITE; do { EnterCriticalSection(&rwcs); // // acquire lock if // - there are no active writers and // - readers have priority or // - writers have priority and there are no waiting writers // if(!wrcount && (!wrpriority || !wrwaiting)) { if(wait) { rdwaiting--; wait = false; } rdcount++; } else { if(!wait) { rdwaiting++; wait = true; } // always reset the event to avoid 100% CPU usage ResetEvent(rdgreen); } LeaveCriticalSection(&rwcs); if (wait) { if (WaitForSingleObject(rdgreen, timeout) != WAIT_OBJECT_0) { EnterCriticalSection(&rwcs); rdwaiting--; SetEvent(rdgreen); SetEvent(wrgreen); LeaveCriticalSection(&rwcs); return false; } } } while (wait); return true; #else int ret = pthread_rwlock_rdlock(&m_rwlock); return (ret == 0); #endif } bool ReadWriteLock::LockWrite() { #ifdef TARGET_OS_WINDOWS bool wait = false; DWORD timeout = INFINITE; do { EnterCriticalSection(&rwcs); // // acquire lock if // - there are no active readers nor writers and // - writers have priority or // - readers have priority and there are no waiting readers // if (!rdcount && !wrcount && (wrpriority || !rdwaiting)) { if(wait) { wrwaiting--; wait = false; } wrcount++; } else { if(!wait) { wrwaiting++; wait = true; } // always reset the event to avoid 100% CPU usage ResetEvent(wrgreen); } LeaveCriticalSection(&rwcs); if (wait) { if (WaitForSingleObject(wrgreen, timeout) != WAIT_OBJECT_0) { EnterCriticalSection(&rwcs); wrwaiting--; SetEvent(rdgreen); SetEvent(wrgreen); LeaveCriticalSection(&rwcs); return false; } } } while (wait); return true; #else int ret = pthread_rwlock_wrlock(&m_rwlock); return (ret == 0); #endif } #ifdef TARGET_OS_WINDOWS void ReadWriteLock::UnlockRead() { EnterCriticalSection(&rwcs); rdcount--; // always release waiting threads (do not check for rdcount == 0) if (wrpriority) { if (wrwaiting) SetEvent(wrgreen); else if (rdwaiting) SetEvent(rdgreen); } else { if (rdwaiting) SetEvent(rdgreen); else if (wrwaiting) SetEvent(wrgreen); } LeaveCriticalSection(&rwcs); } void ReadWriteLock::UnlockWrite() { EnterCriticalSection(&rwcs); wrcount--; if (wrpriority) { if (wrwaiting) SetEvent(wrgreen); else if (rdwaiting) SetEvent(rdgreen); } else { if (rdwaiting) SetEvent(rdgreen); else if (wrwaiting) SetEvent(wrgreen); } LeaveCriticalSection(&rwcs); } #else void ReadWriteLock::Unlock() { pthread_rwlock_unlock(&m_rwlock); } #endif RWLockHolder::RWLockHolder(ReadWriteLock *_lock, RWLockHolderType _type) : m_lock(_lock), m_type(_type) { CoreAssert(_lock); switch(_type) { case LOCK_READ: m_lock->LockRead(); break; case LOCK_WRITE: m_lock->LockWrite(); break; default: CoreAssert(_type != LOCK_READ && _type != LOCK_WRITE); } } RWLockHolder::~RWLockHolder() { #ifdef TARGET_OS_WINDOWS switch(m_type) { case LOCK_READ: m_lock->UnlockRead(); break; case LOCK_WRITE: m_lock->UnlockWrite(); break; default: CoreAssert(m_type != LOCK_READ && m_type != LOCK_WRITE); } #else m_lock->Unlock(); #endif } } } #endif <|endoftext|>
<commit_before>// Copyright © 2013, Université catholique de Louvain // 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. // // 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 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. #ifndef MOZART_WINDOWS # error "This program is Windows-specific, it must not be compiled on other platforms." #endif #include <iostream> #include <windows.h> inline size_t nposToMinus1(size_t pos) { return pos == std::string::npos ? -1 : pos; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { // Compute ozengine.exe path from my own path char buffer[2048]; GetModuleFileName(nullptr, buffer, sizeof(buffer)); std::string myPath(buffer); size_t backslashPos = nposToMinus1(myPath.rfind('\\')); std::string ozenginePath = myPath.substr(0, backslashPos+1) + "ozengine.exe"; // Construct the command line std::string cmdline = std::string("\"") + ozenginePath + "\" x-oz://system/Compile.ozf " + lpszCmdLine; // Execute ozengine STARTUPINFOA si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; SetHandleInformation(GetStdHandle(STD_INPUT_HANDLE), HANDLE_FLAG_INHERIT,HANDLE_FLAG_INHERIT); SetHandleInformation(GetStdHandle(STD_OUTPUT_HANDLE), HANDLE_FLAG_INHERIT,HANDLE_FLAG_INHERIT); SetHandleInformation(GetStdHandle(STD_ERROR_HANDLE), HANDLE_FLAG_INHERIT,HANDLE_FLAG_INHERIT); si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError = GetStdHandle(STD_ERROR_HANDLE); PROCESS_INFORMATION pinf; if (!CreateProcessA(const_cast<char*>(ozenginePath.c_str()), const_cast<char*>(cmdline.c_str()), nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pinf)) { std::cerr << "panic: cannot start ozengine" << std::endl; return 254; } // Wait for completion WaitForSingleObject(pinf.hProcess, INFINITE); // Get the exit code DWORD exitCode; if (!GetExitCodeProcess(pinf.hProcess, &exitCode)) exitCode = 255; // Close the handles CloseHandle(pinf.hProcess); CloseHandle(pinf.hThread); return exitCode; } <commit_msg>Fix non-displaying ozc messages in Windows<commit_after>// Copyright © 2013, Université catholique de Louvain // 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. // // 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 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. #ifndef MOZART_WINDOWS # error "This program is Windows-specific, it must not be compiled on other platforms." #endif #include <iostream> #include <windows.h> inline size_t nposToMinus1(size_t pos) { return pos == std::string::npos ? -1 : pos; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { // Compute ozengine.exe path from my own path char buffer[2048]; GetModuleFileName(nullptr, buffer, sizeof(buffer)); std::string myPath(buffer); size_t backslashPos = nposToMinus1(myPath.rfind('\\')); std::string ozenginePath = myPath.substr(0, backslashPos+1) + "ozengine.exe"; // Construct the command line std::string cmdline = std::string("\"") + ozenginePath + "\" x-oz://system/Compile.ozf " + lpszCmdLine; // Execute ozengine STARTUPINFOA si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; SetHandleInformation(GetStdHandle(STD_INPUT_HANDLE), HANDLE_FLAG_INHERIT,HANDLE_FLAG_INHERIT); SetHandleInformation(GetStdHandle(STD_OUTPUT_HANDLE), HANDLE_FLAG_INHERIT,HANDLE_FLAG_INHERIT); SetHandleInformation(GetStdHandle(STD_ERROR_HANDLE), HANDLE_FLAG_INHERIT,HANDLE_FLAG_INHERIT); si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError = GetStdHandle(STD_ERROR_HANDLE); PROCESS_INFORMATION pinf; if (!CreateProcessA(const_cast<char*>(ozenginePath.c_str()), const_cast<char*>(cmdline.c_str()), nullptr, nullptr, true, 0, nullptr, nullptr, &si, &pinf)) { std::cerr << "panic: cannot start ozengine" << std::endl; return 254; } // Wait for completion WaitForSingleObject(pinf.hProcess, INFINITE); // Get the exit code DWORD exitCode; if (!GetExitCodeProcess(pinf.hProcess, &exitCode)) exitCode = 255; // Close the handles CloseHandle(pinf.hProcess); CloseHandle(pinf.hThread); return exitCode; } <|endoftext|>
<commit_before>//needed for testing #define CATCH_CONFIG_RUNNER #include <catch.hpp> //other stuff needed #include <glm/vec3.hpp> #include <cmath> #include <iostream> //include classes for testing #include "shape.hpp" #include "sphere.hpp" #include "box.hpp" #include "material.hpp" #include "color.hpp" // ---------------------------------- // SHAPE TESTS // ---------------------------------- TEST_CASE("getter shape","[shape]") { Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f}; REQUIRE(s.get_name() == "name"); Material c{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}; REQUIRE(s.get_material() == c); //added operator == in color.hpp } TEST_CASE("operator<< and print shape","[shape]") { Sphere es {"empty_sphere"}; std::cout << es; Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f}; std::cout << s; } // ---------------------------------- // SPHERE TESTS // ---------------------------------- TEST_CASE("constructors of sphere","[sphere]") { Sphere s1 {"name"}; Sphere s2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f}; REQUIRE(s1.get_center() == s2.get_center()); REQUIRE(s1.get_radius() == s2.get_radius()); } TEST_CASE("get_center and get_radius","[sphere]") { Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f}; REQUIRE(s.get_radius() == 1.0f); REQUIRE(s.get_center() == glm::vec3{0.0f}); } TEST_CASE("area","[sphere]") { Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f}; REQUIRE(12.566f == Approx(s.area()).epsilon(0.001)); } TEST_CASE("volume","[sphere]") { Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f}; REQUIRE(4.189 == Approx(s.volume()).epsilon(0.001)); } TEST_CASE("print sphere","[sphere]") { Sphere es {"empty_sphere"}; std::cout << es; Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f}; std::cout << s; } // ---------------------------------- // BOX TESTS // ---------------------------------- TEST_CASE("constructors of box","[box]") { Box b1 {"name"}; Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}}; REQUIRE(b1.get_min() == b2.get_min()); REQUIRE(b1.get_max() == b2.get_max()); } TEST_CASE("get_min and get_max","[box]") { Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}}; REQUIRE(b2.get_min() == glm::vec3{0.0f}); REQUIRE(b2.get_max() == glm::vec3{1.0f}); } TEST_CASE("area of box","[box]") { Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}}; REQUIRE(6.0f == Approx(b2.area()).epsilon(0.001)); } TEST_CASE("volume of box","[box]") { Box b2 {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}}; REQUIRE(1.0f == Approx(b2.volume()).epsilon(0.001)); } TEST_CASE("print box","[box]") { Box eb {"empty_box"}; std::cout << eb; Box b {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}}; std::cout << b; } // ---------------------------------- // AUFGABE 5.6 TEST // ---------------------------------- TEST_CASE("intersectRaySphere", "[intersect]") { //Ray glm::vec3 ray_origin{0.0f, 0.0f, 0.0f}; //ray direction has to be normalized ! //you can use: //v = glm::normalize(some_vector); glm::vec3 ray_direction{0.0f, 0.0f, 1.0f}; //Sphere glm::vec3 sphere_center{0.0f, 0.0f, 5.0f}; float sphere_radius{1.0f}; float distance{0.0f}; auto result = glm::intersectRaySphere( ray_origin, ray_direction, sphere_center, sphere_radius * sphere_radius, distance); REQUIRE(distance == Approx(4.0f)); Sphere s {"some_sphere", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, sphere_center, sphere_radius}; Ray r {ray_origin,ray_direction}; s.intersect(r,distance); REQUIRE(distance == Approx(4.0f)); } // ---------------------------------- // AUFGABE 5.8 TEST // ---------------------------------- TEST_CASE("virtual", "[Destructors]") { std::cout << "\ntesting virtual and non-virtual construction and destruction\n"; Color c_red {255.0f, 0.0f, 0.0f}; Material red {"", c_red, c_red, c_red, 0.0f}; glm::vec3 position {0.0f,0.0f,0.0f}; std::cout << "Create s1\n"; Sphere* s1 = new Sphere("sphere0",red,position,1.2f); std::cout << "Create s2\n"; Shape* s2 = new Sphere("sphere1",red,position,1.2f); std::cout << "Printing objects: \n"; std::cout << *s1; std::cout << *s2 << "\n"; std::cout << "Delete s1\n"; delete s1; std::cout << "Delete s2\n"; delete s2; } // ---------------------------------- // MATERIAL Tests // ---------------------------------- TEST_CASE("material in place of color struct", "Material") { Color c{0.0f,0.0f,0.0f}; Material mate1 {}; std::cout << mate1; Material mate2 {"some material",c,c,c,0.0f}; std::cout << mate2; } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } <commit_msg>:heart:<commit_after>//needed for testing #define CATCH_CONFIG_RUNNER #include <catch.hpp> //other stuff needed #include <glm/vec3.hpp> #include <cmath> #include <iostream> //include classes for testing #include "shape.hpp" #include "sphere.hpp" #include "box.hpp" #include "material.hpp" #include "color.hpp" // ---------------------------------- // SHAPE TESTS // ---------------------------------- //hallo ich heiße lissy tschüß TEST_CASE("getter shape","[shape]") { Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f}; REQUIRE(s.get_name() == "name"); Material c{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}; REQUIRE(s.get_material() == c); //added operator == in color.hpp } TEST_CASE("operator<< and print shape","[shape]") { Sphere es {"empty_sphere"}; std::cout << es; Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f}; std::cout << s; } // ---------------------------------- // SPHERE TESTS // ---------------------------------- TEST_CASE("constructors of sphere","[sphere]") { Sphere s1 {"name"}; Sphere s2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f}; REQUIRE(s1.get_center() == s2.get_center()); REQUIRE(s1.get_radius() == s2.get_radius()); } TEST_CASE("get_center and get_radius","[sphere]") { Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f}; REQUIRE(s.get_radius() == 1.0f); REQUIRE(s.get_center() == glm::vec3{0.0f}); } TEST_CASE("area","[sphere]") { Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f}; REQUIRE(12.566f == Approx(s.area()).epsilon(0.001)); } TEST_CASE("volume","[sphere]") { Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f}; REQUIRE(4.189 == Approx(s.volume()).epsilon(0.001)); } TEST_CASE("print sphere","[sphere]") { Sphere es {"empty_sphere"}; std::cout << es; Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f}; std::cout << s; } // ---------------------------------- // BOX TESTS // ---------------------------------- TEST_CASE("constructors of box","[box]") { Box b1 {"name"}; Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}}; REQUIRE(b1.get_min() == b2.get_min()); REQUIRE(b1.get_max() == b2.get_max()); } TEST_CASE("get_min and get_max","[box]") { Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}}; REQUIRE(b2.get_min() == glm::vec3{0.0f}); REQUIRE(b2.get_max() == glm::vec3{1.0f}); } TEST_CASE("area of box","[box]") { Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}}; REQUIRE(6.0f == Approx(b2.area()).epsilon(0.001)); } TEST_CASE("volume of box","[box]") { Box b2 {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}}; REQUIRE(1.0f == Approx(b2.volume()).epsilon(0.001)); } TEST_CASE("print box","[box]") { Box eb {"empty_box"}; std::cout << eb; Box b {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}}; std::cout << b; } // ---------------------------------- // AUFGABE 5.6 TEST // ---------------------------------- TEST_CASE("intersectRaySphere", "[intersect]") { //Ray glm::vec3 ray_origin{0.0f, 0.0f, 0.0f}; //ray direction has to be normalized ! //you can use: //v = glm::normalize(some_vector); glm::vec3 ray_direction{0.0f, 0.0f, 1.0f}; //Sphere glm::vec3 sphere_center{0.0f, 0.0f, 5.0f}; float sphere_radius{1.0f}; float distance{0.0f}; auto result = glm::intersectRaySphere( ray_origin, ray_direction, sphere_center, sphere_radius * sphere_radius, distance); REQUIRE(distance == Approx(4.0f)); Sphere s {"some_sphere", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, sphere_center, sphere_radius}; Ray r {ray_origin,ray_direction}; s.intersect(r,distance); REQUIRE(distance == Approx(4.0f)); } // ---------------------------------- // AUFGABE 5.8 TEST // ---------------------------------- TEST_CASE("virtual", "[Destructors]") { std::cout << "\ntesting virtual and non-virtual construction and destruction\n"; Color c_red {255.0f, 0.0f, 0.0f}; Material red {"", c_red, c_red, c_red, 0.0f}; glm::vec3 position {0.0f,0.0f,0.0f}; std::cout << "Create s1\n"; Sphere* s1 = new Sphere("sphere0",red,position,1.2f); std::cout << "Create s2\n"; Shape* s2 = new Sphere("sphere1",red,position,1.2f); std::cout << "Printing objects: \n"; std::cout << *s1; std::cout << *s2 << "\n"; std::cout << "Delete s1\n"; delete s1; std::cout << "Delete s2\n"; delete s2; } // ---------------------------------- // MATERIAL Tests // ---------------------------------- TEST_CASE("material in place of color struct", "Material") { Color c{0.0f,0.0f,0.0f}; Material mate1 {}; std::cout << mate1; Material mate2 {"some material",c,c,c,0.0f}; std::cout << mate2; } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } <|endoftext|>