text
stringlengths
54
60.6k
<commit_before>#include <iostream> #include <vector> #include <node.hpp> #include "redblacktree.hpp" int main() { std::vector<int> v = {6,5,9}; ch13::RedBlackTree<int,std::string> tree; for(auto i : v) tree.insert(i); tree.print(); std::cout << "length = " << v.size() << std::endl; return 0; } <commit_msg>testing remove On branch ch13 modified: ch13/main.cpp<commit_after>#include <iostream> #include <vector> #include <node.hpp> #include "redblacktree.hpp" int main() { std::vector<int> v = {6,5,9}; ch13::RedBlackTree<int,std::string> tree; for(auto i : v) tree.insert(i); tree.print(); tree.remove(tree.search(6)); tree.print(); std::cout << debug::green("\n====end====") << std::endl; return 0; } <|endoftext|>
<commit_before>///////////////////////////////////////// // // OpenLieroX // // code under LGPL, based on JasonBs work, // enhanced by Dark Charlie and Albert Zeyer // // ///////////////////////////////////////// // TODO: this file was really created by Jason? // Background music handling // Created 29/7/02 // Jason Boettcher #include "Music.h" #ifndef DEDICATED_ONLY #include <set> #include <SDL_thread.h> #include <SDL_mutex.h> #include "FindFile.h" #include "Sounds.h" #include "StringUtils.h" bool breakThread = false; SDL_Thread *musicThread = NULL; SDL_cond *waitCond = NULL; SDL_mutex *waitMutex = NULL; // Load the playlist class PlaylistFiller { public: std::set<std::string> *list; PlaylistFiller(std::set<std::string>* c) : list(c) {} bool operator() (const std::string& filename) { std::string ext = filename.substr(filename.rfind('.')); if (stringcaseequal(ext, ".mp3")) list->insert(filename); return true; } }; /////////////////// // Called when a song finishes void OnSongFinished() { SDL_CondSignal(waitCond); } ///////////////////// // The player thread int MusicMain(void *) { std::set<std::string> playlist; PlaylistFiller filler(&playlist); FindFiles(filler, "music", false, FM_REG); // Nothing to play, just quit if (!playlist.size()) return 0; std::set<std::string>::iterator song = playlist.begin(); SoundMusic *songHandle = NULL; while (!breakThread) { // If not playing, start some song if (!PlayingMusic()) { // Free any previous song if (songHandle) FreeMusic(songHandle); // Load and skip to next one songHandle = LoadMusic(*song); song++; if (song == playlist.end()) song = playlist.begin(); // Could not open, move on to next one if (!songHandle) continue; // Play PlayMusic(songHandle); // Wait until the song finishes SDL_LockMutex(waitMutex); SDL_CondWait(waitCond, waitMutex); } } // Stop/free the playing song if (songHandle) FreeMusic(songHandle); return 0; } ////////////////////// // Initializes the background music thread void InitializeBackgroundMusic() { if(bDedicated) return; if(musicThread) return; InitializeMusic(); musicThread = SDL_CreateThread(&MusicMain, NULL); waitMutex = SDL_CreateMutex(); waitCond = SDL_CreateCond(); SetMusicFinishedHandler(&OnSongFinished); } /////////////////////// // Shuts down the background music playing void ShutdownBackgroundMusic() { if( ! musicThread ) return; SetMusicFinishedHandler(NULL); breakThread = true; if (musicThread) { SDL_CondSignal(waitCond); SDL_WaitThread(musicThread, NULL); SDL_DestroyCond(waitCond); SDL_DestroyMutex(waitMutex); } breakThread = false; musicThread = NULL; waitCond = NULL; waitMutex = NULL; ShutdownMusic(); } #else // DEDICATED_ONLY // dummies void InitializeBackgroundMusic() {} void ShutdownBackgroundMusic() {} #endif <commit_msg>missing include<commit_after>///////////////////////////////////////// // // OpenLieroX // // code under LGPL, based on JasonBs work, // enhanced by Dark Charlie and Albert Zeyer // // ///////////////////////////////////////// // TODO: this file was really created by Jason? // Background music handling // Created 29/7/02 // Jason Boettcher #include "Music.h" #ifndef DEDICATED_ONLY #include <set> #include <SDL_thread.h> #include <SDL_mutex.h> #include "FindFile.h" #include "Sounds.h" #include "StringUtils.h" #include "LieroX.h" // for bDedicated bool breakThread = false; SDL_Thread *musicThread = NULL; SDL_cond *waitCond = NULL; SDL_mutex *waitMutex = NULL; // Load the playlist class PlaylistFiller { public: std::set<std::string> *list; PlaylistFiller(std::set<std::string>* c) : list(c) {} bool operator() (const std::string& filename) { std::string ext = filename.substr(filename.rfind('.')); if (stringcaseequal(ext, ".mp3")) list->insert(filename); return true; } }; /////////////////// // Called when a song finishes void OnSongFinished() { SDL_CondSignal(waitCond); } ///////////////////// // The player thread int MusicMain(void *) { std::set<std::string> playlist; PlaylistFiller filler(&playlist); FindFiles(filler, "music", false, FM_REG); // Nothing to play, just quit if (!playlist.size()) return 0; std::set<std::string>::iterator song = playlist.begin(); SoundMusic *songHandle = NULL; while (!breakThread) { // If not playing, start some song if (!PlayingMusic()) { // Free any previous song if (songHandle) FreeMusic(songHandle); // Load and skip to next one songHandle = LoadMusic(*song); song++; if (song == playlist.end()) song = playlist.begin(); // Could not open, move on to next one if (!songHandle) continue; // Play PlayMusic(songHandle); // Wait until the song finishes SDL_LockMutex(waitMutex); SDL_CondWait(waitCond, waitMutex); } } // Stop/free the playing song if (songHandle) FreeMusic(songHandle); return 0; } ////////////////////// // Initializes the background music thread void InitializeBackgroundMusic() { if(bDedicated) return; if(musicThread) return; InitializeMusic(); musicThread = SDL_CreateThread(&MusicMain, NULL); waitMutex = SDL_CreateMutex(); waitCond = SDL_CreateCond(); SetMusicFinishedHandler(&OnSongFinished); } /////////////////////// // Shuts down the background music playing void ShutdownBackgroundMusic() { if( ! musicThread ) return; SetMusicFinishedHandler(NULL); breakThread = true; if (musicThread) { SDL_CondSignal(waitCond); SDL_WaitThread(musicThread, NULL); SDL_DestroyCond(waitCond); SDL_DestroyMutex(waitMutex); } breakThread = false; musicThread = NULL; waitCond = NULL; waitMutex = NULL; ShutdownMusic(); } #else // DEDICATED_ONLY // dummies void InitializeBackgroundMusic() {} void ShutdownBackgroundMusic() {} #endif <|endoftext|>
<commit_before>#include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" #include <cstring> #include "../config.h" #include <serializer/checksum_block.h> TEST_GROUP(ConfigPage) { static const int page_size = 30; char page1[page_size], page2[page_size]; void teardown(void) { mock().checkExpectations(); mock().clear(); } }; TEST(ConfigPage, WhenConfigCRCMatchesNoWriteOccurs) { // Makes two valid CRC blocks block_crc_update(page1, page_size); block_crc_update(page2, page_size); // We don't expect any flash writes to occur config_sync_pages(page1, page2, page_size); } TEST(ConfigPage, FirstPageIsCopiedIntoSecond) { mock("flash").expectOneCall("page_write") .withPointerParameter("page_adress", page2) .withIntParameter("size", page_size); mock("flash").expectOneCall("page_erase") .withPointerParameter("adress", page2); // Mark first page as valid block_crc_update(page1, page_size); config_sync_pages(page1, page2, page_size); } TEST(ConfigPage, SecondPageIsCopiedIntoFirst) { mock("flash").expectOneCall("page_write") .withPointerParameter("page_adress", page1) .withIntParameter("size", page_size); mock("flash").expectOneCall("page_erase") .withPointerParameter("adress", page1); // Mark second page as valid block_crc_update(page2, page_size); config_sync_pages(page1, page2, page_size); } TEST(ConfigPage, ConfigIsInvalid) { CHECK_FALSE(config_is_valid(page1, page_size)); } TEST(ConfigPage, ConfigIsValid) { block_crc_update(page1, page_size); CHECK_TRUE(config_is_valid(page1, page_size)); } TEST_GROUP(ConfigSerializationTest) { char config_buffer[1024]; bootloader_config_t config, result; void setup(void) { memset(config_buffer, 0, sizeof(config_buffer)); memset(&config, 0, sizeof (bootloader_config_t)); memset(&result, 0, sizeof (bootloader_config_t)); } void config_read_and_write() { config_write(config_buffer, config, sizeof config_buffer); result = config_read(config_buffer, sizeof config_buffer); } }; TEST(ConfigSerializationTest, CanSerializeNodeID) { config.ID = 0x12; config_read_and_write(); CHECK_EQUAL(config.ID, result.ID); } TEST(ConfigSerializationTest, CanSerializeNodeName) { strncpy(config.board_name, "test.dummy", 64); config_read_and_write(); STRCMP_EQUAL(config.board_name, result.board_name); } TEST(ConfigSerializationTest, CanSerializeNodeDeviceClass) { strncpy(config.device_class, "CVRA.dummy.v1", 64); config_read_and_write(); STRCMP_EQUAL(config.device_class, result.device_class); } TEST(ConfigSerializationTest, CanSerializeApplicationCRC) { config.application_crc = 0xdeadbeef; config_read_and_write(); CHECK_EQUAL(0xdeadbeef, result.application_crc); } <commit_msg>Fix and complete config test.<commit_after>#include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" #include <cstring> #include "../config.h" #include <serializer/checksum_block.h> TEST_GROUP(ConfigPage) { static const int page_size = 30; char page1[page_size], page2[page_size]; void teardown(void) { mock().checkExpectations(); mock().clear(); } }; TEST(ConfigPage, WhenConfigCRCMatchesNoWriteOccurs) { // Makes two valid CRC blocks block_crc_update(page1, page_size); block_crc_update(page2, page_size); // We don't expect any flash writes to occur config_sync_pages(page1, page2, page_size); } TEST(ConfigPage, FirstPageIsCopiedIntoSecond) { mock("flash").expectOneCall("page_write") .withPointerParameter("page_adress", page2) .withIntParameter("size", page_size); mock("flash").expectOneCall("page_erase") .withPointerParameter("adress", page2); // Mark first page as valid block_crc_update(page1, page_size); config_sync_pages(page1, page2, page_size); } TEST(ConfigPage, SecondPageIsCopiedIntoFirst) { mock("flash").expectOneCall("page_write") .withPointerParameter("page_adress", page1) .withIntParameter("size", page_size); mock("flash").expectOneCall("page_erase") .withPointerParameter("adress", page1); // Mark second page as valid block_crc_update(page2, page_size); config_sync_pages(page1, page2, page_size); } TEST(ConfigPage, ConfigIsInvalid) { CHECK_FALSE(config_is_valid(page1, page_size)); } TEST(ConfigPage, ConfigIsValid) { block_crc_update(page1, page_size); CHECK_TRUE(config_is_valid(page1, page_size)); } TEST_GROUP(ConfigSerializationTest) { char config_buffer[1024]; bootloader_config_t config, result; void setup(void) { memset(config_buffer, 0, sizeof(config_buffer)); memset(&config, 0, sizeof (bootloader_config_t)); memset(&result, 0, sizeof (bootloader_config_t)); } void config_read_and_write() { config_write(config_buffer, &config, sizeof config_buffer); result = config_read(config_buffer, sizeof config_buffer); } }; TEST(ConfigSerializationTest, CanSerializeNodeID) { config.ID = 0x12; config_read_and_write(); CHECK_EQUAL(config.ID, result.ID); } TEST(ConfigSerializationTest, CanSerializeNodeName) { strncpy(config.board_name, "test.dummy", 64); config_read_and_write(); STRCMP_EQUAL(config.board_name, result.board_name); } TEST(ConfigSerializationTest, CanSerializeNodeDeviceClass) { strncpy(config.device_class, "CVRA.dummy.v1", 64); config_read_and_write(); STRCMP_EQUAL(config.device_class, result.device_class); } TEST(ConfigSerializationTest, CanSerializeApplicationCRC) { config.application_crc = 0xdeadbeef; config_read_and_write(); CHECK_EQUAL(0xdeadbeef, result.application_crc); } TEST(ConfigSerializationTest, CanSerializeApplicationSize) { config.application_size = 42; config_read_and_write(); CHECK_EQUAL(42, result.application_size); } TEST(ConfigSerializationTest, CanSerializeUpdateCount) { config.update_count = 23; config_read_and_write(); CHECK_EQUAL(23, result.update_count); } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <string> #include <getopt.h> #include <iostream> #include <sstream> #include <vector> #include "../common/CycleTimer.h" #include "../common/graph.h" #include "../common/grade.h" #include "page_rank.h" #define USE_BINARY_GRAPH 1 #define PageRankDampening 0.3f #define PageRankConvergence 0.01f void reference_pageRank(Graph g, double* solution, double damping, double convergence); int main(int argc, char** argv) { int num_threads = -1; std::string graph_filename; if (argc < 2) { std::cerr << "Usage: <path/to/graph/file> [manual_set_thread_count]\n"; std::cerr << "To get results across all thread counts: <path/to/graph/file>\n"; std::cerr << "Run with certain threads count (no correctness run): <path/to/graph/file> <thread_count>\n"; exit(1); } int thread_count = -1; if (argc == 3) { thread_count = atoi(argv[2]); } graph_filename = argv[1]; Graph g; printf("----------------------------------------------------------\n"); printf("Max system threads = %d\n", omp_get_max_threads()); if (thread_count > 0) { thread_count = std::min(thread_count, omp_get_max_threads()); printf("Running with %d threads\n", thread_count); } printf("----------------------------------------------------------\n"); printf("Loading graph...\n"); if (USE_BINARY_GRAPH) { g = load_graph_binary(graph_filename.c_str()); } else { g = load_graph(argv[1]); printf("storing binary form of graph!\n"); store_graph_binary(graph_filename.append(".bin").c_str(), g); delete g; exit(1); } printf("\n"); printf("Graph stats:\n"); printf(" Edges: %d\n", g->num_edges); printf(" Nodes: %d\n", g->num_nodes); //If we want to run on all threads if (thread_count <= -1) { //Static num_threads to get consistent usage across trials int max_threads = omp_get_max_threads(); std::vector<int> num_threads; //dynamic num_threads for (int i = 1; i < max_threads; i *= 2) { num_threads.push_back(i); } num_threads.push_back(max_threads); int n_usage = num_threads.size(); double* sol1; sol1 = (double*)malloc(sizeof(double) * g->num_nodes); double* sol2; sol2 = (double*)malloc(sizeof(double) * g->num_nodes); double* sol3; sol3 = (double*)malloc(sizeof(double) * g->num_nodes); //Solution sphere double* sol4; sol4 = (double*)malloc(sizeof(double) * g->num_nodes); double pagerank_base; double pagerank_time; double ref_pagerank_base; double ref_pagerank_time; double start; std::stringstream timing; std::stringstream ref_timing; std::stringstream relative_timing; bool pr_check = true; timing << "Threads Page Rank\n"; ref_timing << "Threads Page Rank\n"; relative_timing << "Threads Page Rank\n"; //Loop through num_threads values; for (int i = 0; i < n_usage; i++) { printf("----------------------------------------------------------\n"); std::cout << "Running with " << num_threads[i] << " threads" << std::endl; //Set thread count omp_set_num_threads(num_threads[i]); //Run implementations start = CycleTimer::currentSeconds(); pageRank(g, sol1, PageRankDampening, PageRankConvergence); pagerank_time = CycleTimer::currentSeconds() - start; //Run reference implementation start = CycleTimer::currentSeconds(); reference_pageRank(g, sol4, PageRankDampening, PageRankConvergence); ref_pagerank_time = CycleTimer::currentSeconds() - start; std::cout << "Testing Correctness of Page Rank\n"; if (!compareApprox(g, sol4, sol1)) { pr_check = false; //break; } char buf[1024]; char ref_buf[1024]; char relative_buf[1024]; sprintf(buf, "%4d: %.4f (%.4fx)\n", num_threads[i], pagerank_time, pagerank_base/pagerank_time); sprintf(ref_buf, "%4d: %.4f (%.4fx)\n", num_threads[i], ref_pagerank_time, ref_pagerank_base/ref_pagerank_time); sprintf(relative_buf, "%4d: %.2fp\n", num_threads[i], 100*pagerank_time/ref_pagerank_time); timing << buf; ref_timing << ref_buf; relative_timing << relative_buf; } printf("----------------------------------------------------------\n"); std::cout << "Timing Summary" << std::endl; std::cout << timing.str(); printf("----------------------------------------------------------\n"); std::cout << "Reference Summary" << std::endl; std::cout << ref_timing.str(); printf("----------------------------------------------------------\n"); std::cout << "For grading reference (based on execution times)" << std::endl << std::endl; std::cout << "Correctness: " << std::endl; if (!pr_check) std::cout << "Page Rank is not Correct" << std::endl; std::cout << std::endl << "Timing: " << std::endl << relative_timing.str(); } //Run the code with only one thread count and only report speedup else { bool pr_check = true; double* sol1; sol1 = (double*)malloc(sizeof(double) * g->num_nodes); double* sol2; sol2 = (double*)malloc(sizeof(double) * g->num_nodes); double* sol3; sol3 = (double*)malloc(sizeof(double) * g->num_nodes); //Double* sphere double* sol4; sol4 = (double*)malloc(sizeof(double) * g->num_nodes); double pagerank_base; double pagerank_time; double ref_pagerank_base; double ref_pagerank_time; double start; std::stringstream timing; std::stringstream ref_timing; timing << "Threads Page Rank\n"; ref_timing << "Threads Page Rank\n"; //Loop through assignment values; std::cout << "Running with " << thread_count << " threads" << std::endl; //Set thread count omp_set_num_threads(thread_count); //Run implementations start = CycleTimer::currentSeconds(); pageRank(g, sol1, PageRankDampening, PageRankConvergence); pagerank_time = CycleTimer::currentSeconds() - start; //Run reference implementation start = CycleTimer::currentSeconds(); reference_pageRank(g, sol4, PageRankDampening, PageRankConvergence); ref_pagerank_time = CycleTimer::currentSeconds() - start; std::cout << "Testing Correctness of Page Rank\n"; if (!compareApprox(g, sol4, sol1)) { pr_check = false; } char buf[1024]; char ref_buf[1024]; sprintf(buf, "%4d: %.4f (%.4fx)\n", thread_count, pagerank_time, pagerank_base/pagerank_time); sprintf(ref_buf, "%4d: %.4f (%.4fx)\n", thread_count, ref_pagerank_time, ref_pagerank_base/ref_pagerank_time); timing << buf; ref_timing << ref_buf; if (!pr_check) std::cout << "Page Rank is not Correct" << std::endl; printf("----------------------------------------------------------\n"); std::cout << "Timing Summary" << std::endl; std::cout << timing.str(); printf("----------------------------------------------------------\n"); std::cout << "Reference Summary" << std::endl; std::cout << ref_timing.str(); printf("----------------------------------------------------------\n"); } delete g; return 0; } <commit_msg>Remove speedup for pagerank point test<commit_after>#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <string> #include <getopt.h> #include <iostream> #include <sstream> #include <vector> #include "../common/CycleTimer.h" #include "../common/graph.h" #include "../common/grade.h" #include "page_rank.h" #define USE_BINARY_GRAPH 1 #define PageRankDampening 0.3f #define PageRankConvergence 0.01f void reference_pageRank(Graph g, double* solution, double damping, double convergence); int main(int argc, char** argv) { int num_threads = -1; std::string graph_filename; if (argc < 2) { std::cerr << "Usage: <path/to/graph/file> [manual_set_thread_count]\n"; std::cerr << "To get results across all thread counts: <path/to/graph/file>\n"; std::cerr << "Run with certain threads count (no correctness run): <path/to/graph/file> <thread_count>\n"; exit(1); } int thread_count = -1; if (argc == 3) { thread_count = atoi(argv[2]); } graph_filename = argv[1]; Graph g; printf("----------------------------------------------------------\n"); printf("Max system threads = %d\n", omp_get_max_threads()); if (thread_count > 0) { thread_count = std::min(thread_count, omp_get_max_threads()); printf("Running with %d threads\n", thread_count); } printf("----------------------------------------------------------\n"); printf("Loading graph...\n"); if (USE_BINARY_GRAPH) { g = load_graph_binary(graph_filename.c_str()); } else { g = load_graph(argv[1]); printf("storing binary form of graph!\n"); store_graph_binary(graph_filename.append(".bin").c_str(), g); delete g; exit(1); } printf("\n"); printf("Graph stats:\n"); printf(" Edges: %d\n", g->num_edges); printf(" Nodes: %d\n", g->num_nodes); //If we want to run on all threads if (thread_count <= -1) { //Static num_threads to get consistent usage across trials int max_threads = omp_get_max_threads(); std::vector<int> num_threads; //dynamic num_threads for (int i = 1; i < max_threads; i *= 2) { num_threads.push_back(i); } num_threads.push_back(max_threads); int n_usage = num_threads.size(); double* sol1; sol1 = (double*)malloc(sizeof(double) * g->num_nodes); double* sol2; sol2 = (double*)malloc(sizeof(double) * g->num_nodes); double* sol3; sol3 = (double*)malloc(sizeof(double) * g->num_nodes); //Solution sphere double* sol4; sol4 = (double*)malloc(sizeof(double) * g->num_nodes); double pagerank_base; double pagerank_time; double ref_pagerank_base; double ref_pagerank_time; double start; std::stringstream timing; std::stringstream ref_timing; std::stringstream relative_timing; bool pr_check = true; timing << "Threads Page Rank\n"; ref_timing << "Threads Page Rank\n"; relative_timing << "Threads Page Rank\n"; //Loop through num_threads values; for (int i = 0; i < n_usage; i++) { printf("----------------------------------------------------------\n"); std::cout << "Running with " << num_threads[i] << " threads" << std::endl; //Set thread count omp_set_num_threads(num_threads[i]); //Run implementations start = CycleTimer::currentSeconds(); pageRank(g, sol1, PageRankDampening, PageRankConvergence); pagerank_time = CycleTimer::currentSeconds() - start; //Run reference implementation start = CycleTimer::currentSeconds(); reference_pageRank(g, sol4, PageRankDampening, PageRankConvergence); ref_pagerank_time = CycleTimer::currentSeconds() - start; std::cout << "Testing Correctness of Page Rank\n"; if (!compareApprox(g, sol4, sol1)) { pr_check = false; //break; } char buf[1024]; char ref_buf[1024]; char relative_buf[1024]; sprintf(buf, "%4d: %.4f (%.4fx)\n", num_threads[i], pagerank_time, pagerank_base/pagerank_time); sprintf(ref_buf, "%4d: %.4f (%.4fx)\n", num_threads[i], ref_pagerank_time, ref_pagerank_base/ref_pagerank_time); sprintf(relative_buf, "%4d: %.2fp\n", num_threads[i], 100*pagerank_time/ref_pagerank_time); timing << buf; ref_timing << ref_buf; relative_timing << relative_buf; } printf("----------------------------------------------------------\n"); std::cout << "Timing Summary" << std::endl; std::cout << timing.str(); printf("----------------------------------------------------------\n"); std::cout << "Reference Summary" << std::endl; std::cout << ref_timing.str(); printf("----------------------------------------------------------\n"); std::cout << "For grading reference (based on execution times)" << std::endl << std::endl; std::cout << "Correctness: " << std::endl; if (!pr_check) std::cout << "Page Rank is not Correct" << std::endl; std::cout << std::endl << "Timing: " << std::endl << relative_timing.str(); } //Run the code with only one thread count and only report speedup else { bool pr_check = true; double* sol1; sol1 = (double*)malloc(sizeof(double) * g->num_nodes); double* sol2; sol2 = (double*)malloc(sizeof(double) * g->num_nodes); double* sol3; sol3 = (double*)malloc(sizeof(double) * g->num_nodes); //Double* sphere double* sol4; sol4 = (double*)malloc(sizeof(double) * g->num_nodes); double pagerank_base; double pagerank_time; double ref_pagerank_base; double ref_pagerank_time; double start; std::stringstream timing; std::stringstream ref_timing; timing << "Threads Page Rank\n"; ref_timing << "Threads Page Rank\n"; //Loop through assignment values; std::cout << "Running with " << thread_count << " threads" << std::endl; //Set thread count omp_set_num_threads(thread_count); //Run implementations start = CycleTimer::currentSeconds(); pageRank(g, sol1, PageRankDampening, PageRankConvergence); pagerank_time = CycleTimer::currentSeconds() - start; //Run reference implementation start = CycleTimer::currentSeconds(); reference_pageRank(g, sol4, PageRankDampening, PageRankConvergence); ref_pagerank_time = CycleTimer::currentSeconds() - start; std::cout << "Testing Correctness of Page Rank\n"; if (!compareApprox(g, sol4, sol1)) { pr_check = false; } char buf[1024]; char ref_buf[1024]; sprintf(buf, "%4d: %.4f\n", thread_count, pagerank_time); sprintf(ref_buf, "%4d: %.4f\n", thread_count, ref_pagerank_time); timing << buf; ref_timing << ref_buf; if (!pr_check) std::cout << "Page Rank is not Correct" << std::endl; printf("----------------------------------------------------------\n"); std::cout << "Timing Summary" << std::endl; std::cout << timing.str(); printf("----------------------------------------------------------\n"); std::cout << "Reference Summary" << std::endl; std::cout << ref_timing.str(); printf("----------------------------------------------------------\n"); } delete g; return 0; } <|endoftext|>
<commit_before>#include "VEmitter.h" #include "VGlobal.h" VEmitter* VEmitter::LoadParticlesFromFile(int Amount, sf::String Filename, bool Animated, int Width, int Height, const sf::IntRect& Rect, bool RandomFrames) { MaxSize = Amount; RenderState.texture = &VGlobal::p()->Content->LoadTexture(Filename); setSize(Amount, Animated, Width, Height, Rect, RandomFrames); return this; } VEmitter* VEmitter::LoadParticles(int Amount, sf::Texture& Texture, bool Animated, int Width, int Height, const sf::IntRect& Rect, bool RandomFrames) { MaxSize = Amount; RenderState.texture = &Texture; setSize(Amount, Animated, Width, Height, Rect, RandomFrames); return this; } VEmitter* VEmitter::MakeParticles(int Amount, int Width, int Height, sf::Color Color) { MaxSize = Amount; if (disposible) { delete RenderState.texture; RenderState.texture = nullptr; } sf::Image image; image.create(Width, Height, Color); sf::Texture* tex = new sf::Texture(); tex->loadFromImage(image); disposible = true; RenderState.texture = tex; setSize(Amount, false, Width, Height, sf::IntRect(0, 0, Width, Height), false); return this; } void VEmitter::setSize(int Amount, bool Animated, int Width, int Height, const sf::IntRect& Rect, bool RandomFrames) { sf::Vector2f Size; int FrameCount; int FrameCountY; int TextureWidth = Rect.width == 0 ? RenderState.texture->getSize().x : Rect.width; sf::Vector2f Offset = sf::Vector2f((float)Rect.left, (float)Rect.top); if (Animated) { Size = sf::Vector2f(static_cast<float>(Width), static_cast<float>(Height)); FrameCount = TextureWidth / Width; FrameCountY = RenderState.texture->getSize().y / Height; } else { Size = sf::Vector2f(RenderState.texture->getSize()); FrameCount = 1; FrameCountY = 1; } ParticleInstance->Size = Size; vertices.clear(); vertices.resize(Amount * 4); for (int i = 0; i < Amount; i++) { VParticle* particle = new VParticle(*ParticleInstance); Add(particle); int RandomFrame = RandomFrames ? VGlobal::p()->Random->GetInt((FrameCount * FrameCountY) - 1) : i % (FrameCount * FrameCountY); int FrameX = RandomFrame % FrameCount; int FrameY = RandomFrame / FrameCount; vertices[0 + (i * 4)].texCoords = Offset + sf::Vector2f(FrameX * Size.x, FrameY * Size.y); vertices[1 + (i * 4)].texCoords = Offset + sf::Vector2f((FrameX + 1) * Size.x, FrameY * Size.y); vertices[2 + (i * 4)].texCoords = Offset + sf::Vector2f((FrameX + 1) * Size.x, (FrameY + 1) * Size.y); vertices[3 + (i * 4)].texCoords = Offset + sf::Vector2f(FrameX * Size.x, (FrameY + 1) * Size.y); } #if _DEBUG debuggingVertices.clear(); debuggingVertices.resize(8); #endif } void VEmitter::Destroy() { VSUPERCLASS::Destroy(); if (disposible) { delete RenderState.texture; RenderState.texture = nullptr; } if (ParticleInstance) { delete ParticleInstance; ParticleInstance = nullptr; } vertices.clear(); } void VEmitter::Update(float dt) { if (running) { if (Explosion) { for (int i = 0; i < amount; i++) { EmitParticle(); } running = false; willKill = true; amount = 0; } else { if (Frequency <= 0) { for (unsigned int i = 0; i < AmountPerEmit; i++) EmitParticle(); if (!Constant && ++counter >= amount) { running = false; willKill = true; amount = 0; } } else { timer += dt; while (timer > Frequency) { timer -= Frequency; for (unsigned int i = 0; i < AmountPerEmit; i++) EmitParticle(); if (!Constant && ++counter >= amount) { running = false; willKill = true; amount = 0; } } } } } else if (willKill) { timer += dt; if (Lifespan.B > 0 && timer > Lifespan.B) { Kill(); return; } } VSUPERCLASS::Update(dt); } void VEmitter::Draw(sf::RenderTarget& RenderTarget) { VParticle* base; sf::Transformable transformable; sf::Transform transform; sf::View renderTargetView = RenderTarget.getView(); sf::View scrollView = RenderTarget.getDefaultView(); sf::Vector2f scroll = renderTargetView.getCenter() - scrollView.getCenter(); float rotate = renderTargetView.getRotation() - scrollView.getRotation(); float zoom = renderTargetView.getSize().x / scrollView.getSize().x; if (ScrollFactor.x != 1 && ScrollFactor.y != 1 && RotateFactor != 1 && ZoomFactor != 1) { scroll.x *= ScrollFactor.x; scroll.y *= ScrollFactor.y; rotate *= RotateFactor; zoom--; zoom *= ZoomFactor; zoom++; } scrollView.move(scroll); scrollView.rotate(rotate); scrollView.zoom(zoom); scrollView.setViewport(renderTargetView.getViewport()); for (unsigned int i = 0; i < members.size(); i++) { base = dynamic_cast<VParticle*>(members[i]); if (base != nullptr && base->exists && base->visible) { transformable.setOrigin(base->Size/2.0f); transformable.setPosition(base->Position + transformable.getOrigin()); transformable.setScale(base->Scale); transformable.setRotation(base->Angle); transform = transformable.getTransform(); vertices[0 + (i * 4)].position = transform.transformPoint(sf::Vector2f(0,0)); vertices[1 + (i * 4)].position = transform.transformPoint(sf::Vector2f(base->Size.x, 0)); vertices[2 + (i * 4)].position = transform.transformPoint(sf::Vector2f(base->Size.x, base->Size.y)); vertices[3 + (i * 4)].position = transform.transformPoint(sf::Vector2f(0, base->Size.y)); vertices[0 + (i * 4)].color = base->Tint; vertices[1 + (i * 4)].color = base->Tint; vertices[2 + (i * 4)].color = base->Tint; vertices[3 + (i * 4)].color = base->Tint; } else { vertices[0 + (i * 4)].position = Position; vertices[1 + (i * 4)].position = Position; vertices[2 + (i * 4)].position = Position; vertices[3 + (i * 4)].position = Position; vertices[0 + (i * 4)].color.a = 0; vertices[1 + (i * 4)].color.a = 0; vertices[2 + (i * 4)].color.a = 0; vertices[3 + (i * 4)].color.a = 0; } } sf::FloatRect renderBox = vertices.getBounds();; float maxSize = fmaxf(scrollView.getSize().x, scrollView.getSize().y); sf::FloatRect scrollBox = sf::FloatRect(scrollView.getCenter() - sf::Vector2f(maxSize, maxSize) / 2.0f, sf::Vector2f(maxSize, maxSize)); if (renderBox.left < scrollBox.left + scrollBox.width && renderBox.left + renderBox.width > scrollBox.left && renderBox.top < scrollBox.top + scrollBox.height && renderBox.top + renderBox.height > scrollBox.top) { RenderTarget.setView(scrollView); RenderTarget.draw(vertices, RenderState); #ifdef _DEBUG if (VGlobal::p()->DrawDebug) { debuggingVertices[0].position = sf::Vector2f(renderBox.left, renderBox.top); debuggingVertices[1].position = sf::Vector2f(renderBox.left + renderBox.width, renderBox.top); debuggingVertices[2].position = sf::Vector2f(renderBox.left + renderBox.width, renderBox.top); debuggingVertices[3].position = sf::Vector2f(renderBox.left + renderBox.width, renderBox.top + renderBox.height); debuggingVertices[4].position = sf::Vector2f(renderBox.left + renderBox.width, renderBox.top + renderBox.height); debuggingVertices[5].position = sf::Vector2f(renderBox.left, renderBox.top + renderBox.height); debuggingVertices[6].position = sf::Vector2f(renderBox.left, renderBox.top + renderBox.height); debuggingVertices[7].position = sf::Vector2f(renderBox.left, renderBox.top); } #endif RenderTarget.setView(renderTargetView); } } void VEmitter::Kill() { running = false; VSUPERCLASS::Kill(); } void VEmitter::Revive() { running = false; VSUPERCLASS::Revive(); } VEmitter* VEmitter::Start(int Amount) { if (!running) { exists = true; visible = true; running = true; counter = 0; timer = 0; willKill = false; amount = Amount != 0 ? Amount : Length(); } return this; } void VEmitter::Stop() { running = false; } bool VEmitter::IsRunning() { return running; } void VEmitter::EmitParticle() { auto particle = static_cast<VParticle*>(FirstAvailable()); VRandom random((unsigned int)((uint64_t)particle) + (unsigned int)(time(NULL))); if (particle) { particle->Revive(); particle->Reset(0, 0); particle->Immovable = Immovable; particle->AllowCollisions = AllowCollisions; if (Circular) { float angle = random.GetFloat(EmittingAngle.B, EmittingAngle.A) * (3.1415926f / 180); float speed = random.GetFloat(SpeedRange.B, SpeedRange.A); particle->Velocity = sf::Vector2f(cos(angle), sinf(angle)) * speed; } else { particle->Velocity = VGlobal::p()->Random->GetVector2f(VelocityRange.B, VelocityRange.A); } particle->AngleAcceleration = VGlobal::p()->Random->GetFloat(AngleAccelerationRange.B, AngleAccelerationRange.A); particle->AngleDrag = VGlobal::p()->Random->GetFloat(AngleDragRange.B, AngleDragRange.A); particle->AngleVelocity = VGlobal::p()->Random->GetFloat(AngleVelocityRange.B, AngleVelocityRange.A); particle->Angle = VGlobal::p()->Random->GetFloat(AngleRange.B, AngleRange.A); particle->Lifespan = VGlobal::p()->Random->GetFloat(Lifespan.B, Lifespan.A); particle->ScaleRange.A = VGlobal::p()->Random->GetVector2f(ScaleRange.A.B, ScaleRange.A.A); particle->ScaleRange.B = VGlobal::p()->Random->GetVector2f(ScaleRange.B.B, ScaleRange.B.A); particle->ColourRange.A = VGlobal::p()->Random->GetColor(ColourRange.A.B, ColourRange.A.A); particle->ColourRange.B = VGlobal::p()->Random->GetColor(ColourRange.B.B, ColourRange.B.A); particle->AlphaRange.A = VGlobal::p()->Random->GetFloat(AlphaRange.A.B, AlphaRange.A.A); particle->AlphaRange.B = VGlobal::p()->Random->GetFloat(AlphaRange.B.B, AlphaRange.B.A); particle->Drag = VGlobal::p()->Random->GetVector2f(DragRange.B, DragRange.A); particle->Acceleration = VGlobal::p()->Random->GetVector2f(AccelerationRange.B, AccelerationRange.A); particle->Elasticity = VGlobal::p()->Random->GetFloat(ElasticityRange.B, ElasticityRange.A); particle->Position = VGlobal::p()->Random->GetVector2f(Position + Size, Position) - (Size / 2.0f); particle->OnEmit(); } } <commit_msg>Fixed rect parameter for loading particle graphics.<commit_after>#include "VEmitter.h" #include "VGlobal.h" VEmitter* VEmitter::LoadParticlesFromFile(int Amount, sf::String Filename, bool Animated, int Width, int Height, const sf::IntRect& Rect, bool RandomFrames) { MaxSize = Amount; RenderState.texture = &VGlobal::p()->Content->LoadTexture(Filename); setSize(Amount, Animated, Width, Height, Rect, RandomFrames); return this; } VEmitter* VEmitter::LoadParticles(int Amount, sf::Texture& Texture, bool Animated, int Width, int Height, const sf::IntRect& Rect, bool RandomFrames) { MaxSize = Amount; RenderState.texture = &Texture; setSize(Amount, Animated, Width, Height, Rect, RandomFrames); return this; } VEmitter* VEmitter::MakeParticles(int Amount, int Width, int Height, sf::Color Color) { MaxSize = Amount; if (disposible) { delete RenderState.texture; RenderState.texture = nullptr; } sf::Image image; image.create(Width, Height, Color); sf::Texture* tex = new sf::Texture(); tex->loadFromImage(image); disposible = true; RenderState.texture = tex; setSize(Amount, false, Width, Height, sf::IntRect(0, 0, Width, Height), false); return this; } void VEmitter::setSize(int Amount, bool Animated, int Width, int Height, const sf::IntRect& Rect, bool RandomFrames) { sf::Vector2f Size; int FrameCount; int FrameCountY; int TextureWidth = Rect.width == 0 ? RenderState.texture->getSize().x : Rect.width; sf::Vector2f Offset = sf::Vector2f((float)Rect.left, (float)Rect.top); if (Animated) { Size = sf::Vector2f(static_cast<float>(Width), static_cast<float>(Height)); FrameCount = TextureWidth / Width; FrameCountY = RenderState.texture->getSize().y / Height; } else { if (Rect == sf::IntRect()) Size = sf::Vector2f(RenderState.texture->getSize()); else Size = sf::Vector2f(Rect.width, Rect.height); FrameCount = 1; FrameCountY = 1; } ParticleInstance->Size = Size; vertices.clear(); vertices.resize(Amount * 4); for (int i = 0; i < Amount; i++) { VParticle* particle = new VParticle(*ParticleInstance); Add(particle); int RandomFrame = RandomFrames ? VGlobal::p()->Random->GetInt((FrameCount * FrameCountY) - 1) : i % (FrameCount * FrameCountY); int FrameX = RandomFrame % FrameCount; int FrameY = RandomFrame / FrameCount; vertices[0 + (i * 4)].texCoords = Offset + sf::Vector2f(FrameX * Size.x, FrameY * Size.y); vertices[1 + (i * 4)].texCoords = Offset + sf::Vector2f((FrameX + 1) * Size.x, FrameY * Size.y); vertices[2 + (i * 4)].texCoords = Offset + sf::Vector2f((FrameX + 1) * Size.x, (FrameY + 1) * Size.y); vertices[3 + (i * 4)].texCoords = Offset + sf::Vector2f(FrameX * Size.x, (FrameY + 1) * Size.y); } #if _DEBUG debuggingVertices.clear(); debuggingVertices.resize(8); #endif } void VEmitter::Destroy() { VSUPERCLASS::Destroy(); if (disposible) { delete RenderState.texture; RenderState.texture = nullptr; } if (ParticleInstance) { delete ParticleInstance; ParticleInstance = nullptr; } vertices.clear(); } void VEmitter::Update(float dt) { if (running) { if (Explosion) { for (int i = 0; i < amount; i++) { EmitParticle(); } running = false; willKill = true; amount = 0; } else { if (Frequency <= 0) { for (unsigned int i = 0; i < AmountPerEmit; i++) EmitParticle(); if (!Constant && ++counter >= amount) { running = false; willKill = true; amount = 0; } } else { timer += dt; while (timer > Frequency) { timer -= Frequency; for (unsigned int i = 0; i < AmountPerEmit; i++) EmitParticle(); if (!Constant && ++counter >= amount) { running = false; willKill = true; amount = 0; } } } } } else if (willKill) { timer += dt; if (Lifespan.B > 0 && timer > Lifespan.B) { Kill(); return; } } VSUPERCLASS::Update(dt); } void VEmitter::Draw(sf::RenderTarget& RenderTarget) { VParticle* base; sf::Transformable transformable; sf::Transform transform; sf::View renderTargetView = RenderTarget.getView(); sf::View scrollView = RenderTarget.getDefaultView(); sf::Vector2f scroll = renderTargetView.getCenter() - scrollView.getCenter(); float rotate = renderTargetView.getRotation() - scrollView.getRotation(); float zoom = renderTargetView.getSize().x / scrollView.getSize().x; if (ScrollFactor.x != 1 && ScrollFactor.y != 1 && RotateFactor != 1 && ZoomFactor != 1) { scroll.x *= ScrollFactor.x; scroll.y *= ScrollFactor.y; rotate *= RotateFactor; zoom--; zoom *= ZoomFactor; zoom++; } scrollView.move(scroll); scrollView.rotate(rotate); scrollView.zoom(zoom); scrollView.setViewport(renderTargetView.getViewport()); for (unsigned int i = 0; i < members.size(); i++) { base = dynamic_cast<VParticle*>(members[i]); if (base != nullptr && base->exists && base->visible) { transformable.setOrigin(base->Size/2.0f); transformable.setPosition(base->Position + transformable.getOrigin()); transformable.setScale(base->Scale); transformable.setRotation(base->Angle); transform = transformable.getTransform(); vertices[0 + (i * 4)].position = transform.transformPoint(sf::Vector2f(0,0)); vertices[1 + (i * 4)].position = transform.transformPoint(sf::Vector2f(base->Size.x, 0)); vertices[2 + (i * 4)].position = transform.transformPoint(sf::Vector2f(base->Size.x, base->Size.y)); vertices[3 + (i * 4)].position = transform.transformPoint(sf::Vector2f(0, base->Size.y)); vertices[0 + (i * 4)].color = base->Tint; vertices[1 + (i * 4)].color = base->Tint; vertices[2 + (i * 4)].color = base->Tint; vertices[3 + (i * 4)].color = base->Tint; } else { vertices[0 + (i * 4)].position = Position; vertices[1 + (i * 4)].position = Position; vertices[2 + (i * 4)].position = Position; vertices[3 + (i * 4)].position = Position; vertices[0 + (i * 4)].color.a = 0; vertices[1 + (i * 4)].color.a = 0; vertices[2 + (i * 4)].color.a = 0; vertices[3 + (i * 4)].color.a = 0; } } sf::FloatRect renderBox = vertices.getBounds();; float maxSize = fmaxf(scrollView.getSize().x, scrollView.getSize().y); sf::FloatRect scrollBox = sf::FloatRect(scrollView.getCenter() - sf::Vector2f(maxSize, maxSize) / 2.0f, sf::Vector2f(maxSize, maxSize)); if (renderBox.left < scrollBox.left + scrollBox.width && renderBox.left + renderBox.width > scrollBox.left && renderBox.top < scrollBox.top + scrollBox.height && renderBox.top + renderBox.height > scrollBox.top) { RenderTarget.setView(scrollView); RenderTarget.draw(vertices, RenderState); #ifdef _DEBUG if (VGlobal::p()->DrawDebug) { debuggingVertices[0].position = sf::Vector2f(renderBox.left, renderBox.top); debuggingVertices[1].position = sf::Vector2f(renderBox.left + renderBox.width, renderBox.top); debuggingVertices[2].position = sf::Vector2f(renderBox.left + renderBox.width, renderBox.top); debuggingVertices[3].position = sf::Vector2f(renderBox.left + renderBox.width, renderBox.top + renderBox.height); debuggingVertices[4].position = sf::Vector2f(renderBox.left + renderBox.width, renderBox.top + renderBox.height); debuggingVertices[5].position = sf::Vector2f(renderBox.left, renderBox.top + renderBox.height); debuggingVertices[6].position = sf::Vector2f(renderBox.left, renderBox.top + renderBox.height); debuggingVertices[7].position = sf::Vector2f(renderBox.left, renderBox.top); } #endif RenderTarget.setView(renderTargetView); } } void VEmitter::Kill() { running = false; VSUPERCLASS::Kill(); } void VEmitter::Revive() { running = false; VSUPERCLASS::Revive(); } VEmitter* VEmitter::Start(int Amount) { if (!running) { exists = true; visible = true; running = true; counter = 0; timer = 0; willKill = false; amount = Amount != 0 ? Amount : Length(); } return this; } void VEmitter::Stop() { running = false; } bool VEmitter::IsRunning() { return running; } void VEmitter::EmitParticle() { auto particle = static_cast<VParticle*>(FirstAvailable()); VRandom random((unsigned int)((uint64_t)particle) + (unsigned int)(time(NULL))); if (particle) { particle->Revive(); particle->Reset(0, 0); particle->Immovable = Immovable; particle->AllowCollisions = AllowCollisions; if (Circular) { float angle = random.GetFloat(EmittingAngle.B, EmittingAngle.A) * (3.1415926f / 180); float speed = random.GetFloat(SpeedRange.B, SpeedRange.A); particle->Velocity = sf::Vector2f(cos(angle), sinf(angle)) * speed; } else { particle->Velocity = VGlobal::p()->Random->GetVector2f(VelocityRange.B, VelocityRange.A); } particle->AngleAcceleration = VGlobal::p()->Random->GetFloat(AngleAccelerationRange.B, AngleAccelerationRange.A); particle->AngleDrag = VGlobal::p()->Random->GetFloat(AngleDragRange.B, AngleDragRange.A); particle->AngleVelocity = VGlobal::p()->Random->GetFloat(AngleVelocityRange.B, AngleVelocityRange.A); particle->Angle = VGlobal::p()->Random->GetFloat(AngleRange.B, AngleRange.A); particle->Lifespan = VGlobal::p()->Random->GetFloat(Lifespan.B, Lifespan.A); particle->ScaleRange.A = VGlobal::p()->Random->GetVector2f(ScaleRange.A.B, ScaleRange.A.A); particle->ScaleRange.B = VGlobal::p()->Random->GetVector2f(ScaleRange.B.B, ScaleRange.B.A); particle->ColourRange.A = VGlobal::p()->Random->GetColor(ColourRange.A.B, ColourRange.A.A); particle->ColourRange.B = VGlobal::p()->Random->GetColor(ColourRange.B.B, ColourRange.B.A); particle->AlphaRange.A = VGlobal::p()->Random->GetFloat(AlphaRange.A.B, AlphaRange.A.A); particle->AlphaRange.B = VGlobal::p()->Random->GetFloat(AlphaRange.B.B, AlphaRange.B.A); particle->Drag = VGlobal::p()->Random->GetVector2f(DragRange.B, DragRange.A); particle->Acceleration = VGlobal::p()->Random->GetVector2f(AccelerationRange.B, AccelerationRange.A); particle->Elasticity = VGlobal::p()->Random->GetFloat(ElasticityRange.B, ElasticityRange.A); particle->Position = VGlobal::p()->Random->GetVector2f(Position + Size, Position) - (Size / 2.0f); particle->OnEmit(); } } <|endoftext|>
<commit_before>#ifndef ENTT_CORE_TYPE_TRAITS_HPP #define ENTT_CORE_TYPE_TRAITS_HPP #include <type_traits> #include "../core/hashed_string.hpp" namespace entt { /*! @brief A class to use to push around lists of types, nothing more. */ template<typename... Type> struct type_list {}; /*! @brief Traits class used mainly to push things across boundaries. */ template<typename> struct named_type_traits; /** * @brief Specialization used to get rid of constness. * @tparam Type Named type. */ template<typename Type> struct named_type_traits<const Type> : named_type_traits<Type> {}; /** * @brief Helper type. * @tparam Type Potentially named type. */ template<typename Type> using named_type_traits_t = typename named_type_traits<Type>::type; /** * @brief Provides the member constant `value` to true if a given type has a * name. In all other cases, `value` is false. */ template<typename, typename = std::void_t<>> struct is_named_type: std::false_type {}; /** * @brief Provides the member constant `value` to true if a given type has a * name. In all other cases, `value` is false. * @tparam Type Potentially named type. */ template<typename Type> struct is_named_type<Type, std::void_t<named_type_traits_t<std::decay_t<Type>>>>: std::true_type {}; /** * @brief Helper variable template. * * True if a given type has a name, false otherwise. * * @tparam Type Potentially named type. */ template<class Type> constexpr auto is_named_type_v = is_named_type<Type>::value; } /** * @brief Utility macro to deal with an issue of MSVC. * * See _msvc-doesnt-expand-va-args-correctly_ on SO for all the details. * * @param args Argument to expand. */ #define ENTT_EXPAND(args) args /** * @brief Makes an already existing type a named type. * @param type Type to assign a name to. */ #define ENTT_NAMED_TYPE(type)\ template<>\ struct entt::named_type_traits<type>\ : std::integral_constant<typename entt::hashed_string::hash_type, entt::hashed_string::to_value(#type)>\ {}; /** * @brief Defines a named type (to use for structs). * @param clazz Name of the type to define. * @param body Body of the type to define. */ #define ENTT_NAMED_STRUCT_ONLY(clazz, body)\ struct clazz body;\ ENTT_NAMED_TYPE(clazz) /** * @brief Defines a named type (to use for structs). * @param ns Namespace where to define the named type. * @param clazz Name of the type to define. * @param body Body of the type to define. */ #define ENTT_NAMED_STRUCT_WITH_NAMESPACE(ns, clazz, body)\ namespace ns { struct clazz body; }\ ENTT_NAMED_TYPE(ns::clazz) /*! @brief Utility function to simulate macro overloading. */ #define ENTT_NAMED_STRUCT_OVERLOAD(_1, _2, _3, FUNC, ...) FUNC /*! @brief Defines a named type (to use for structs). */ #define ENTT_NAMED_STRUCT(...) ENTT_EXPAND(ENTT_NAMED_STRUCT_OVERLOAD(__VA_ARGS__, ENTT_NAMED_STRUCT_WITH_NAMESPACE, ENTT_NAMED_STRUCT_ONLY,)(__VA_ARGS__)) /** * @brief Defines a named type (to use for classes). * @param clazz Name of the type to define. * @param body Body of the type to define. */ #define ENTT_NAMED_CLASS_ONLY(clazz, body)\ class clazz body;\ ENTT_NAMED_TYPE(clazz) /** * @brief Defines a named type (to use for classes). * @param ns Namespace where to define the named type. * @param clazz Name of the type to define. * @param body Body of the type to define. */ #define ENTT_NAMED_CLASS_WITH_NAMESPACE(ns, clazz, body)\ namespace ns { class clazz body; }\ ENTT_NAMED_TYPE(ns::clazz) /*! @brief Utility function to simulate macro overloading. */ #define ENTT_NAMED_CLASS_MACRO(_1, _2, _3, FUNC, ...) FUNC /*! @brief Defines a named type (to use for classes). */ #define ENTT_NAMED_CLASS(...) ENTT_EXPAND(ENTT_NAMED_CLASS_MACRO(__VA_ARGS__, ENTT_NAMED_CLASS_WITH_NAMESPACE, ENTT_NAMED_CLASS_ONLY,)(__VA_ARGS__)) #endif // ENTT_CORE_TYPE_TRAITS_HPP <commit_msg>cleanup<commit_after>#ifndef ENTT_CORE_TYPE_TRAITS_HPP #define ENTT_CORE_TYPE_TRAITS_HPP #include <type_traits> #include "../core/hashed_string.hpp" namespace entt { /*! @brief A class to use to push around lists of types, nothing more. */ template<typename... Type> struct type_list {}; /*! @brief Traits class used mainly to push things across boundaries. */ template<typename> struct named_type_traits; /** * @brief Specialization used to get rid of constness. * @tparam Type Named type. */ template<typename Type> struct named_type_traits<const Type> : named_type_traits<Type> {}; /** * @brief Provides the member constant `value` to true if a given type has a * name. In all other cases, `value` is false. */ template<typename, typename = std::void_t<>> struct is_named_type: std::false_type {}; /** * @brief Provides the member constant `value` to true if a given type has a * name. In all other cases, `value` is false. * @tparam Type Potentially named type. */ template<typename Type> struct is_named_type<Type, std::enable_if_t<std::is_same_v<decltype(named_type_traits<std::decay_t<Type>>::value), ENTT_ID_TYPE>>> {}; /** * @brief Helper variable template. * * True if a given type has a name, false otherwise. * * @tparam Type Potentially named type. */ template<class Type> constexpr auto is_named_type_v = is_named_type<Type>::value; } /** * @brief Utility macro to deal with an issue of MSVC. * * See _msvc-doesnt-expand-va-args-correctly_ on SO for all the details. * * @param args Argument to expand. */ #define ENTT_EXPAND(args) args /** * @brief Makes an already existing type a named type. * @param type Type to assign a name to. */ #define ENTT_NAMED_TYPE(type)\ template<>\ struct entt::named_type_traits<type>\ : std::integral_constant<typename entt::hashed_string::hash_type, entt::hashed_string::to_value(#type)>\ {\ static_assert(std::is_same_v<std::decay_t<type>, type>);\ }; /** * @brief Defines a named type (to use for structs). * @param clazz Name of the type to define. * @param body Body of the type to define. */ #define ENTT_NAMED_STRUCT_ONLY(clazz, body)\ struct clazz body;\ ENTT_NAMED_TYPE(clazz) /** * @brief Defines a named type (to use for structs). * @param ns Namespace where to define the named type. * @param clazz Name of the type to define. * @param body Body of the type to define. */ #define ENTT_NAMED_STRUCT_WITH_NAMESPACE(ns, clazz, body)\ namespace ns { struct clazz body; }\ ENTT_NAMED_TYPE(ns::clazz) /*! @brief Utility function to simulate macro overloading. */ #define ENTT_NAMED_STRUCT_OVERLOAD(_1, _2, _3, FUNC, ...) FUNC /*! @brief Defines a named type (to use for structs). */ #define ENTT_NAMED_STRUCT(...) ENTT_EXPAND(ENTT_NAMED_STRUCT_OVERLOAD(__VA_ARGS__, ENTT_NAMED_STRUCT_WITH_NAMESPACE, ENTT_NAMED_STRUCT_ONLY,)(__VA_ARGS__)) /** * @brief Defines a named type (to use for classes). * @param clazz Name of the type to define. * @param body Body of the type to define. */ #define ENTT_NAMED_CLASS_ONLY(clazz, body)\ class clazz body;\ ENTT_NAMED_TYPE(clazz) /** * @brief Defines a named type (to use for classes). * @param ns Namespace where to define the named type. * @param clazz Name of the type to define. * @param body Body of the type to define. */ #define ENTT_NAMED_CLASS_WITH_NAMESPACE(ns, clazz, body)\ namespace ns { class clazz body; }\ ENTT_NAMED_TYPE(ns::clazz) /*! @brief Utility function to simulate macro overloading. */ #define ENTT_NAMED_CLASS_MACRO(_1, _2, _3, FUNC, ...) FUNC /*! @brief Defines a named type (to use for classes). */ #define ENTT_NAMED_CLASS(...) ENTT_EXPAND(ENTT_NAMED_CLASS_MACRO(__VA_ARGS__, ENTT_NAMED_CLASS_WITH_NAMESPACE, ENTT_NAMED_CLASS_ONLY,)(__VA_ARGS__)) #endif // ENTT_CORE_TYPE_TRAITS_HPP <|endoftext|>
<commit_before>/* ndhs.c - dhcp server * * (c) 2011-2016 Nicholas J. Kain <njkain at gmail dot com> * 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. */ #define NDHS_VERSION "1.0" #include <string> #include <vector> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/stat.h> #include <fcntl.h> #include <ctype.h> #include <pwd.h> #include <grp.h> #include <signal.h> #include <errno.h> #include <boost/asio.hpp> #include <format.hpp> #include <nk/optionarg.hpp> extern "C" { #include "nk/privilege.h" #include "nk/pidfile.h" #include "nk/exec.h" #include "nk/seccomp-bpf.h" } #include "dhcpclient.hpp" #include "dhcplua.hpp" #include "leasestore.hpp" boost::asio::io_service io_service; static boost::asio::signal_set asio_signal_set(io_service); static std::vector<std::unique_ptr<ClientListener>> listeners; static uid_t ndhs_uid; static gid_t ndhs_gid; extern int gflags_detach; extern int gflags_quiet; static bool use_seccomp(false); std::unique_ptr<LeaseStore> gLeaseStore; std::unique_ptr<DhcpLua> gLua; static void process_signals() { sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGPIPE); sigaddset(&mask, SIGUSR1); sigaddset(&mask, SIGUSR2); sigaddset(&mask, SIGTSTP); sigaddset(&mask, SIGTTIN); sigaddset(&mask, SIGHUP); if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { fmt::print(stderr, "sigprocmask failed\n"); std::quick_exit(EXIT_FAILURE); } asio_signal_set.add(SIGINT); asio_signal_set.add(SIGTERM); asio_signal_set.async_wait( [](const boost::system::error_code &, int signum) { io_service.stop(); }); } static int enforce_seccomp(bool changed_uidgid) { if (!use_seccomp) return 0; struct sock_filter filter[] = { VALIDATE_ARCHITECTURE, EXAMINE_SYSCALL, #if defined(__x86_64__) || (defined(__arm__) && defined(__ARM_EABI__)) ALLOW_SYSCALL(sendmsg), ALLOW_SYSCALL(recvmsg), ALLOW_SYSCALL(socket), ALLOW_SYSCALL(getsockname), ALLOW_SYSCALL(getpeername), ALLOW_SYSCALL(setsockopt), ALLOW_SYSCALL(connect), ALLOW_SYSCALL(sendto), // used for glibc syslog routines ALLOW_SYSCALL(recvfrom), ALLOW_SYSCALL(fcntl), ALLOW_SYSCALL(accept), ALLOW_SYSCALL(shutdown), #elif defined(__i386__) ALLOW_SYSCALL(socketcall), ALLOW_SYSCALL(fcntl64), #else #error Target platform does not support seccomp-filter. #endif ALLOW_SYSCALL(read), ALLOW_SYSCALL(write), ALLOW_SYSCALL(epoll_wait), ALLOW_SYSCALL(epoll_ctl), ALLOW_SYSCALL(stat), ALLOW_SYSCALL(open), ALLOW_SYSCALL(close), ALLOW_SYSCALL(ioctl), ALLOW_SYSCALL(timerfd_settime), ALLOW_SYSCALL(access), ALLOW_SYSCALL(fstat), ALLOW_SYSCALL(lseek), ALLOW_SYSCALL(umask), ALLOW_SYSCALL(geteuid), ALLOW_SYSCALL(fsync), ALLOW_SYSCALL(unlink), ALLOW_SYSCALL(rt_sigreturn), ALLOW_SYSCALL(rt_sigaction), #ifdef __NR_sigreturn ALLOW_SYSCALL(sigreturn), #endif #ifdef __NR_sigaction ALLOW_SYSCALL(sigaction), #endif // Allowed by vDSO ALLOW_SYSCALL(getcpu), ALLOW_SYSCALL(time), ALLOW_SYSCALL(gettimeofday), ALLOW_SYSCALL(clock_gettime), // operator new ALLOW_SYSCALL(brk), ALLOW_SYSCALL(mmap), ALLOW_SYSCALL(munmap), ALLOW_SYSCALL(mremap), ALLOW_SYSCALL(exit_group), ALLOW_SYSCALL(exit), KILL_PROCESS, }; struct sock_fprog prog; memset(&prog, 0, sizeof prog); prog.len = (unsigned short)(sizeof filter / sizeof filter[0]); prog.filter = filter; if (!changed_uidgid && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) return -1; if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) return -1; fmt::print("seccomp filter installed. Please disable seccomp if you encounter problems.\n"); std::fflush(stdout); return 0; } static void print_version(void) { fmt::print("ndhs " NDHS_VERSION ", dhcp server.\n" "Copyright (c) 2011-2016 Nicholas J. Kain\n" "All rights reserved.\n\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are met:\n\n" "- Redistributions of source code must retain the above copyright notice,\n" " this list of conditions and the following disclaimer.\n" "- Redistributions in binary form must reproduce the above copyright notice,\n" " this list of conditions and the following disclaimer in the documentation\n" " and/or other materials provided with the distribution.\n\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n" "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" "POSSIBILITY OF SUCH DAMAGE.\n"); } enum OpIdx { OPT_UNKNOWN, OPT_HELP, OPT_VERSION, OPT_BACKGROUND, OPT_PIDFILE, OPT_CHROOT, OPT_USER, OPT_SCRIPTFILE, OPT_LEASEFILE, OPT_SECCOMP, OPT_QUIET }; static const option::Descriptor usage[] = { { OPT_UNKNOWN, 0, "", "", Arg::Unknown, "ndhs " NDHS_VERSION ", dhcp server.\n" "Copyright (c) 2011-2016 Nicholas J. Kain\n" "ndhs [options] interface...\n\nOptions:" }, { OPT_HELP, 0, "h", "help", Arg::None, "\t-h, \t--help \tPrint usage and exit." }, { OPT_VERSION, 0, "v", "version", Arg::None, "\t-v, \t--version \tPrint version and exit." }, { OPT_BACKGROUND, 0, "b", "background", Arg::None, "\t-b, \t--background \tRun as a background daemon." }, { OPT_PIDFILE, 0, "f", "pidfile", Arg::String, "\t-f, \t--pidfile \tPath to process id file." }, { OPT_CHROOT, 0, "C", "chroot", Arg::String, "\t-C, \t--chroot \tPath in which nident should chroot itself." }, { OPT_USER, 0, "u", "user", Arg::String, "\t-u, \t--user \tUser name that nrad6 should run as." }, { OPT_SCRIPTFILE, 0, "s", "script", Arg::String, "\t-s, \t--script \tPath to response script file." }, { OPT_LEASEFILE, 0, "l", "leasefile", Arg::String, "\t-l, \t--leasefile \tPath to lease database file." }, { OPT_SECCOMP, 0, "S", "seccomp-enforce", Arg::None, "\t-S \t--seccomp-enforce \tEnforce seccomp syscall restrictions." }, { OPT_QUIET, 0, "q", "quiet", Arg::None, "\t-q, \t--quiet \tDon't log to std(out|err) or syslog." }, {0,0,0,0,0,0} }; static void process_options(int ac, char *av[]) { ac-=ac>0; av+=ac>0; option::Stats stats(usage, ac, av); #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wvla" option::Option options[stats.options_max], buffer[stats.buffer_max]; #pragma GCC diagnostic pop option::Parser parse(usage, ac, av, options, buffer); #else auto options = std::make_unique<option::Option[]>(stats.options_max); auto buffer = std::make_unique<option::Option[]>(stats.buffer_max); option::Parser parse(usage, ac, av, options.get(), buffer.get()); #endif if (parse.error()) std::exit(EXIT_FAILURE); if (options[OPT_HELP]) { int col = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80; option::printUsage(fwrite, stdout, usage, col); std::exit(EXIT_FAILURE); } if (options[OPT_VERSION]) { print_version(); std::exit(EXIT_FAILURE); } std::vector<std::string> iflist; std::string pidfile, chroot_path, leasefile_path, scriptfile_path; for (int i = 0; i < parse.optionsCount(); ++i) { option::Option &opt = buffer[i]; switch (opt.index()) { case OPT_BACKGROUND: gflags_detach = 1; break; case OPT_PIDFILE: pidfile = std::string(opt.arg); break; case OPT_CHROOT: chroot_path = std::string(opt.arg); break; case OPT_USER: { if (nk_uidgidbyname(opt.arg, &ndhs_uid, &ndhs_gid)) { fmt::print(stderr, "invalid user '{}' specified\n", opt.arg); std::exit(EXIT_FAILURE); } break; } case OPT_SCRIPTFILE: scriptfile_path = std::string(opt.arg); break; case OPT_LEASEFILE: leasefile_path = std::string(opt.arg); break; case OPT_SECCOMP: use_seccomp = true; break; case OPT_QUIET: gflags_quiet = 1; break; } } for (int i = 0; i < parse.nonOptionsCount(); ++i) { iflist.emplace_back(parse.nonOption(i)); } for (const auto &i: iflist) { try { auto addy = boost::asio::ip::address_v4::any(); auto ep = boost::asio::ip::udp::endpoint(addy, 67); listeners.emplace_back(std::make_unique<ClientListener> (io_service, ep, i)); } catch (boost::system::error_code &ec) { fmt::print(stderr, "bad interface: {}\n", i); } } if (!iflist.size()) { fmt::print(stderr, "At least one listening interface must be specified\n"); std::exit(EXIT_FAILURE); } if (gflags_detach && daemon(0,0)) { fmt::print(stderr, "detaching fork failed\n"); std::exit(EXIT_FAILURE); } if (pidfile.size() && file_exists(pidfile.c_str(), "w")) write_pid(pidfile.c_str()); umask(077); process_signals(); nk_fix_env(ndhs_uid, 0); gLua = std::make_unique<DhcpLua>(scriptfile_path); if (chroot_path.size()) nk_set_chroot(chroot_path.c_str()); if (ndhs_uid != 0 || ndhs_gid != 0) nk_set_uidgid(ndhs_uid, ndhs_gid, NULL, 0); init_client_states_v4(io_service); gLeaseStore = std::make_unique<LeaseStore>(leasefile_path); if (enforce_seccomp(ndhs_uid || ndhs_gid)) { fmt::print(stderr, "seccomp filter cannot be installed\n"); std::exit(EXIT_FAILURE); } } int main(int ac, char *av[]) { process_options(ac, av); io_service.run(); std::exit(EXIT_SUCCESS); } <commit_msg>nk_fix_env() no longer exists.<commit_after>/* ndhs.c - dhcp server * * (c) 2011-2016 Nicholas J. Kain <njkain at gmail dot com> * 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. */ #define NDHS_VERSION "1.0" #include <string> #include <vector> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/stat.h> #include <fcntl.h> #include <ctype.h> #include <pwd.h> #include <grp.h> #include <signal.h> #include <errno.h> #include <boost/asio.hpp> #include <format.hpp> #include <nk/optionarg.hpp> extern "C" { #include "nk/privilege.h" #include "nk/pidfile.h" #include "nk/exec.h" #include "nk/seccomp-bpf.h" } #include "dhcpclient.hpp" #include "dhcplua.hpp" #include "leasestore.hpp" boost::asio::io_service io_service; static boost::asio::signal_set asio_signal_set(io_service); static std::vector<std::unique_ptr<ClientListener>> listeners; static uid_t ndhs_uid; static gid_t ndhs_gid; extern int gflags_detach; extern int gflags_quiet; static bool use_seccomp(false); std::unique_ptr<LeaseStore> gLeaseStore; std::unique_ptr<DhcpLua> gLua; static void process_signals() { sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGPIPE); sigaddset(&mask, SIGUSR1); sigaddset(&mask, SIGUSR2); sigaddset(&mask, SIGTSTP); sigaddset(&mask, SIGTTIN); sigaddset(&mask, SIGHUP); if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { fmt::print(stderr, "sigprocmask failed\n"); std::quick_exit(EXIT_FAILURE); } asio_signal_set.add(SIGINT); asio_signal_set.add(SIGTERM); asio_signal_set.async_wait( [](const boost::system::error_code &, int signum) { io_service.stop(); }); } static int enforce_seccomp(bool changed_uidgid) { if (!use_seccomp) return 0; struct sock_filter filter[] = { VALIDATE_ARCHITECTURE, EXAMINE_SYSCALL, #if defined(__x86_64__) || (defined(__arm__) && defined(__ARM_EABI__)) ALLOW_SYSCALL(sendmsg), ALLOW_SYSCALL(recvmsg), ALLOW_SYSCALL(socket), ALLOW_SYSCALL(getsockname), ALLOW_SYSCALL(getpeername), ALLOW_SYSCALL(setsockopt), ALLOW_SYSCALL(connect), ALLOW_SYSCALL(sendto), // used for glibc syslog routines ALLOW_SYSCALL(recvfrom), ALLOW_SYSCALL(fcntl), ALLOW_SYSCALL(accept), ALLOW_SYSCALL(shutdown), #elif defined(__i386__) ALLOW_SYSCALL(socketcall), ALLOW_SYSCALL(fcntl64), #else #error Target platform does not support seccomp-filter. #endif ALLOW_SYSCALL(read), ALLOW_SYSCALL(write), ALLOW_SYSCALL(epoll_wait), ALLOW_SYSCALL(epoll_ctl), ALLOW_SYSCALL(stat), ALLOW_SYSCALL(open), ALLOW_SYSCALL(close), ALLOW_SYSCALL(ioctl), ALLOW_SYSCALL(timerfd_settime), ALLOW_SYSCALL(access), ALLOW_SYSCALL(fstat), ALLOW_SYSCALL(lseek), ALLOW_SYSCALL(umask), ALLOW_SYSCALL(geteuid), ALLOW_SYSCALL(fsync), ALLOW_SYSCALL(unlink), ALLOW_SYSCALL(rt_sigreturn), ALLOW_SYSCALL(rt_sigaction), #ifdef __NR_sigreturn ALLOW_SYSCALL(sigreturn), #endif #ifdef __NR_sigaction ALLOW_SYSCALL(sigaction), #endif // Allowed by vDSO ALLOW_SYSCALL(getcpu), ALLOW_SYSCALL(time), ALLOW_SYSCALL(gettimeofday), ALLOW_SYSCALL(clock_gettime), // operator new ALLOW_SYSCALL(brk), ALLOW_SYSCALL(mmap), ALLOW_SYSCALL(munmap), ALLOW_SYSCALL(mremap), ALLOW_SYSCALL(exit_group), ALLOW_SYSCALL(exit), KILL_PROCESS, }; struct sock_fprog prog; memset(&prog, 0, sizeof prog); prog.len = (unsigned short)(sizeof filter / sizeof filter[0]); prog.filter = filter; if (!changed_uidgid && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) return -1; if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) return -1; fmt::print("seccomp filter installed. Please disable seccomp if you encounter problems.\n"); std::fflush(stdout); return 0; } static void print_version(void) { fmt::print("ndhs " NDHS_VERSION ", dhcp server.\n" "Copyright (c) 2011-2016 Nicholas J. Kain\n" "All rights reserved.\n\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are met:\n\n" "- Redistributions of source code must retain the above copyright notice,\n" " this list of conditions and the following disclaimer.\n" "- Redistributions in binary form must reproduce the above copyright notice,\n" " this list of conditions and the following disclaimer in the documentation\n" " and/or other materials provided with the distribution.\n\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n" "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" "POSSIBILITY OF SUCH DAMAGE.\n"); } enum OpIdx { OPT_UNKNOWN, OPT_HELP, OPT_VERSION, OPT_BACKGROUND, OPT_PIDFILE, OPT_CHROOT, OPT_USER, OPT_SCRIPTFILE, OPT_LEASEFILE, OPT_SECCOMP, OPT_QUIET }; static const option::Descriptor usage[] = { { OPT_UNKNOWN, 0, "", "", Arg::Unknown, "ndhs " NDHS_VERSION ", dhcp server.\n" "Copyright (c) 2011-2016 Nicholas J. Kain\n" "ndhs [options] interface...\n\nOptions:" }, { OPT_HELP, 0, "h", "help", Arg::None, "\t-h, \t--help \tPrint usage and exit." }, { OPT_VERSION, 0, "v", "version", Arg::None, "\t-v, \t--version \tPrint version and exit." }, { OPT_BACKGROUND, 0, "b", "background", Arg::None, "\t-b, \t--background \tRun as a background daemon." }, { OPT_PIDFILE, 0, "f", "pidfile", Arg::String, "\t-f, \t--pidfile \tPath to process id file." }, { OPT_CHROOT, 0, "C", "chroot", Arg::String, "\t-C, \t--chroot \tPath in which nident should chroot itself." }, { OPT_USER, 0, "u", "user", Arg::String, "\t-u, \t--user \tUser name that nrad6 should run as." }, { OPT_SCRIPTFILE, 0, "s", "script", Arg::String, "\t-s, \t--script \tPath to response script file." }, { OPT_LEASEFILE, 0, "l", "leasefile", Arg::String, "\t-l, \t--leasefile \tPath to lease database file." }, { OPT_SECCOMP, 0, "S", "seccomp-enforce", Arg::None, "\t-S \t--seccomp-enforce \tEnforce seccomp syscall restrictions." }, { OPT_QUIET, 0, "q", "quiet", Arg::None, "\t-q, \t--quiet \tDon't log to std(out|err) or syslog." }, {0,0,0,0,0,0} }; static void process_options(int ac, char *av[]) { ac-=ac>0; av+=ac>0; option::Stats stats(usage, ac, av); #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wvla" option::Option options[stats.options_max], buffer[stats.buffer_max]; #pragma GCC diagnostic pop option::Parser parse(usage, ac, av, options, buffer); #else auto options = std::make_unique<option::Option[]>(stats.options_max); auto buffer = std::make_unique<option::Option[]>(stats.buffer_max); option::Parser parse(usage, ac, av, options.get(), buffer.get()); #endif if (parse.error()) std::exit(EXIT_FAILURE); if (options[OPT_HELP]) { int col = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80; option::printUsage(fwrite, stdout, usage, col); std::exit(EXIT_FAILURE); } if (options[OPT_VERSION]) { print_version(); std::exit(EXIT_FAILURE); } std::vector<std::string> iflist; std::string pidfile, chroot_path, leasefile_path, scriptfile_path; for (int i = 0; i < parse.optionsCount(); ++i) { option::Option &opt = buffer[i]; switch (opt.index()) { case OPT_BACKGROUND: gflags_detach = 1; break; case OPT_PIDFILE: pidfile = std::string(opt.arg); break; case OPT_CHROOT: chroot_path = std::string(opt.arg); break; case OPT_USER: { if (nk_uidgidbyname(opt.arg, &ndhs_uid, &ndhs_gid)) { fmt::print(stderr, "invalid user '{}' specified\n", opt.arg); std::exit(EXIT_FAILURE); } break; } case OPT_SCRIPTFILE: scriptfile_path = std::string(opt.arg); break; case OPT_LEASEFILE: leasefile_path = std::string(opt.arg); break; case OPT_SECCOMP: use_seccomp = true; break; case OPT_QUIET: gflags_quiet = 1; break; } } for (int i = 0; i < parse.nonOptionsCount(); ++i) { iflist.emplace_back(parse.nonOption(i)); } for (const auto &i: iflist) { try { auto addy = boost::asio::ip::address_v4::any(); auto ep = boost::asio::ip::udp::endpoint(addy, 67); listeners.emplace_back(std::make_unique<ClientListener> (io_service, ep, i)); } catch (boost::system::error_code &ec) { fmt::print(stderr, "bad interface: {}\n", i); } } if (!iflist.size()) { fmt::print(stderr, "At least one listening interface must be specified\n"); std::exit(EXIT_FAILURE); } if (gflags_detach && daemon(0,0)) { fmt::print(stderr, "detaching fork failed\n"); std::exit(EXIT_FAILURE); } if (pidfile.size() && file_exists(pidfile.c_str(), "w")) write_pid(pidfile.c_str()); umask(077); process_signals(); gLua = std::make_unique<DhcpLua>(scriptfile_path); if (chroot_path.size()) nk_set_chroot(chroot_path.c_str()); if (ndhs_uid != 0 || ndhs_gid != 0) nk_set_uidgid(ndhs_uid, ndhs_gid, NULL, 0); init_client_states_v4(io_service); gLeaseStore = std::make_unique<LeaseStore>(leasefile_path); if (enforce_seccomp(ndhs_uid || ndhs_gid)) { fmt::print(stderr, "seccomp filter cannot be installed\n"); std::exit(EXIT_FAILURE); } } int main(int ac, char *av[]) { process_options(ac, av); io_service.run(); std::exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>#include "Iop_Sysclib.h" using namespace Iop; CSysclib::CSysclib(uint8* ram, CStdio& stdio) : m_ram(ram) , m_stdio(stdio) { } CSysclib::~CSysclib() { } std::string CSysclib::GetId() const { return "sysclib"; } std::string CSysclib::GetFunctionName(unsigned int functionId) const { switch(functionId) { case 8: return "look_ctype_table"; break; case 11: return "memcmp"; break; case 12: return "memcpy"; break; case 14: return "memset"; break; case 16: return "bcopy"; break; case 17: return "bzero"; break; case 19: return "sprintf"; break; case 22: return "strcmp"; break; case 23: return "strcpy"; break; case 27: return "strlen"; break; case 29: return "strncmp"; break; case 32: return "strrchr"; break; case 36: return "strtol"; break; default: return "unknown"; break; } } void CSysclib::Invoke(CMIPS& context, unsigned int functionId) { switch(functionId) { case 8: context.m_State.nGPR[CMIPS::V0].nD0 = __look_ctype_table( context.m_State.nGPR[CMIPS::A0].nV0); break; case 11: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__memcmp( reinterpret_cast<void*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<void*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]), context.m_State.nGPR[CMIPS::A2].nV0 )); break; case 12: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __memcpy( &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], &m_ram[context.m_State.nGPR[CMIPS::A1].nV0], context.m_State.nGPR[CMIPS::A2].nV0); break; case 13: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __memmove( &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], &m_ram[context.m_State.nGPR[CMIPS::A1].nV0], context.m_State.nGPR[CMIPS::A2].nV0); break; case 14: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __memset( &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], context.m_State.nGPR[CMIPS::A1].nV0, context.m_State.nGPR[CMIPS::A2].nV0); break; case 16: //bcopy memmove( &m_ram[context.m_State.nGPR[CMIPS::A1].nV0], &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], context.m_State.nGPR[CMIPS::A2].nV0); break; case 17: //bzero __memset( &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], 0, context.m_State.nGPR[CMIPS::A1].nV0); break; case 19: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__sprintf(context)); break; case 22: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__strcmp( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]) )); break; case 23: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __strcpy( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]) ); break; case 27: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__strlen( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]) )); break; case 29: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__strncmp( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]), context.m_State.nGPR[CMIPS::A2].nV0)); break; case 30: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __strncpy( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]), context.m_State.nGPR[CMIPS::A2].nV0); break; case 32: context.m_State.nGPR[CMIPS::V0].nD0 = __strrchr( context.m_State.nGPR[CMIPS::A0].nV0, context.m_State.nGPR[CMIPS::A1].nV0 ); break; case 36: assert(context.m_State.nGPR[CMIPS::A1].nV0 == 0); context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__strtol( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), context.m_State.nGPR[CMIPS::A2].nV0 )); break; default: printf("%s(%0.8X): Unknown function (%d) called.\r\n", __FUNCTION__, context.m_State.nPC, functionId); assert(0); break; } } uint32 CSysclib::__look_ctype_table(uint32 character) { static const uint8 ctype_table[128] = { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x08, 0x08, 0x08, 0x08, 0x08, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x18, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x10, 0x10, 0x10, 0x10, 0x20 }; assert(character < 128); return ctype_table[character & 0x7F]; } uint32 CSysclib::__memcmp(const void* dst, const void* src, uint32 length) { return static_cast<uint32>(memcmp(dst, src, length)); } void CSysclib::__memcpy(void* dest, const void* src, unsigned int length) { memcpy(dest, src, length); } void CSysclib::__memmove(void* dest, const void* src, uint32 length) { memmove(dest, src, length); } void CSysclib::__memset(void* dest, int character, unsigned int length) { memset(dest, character, length); } uint32 CSysclib::__sprintf(CMIPS& context) { CArgumentIterator args(context); char* destination = reinterpret_cast<char*>(&m_ram[args.GetNext()]); std::string output = m_stdio.PrintFormatted(args); strcpy(destination, output.c_str()); return static_cast<uint32>(output.length()); } uint32 CSysclib::__strlen(const char* string) { return static_cast<uint32>(strlen(string)); } uint32 CSysclib::__strcmp(const char* s1, const char* s2) { return static_cast<uint32>(strcmp(s1, s2)); } void CSysclib::__strcpy(char* dst, const char* src) { strcpy(dst, src); } uint32 CSysclib::__strncmp(const char* s1, const char* s2, uint32 length) { return static_cast<uint32>(strncmp(s1, s2, length)); } void CSysclib::__strncpy(char* dst, const char* src, unsigned int count) { strncpy(dst, src, count); } uint32 CSysclib::__strrchr(uint32 strPtr, uint32 character) { const char* str = reinterpret_cast<char*>(m_ram + strPtr); const char* result = strrchr(str, static_cast<int>(character)); if(result == nullptr) return 0; size_t ptrDiff = result - str; return strPtr + ptrDiff; } uint32 CSysclib::__strtol(const char* string, unsigned int radix) { return strtol(string, NULL, radix); } <commit_msg>implement toupper and tolower for return to arms<commit_after>#include "Iop_Sysclib.h" using namespace Iop; CSysclib::CSysclib(uint8* ram, CStdio& stdio) : m_ram(ram) , m_stdio(stdio) { } CSysclib::~CSysclib() { } std::string CSysclib::GetId() const { return "sysclib"; } std::string CSysclib::GetFunctionName(unsigned int functionId) const { switch(functionId) { case 6: return "toupper"; break; case 7: return "tolower"; break; case 8: return "look_ctype_table"; break; case 11: return "memcmp"; break; case 12: return "memcpy"; break; case 14: return "memset"; break; case 16: return "bcopy"; break; case 17: return "bzero"; break; case 19: return "sprintf"; break; case 22: return "strcmp"; break; case 23: return "strcpy"; break; case 27: return "strlen"; break; case 29: return "strncmp"; break; case 32: return "strrchr"; break; case 36: return "strtol"; break; default: return "unknown"; break; } } void CSysclib::Invoke(CMIPS& context, unsigned int functionId) { switch(functionId) { case 6: context.m_State.nGPR[CMIPS::V0].nD0 = toupper( context.m_State.nGPR[CMIPS::A0].nV0); break; case 7: context.m_State.nGPR[CMIPS::V0].nD0 = tolower( context.m_State.nGPR[CMIPS::A0].nV0); break; case 8: context.m_State.nGPR[CMIPS::V0].nD0 = __look_ctype_table( context.m_State.nGPR[CMIPS::A0].nV0); break; case 11: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__memcmp( reinterpret_cast<void*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<void*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]), context.m_State.nGPR[CMIPS::A2].nV0 )); break; case 12: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __memcpy( &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], &m_ram[context.m_State.nGPR[CMIPS::A1].nV0], context.m_State.nGPR[CMIPS::A2].nV0); break; case 13: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __memmove( &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], &m_ram[context.m_State.nGPR[CMIPS::A1].nV0], context.m_State.nGPR[CMIPS::A2].nV0); break; case 14: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __memset( &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], context.m_State.nGPR[CMIPS::A1].nV0, context.m_State.nGPR[CMIPS::A2].nV0); break; case 16: //bcopy memmove( &m_ram[context.m_State.nGPR[CMIPS::A1].nV0], &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], context.m_State.nGPR[CMIPS::A2].nV0); break; case 17: //bzero __memset( &m_ram[context.m_State.nGPR[CMIPS::A0].nV0], 0, context.m_State.nGPR[CMIPS::A1].nV0); break; case 19: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__sprintf(context)); break; case 22: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__strcmp( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]) )); break; case 23: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __strcpy( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]) ); break; case 27: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__strlen( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]) )); break; case 29: context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__strncmp( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]), context.m_State.nGPR[CMIPS::A2].nV0)); break; case 30: context.m_State.nGPR[CMIPS::V0].nD0 = context.m_State.nGPR[CMIPS::A0].nD0; __strncpy( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A1].nV0]), context.m_State.nGPR[CMIPS::A2].nV0); break; case 32: context.m_State.nGPR[CMIPS::V0].nD0 = __strrchr( context.m_State.nGPR[CMIPS::A0].nV0, context.m_State.nGPR[CMIPS::A1].nV0 ); break; case 36: assert(context.m_State.nGPR[CMIPS::A1].nV0 == 0); context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(__strtol( reinterpret_cast<char*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0]), context.m_State.nGPR[CMIPS::A2].nV0 )); break; default: printf("%s(%0.8X): Unknown function (%d) called.\r\n", __FUNCTION__, context.m_State.nPC, functionId); assert(0); break; } } uint32 CSysclib::__look_ctype_table(uint32 character) { static const uint8 ctype_table[128] = { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x08, 0x08, 0x08, 0x08, 0x08, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x18, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x10, 0x10, 0x10, 0x10, 0x20 }; assert(character < 128); return ctype_table[character & 0x7F]; } uint32 CSysclib::__memcmp(const void* dst, const void* src, uint32 length) { return static_cast<uint32>(memcmp(dst, src, length)); } void CSysclib::__memcpy(void* dest, const void* src, unsigned int length) { memcpy(dest, src, length); } void CSysclib::__memmove(void* dest, const void* src, uint32 length) { memmove(dest, src, length); } void CSysclib::__memset(void* dest, int character, unsigned int length) { memset(dest, character, length); } uint32 CSysclib::__sprintf(CMIPS& context) { CArgumentIterator args(context); char* destination = reinterpret_cast<char*>(&m_ram[args.GetNext()]); std::string output = m_stdio.PrintFormatted(args); strcpy(destination, output.c_str()); return static_cast<uint32>(output.length()); } uint32 CSysclib::__strlen(const char* string) { return static_cast<uint32>(strlen(string)); } uint32 CSysclib::__strcmp(const char* s1, const char* s2) { return static_cast<uint32>(strcmp(s1, s2)); } void CSysclib::__strcpy(char* dst, const char* src) { strcpy(dst, src); } uint32 CSysclib::__strncmp(const char* s1, const char* s2, uint32 length) { return static_cast<uint32>(strncmp(s1, s2, length)); } void CSysclib::__strncpy(char* dst, const char* src, unsigned int count) { strncpy(dst, src, count); } uint32 CSysclib::__strrchr(uint32 strPtr, uint32 character) { const char* str = reinterpret_cast<char*>(m_ram + strPtr); const char* result = strrchr(str, static_cast<int>(character)); if(result == nullptr) return 0; size_t ptrDiff = result - str; return strPtr + ptrDiff; } uint32 CSysclib::__strtol(const char* string, unsigned int radix) { return strtol(string, NULL, radix); } <|endoftext|>
<commit_before> #include <raytracer.h> #include <bodies.h> using namespace raytracer; class OneWayPlane : public Plane { public: OneWayPlane() { useDefaults(); } virtual double getDistance(const Ray & ray) const; }; double OneWayPlane::getDistance(const Ray & ray) const { if (ray.v.dot(this->orientation) > ZERO) return -1.0; else return Plane::getDistance(ray); } static const int height_pixels = 960; static const double aspect_ratio = 1.125; //1080x960 static const int anti_alias = 32; static const int recursion_depth = 8; static const char * filename = "phone.png"; static Plane * newWall(); static Cylinder * newCylinder(const Vector & pos); int main() { double window_h = 4.0; double window_w = window_h * aspect_ratio; RNG::init(); Tracer t; World * world = t.getWorld(); Camera * cam = t.getCamera(); //init cam Vector forward, up, right, focus, position; focus.copy(0.0,1.0,0.0); position.copy(5.0,2.5,10.0); forward.copy(focus); forward.subtract(position); forward.normalize(); up.copy(0.0,1.0,0.0); right = forward.cross(up); right.normalize(); up = right.cross(forward); up.normalize(); cam->setOrientation(right,up); cam->setFocus(Vector(0.0,1.0,0.0)); cam->setPosition(Vector(5.0,2.5,10.0)); cam->setSize(window_w,window_h); cam->setResolution(height_pixels); cam->setBlur(0.25); cam->init(); //init ball Sphere * ball = new Sphere(); ball->setPosition(Vector(0.0,0.2,0.0)); ball->setSize(1.0); ball->setColor(Vector(0.2,0.1,0.1)); ball->setReflectivity(0.6); world->addBody(ball); //init floor CheckeredPlane * floor = new CheckeredPlane(); floor->setSize(1.0); floor->setNormal(Vector(0.0,1.0,0.0)); floor->setOrientation(Vector(1.0,0.0,0.0), Vector(0.0,0.0,1.0)); floor->setColors(Vector(0.1,0.1,0.2),Vector(0.99,0.99,0.99)); floor->setReflectivity(0.0); world->addBody(floor); //init all walls (and ceiling) Plane * p = NULL; p = newWall(); p->setPosition(Vector(0.0,0.0,6.0)); p->setOrientation(Vector(1.0,0.0,-3.0)); world->addBody(p); p = NULL; p = newWall(); p->setPosition(Vector(0.0,0.0,-6.0)); p->setOrientation(Vector(-1.0,0.0,3.0)); world->addBody(p); p = NULL; p = newWall(); p->setPosition(Vector(6.0,0.0,0.0)); p->setOrientation(Vector(-3.0,0.0,-1.0)); world->addBody(p); p = NULL; p = newWall(); p->setPosition(Vector(-6.0,0.0,0.0)); p->setOrientation(Vector(3.0,0.0,1.0)); world->addBody(p); p = NULL; p = newWall(); p->setPosition(Vector(0.0,6.0,0.0)); p->setOrientation(Vector(0.0,-1.0,0.0)); world->addBody(p); p = NULL; //init cylinders world->addBody(newCylinder(Vector(-3.0,0.0,6.0))); world->addBody(newCylinder(Vector(3.0,0.0,-6.0))); world->addBody(newCylinder(Vector(-6.0,0.0,3.0))); world->addBody(newCylinder(Vector(6.0,0.0,-3.0))); t.setOutputName(filename); t.render(anti_alias,recursion_depth); return 0; } static Plane * newWall() { OneWayPlane * p = new OneWayPlane(); p->setReflectivity(0.6); p->setColor(Vector(0.01,0.01,0.01)); return (Plane*)p; } static Cylinder * newCylinder(const Vector & pos) { Cylinder * c = new Cylinder(); c->setPosition(pos); c->setOrientation(Vector(0.0,1.0,0.0)); Builder::makeGlass(c); c->setSize(0.3); return c; } <commit_msg>removed the ugly glass cylinders<commit_after> #include <raytracer.h> #include <bodies.h> using namespace raytracer; class OneWayPlane : public Plane { public: OneWayPlane() { useDefaults(); } virtual double getDistance(const Ray & ray) const; }; double OneWayPlane::getDistance(const Ray & ray) const { if (ray.v.dot(this->orientation) > ZERO) return -1.0; else return Plane::getDistance(ray); } static const int height_pixels = 960; static const double aspect_ratio = 1.125; //1080x960 static const int anti_alias = 32; static const int recursion_depth = 8; static const char * filename = "phone.png"; static Plane * newWall(); //static Cylinder * newCylinder(const Vector & pos); int main() { double window_h = 4.0; double window_w = window_h * aspect_ratio; RNG::init(); Tracer t; World * world = t.getWorld(); Camera * cam = t.getCamera(); //init cam Vector forward, up, right, focus, position; focus.copy(0.0,1.0,0.0); position.copy(5.0,2.5,10.0); forward.copy(focus); forward.subtract(position); forward.normalize(); up.copy(0.0,1.0,0.0); right = forward.cross(up); right.normalize(); up = right.cross(forward); up.normalize(); cam->setOrientation(right,up); cam->setFocus(focus); cam->setPosition(position); cam->setSize(window_w,window_h); cam->setResolution(height_pixels); //cam->setBlur(0.25); cam->init(); //init ball Sphere * ball = new Sphere(); ball->setPosition(Vector(0.0,0.2,0.0)); ball->setSize(1.0); ball->setColor(Vector(0.2,0.1,0.1)); ball->setReflectivity(0.6); world->addBody(ball); //init floor CheckeredPlane * floor = new CheckeredPlane(); floor->setSize(1.0); floor->setNormal(Vector(0.0,1.0,0.0)); floor->setOrientation(Vector(1.0,0.0,0.0), Vector(0.0,0.0,1.0)); floor->setColors(Vector(0.1,0.1,0.2),Vector(0.99,0.99,0.99)); floor->setReflectivity(0.0); world->addBody(floor); //init all walls (and ceiling) Plane * p = NULL; p = newWall(); p->setPosition(Vector(0.0,0.0,6.0)); p->setOrientation(Vector(1.0,0.0,-3.0)); world->addBody(p); p = NULL; p = newWall(); p->setPosition(Vector(0.0,0.0,-6.0)); p->setOrientation(Vector(-1.0,0.0,3.0)); world->addBody(p); p = NULL; p = newWall(); p->setPosition(Vector(6.0,0.0,0.0)); p->setOrientation(Vector(-3.0,0.0,-1.0)); world->addBody(p); p = NULL; p = newWall(); p->setPosition(Vector(-6.0,0.0,0.0)); p->setOrientation(Vector(3.0,0.0,1.0)); world->addBody(p); p = NULL; p = newWall(); p->setPosition(Vector(0.0,6.0,0.0)); p->setOrientation(Vector(0.0,-1.0,0.0)); world->addBody(p); p = NULL; /* //init cylinders world->addBody(newCylinder(Vector(-3.0,0.0,-6.0))); world->addBody(newCylinder(Vector(3.0,0.0,6.0))); world->addBody(newCylinder(Vector(-6.0,0.0,3.0))); world->addBody(newCylinder(Vector(6.0,0.0,-3.0))); */ t.setOutputName(filename); t.render(anti_alias,recursion_depth); return 0; } static Plane * newWall() { OneWayPlane * p = new OneWayPlane(); p->setReflectivity(0.6); p->setColor(Vector(0.01,0.01,0.01)); return (Plane*)p; } /* static Cylinder * newCylinder(const Vector & pos) { Cylinder * c = new Cylinder(); c->setPosition(pos); c->setOrientation(Vector(0.0,1.0,0.0)); Builder::makeGlass(c); c->setSize(0.3); return c; } */ <|endoftext|>
<commit_before>/* This file is part of the Vc library. Copyright (C) 2010-2011 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include <Vc/Vc> #include "unittest.h" #include <iostream> #include <limits> using namespace Vc; /* * V \ M | float | double | ushort | short | uint | int * ---------+---------------------------------------------- * float_v | X | | X | X | | * sfloat_v | X | | X | X | | * double_v | | X | | | | * int_v | | | | X | | X * uint_v | | | X | | X | * short_v | | | | X | | * ushort_v | | | X | | | */ template<typename A, typename B> struct TPair { typedef A V; typedef B M; }; typedef TPair<float_v, float> float_float; typedef TPair<float_v, unsigned short> float_ushort; typedef TPair<float_v, short> float_short; typedef TPair<sfloat_v, float> sfloat_float; typedef TPair<sfloat_v, unsigned short> sfloat_ushort; typedef TPair<sfloat_v, short> sfloat_short; typedef TPair<double_v, double> double_double; typedef TPair<short_v, short> short_short; typedef TPair<ushort_v, unsigned short> ushort_ushort; typedef TPair<int_v, int> int_int; typedef TPair<int_v, short> int_short; typedef TPair<uint_v, unsigned int> uint_uint; typedef TPair<uint_v, unsigned short> uint_ushort; template<typename Pair> void testDeinterleave() { typedef typename Pair::V V; typedef typename Pair::M M; typedef typename V::IndexType I; const bool isSigned = std::numeric_limits<M>::is_signed; const typename V::EntryType offset = isSigned ? -512 : 0; const V _0246 = static_cast<V>(I::IndexesFromZero()) * 2 + offset; M memory[1024]; for (int i = 0; i < 1024; ++i) { memory[i] = static_cast<M>(i + offset); } V a, b; for (int i = 0; i < 1024 - 2 * V::Size; ++i) { // note that a 32 bit integer is certainly enough to decide on alignment... // ... but uintptr_t is C99 but not C++ yet // ... and GCC refuses to do the cast, even if I know what I'm doing if (reinterpret_cast<unsigned long>(&memory[i]) & (VectorAlignment - 1)) { Vc::deinterleave(&a, &b, &memory[i], Unaligned); } else { Vc::deinterleave(&a, &b, &memory[i]); } COMPARE(_0246 + i, a); COMPARE(_0246 + i + 1, b); } } template<typename T, size_t N> struct SomeStruct { T d[N]; }; template<typename V, size_t StructSize> struct Types { typedef typename V::EntryType T; typedef typename V::IndexType I; typedef SomeStruct<T, StructSize> S; typedef const Vc::InterleavedMemoryWrapper<S, V> &Wrapper; }; template<typename V, size_t StructSize, size_t N = StructSize> struct TestDeinterleaveGatherCompare; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 8> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V v0, v1, v2, v3, v4, v5, v6, v7; (v0, v1, v2, v3, v4, v5, v6, v7) = data_v[indexes]; COMPARE(v0, reference + 0) << "N = 8"; COMPARE(v1, reference + 1) << "N = 8"; COMPARE(v2, reference + 2) << "N = 8"; COMPARE(v3, reference + 3) << "N = 8"; COMPARE(v4, reference + 4) << "N = 8"; COMPARE(v5, reference + 5) << "N = 8"; COMPARE(v6, reference + 6) << "N = 8"; COMPARE(v7, reference + 7) << "N = 8"; TestDeinterleaveGatherCompare<V, StructSize, 7>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 7> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V v0, v1, v2, v3, v4, v5, v6; (v0, v1, v2, v3, v4, v5, v6) = data_v[indexes]; COMPARE(v0, reference + 0) << "N = 7"; COMPARE(v1, reference + 1) << "N = 7"; COMPARE(v2, reference + 2) << "N = 7"; COMPARE(v3, reference + 3) << "N = 7"; COMPARE(v4, reference + 4) << "N = 7"; COMPARE(v5, reference + 5) << "N = 7"; COMPARE(v6, reference + 6) << "N = 7"; TestDeinterleaveGatherCompare<V, StructSize, 6>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 6> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V v0, v1, v2, v3, v4, v5; (v0, v1, v2, v3, v4, v5) = data_v[indexes]; COMPARE(v0, reference + 0) << "N = 6"; COMPARE(v1, reference + 1) << "N = 6"; COMPARE(v2, reference + 2) << "N = 6"; COMPARE(v3, reference + 3) << "N = 6"; COMPARE(v4, reference + 4) << "N = 6"; COMPARE(v5, reference + 5) << "N = 6"; TestDeinterleaveGatherCompare<V, StructSize, 5>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 5> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V v0, v1, v2, v3, v4; (v0, v1, v2, v3, v4) = data_v[indexes]; COMPARE(v0, reference + 0) << "N = 5"; COMPARE(v1, reference + 1) << "N = 5"; COMPARE(v2, reference + 2) << "N = 5"; COMPARE(v3, reference + 3) << "N = 5"; COMPARE(v4, reference + 4) << "N = 5"; TestDeinterleaveGatherCompare<V, StructSize, 4>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 4> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V a, b, c, d; (a, b, c, d) = data_v[indexes]; COMPARE(a, reference + 0) << "N = 4"; COMPARE(b, reference + 1) << "N = 4"; COMPARE(c, reference + 2) << "N = 4"; COMPARE(d, reference + 3) << "N = 4"; TestDeinterleaveGatherCompare<V, StructSize, 3>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 3> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V a, b, c; (a, b, c) = data_v[indexes]; COMPARE(a, reference + 0) << "N = 3"; COMPARE(b, reference + 1) << "N = 3"; COMPARE(c, reference + 2) << "N = 3"; TestDeinterleaveGatherCompare<V, StructSize, 2>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 2> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V a, b; (a, b) = data_v[indexes]; COMPARE(a, reference + 0) << "N = 2"; COMPARE(b, reference + 1) << "N = 2"; } }; template<typename V, size_t StructSize> void testDeinterleaveGatherImpl() { typedef typename V::EntryType T; typedef typename V::IndexType I; typedef SomeStruct<T, StructSize> S; typedef Vc::InterleavedMemoryWrapper<S, V> Wrapper; const size_t N = 1024 * 1024 / sizeof(S); S *data = Vc::malloc<S, Vc::AlignOnVector>(N); for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < StructSize; ++j) { data[i].d[j] = i * StructSize + j; } } const Wrapper data_v(data); for (int retest = 0; retest < 10000; ++retest) { I indexes = I::Random() >> 10; indexes = Vc::min(I(N - 1), Vc::max(I::Zero(), indexes)); const V reference = static_cast<V>(indexes) * V(StructSize); TestDeinterleaveGatherCompare<V, StructSize>::test(data_v, indexes, reference); } } template<typename V> void testDeinterleaveGather() { testDeinterleaveGatherImpl<V, 2>(); testDeinterleaveGatherImpl<V, 3>(); testDeinterleaveGatherImpl<V, 4>(); testDeinterleaveGatherImpl<V, 5>(); testDeinterleaveGatherImpl<V, 6>(); testDeinterleaveGatherImpl<V, 7>(); testDeinterleaveGatherImpl<V, 8>(); } int main() { runTest(testDeinterleave<float_float>); runTest(testDeinterleave<float_ushort>); runTest(testDeinterleave<float_short>); runTest(testDeinterleave<sfloat_float>); runTest(testDeinterleave<sfloat_ushort>); runTest(testDeinterleave<sfloat_short>); runTest(testDeinterleave<double_double>); runTest(testDeinterleave<int_int>); runTest(testDeinterleave<int_short>); runTest(testDeinterleave<uint_uint>); runTest(testDeinterleave<uint_ushort>); runTest(testDeinterleave<short_short>); runTest(testDeinterleave<ushort_ushort>); runTest(testDeinterleaveGather<float_v>); runTest(testDeinterleaveGather<int_v>); runTest(testDeinterleaveGather<uint_v>); runTest(testDeinterleaveGather<double_v>); } <commit_msg>test deinterleaving gathers with all types<commit_after>/* This file is part of the Vc library. Copyright (C) 2010-2011 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include <Vc/Vc> #include "unittest.h" #include <iostream> #include <limits> using namespace Vc; /* * V \ M | float | double | ushort | short | uint | int * ---------+---------------------------------------------- * float_v | X | | X | X | | * sfloat_v | X | | X | X | | * double_v | | X | | | | * int_v | | | | X | | X * uint_v | | | X | | X | * short_v | | | | X | | * ushort_v | | | X | | | */ template<typename A, typename B> struct TPair { typedef A V; typedef B M; }; typedef TPair<float_v, float> float_float; typedef TPair<float_v, unsigned short> float_ushort; typedef TPair<float_v, short> float_short; typedef TPair<sfloat_v, float> sfloat_float; typedef TPair<sfloat_v, unsigned short> sfloat_ushort; typedef TPair<sfloat_v, short> sfloat_short; typedef TPair<double_v, double> double_double; typedef TPair<short_v, short> short_short; typedef TPair<ushort_v, unsigned short> ushort_ushort; typedef TPair<int_v, int> int_int; typedef TPair<int_v, short> int_short; typedef TPair<uint_v, unsigned int> uint_uint; typedef TPair<uint_v, unsigned short> uint_ushort; template<typename Pair> void testDeinterleave() { typedef typename Pair::V V; typedef typename Pair::M M; typedef typename V::IndexType I; const bool isSigned = std::numeric_limits<M>::is_signed; const typename V::EntryType offset = isSigned ? -512 : 0; const V _0246 = static_cast<V>(I::IndexesFromZero()) * 2 + offset; M memory[1024]; for (int i = 0; i < 1024; ++i) { memory[i] = static_cast<M>(i + offset); } V a, b; for (int i = 0; i < 1024 - 2 * V::Size; ++i) { // note that a 32 bit integer is certainly enough to decide on alignment... // ... but uintptr_t is C99 but not C++ yet // ... and GCC refuses to do the cast, even if I know what I'm doing if (reinterpret_cast<unsigned long>(&memory[i]) & (VectorAlignment - 1)) { Vc::deinterleave(&a, &b, &memory[i], Unaligned); } else { Vc::deinterleave(&a, &b, &memory[i]); } COMPARE(_0246 + i, a); COMPARE(_0246 + i + 1, b); } } template<typename T, size_t N> struct SomeStruct { T d[N]; }; template<typename V, size_t StructSize> struct Types { typedef typename V::EntryType T; typedef typename V::IndexType I; typedef SomeStruct<T, StructSize> S; typedef const Vc::InterleavedMemoryWrapper<S, V> &Wrapper; }; template<typename V, size_t StructSize, size_t N = StructSize> struct TestDeinterleaveGatherCompare; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 8> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V v0, v1, v2, v3, v4, v5, v6, v7; (v0, v1, v2, v3, v4, v5, v6, v7) = data_v[indexes]; COMPARE(v0, reference + 0) << "N = 8"; COMPARE(v1, reference + 1) << "N = 8"; COMPARE(v2, reference + 2) << "N = 8"; COMPARE(v3, reference + 3) << "N = 8"; COMPARE(v4, reference + 4) << "N = 8"; COMPARE(v5, reference + 5) << "N = 8"; COMPARE(v6, reference + 6) << "N = 8"; COMPARE(v7, reference + 7) << "N = 8"; TestDeinterleaveGatherCompare<V, StructSize, 7>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 7> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V v0, v1, v2, v3, v4, v5, v6; (v0, v1, v2, v3, v4, v5, v6) = data_v[indexes]; COMPARE(v0, reference + 0) << "N = 7"; COMPARE(v1, reference + 1) << "N = 7"; COMPARE(v2, reference + 2) << "N = 7"; COMPARE(v3, reference + 3) << "N = 7"; COMPARE(v4, reference + 4) << "N = 7"; COMPARE(v5, reference + 5) << "N = 7"; COMPARE(v6, reference + 6) << "N = 7"; TestDeinterleaveGatherCompare<V, StructSize, 6>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 6> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V v0, v1, v2, v3, v4, v5; (v0, v1, v2, v3, v4, v5) = data_v[indexes]; COMPARE(v0, reference + 0) << "N = 6"; COMPARE(v1, reference + 1) << "N = 6"; COMPARE(v2, reference + 2) << "N = 6"; COMPARE(v3, reference + 3) << "N = 6"; COMPARE(v4, reference + 4) << "N = 6"; COMPARE(v5, reference + 5) << "N = 6"; TestDeinterleaveGatherCompare<V, StructSize, 5>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 5> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V v0, v1, v2, v3, v4; (v0, v1, v2, v3, v4) = data_v[indexes]; COMPARE(v0, reference + 0) << "N = 5"; COMPARE(v1, reference + 1) << "N = 5"; COMPARE(v2, reference + 2) << "N = 5"; COMPARE(v3, reference + 3) << "N = 5"; COMPARE(v4, reference + 4) << "N = 5"; TestDeinterleaveGatherCompare<V, StructSize, 4>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 4> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V a, b, c, d; (a, b, c, d) = data_v[indexes]; COMPARE(a, reference + 0) << "N = 4"; COMPARE(b, reference + 1) << "N = 4"; COMPARE(c, reference + 2) << "N = 4"; COMPARE(d, reference + 3) << "N = 4"; TestDeinterleaveGatherCompare<V, StructSize, 3>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 3> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V a, b, c; (a, b, c) = data_v[indexes]; COMPARE(a, reference + 0) << "N = 3"; COMPARE(b, reference + 1) << "N = 3"; COMPARE(c, reference + 2) << "N = 3"; TestDeinterleaveGatherCompare<V, StructSize, 2>::test(data_v, indexes, reference); } }; template<typename V, size_t StructSize> struct TestDeinterleaveGatherCompare<V, StructSize, 2> { static void test(typename Types<V, StructSize>::Wrapper data_v, typename Types<V, StructSize>::I indexes, const V reference) { V a, b; (a, b) = data_v[indexes]; COMPARE(a, reference + 0) << "N = 2"; COMPARE(b, reference + 1) << "N = 2"; } }; template<typename V, size_t StructSize> void testDeinterleaveGatherImpl() { typedef typename V::EntryType T; typedef typename V::IndexType I; typedef SomeStruct<T, StructSize> S; typedef Vc::InterleavedMemoryWrapper<S, V> Wrapper; const size_t N = std::min<size_t>(std::numeric_limits<typename I::EntryType>::max(), 1024 * 1024 / sizeof(S)); S *data = Vc::malloc<S, Vc::AlignOnVector>(N); for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < StructSize; ++j) { data[i].d[j] = i * StructSize + j; } } const Wrapper data_v(data); for (int retest = 0; retest < 10000; ++retest) { I indexes = I::Random() >> 10; indexes = Vc::min(I(N - 1), Vc::max(I::Zero(), indexes)); const V reference = static_cast<V>(indexes) * V(StructSize); TestDeinterleaveGatherCompare<V, StructSize>::test(data_v, indexes, reference); } } template<typename V> void testDeinterleaveGather() { testDeinterleaveGatherImpl<V, 2>(); testDeinterleaveGatherImpl<V, 3>(); testDeinterleaveGatherImpl<V, 4>(); testDeinterleaveGatherImpl<V, 5>(); testDeinterleaveGatherImpl<V, 6>(); testDeinterleaveGatherImpl<V, 7>(); testDeinterleaveGatherImpl<V, 8>(); } int main() { runTest(testDeinterleave<float_float>); runTest(testDeinterleave<float_ushort>); runTest(testDeinterleave<float_short>); runTest(testDeinterleave<sfloat_float>); runTest(testDeinterleave<sfloat_ushort>); runTest(testDeinterleave<sfloat_short>); runTest(testDeinterleave<double_double>); runTest(testDeinterleave<int_int>); runTest(testDeinterleave<int_short>); runTest(testDeinterleave<uint_uint>); runTest(testDeinterleave<uint_ushort>); runTest(testDeinterleave<short_short>); runTest(testDeinterleave<ushort_ushort>); testAllTypes(testDeinterleaveGather); } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "server_util.hpp" #include <glog/logging.h> #include <iostream> #include <pficommon/text/json.h> #include "../common/util.hpp" #include "../common/network.hpp" #include "../common/cmdline.h" #include "../common/exception.hpp" #include "../common/membership.hpp" #include "../fv_converter/datum_to_fv_converter.hpp" #include "../fv_converter/converter_config.hpp" #include "../fv_converter/exception.hpp" namespace jubatus { namespace framework { static const std::string VERSION(JUBATUS_VERSION); void print_version(const std::string& progname){ std::cout << "jubatus-" << VERSION << " (" << progname << ")" << std::endl; } server_argv::server_argv(int args, char** argv, const std::string& type) : type(type) { google::InitGoogleLogging(argv[0]); google::LogToStderr(); // only when debug cmdline::parser p; p.add<int>("rpc-port", 'p', "port number", false, 9199); p.add<int>("thread", 'c', "concurrency = thread number", false, 2); p.add<int>("timeout", 't', "time out (sec)", false, 10); p.add<std::string>("tmpdir", 'd', "directory to output logs", false, "/tmp"); #ifdef HAVE_ZOOKEEPER_H p.add<std::string>("zookeeper", 'z', "zookeeper location", false); p.add<std::string>("name", 'n', "learning machine instance name", false); p.add("join", 'j', "join to the existing cluster"); p.add<int>("interval_sec", 's', "mix interval by seconds", false, 16); p.add<int>("interval_count", 'i', "mix interval by update count", false, 512); #endif // APPLY CHANGES TO JUBAVISOR WHEN ARGUMENTS MODIFIED p.add("version", 'v', "version"); p.parse_check(args, argv); if( p.exist("version") ){ print_version(jubatus::util::get_program_name()); exit(0); } port = p.get<int>("rpc-port"); threadnum = p.get<int>("thread"); timeout = p.get<int>("timeout"); program_name = jubatus::util::get_program_name(); tmpdir = p.get<std::string>("tmpdir"); // eth = "localhost"; eth = jubatus::common::get_default_v4_address(); #ifdef HAVE_ZOOKEEPER_H z = p.get<std::string>("zookeeper"); name = p.get<std::string>("name"); join = p.exist("join"); interval_sec = p.get<int>("interval_sec"); interval_count = p.get<int>("interval_count"); #else z = ""; name = ""; join = false; interval_sec = 16; interval_count = 512; #endif if(z != "" and name == ""){ throw JUBATUS_EXCEPTION(argv_error("can't start multinode mode without name specified")); } LOG(INFO) << boot_message(jubatus::util::get_program_name()); }; server_argv::server_argv(): join(false), port(9199), timeout(10), threadnum(2), z(""), name(""), tmpdir("/tmp"), eth("localhost"), interval_sec(5), interval_count(1024) { }; std::string server_argv::boot_message(const std::string& progname) const { std::stringstream ret; ret << "starting " << progname << " " << VERSION << " RPC server at " << eth << ":" << port << " with timeout: " << timeout; return ret.str(); }; std::string get_server_identifier(const server_argv& a) { std::stringstream ss; ss << a.eth; ss << "_"; ss << a.port; return ss.str(); } keeper_argv::keeper_argv(int args, char** argv, const std::string& t) : type(t) { google::InitGoogleLogging(argv[0]); google::LogToStderr(); // only when debug cmdline::parser p; p.add<int>("rpc-port", 'p', "port number", false, 9199); p.add<int>("thread", 'c', "concurrency = thread number", false, 16); p.add<int>("timeout", 't', "time out (sec)", false, 10); p.add<std::string>("zookeeper", 'z', "zookeeper location", false, "localhost:2181"); p.add("version", 'v', "version"); p.parse_check(args, argv); if( p.exist("version") ){ print_version(jubatus::util::get_program_name()); exit(0); } port = p.get<int>("rpc-port"); threadnum = p.get<int>("thread"); timeout = p.get<int>("timeout"); z = p.get<std::string>("zookeeper"); eth = jubatus::common::get_default_v4_address(); LOG(INFO) << boot_message(jubatus::util::get_program_name()); }; keeper_argv::keeper_argv(): port(9199), timeout(10), threadnum(16), z("localhost:2181"), eth("") { }; std::string keeper_argv::boot_message(const std::string& progname) const { std::stringstream ret; ret << "starting " << progname << " " << VERSION << " RPC server at " << eth << ":" << port << " with timeout: " << timeout; return ret.str(); }; common::cshared_ptr<jubatus::common::lock_service> ls; void atexit(void){ #ifdef HAVE_ZOOKEEPER_H if(ls) ls->force_close(); #endif } pfi::lang::shared_ptr<fv_converter::datum_to_fv_converter> make_fv_converter(const std::string& config) { if (config == "") throw JUBATUS_EXCEPTION(fv_converter::converter_exception("Config of feature vector converter is empty")); pfi::lang::shared_ptr<fv_converter::datum_to_fv_converter> converter(new fv_converter::datum_to_fv_converter); fv_converter::converter_config c; std::stringstream ss(config); // FIXME: check invalid json format ss >> pfi::text::json::via_json(c); fv_converter::initialize_converter(c, *converter); return converter; } } } <commit_msg>Catch bad_cast of fv_converter config and throw it as jubatus_exception<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "server_util.hpp" #include <glog/logging.h> #include <iostream> #include <pficommon/text/json.h> #include "../common/util.hpp" #include "../common/network.hpp" #include "../common/cmdline.h" #include "../common/exception.hpp" #include "../common/membership.hpp" #include "../fv_converter/datum_to_fv_converter.hpp" #include "../fv_converter/converter_config.hpp" #include "../fv_converter/exception.hpp" namespace jubatus { namespace framework { static const std::string VERSION(JUBATUS_VERSION); void print_version(const std::string& progname){ std::cout << "jubatus-" << VERSION << " (" << progname << ")" << std::endl; } server_argv::server_argv(int args, char** argv, const std::string& type) : type(type) { google::InitGoogleLogging(argv[0]); google::LogToStderr(); // only when debug cmdline::parser p; p.add<int>("rpc-port", 'p', "port number", false, 9199); p.add<int>("thread", 'c', "concurrency = thread number", false, 2); p.add<int>("timeout", 't', "time out (sec)", false, 10); p.add<std::string>("tmpdir", 'd', "directory to output logs", false, "/tmp"); #ifdef HAVE_ZOOKEEPER_H p.add<std::string>("zookeeper", 'z', "zookeeper location", false); p.add<std::string>("name", 'n', "learning machine instance name", false); p.add("join", 'j', "join to the existing cluster"); p.add<int>("interval_sec", 's', "mix interval by seconds", false, 16); p.add<int>("interval_count", 'i', "mix interval by update count", false, 512); #endif // APPLY CHANGES TO JUBAVISOR WHEN ARGUMENTS MODIFIED p.add("version", 'v', "version"); p.parse_check(args, argv); if( p.exist("version") ){ print_version(jubatus::util::get_program_name()); exit(0); } port = p.get<int>("rpc-port"); threadnum = p.get<int>("thread"); timeout = p.get<int>("timeout"); program_name = jubatus::util::get_program_name(); tmpdir = p.get<std::string>("tmpdir"); // eth = "localhost"; eth = jubatus::common::get_default_v4_address(); #ifdef HAVE_ZOOKEEPER_H z = p.get<std::string>("zookeeper"); name = p.get<std::string>("name"); join = p.exist("join"); interval_sec = p.get<int>("interval_sec"); interval_count = p.get<int>("interval_count"); #else z = ""; name = ""; join = false; interval_sec = 16; interval_count = 512; #endif if(z != "" and name == ""){ throw JUBATUS_EXCEPTION(argv_error("can't start multinode mode without name specified")); } LOG(INFO) << boot_message(jubatus::util::get_program_name()); }; server_argv::server_argv(): join(false), port(9199), timeout(10), threadnum(2), z(""), name(""), tmpdir("/tmp"), eth("localhost"), interval_sec(5), interval_count(1024) { }; std::string server_argv::boot_message(const std::string& progname) const { std::stringstream ret; ret << "starting " << progname << " " << VERSION << " RPC server at " << eth << ":" << port << " with timeout: " << timeout; return ret.str(); }; std::string get_server_identifier(const server_argv& a) { std::stringstream ss; ss << a.eth; ss << "_"; ss << a.port; return ss.str(); } keeper_argv::keeper_argv(int args, char** argv, const std::string& t) : type(t) { google::InitGoogleLogging(argv[0]); google::LogToStderr(); // only when debug cmdline::parser p; p.add<int>("rpc-port", 'p', "port number", false, 9199); p.add<int>("thread", 'c', "concurrency = thread number", false, 16); p.add<int>("timeout", 't', "time out (sec)", false, 10); p.add<std::string>("zookeeper", 'z', "zookeeper location", false, "localhost:2181"); p.add("version", 'v', "version"); p.parse_check(args, argv); if( p.exist("version") ){ print_version(jubatus::util::get_program_name()); exit(0); } port = p.get<int>("rpc-port"); threadnum = p.get<int>("thread"); timeout = p.get<int>("timeout"); z = p.get<std::string>("zookeeper"); eth = jubatus::common::get_default_v4_address(); LOG(INFO) << boot_message(jubatus::util::get_program_name()); }; keeper_argv::keeper_argv(): port(9199), timeout(10), threadnum(16), z("localhost:2181"), eth("") { }; std::string keeper_argv::boot_message(const std::string& progname) const { std::stringstream ret; ret << "starting " << progname << " " << VERSION << " RPC server at " << eth << ":" << port << " with timeout: " << timeout; return ret.str(); }; common::cshared_ptr<jubatus::common::lock_service> ls; void atexit(void){ #ifdef HAVE_ZOOKEEPER_H if(ls) ls->force_close(); #endif } pfi::lang::shared_ptr<fv_converter::datum_to_fv_converter> make_fv_converter(const std::string& config) { if (config == "") throw JUBATUS_EXCEPTION(fv_converter::converter_exception("Config of feature vector converter is empty")); pfi::lang::shared_ptr<fv_converter::datum_to_fv_converter> converter(new fv_converter::datum_to_fv_converter); fv_converter::converter_config c; std::stringstream ss(config); try { ss >> pfi::text::json::via_json(c); } catch (std::bad_cast& e) { std::string msg = std::string("Invalid config format: ") + e.what(); throw JUBATUS_EXCEPTION(fv_converter::converter_exception(msg.c_str())); } fv_converter::initialize_converter(c, *converter); return converter; } } } <|endoftext|>
<commit_before>/* Copyright (c) 2014 Auston Sterling See LICENSE for copying permissions. -----Note Implementation File----- Auston Sterling austonst@gmail.com Contains the implementations for the Note class and other related classes. */ #include "note.hpp" namespace midi { //Default constructor sets the internal note to 0, the lowest MIDI note Note::Note() : number_(0) {} //Takes in a note in format [Note][Octave] (C4, D#2, Bb6) Note::Note(const std::string& notation) { //Extract components and verify size and input int8_t note, mod, octave; int8_t unused = -2; note = notation[0]; if (notation.size() == 2) { octave = notation[1] - '0'; mod = unused; } else if (notation.size() == 3) { //Two cases, _10 or _[#b]_ if (notation[1] == '1') { if (notation[2] != '0') { number_ = 0; return; } else octave = 10; mod = unused; } else if (notation[1] == '#' || notation[1] == 'b') { mod = notation[1]; octave = notation[2] - '0'; } } else if (notation.size() == 4) { if (notation[2] != '1' || notation[3] != '0') { number_ = 0; return; } mod = notation[1]; octave = 10; } else { number_ = 0; return; } //Convert lower case note to upper case if (note > 'Z' || note < 'A') note -= 'a'-'A'; //Lowest note is C, not A if (note < 'C') note += 'H'-'A'; //Make room for the various sharps and flats int8_t newnote = note; if (note > 'C') newnote++; if (note > 'D') newnote++; if (note > 'F') newnote++; if (note > 'G') newnote++; if (note > 'H') newnote++; note = newnote; //Find any modification from sharp or flat if (mod != unused) { switch (mod) { case 'b': if (note != 0) note--; break; case '#': if (note != 127) note++; break; default: break; } } //Verify that the octave is a reasonable number if (octave < 0 || octave > 10) { number_ = 0; return; } //Finally, convert to midi number number_ = (note - 'C') + (12 * octave); } //Takes in a note as a string Note::Note(const char* notation) { std::string str(notation); *this = Note(str); } //Takes in a note as a midi number Note::Note(int8_t innumber) : number_(innumber) {} //Takes in a note as a midi number Note::Note(int innumber) : number_(innumber) {} //Returns the data in format [Note][Octave] std::string Note::val() const { //Return the proper string if (number_/12 < 10) { return MIDI_NOTE[number_%12] + char(((number_/12)) + '0'); } else { return MIDI_NOTE[number_%12] + "10"; } } //Typecast to string Note::operator std::string() const { return val(); } //Returns the note as a midi number int8_t Note::midiVal() const { return number_; } //Typecast to int8_t Note::operator int8_t() const { return midiVal(); } //Note operators bool operator==(const Note& n1, const Note& n2) { return n1.midiVal() == n2.midiVal(); } bool operator!=(const Note& n1, const Note& n2) { return n1.midiVal() != n2.midiVal(); } bool operator==(const Note& n1, const int& n2) { return n1.midiVal() == n2; } bool operator!=(const Note& n1, const int& n2) { return n1.midiVal() != n2; } bool operator==(const int& n1, const Note& n2) { return n1 == n2.midiVal(); } bool operator!=(const int& n1, const Note& n2) { return n1 != n2.midiVal(); } //Default constructor does nothing! Chord::Chord() {}; //Standard constructor allows for up to five initial notes Chord::Chord(const Note n1, const Note n2, const Note n3, const Note n4, const Note n5) { //Just add all five add(n1, n2, n3, n4, n5); } //Adds the given notes. Returns true only if all were added properly bool Chord::add(const Note n1, const Note n2, const Note n3, const Note n4, const Note n5) { bool ret = true; //Always try to insert n1 if (!(note_.insert(n1).second)) ret = false; //Only insert the others if they aren't -1 if (n2 != -1) if (!(note_.insert(n2).second)) ret = false; if (n3 != -1) if (!(note_.insert(n3).second)) ret = false; if (n4 != -1) if (!(note_.insert(n4).second)) ret = false; if (n5 != -1) if (!(note_.insert(n5).second)) ret = false; return ret; } //Removes the given notes bool Chord::remove(const Note n1, const Note n2, const Note n3, const Note n4, const Note n5) { bool ret = true; //Always try to remove n1 if (note_.erase(n1) == 0) ret = false; //Only erase the others if they aren't -1 if (n2 != -1) if (note_.erase(n2) == 0) ret = false; if (n3 != -1) if (note_.erase(n3) == 0) ret = false; if (n4 != -1) if (note_.erase(n4) == 0) ret = false; if (n5 != -1) if (note_.erase(n5) == 0) ret = false; return ret; } //Returns true only if the given note is contained in the chord bool Chord::contains(const Note innote) const { return note_.find(innote) != note_.end(); } //Returns the set for viewing const std::set<Note>& Chord::notes() const { return note_; } } //Namespace <commit_msg>Added handling for incorrect Note notation of length 3.<commit_after>/* Copyright (c) 2014 Auston Sterling See LICENSE for copying permissions. -----Note Implementation File----- Auston Sterling austonst@gmail.com Contains the implementations for the Note class and other related classes. */ #include "note.hpp" namespace midi { //Default constructor sets the internal note to 0, the lowest MIDI note Note::Note() : number_(0) {} //Takes in a note in format [Note][Octave] (C4, D#2, Bb6) Note::Note(const std::string& notation) { //Extract components and verify size and input int8_t note, mod, octave; int8_t unused = -2; note = notation[0]; if (notation.size() == 2) { octave = notation[1] - '0'; mod = unused; } else if (notation.size() == 3) { //Two cases, _10 or _[#b]_ if (notation[1] == '1') { if (notation[2] != '0') { number_ = 0; return; } else octave = 10; mod = unused; } else if (notation[1] == '#' || notation[1] == 'b') { mod = notation[1]; octave = notation[2] - '0'; } else { number_ = 0; return; } } else if (notation.size() == 4) { if (notation[2] != '1' || notation[3] != '0') { number_ = 0; return; } mod = notation[1]; octave = 10; } else { number_ = 0; return; } //Convert lower case note to upper case if (note > 'Z' || note < 'A') note -= 'a'-'A'; //Lowest note is C, not A if (note < 'C') note += 'H'-'A'; //Make room for the various sharps and flats int8_t newnote = note; if (note > 'C') newnote++; if (note > 'D') newnote++; if (note > 'F') newnote++; if (note > 'G') newnote++; if (note > 'H') newnote++; note = newnote; //Find any modification from sharp or flat if (mod != unused) { switch (mod) { case 'b': if (note != 0) note--; break; case '#': if (note != 127) note++; break; default: break; } } //Verify that the octave is a reasonable number if (octave < 0 || octave > 10) { number_ = 0; return; } //Finally, convert to midi number number_ = (note - 'C') + (12 * octave); } //Takes in a note as a string Note::Note(const char* notation) { std::string str(notation); *this = Note(str); } //Takes in a note as a midi number Note::Note(int8_t innumber) : number_(innumber) {} //Takes in a note as a midi number Note::Note(int innumber) : number_(innumber) {} //Returns the data in format [Note][Octave] std::string Note::val() const { //Return the proper string if (number_/12 < 10) { return MIDI_NOTE[number_%12] + char(((number_/12)) + '0'); } else { return MIDI_NOTE[number_%12] + "10"; } } //Typecast to string Note::operator std::string() const { return val(); } //Returns the note as a midi number int8_t Note::midiVal() const { return number_; } //Typecast to int8_t Note::operator int8_t() const { return midiVal(); } //Note operators bool operator==(const Note& n1, const Note& n2) { return n1.midiVal() == n2.midiVal(); } bool operator!=(const Note& n1, const Note& n2) { return n1.midiVal() != n2.midiVal(); } bool operator==(const Note& n1, const int& n2) { return n1.midiVal() == n2; } bool operator!=(const Note& n1, const int& n2) { return n1.midiVal() != n2; } bool operator==(const int& n1, const Note& n2) { return n1 == n2.midiVal(); } bool operator!=(const int& n1, const Note& n2) { return n1 != n2.midiVal(); } //Default constructor does nothing! Chord::Chord() {}; //Standard constructor allows for up to five initial notes Chord::Chord(const Note n1, const Note n2, const Note n3, const Note n4, const Note n5) { //Just add all five add(n1, n2, n3, n4, n5); } //Adds the given notes. Returns true only if all were added properly bool Chord::add(const Note n1, const Note n2, const Note n3, const Note n4, const Note n5) { bool ret = true; //Always try to insert n1 if (!(note_.insert(n1).second)) ret = false; //Only insert the others if they aren't -1 if (n2 != -1) if (!(note_.insert(n2).second)) ret = false; if (n3 != -1) if (!(note_.insert(n3).second)) ret = false; if (n4 != -1) if (!(note_.insert(n4).second)) ret = false; if (n5 != -1) if (!(note_.insert(n5).second)) ret = false; return ret; } //Removes the given notes bool Chord::remove(const Note n1, const Note n2, const Note n3, const Note n4, const Note n5) { bool ret = true; //Always try to remove n1 if (note_.erase(n1) == 0) ret = false; //Only erase the others if they aren't -1 if (n2 != -1) if (note_.erase(n2) == 0) ret = false; if (n3 != -1) if (note_.erase(n3) == 0) ret = false; if (n4 != -1) if (note_.erase(n4) == 0) ret = false; if (n5 != -1) if (note_.erase(n5) == 0) ret = false; return ret; } //Returns true only if the given note is contained in the chord bool Chord::contains(const Note innote) const { return note_.find(innote) != note_.end(); } //Returns the set for viewing const std::set<Note>& Chord::notes() const { return note_; } } //Namespace <|endoftext|>
<commit_before>/* * PartitionCoarsening.cpp * * Created on: 28.01.2014 * Author: cls */ #include "PartitionCoarsening.h" #include <omp.h> #include "../auxiliary/Timer.h" namespace NetworKit { std::pair<Graph, std::vector<node> > NetworKit::PartitionCoarsening::run(const Graph& G, const Clustering& zeta) { Aux::Timer timer; timer.start(); Graph Ginit(0); // initial graph containing supernodes Ginit.markAsWeighted(); // Gcon will be a weighted graph std::vector<node> subsetToSuperNode(zeta.upperBound(), none); // there is one supernode for each cluster // populate map subset -> supernode G.forNodes([&](node v){ cluster c = zeta.clusterOf(v); if (subsetToSuperNode[c] == none) { subsetToSuperNode[c] = Ginit.addNode(); // TODO: probably does not scale well, think about allocating ranges of nodes } }); index z = G.upperNodeIdBound(); std::vector<node> nodeToSuperNode(z); // set entries node -> supernode G.parallelForNodes([&](node v){ nodeToSuperNode[v] = subsetToSuperNode[zeta.clusterOf(v)]; }); // make copies of initial graph count nThreads = omp_get_max_threads(); std::vector<Graph> localGraphs(nThreads, Ginit); // thread-local graphs // iterate over edges of G and create edges in coarse graph or update edge and node weights in Gcon G.parallelForWeightedEdges([&](node u, node v, edgeweight ew) { index t = omp_get_thread_num(); node su = nodeToSuperNode[u]; node sv = nodeToSuperNode[v]; localGraphs.at(t).increaseWeight(su, sv, ew); }); Aux::Timer timer2; timer2.start(); // combine local graphs for (index i = 0; i < (nThreads - 1); ++i) { localGraphs[i].forWeightedEdges([&](node u, node v, edgeweight ew) { localGraphs.at(i+1).increaseWeight(u, v, ew); }); } timer2.stop(); INFO("combining coarse graphs took ", timer.elapsedTag()); timer.stop(); INFO("parallel coarsening took ", timer.elapsedTag()); return std::make_pair(localGraphs.back(), nodeToSuperNode); } } /* namespace NetworKit */ <commit_msg>timer bug fixed<commit_after>/* * PartitionCoarsening.cpp * * Created on: 28.01.2014 * Author: cls */ #include "PartitionCoarsening.h" #include <omp.h> #include "../auxiliary/Timer.h" namespace NetworKit { std::pair<Graph, std::vector<node> > NetworKit::PartitionCoarsening::run(const Graph& G, const Clustering& zeta) { Aux::Timer timer; timer.start(); Graph Ginit(0); // initial graph containing supernodes Ginit.markAsWeighted(); // Gcon will be a weighted graph std::vector<node> subsetToSuperNode(zeta.upperBound(), none); // there is one supernode for each cluster // populate map subset -> supernode G.forNodes([&](node v){ cluster c = zeta.clusterOf(v); if (subsetToSuperNode[c] == none) { subsetToSuperNode[c] = Ginit.addNode(); // TODO: probably does not scale well, think about allocating ranges of nodes } }); index z = G.upperNodeIdBound(); std::vector<node> nodeToSuperNode(z); // set entries node -> supernode G.parallelForNodes([&](node v){ nodeToSuperNode[v] = subsetToSuperNode[zeta.clusterOf(v)]; }); // make copies of initial graph count nThreads = omp_get_max_threads(); std::vector<Graph> localGraphs(nThreads, Ginit); // thread-local graphs // iterate over edges of G and create edges in coarse graph or update edge and node weights in Gcon G.parallelForWeightedEdges([&](node u, node v, edgeweight ew) { index t = omp_get_thread_num(); node su = nodeToSuperNode[u]; node sv = nodeToSuperNode[v]; localGraphs.at(t).increaseWeight(su, sv, ew); }); Aux::Timer timer2; timer2.start(); // combine local graphs for (index i = 0; i < (nThreads - 1); ++i) { localGraphs[i].forWeightedEdges([&](node u, node v, edgeweight ew) { localGraphs.at(i+1).increaseWeight(u, v, ew); }); } timer2.stop(); INFO("combining coarse graphs took ", timer2.elapsedTag()); timer.stop(); INFO("parallel coarsening took ", timer.elapsedTag()); return std::make_pair(localGraphs.back(), nodeToSuperNode); } } /* namespace NetworKit */ <|endoftext|>
<commit_before>#include "extraction.h" using namespace std; vector< vector<string> > vector_coords; int totalatoms = 10; //Extracts Coords from Input and places them into a 2D array int extract_input(const char *inputfile) { ifstream orig_file(inputfile); ofstream log; string line, sub_line; string header1 = "Redundant internal coordinates found in file"; string footer1 = "Recover connectivity data from disk."; int i; int count_line = 0; vector<string> temp_vector; assert(orig_file.good()); log.open("log.txt", ios::app); //Parse for header key phrase while(getline(orig_file, line)) { count_line++; if(line.find(header1, 0) != string::npos) { log << "Found: " << header1 << " at position " << count_line << endl; //If it's found, skip first two lines for(int i = 0; i < 500; i++) { getline(orig_file, line); if(i < 1) continue; //Make sure the string isn't the footer key phrase if (line.find(footer1, 0) == string::npos) { //Place into temporary vector separated by newline temp_vector.clear(); stringstream newstring(line); //Separate data based upon commas while(getline(newstring, sub_line, ',')) { temp_vector.push_back(sub_line); } //Place comma-separated data into final vector vector_coords.push_back(temp_vector); //When footer is found, end process } else { log << "Found: " << footer1 << endl; log << "Search for main coordinates complete." << endl; break; } } } } orig_file.close(); log.close(); return 0; } //Prints vector size and vector contents to console, logfile, and outputfile int print_vector_coords() { ofstream log; ofstream outputfile; log.open("log.txt", ios::app); outputfile.open("outputfile.txt", ios::app); cout << "Model Parameters:" << endl << vector_coords.size() << endl; outputfile << "Model Parameters:" << endl << vector_coords.size() << endl; for(int i = 0; i < vector_coords.size(); i++) { for (int j = 0; j < vector_coords[i].size(); j++) { cout << vector_coords[i][j] << " "; log << vector_coords[i][j] << " "; outputfile << vector_coords[i][j] << " "; } cout << endl; log << endl; outputfile << endl; } log.close(); outputfile.close(); return 0; } <commit_msg>correction to include first row atom<commit_after>#include "extraction.h" using namespace std; vector< vector<string> > vector_coords; int totalatoms = 10; //Extracts Coords from Input and places them into a 2D array int extract_input(const char *inputfile) { ifstream orig_file(inputfile); ofstream log; string line, sub_line; string header1 = "Redundant internal coordinates found in file"; string footer1 = "Recover connectivity data from disk."; int i; int count_line = 0; vector<string> temp_vector; assert(orig_file.good()); log.open("log.txt", ios::app); //Parse for header key phrase while(getline(orig_file, line)) { count_line++; if(line.find(header1, 0) != string::npos) { log << "Found: " << header1 << " at position " << count_line << endl; //If it's found, skip first two lines for(int i = 0; i < 500; i++) { getline(orig_file, line); if(i < 0) continue; //Make sure the string isn't the footer key phrase if (line.find(footer1, 0) == string::npos) { //Place into temporary vector separated by newline temp_vector.clear(); stringstream newstring(line); //Separate data based upon commas while(getline(newstring, sub_line, ',')) { temp_vector.push_back(sub_line); } //Place comma-separated data into final vector vector_coords.push_back(temp_vector); //When footer is found, end process } else { log << "Found: " << footer1 << endl; log << "Search for main coordinates complete." << endl; break; } } } } orig_file.close(); log.close(); return 0; } //Prints vector size and vector contents to console, logfile, and outputfile int print_vector_coords() { ofstream log; ofstream outputfile; log.open("log.txt", ios::app); outputfile.open("outputfile.txt", ios::app); cout << "Model Parameters:" << endl << vector_coords.size() << endl; outputfile << "Model Parameters:" << endl << vector_coords.size() << endl; for(int i = 0; i < vector_coords.size(); i++) { for (int j = 0; j < vector_coords[i].size(); j++) { cout << vector_coords[i][j] << " "; log << vector_coords[i][j] << " "; outputfile << vector_coords[i][j] << " "; } cout << endl; log << endl; outputfile << endl; } log.close(); outputfile.close(); return 0; } <|endoftext|>
<commit_before>#include <sys/socket.h> #include "net/length.h" #include "server.h" #include "utils.h" #include "client_binary.h" // // Xapian binary client // BinaryClient::BinaryClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_) : BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_), RemoteProtocol(std::vector<std::string>(), active_timeout_, idle_timeout_, true), database(NULL) { log(this, "Got connection (%d), %d binary client(s) connected.\n", sock, ++total_clients); try { msg_update(std::string()); } catch (const Xapian::NetworkError &e) { log(this, "ERROR: %s\n", e.get_msg().c_str()); } catch (...) { log(this, "ERROR!\n"); } } BinaryClient::~BinaryClient() { if (database) { database_pool->checkin(&database); } log(this, "Lost connection (%d), %d binary client(s) connected.\n", sock, --total_clients); } void BinaryClient::read_cb(ev::io &watcher) { char buf[1024]; ssize_t received = ::recv(watcher.fd, buf, sizeof(buf), 0); if (received < 0) { perror("read error"); return; } if (received == 0) { // The peer has closed its half side of the connection. log(this, "BROKEN PIPE!\n"); destroy(); } else { buffer.append(buf, received); if (buffer.length() >= 2) { const char *o = buffer.data(); const char *p = o; const char *p_end = p + buffer.size(); message_type type = static_cast<message_type>(*p++); size_t len; try { len = decode_length(&p, p_end, true); } catch (const Xapian::NetworkError & e) { return; } std::string data = std::string(p, len); buffer.erase(0, p - o + len); std::string buf = std::string(o, len + (p - o)); log(this, "<<< '%s'\n", repr_string(buf).c_str()); Buffer *msg = new Buffer(type, data.c_str(), data.size()); messages_queue.push(msg); try { run_one(); } catch (const Xapian::NetworkError &e) { log(this, "ERROR: %s\n", e.get_msg().c_str()); } catch (...) { log(this, "ERROR!\n"); } } } } message_type BinaryClient::get_message(double timeout, std::string & result, message_type required_type) { Buffer* msg; if (!messages_queue.pop(msg)) { throw Xapian::NetworkError("No message available"); } const char *msg_str = msg->dpos(); size_t msg_size = msg->nbytes(); std::string buf(&msg->type, 1); buf += encode_length(msg_size); buf += std::string(msg_str, msg_size); log(this, "get_message: '%s'\n", repr_string(buf).c_str()); result.assign(msg_str, msg_size); delete msg; return static_cast<message_type>(msg->type); } void BinaryClient::send_message(reply_type type, const std::string &message) { char type_as_char = static_cast<char>(type); std::string buf(&type_as_char, 1); buf += encode_length(message.size()); buf += message; log(this, "send_message: '%s'\n", repr_string(buf).c_str()); write(buf); } void BinaryClient::send_message(reply_type type, const std::string &message, double end_time) { send_message(type, message); } Xapian::Database * BinaryClient::get_db(bool writable_) { if (endpoints.empty()) { return NULL; } if (!database_pool->checkout(&database, endpoints, writable_)) { return NULL; } return database->db; } void BinaryClient::release_db(Xapian::Database *db_) { if (database) { database_pool->checkin(&database); } } void BinaryClient::select_db(const std::vector<std::string> &dbpaths_, bool writable_) { std::vector<std::string>::const_iterator i(dbpaths_.begin()); for (; i != dbpaths_.end(); i++) { Endpoint endpoint = Endpoint(*i, std::string(), XAPIAND_BINARY_PORT_DEFAULT); endpoints.push_back(endpoint); } dbpaths = dbpaths_; } <commit_msg>Fixed get_message<commit_after>#include <sys/socket.h> #include "net/length.h" #include "server.h" #include "utils.h" #include "client_binary.h" // // Xapian binary client // BinaryClient::BinaryClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_) : BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_), RemoteProtocol(std::vector<std::string>(), active_timeout_, idle_timeout_, true), database(NULL) { log(this, "Got connection (%d), %d binary client(s) connected.\n", sock, ++total_clients); try { msg_update(std::string()); } catch (const Xapian::NetworkError &e) { log(this, "ERROR: %s\n", e.get_msg().c_str()); } catch (...) { log(this, "ERROR!\n"); } } BinaryClient::~BinaryClient() { if (database) { database_pool->checkin(&database); } log(this, "Lost connection (%d), %d binary client(s) connected.\n", sock, --total_clients); } void BinaryClient::read_cb(ev::io &watcher) { char buf[1024]; ssize_t received = ::recv(watcher.fd, buf, sizeof(buf), 0); if (received < 0) { perror("read error"); return; } if (received == 0) { // The peer has closed its half side of the connection. log(this, "BROKEN PIPE!\n"); destroy(); } else { buffer.append(buf, received); if (buffer.length() >= 2) { const char *o = buffer.data(); const char *p = o; const char *p_end = p + buffer.size(); message_type type = static_cast<message_type>(*p++); size_t len; try { len = decode_length(&p, p_end, true); } catch (const Xapian::NetworkError & e) { return; } std::string data = std::string(p, len); buffer.erase(0, p - o + len); std::string buf = std::string(o, len + (p - o)); log(this, "<<< '%s'\n", repr_string(buf).c_str()); Buffer *msg = new Buffer(type, data.c_str(), data.size()); messages_queue.push(msg); try { run_one(); } catch (const Xapian::NetworkError &e) { log(this, "ERROR: %s\n", e.get_msg().c_str()); } catch (...) { log(this, "ERROR!\n"); } } } } message_type BinaryClient::get_message(double timeout, std::string & result, message_type required_type) { Buffer* msg; if (!messages_queue.pop(msg)) { throw Xapian::NetworkError("No message available"); } const char *msg_str = msg->dpos(); size_t msg_size = msg->nbytes(); std::string message = std::string(msg_str, msg_size); std::string buf(&msg->type, 1); buf += encode_length(msg_size); buf += message; log(this, "get_message: '%s'\n", repr_string(buf).c_str()); result = message; message_type type = static_cast<message_type>(msg->type); delete msg; return type; } void BinaryClient::send_message(reply_type type, const std::string &message) { char type_as_char = static_cast<char>(type); std::string buf(&type_as_char, 1); buf += encode_length(message.size()); buf += message; log(this, "send_message: '%s'\n", repr_string(buf).c_str()); write(buf); } void BinaryClient::send_message(reply_type type, const std::string &message, double end_time) { send_message(type, message); } Xapian::Database * BinaryClient::get_db(bool writable_) { if (endpoints.empty()) { return NULL; } if (!database_pool->checkout(&database, endpoints, writable_)) { return NULL; } return database->db; } void BinaryClient::release_db(Xapian::Database *db_) { if (database) { database_pool->checkin(&database); } } void BinaryClient::select_db(const std::vector<std::string> &dbpaths_, bool writable_) { std::vector<std::string>::const_iterator i(dbpaths_.begin()); for (; i != dbpaths_.end(); i++) { Endpoint endpoint = Endpoint(*i, std::string(), XAPIAND_BINARY_PORT_DEFAULT); endpoints.push_back(endpoint); } dbpaths = dbpaths_; } <|endoftext|>
<commit_before>// // // MIT License // // Copyright (c) 2017 Stellacore Corporation. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject // to the following conditions: // // The above copyright notice and this permission notice 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. // // // ==== // ==== Not thread safe (at least global variables are not) // ==== #include <mutex> namespace stb { std::mutex gStbMutex(); } // ==== // ==== Read capabilities // ==== // activate all definitions #define STB_IMAGE_IMPLEMENTATION // enable specific capabilities #define STBI_ONLY_JPEG #define STBI_ONLY_PNG // #define STBI_ONLY_BMP // #define STBI_ONLY_PSD // #define STBI_ONLY_TGA // #define STBI_ONLY_GIF // #define STBI_ONLY_HDR // #define STBI_ONLY_PIC // #define STBI_ONLY_PNM // (.ppm and .pgm) // include source code inlcuding (conditional) definitions #include "stb_image.h" // ==== // ==== Write capabilities // ==== // activate all definitions #define STB_IMAGE_WRITE_IMPLEMENTATION // disable use of stdio.h /* You can define STBI_WRITE_NO_STDIO to disable the file variant of these functions, so the library will not use stdio.h at all. However, this will also disable HDR writing, because it requires stdio for formatted output. */ // #define STBI_WRITE_NO_STDIO // NOTE! bug in #defs, still uses sprintf (HDR) // include source code with (now)activated definitions #include "stb_image_write.h" <commit_msg>extstb/stb.cpp added pragma for GCC to disable warning of unused arg/functions<commit_after>// // // MIT License // // Copyright (c) 2017 Stellacore Corporation. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject // to the following conditions: // // The above copyright notice and this permission notice 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. // // // ==== // ==== Not thread safe (at least global variables are not) // ==== #include <mutex> namespace stb { std::mutex gStbMutex(); } // ==== // ==== Read capabilities // ==== // activate all definitions #define STB_IMAGE_IMPLEMENTATION // enable specific capabilities #define STBI_ONLY_JPEG #define STBI_ONLY_PNG // #define STBI_ONLY_BMP // #define STBI_ONLY_PSD // #define STBI_ONLY_TGA // #define STBI_ONLY_GIF // #define STBI_ONLY_HDR // #define STBI_ONLY_PIC // #define STBI_ONLY_PNM // (.ppm and .pgm) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-function" // include source code inlcuding (conditional) definitions #include "stb_image.h" #pragma GCC diagnostic pop // ==== // ==== Write capabilities // ==== // activate all definitions #define STB_IMAGE_WRITE_IMPLEMENTATION // disable use of stdio.h /* You can define STBI_WRITE_NO_STDIO to disable the file variant of these functions, so the library will not use stdio.h at all. However, this will also disable HDR writing, because it requires stdio for formatted output. */ // #define STBI_WRITE_NO_STDIO // NOTE! bug in #defs, still uses sprintf (HDR) // include source code with (now)activated definitions #include "stb_image_write.h" <|endoftext|>
<commit_before>#include <sys/socket.h> #include "net/length.h" #include "server.h" #include "utils.h" #include "client_binary.h" // // Xapian binary client // BinaryClient::BinaryClient(ev::loop_ref &loop, int sock_, ThreadPool *thread_pool_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_) : BaseClient(loop, sock_, thread_pool_, database_pool_, active_timeout_, idle_timeout_), RemoteProtocol(std::vector<std::string>(), active_timeout_, idle_timeout_, true), database(NULL) { log("Got connection, %d binary client(s) connected.\n", ++total_clients); try { msg_update(std::string()); } catch (const Xapian::NetworkError &e) { log("ERROR: %s\n", e.get_msg().c_str()); } catch (...) { log("ERROR!\n"); } } BinaryClient::~BinaryClient() { log("Lost connection, %d binary client(s) connected.\n", --total_clients); } void BinaryClient::read_cb(ev::io &watcher) { char buf[1024]; ssize_t received = recv(watcher.fd, buf, sizeof(buf), 0); if (received < 0) { perror("read error"); return; } if (received == 0) { // The peer has closed its half side of the connection. log("BROKEN PIPE!\n"); destroy(); } else { buffer.append(buf, received); if (buffer.length() >= 2) { const char *o = buffer.data(); const char *p = o; const char *p_end = p + buffer.size(); message_type type = static_cast<message_type>(*p++); size_t len; try { len = decode_length(&p, p_end, true); } catch (const Xapian::NetworkError & e) { return; } std::string data = std::string(p, len); buffer.erase(0, p - o + len); // log("<<< "); // fprint_string(stderr, data); Buffer *msg = new Buffer(type, data.c_str(), data.size()); messages_queue.push(msg); try { run_one(); } catch (const Xapian::NetworkError &e) { log("ERROR: %s\n", e.get_msg().c_str()); } catch (...) { log("ERROR!\n"); } } } } message_type BinaryClient::get_message(double timeout, std::string & result, message_type required_type) { Buffer* msg; if (!messages_queue.pop(msg)) { throw Xapian::NetworkError("No message available"); } std::string buf(&msg->type, 1); buf += encode_length(msg->nbytes()); buf += std::string(msg->dpos(), msg->nbytes()); log("get_message: "); fprint_string(stderr, buf); message_type type = static_cast<message_type>(msg->type); result.assign(msg->dpos(), msg->nbytes()); delete msg; return type; } void BinaryClient::send_message(reply_type type, const std::string &message) { char type_as_char = static_cast<char>(type); std::string buf(&type_as_char, 1); buf += encode_length(message.size()); buf += message; log("send_message: "); fprint_string(stderr, buf); write(buf); } void BinaryClient::send_message(reply_type type, const std::string &message, double end_time) { send_message(type, message); } Xapian::Database * BinaryClient::get_db(bool writable_) { if (endpoints.empty()) { return NULL; } if (!database_pool->checkout(&database, endpoints, writable_)) { return NULL; } return database->db; } void BinaryClient::release_db(Xapian::Database *db_) { if (database) { database_pool->checkin(&database); } } void BinaryClient::select_db(const std::vector<std::string> &dbpaths_, bool writable_) { std::vector<std::string>::const_iterator i(dbpaths_.begin()); for (; i != dbpaths_.end(); i++) { Endpoint endpoint = Endpoint(*i, std::string(), XAPIAND_BINARY_PORT_DEFAULT); endpoints.push_back(endpoint); } dbpaths = dbpaths_; } <commit_msg>During delete, release database if there's any<commit_after>#include <sys/socket.h> #include "net/length.h" #include "server.h" #include "utils.h" #include "client_binary.h" // // Xapian binary client // BinaryClient::BinaryClient(ev::loop_ref &loop, int sock_, ThreadPool *thread_pool_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_) : BaseClient(loop, sock_, thread_pool_, database_pool_, active_timeout_, idle_timeout_), RemoteProtocol(std::vector<std::string>(), active_timeout_, idle_timeout_, true), database(NULL) { log("Got connection, %d binary client(s) connected.\n", ++total_clients); try { msg_update(std::string()); } catch (const Xapian::NetworkError &e) { log("ERROR: %s\n", e.get_msg().c_str()); } catch (...) { log("ERROR!\n"); } } BinaryClient::~BinaryClient() { if (database) { database_pool->checkin(&database); } log("Lost connection, %d binary client(s) connected.\n", --total_clients); } void BinaryClient::read_cb(ev::io &watcher) { char buf[1024]; ssize_t received = recv(watcher.fd, buf, sizeof(buf), 0); if (received < 0) { perror("read error"); return; } if (received == 0) { // The peer has closed its half side of the connection. log("BROKEN PIPE!\n"); destroy(); } else { buffer.append(buf, received); if (buffer.length() >= 2) { const char *o = buffer.data(); const char *p = o; const char *p_end = p + buffer.size(); message_type type = static_cast<message_type>(*p++); size_t len; try { len = decode_length(&p, p_end, true); } catch (const Xapian::NetworkError & e) { return; } std::string data = std::string(p, len); buffer.erase(0, p - o + len); // log("<<< "); // fprint_string(stderr, data); Buffer *msg = new Buffer(type, data.c_str(), data.size()); messages_queue.push(msg); try { run_one(); } catch (const Xapian::NetworkError &e) { log("ERROR: %s\n", e.get_msg().c_str()); } catch (...) { log("ERROR!\n"); } } } } message_type BinaryClient::get_message(double timeout, std::string & result, message_type required_type) { Buffer* msg; if (!messages_queue.pop(msg)) { throw Xapian::NetworkError("No message available"); } std::string buf(&msg->type, 1); buf += encode_length(msg->nbytes()); buf += std::string(msg->dpos(), msg->nbytes()); log("get_message: "); fprint_string(stderr, buf); message_type type = static_cast<message_type>(msg->type); result.assign(msg->dpos(), msg->nbytes()); delete msg; return type; } void BinaryClient::send_message(reply_type type, const std::string &message) { char type_as_char = static_cast<char>(type); std::string buf(&type_as_char, 1); buf += encode_length(message.size()); buf += message; log("send_message: "); fprint_string(stderr, buf); write(buf); } void BinaryClient::send_message(reply_type type, const std::string &message, double end_time) { send_message(type, message); } Xapian::Database * BinaryClient::get_db(bool writable_) { if (endpoints.empty()) { return NULL; } if (!database_pool->checkout(&database, endpoints, writable_)) { return NULL; } return database->db; } void BinaryClient::release_db(Xapian::Database *db_) { if (database) { database_pool->checkin(&database); } } void BinaryClient::select_db(const std::vector<std::string> &dbpaths_, bool writable_) { std::vector<std::string>::const_iterator i(dbpaths_.begin()); for (; i != dbpaths_.end(); i++) { Endpoint endpoint = Endpoint(*i, std::string(), XAPIAND_BINARY_PORT_DEFAULT); endpoints.push_back(endpoint); } dbpaths = dbpaths_; } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-mdb/MDB.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "FeatureIndexWriter.h" #include "IndexRequest.h" #include "IndexWriter.h" using namespace cm; using namespace fnord; std::atomic<bool> cm_indexbuild_shutdown; /* stats */ void quit(int n) { cm_indexbuild_shutdown = true; } void buildIndexFromFeed( RefPtr<IndexWriter> index_writer, const cli::FlagParser& flags) { size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t db_commit_size = flags.getInt("db_commit_size"); size_t db_commit_interval = flags.getInt("db_commit_interval"); /* start event loop */ fnord::thread::EventLoop ev; auto evloop_thread = std::thread([&ev] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(3600 * 24 * 30 * kMicrosPerSecond); HashMap<String, URI> input_feeds; auto cmcustomer = "dawanda"; input_feeds.emplace( StringUtil::format( "$0.index_requests.feedserver01.nue01.production.fnrd.net", cmcustomer), URI("http://s01.nue01.production.fnrd.net:7001/rpc")); input_feeds.emplace( StringUtil::format( "$0.index_requests.feedserver02.nue01.production.fnrd.net", cmcustomer), URI("http://s02.nue01.production.fnrd.net:7001/rpc")); /* resume from last offset */ auto txn = index_writer->featureDB()->startTransaction(true); try { for (const auto& input_feed : input_feeds) { uint64_t offset = 0; auto last_offset = txn->get( StringUtil::format("__indexfeed_offset~$0", input_feed.first)); if (!last_offset.isEmpty()) { offset = std::stoul(last_offset.get().toString()); } fnord::logInfo( "cm.indexbuild", "Adding source feed:\n feed=$0\n url=$1\n offset: $2", input_feed.first, input_feed.second.toString(), offset); feed_reader.addSourceFeed( input_feed.second, input_feed.first, offset, batch_size, buffer_size); } txn->abort(); } catch (...) { txn->abort(); throw; } fnord::logInfo("cm.indexbuild", "Resuming IndexWriter..."); DateTime last_iter; uint64_t rate_limit_micros = db_commit_interval * kMicrosPerSecond; for (;;) { last_iter = WallClock::now(); feed_reader.fillBuffers(); int i = 0; for (; i < db_commit_size; ++i) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } cm::IndexRequest index_req; const auto& entry_str = entry.get().data; try { index_req = json::fromJSON<cm::IndexRequest>(entry_str); } catch (const std::exception& e) { fnord::logError("cm.indexbuild", e, "invalid json: $0", entry_str); continue; } fnord::logTrace("cm.indexbuild", "Indexing: $0", entry.get().data); index_writer->updateDocument(index_req); } auto stream_offsets = feed_reader.streamOffsets(); String stream_offsets_str; index_writer->commit(); auto txn = index_writer->featureDB()->startTransaction(); for (const auto& soff : stream_offsets) { txn->update( StringUtil::format("__indexfeed_offset~$0", soff.first), StringUtil::toString(soff.second)); stream_offsets_str += StringUtil::format("\n offset[$0]=$1", soff.first, soff.second); } fnord::logInfo( "cm.indexbuild", "IndexWriter comitting...$0", stream_offsets_str); txn->commit(); if (cm_indexbuild_shutdown.load() == true) { break; } auto etime = WallClock::now().unixMicros() - last_iter.unixMicros(); if (i < 1 && etime < rate_limit_micros) { usleep(rate_limit_micros - etime); } } ev.shutdown(); evloop_thread.join(); } int main(int argc, const char** argv) { Application::init(); Application::logToStderr(); /* shutdown hook */ cm_indexbuild_shutdown = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); cli::FlagParser flags; flags.defineFlag( "index", cli::FlagParser::T_STRING, true, NULL, NULL, "index dir", "<path>"); flags.defineFlag( "conf", cli::FlagParser::T_STRING, false, NULL, "./conf", "conf dir", "<path>"); flags.defineFlag( "statsd_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "127.0.0.1:8192", "Statsd addr", "<addr>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "db_commit_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "1024", "db_commit_size", "<num>"); flags.defineFlag( "db_commit_interval", fnord::cli::FlagParser::T_INTEGER, false, NULL, "5", "db_commit_interval", "<num>"); flags.defineFlag( "dbsize", fnord::cli::FlagParser::T_INTEGER, false, NULL, "128", "max sessiondb size", "<MB>"); flags.defineFlag( "rebuild_fts", fnord::cli::FlagParser::T_STRING, false, NULL, "all", "rebuild fts index", ""); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* start stats reporting */ fnord::stats::StatsdAgent statsd_agent( fnord::net::InetAddr::resolve(flags.getString("statsd_addr")), 10 * fnord::kMicrosPerSecond); statsd_agent.start(); /* open index */ fnord::logInfo( "cm.indexbuild", "Opening index at $0", flags.getString("index")); auto index_writer = cm::IndexWriter::openIndex( flags.getString("index"), flags.getString("conf")); index_writer->exportStats("/cm-indexbuild/global"); if (flags.isSet("rebuild_fts")) { auto docid = flags.getString("rebuild_fts"); if (docid == "all") { index_writer->rebuildFTS(); } else { index_writer->rebuildFTS(cm::DocID { .docid = docid }); } } else { buildIndexFromFeed(index_writer, flags); } index_writer->commit(); fnord::logInfo("cm.indexbuild", "Exiting..."); return 0; } /* open lucene index */ /* auto index_path = FileUtil::joinPaths( cmdata_path, StringUtil::format("index/$0/fts", cmcustomer)); FileUtil::mkdir_p(index_path); */ // index document /* */ //index_writer->commit(); //index_writer->close(); // simple search /* auto index_reader = fts::IndexReader::open( fts::FSDirectory::open(StringUtil::convertUTF8To16(index_path)), true); auto searcher = fts::newLucene<fts::IndexSearcher>(index_reader); auto analyzer = fts::newLucene<fts::StandardAnalyzer>( fts::LuceneVersion::LUCENE_CURRENT); auto query_parser = fts::newLucene<fts::QueryParser>( fts::LuceneVersion::LUCENE_CURRENT, L"keywords", analyzer); auto collector = fts::TopScoreDocCollector::create( 500, false); auto query = query_parser->parse(L"fnordy"); searcher->search(query, collector); fnord::iputs("found $0 documents", collector->getTotalHits()); */ <commit_msg>cm-indexbuild flag fix<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-mdb/MDB.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "FeatureIndexWriter.h" #include "IndexRequest.h" #include "IndexWriter.h" using namespace cm; using namespace fnord; std::atomic<bool> cm_indexbuild_shutdown; /* stats */ void quit(int n) { cm_indexbuild_shutdown = true; } void buildIndexFromFeed( RefPtr<IndexWriter> index_writer, const cli::FlagParser& flags) { size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t db_commit_size = flags.getInt("db_commit_size"); size_t db_commit_interval = flags.getInt("db_commit_interval"); /* start event loop */ fnord::thread::EventLoop ev; auto evloop_thread = std::thread([&ev] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(3600 * 24 * 30 * kMicrosPerSecond); HashMap<String, URI> input_feeds; auto cmcustomer = "dawanda"; input_feeds.emplace( StringUtil::format( "$0.index_requests.feedserver01.nue01.production.fnrd.net", cmcustomer), URI("http://s01.nue01.production.fnrd.net:7001/rpc")); input_feeds.emplace( StringUtil::format( "$0.index_requests.feedserver02.nue01.production.fnrd.net", cmcustomer), URI("http://s02.nue01.production.fnrd.net:7001/rpc")); /* resume from last offset */ auto txn = index_writer->featureDB()->startTransaction(true); try { for (const auto& input_feed : input_feeds) { uint64_t offset = 0; auto last_offset = txn->get( StringUtil::format("__indexfeed_offset~$0", input_feed.first)); if (!last_offset.isEmpty()) { offset = std::stoul(last_offset.get().toString()); } fnord::logInfo( "cm.indexbuild", "Adding source feed:\n feed=$0\n url=$1\n offset: $2", input_feed.first, input_feed.second.toString(), offset); feed_reader.addSourceFeed( input_feed.second, input_feed.first, offset, batch_size, buffer_size); } txn->abort(); } catch (...) { txn->abort(); throw; } fnord::logInfo("cm.indexbuild", "Resuming IndexWriter..."); DateTime last_iter; uint64_t rate_limit_micros = db_commit_interval * kMicrosPerSecond; for (;;) { last_iter = WallClock::now(); feed_reader.fillBuffers(); int i = 0; for (; i < db_commit_size; ++i) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } cm::IndexRequest index_req; const auto& entry_str = entry.get().data; try { index_req = json::fromJSON<cm::IndexRequest>(entry_str); } catch (const std::exception& e) { fnord::logError("cm.indexbuild", e, "invalid json: $0", entry_str); continue; } fnord::logTrace("cm.indexbuild", "Indexing: $0", entry.get().data); index_writer->updateDocument(index_req); } auto stream_offsets = feed_reader.streamOffsets(); String stream_offsets_str; index_writer->commit(); auto txn = index_writer->featureDB()->startTransaction(); for (const auto& soff : stream_offsets) { txn->update( StringUtil::format("__indexfeed_offset~$0", soff.first), StringUtil::toString(soff.second)); stream_offsets_str += StringUtil::format("\n offset[$0]=$1", soff.first, soff.second); } fnord::logInfo( "cm.indexbuild", "IndexWriter comitting...$0", stream_offsets_str); txn->commit(); if (cm_indexbuild_shutdown.load() == true) { break; } auto etime = WallClock::now().unixMicros() - last_iter.unixMicros(); if (i < 1 && etime < rate_limit_micros) { usleep(rate_limit_micros - etime); } } ev.shutdown(); evloop_thread.join(); } int main(int argc, const char** argv) { Application::init(); Application::logToStderr(); /* shutdown hook */ cm_indexbuild_shutdown = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); cli::FlagParser flags; flags.defineFlag( "index", cli::FlagParser::T_STRING, true, NULL, NULL, "index dir", "<path>"); flags.defineFlag( "conf", cli::FlagParser::T_STRING, false, NULL, "./conf", "conf dir", "<path>"); flags.defineFlag( "statsd_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "127.0.0.1:8192", "Statsd addr", "<addr>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "db_commit_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "1024", "db_commit_size", "<num>"); flags.defineFlag( "db_commit_interval", fnord::cli::FlagParser::T_INTEGER, false, NULL, "5", "db_commit_interval", "<num>"); flags.defineFlag( "dbsize", fnord::cli::FlagParser::T_INTEGER, false, NULL, "128", "max sessiondb size", "<MB>"); flags.defineFlag( "rebuild_fts", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "rebuild fts index", ""); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* start stats reporting */ fnord::stats::StatsdAgent statsd_agent( fnord::net::InetAddr::resolve(flags.getString("statsd_addr")), 10 * fnord::kMicrosPerSecond); statsd_agent.start(); /* open index */ fnord::logInfo( "cm.indexbuild", "Opening index at $0", flags.getString("index")); auto index_writer = cm::IndexWriter::openIndex( flags.getString("index"), flags.getString("conf")); index_writer->exportStats("/cm-indexbuild/global"); if (flags.isSet("rebuild_fts")) { auto docid = flags.getString("docid"); if (docid == "all") { index_writer->rebuildFTS(); } else { index_writer->rebuildFTS(cm::DocID { .docid = docid }); } } else { buildIndexFromFeed(index_writer, flags); } index_writer->commit(); fnord::logInfo("cm.indexbuild", "Exiting..."); return 0; } /* open lucene index */ /* auto index_path = FileUtil::joinPaths( cmdata_path, StringUtil::format("index/$0/fts", cmcustomer)); FileUtil::mkdir_p(index_path); */ // index document /* */ //index_writer->commit(); //index_writer->close(); // simple search /* auto index_reader = fts::IndexReader::open( fts::FSDirectory::open(StringUtil::convertUTF8To16(index_path)), true); auto searcher = fts::newLucene<fts::IndexSearcher>(index_reader); auto analyzer = fts::newLucene<fts::StandardAnalyzer>( fts::LuceneVersion::LUCENE_CURRENT); auto query_parser = fts::newLucene<fts::QueryParser>( fts::LuceneVersion::LUCENE_CURRENT, L"keywords", analyzer); auto collector = fts::TopScoreDocCollector::create( 500, false); auto query = query_parser->parse(L"fnordy"); searcher->search(query, collector); fnord::iputs("found $0 documents", collector->getTotalHits()); */ <|endoftext|>
<commit_before>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: wangtaize@baidu.com #include "agent/cgroup.h" #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include "common/logging.h" #include "common/util.h" #include "common/this_thread.h" #include "agent/downloader_manager.h" #include "agent/resource_collector.h" #include "agent/resource_collector_engine.h" namespace galaxy { static int CPU_CFS_PERIOD = 100000; static int MIN_CPU_CFS_QUOTA = 1000; int CGroupCtrl::Create(int64_t task_id, std::map<std::string, std::string>& sub_sys_map) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; int status = mkdir(ss.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (status != 0) { if (errno == EEXIST) { // TODO LOG(WARNING, "cgroup already there"); } else { LOG(FATAL, "fail to create subsystem %s ,status is %d", ss.str().c_str(), status); return status; } } sub_sys_map[*it] = ss.str(); LOG(INFO, "create subsystem %s successfully", ss.str().c_str()); } return 0; } //目前不支持递归删除 //删除前应该清空tasks文件 int CGroupCtrl::Destroy(int64_t task_id) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; int status = rmdir(ss.str().c_str()); if(status != 0 ){ LOG(FATAL,"fail to delete subsystem %s status %d",ss.str().c_str(),status); return status; } } return 0; } int AbstractCtrl::AttachTask(pid_t pid) { std::string task_file = _my_cg_root + "/" + "tasks"; int ret = common::util::WriteIntToFile(task_file, pid); if (ret < 0) { LOG(FATAL, "fail to attach pid %d for %s", pid, _my_cg_root.c_str()); return -1; }else{ LOG(INFO,"attach pid %d for %s successfully",pid, _my_cg_root.c_str()); } return 0; } int MemoryCtrl::SetLimit(int64_t limit) { std::string limit_file = _my_cg_root + "/" + "memory.limit_in_bytes"; int ret = common::util::WriteIntToFile(limit_file, limit); if (ret < 0) { LOG(FATAL, "fail to set limt %lld for %s", limit, _my_cg_root.c_str()); return -1; } return 0; } int MemoryCtrl::SetSoftLimit(int64_t soft_limit) { std::string soft_limit_file = _my_cg_root + "/" + "memory.soft_limit_in_bytes"; int ret = common::util::WriteIntToFile(soft_limit_file, soft_limit); if (ret < 0) { LOG(FATAL, "fail to set soft limt %lld for %s", soft_limit, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuShare(int64_t cpu_share) { std::string cpu_share_file = _my_cg_root + "/" + "cpu.shares"; int ret = common::util::WriteIntToFile(cpu_share_file, cpu_share); if (ret < 0) { LOG(FATAL, "fail to set cpu share %lld for %s", cpu_share, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuPeriod(int64_t cpu_period) { std::string cpu_period_file = _my_cg_root + "/" + "cpu.cfs_period_us"; int ret = common::util::WriteIntToFile(cpu_period_file, cpu_period); if (ret < 0) { LOG(FATAL, "fail to set cpu period %lld for %s", cpu_period, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuQuota(int64_t cpu_quota) { std::string cpu_quota_file = _my_cg_root + "/" + "cpu.cfs_quota_us"; int ret = common::util::WriteIntToFile(cpu_quota_file, cpu_quota); if (ret < 0) { LOG(FATAL, "fail to set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return -1; } LOG(INFO, "set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return 0; } ContainerTaskRunner::~ContainerTaskRunner() { if (collector_ != NULL) { ResourceCollectorEngine* engine = GetResourceCollectorEngine(); engine->DelCollector(collector_id_); delete collector_; collector_ = NULL; } delete _cg_ctrl; delete _mem_ctrl; delete _cpu_ctrl; delete _cpu_acct_ctrl; } int ContainerTaskRunner::Prepare() { LOG(INFO, "prepare container for task %d", m_task_info.task_id()); //TODO std::vector<std::string> support_cg; support_cg.push_back("memory"); support_cg.push_back("cpu"); support_cg.push_back("cpuacct"); _cg_ctrl = new CGroupCtrl(_cg_root, support_cg); std::map<std::string, std::string> sub_sys_map; int status = _cg_ctrl->Create(m_task_info.task_id(), sub_sys_map); // NOTE multi thread safe if (collector_ == NULL) { std::string group_path = boost::lexical_cast<std::string>(m_task_info.task_id()); collector_ = new CGroupResourceCollector(group_path); ResourceCollectorEngine* engine = GetResourceCollectorEngine(); collector_id_ = engine->AddCollector(collector_); } else { collector_->ResetCgroupName( boost::lexical_cast<std::string>(m_task_info.task_id())); } if (status != 0) { LOG(FATAL, "fail to create subsystem for task %d,status %d", m_task_info.task_id(), status); return status; } _mem_ctrl = new MemoryCtrl(sub_sys_map["memory"]); _cpu_ctrl = new CpuCtrl(sub_sys_map["cpu"]); _cpu_acct_ctrl = new CpuAcctCtrl(sub_sys_map["cpuacct"]); std::string uri = m_task_info.task_raw(); std::string path = m_workspace->GetPath(); path.append("/"); path.append("tmp.tar.gz"); DownloaderManager* downloader_handler = DownloaderManager::GetInstance(); downloader_handler->DownloadInThread( uri, path, boost::bind(&ContainerTaskRunner::StartAfterDownload, this, _1)); return 0; } void ContainerTaskRunner::StartAfterDownload(int ret) { if (ret == 0) { std::string tar_cmd = "cd " + m_workspace->GetPath() + " && tar -xzf tmp.tar.gz"; int status = system(tar_cmd.c_str()); if (status != 0) { LOG(WARNING, "tar -xf failed"); return; } Start(); } } void ContainerTaskRunner::PutToCGroup(){ int64_t mem_size = m_task_info.required_mem(); double cpu_core = m_task_info.required_cpu(); LOG(INFO, "resource limit cpu %f, mem %ld", cpu_core, mem_size); /* std::string mem_key = "memory"; std::string cpu_key = "cpu"; for (int i = 0; i< m_task_info.resource_list_size(); i++){ ResourceItem item = m_task_info.resource_list(i); if(mem_key.compare(item.name())==0 && item.value() > 0){ mem_size = item.value(); continue; } if(cpu_key.compare(item.name())==0 && item.value() >0){ cpu_share = item.value() * 512; } }*/ _mem_ctrl->SetLimit(mem_size); //_cpu_ctrl->SetCpuShare(cpu_share); int64_t quota = static_cast<int64_t>(cpu_core * CPU_CFS_PERIOD); if (quota < MIN_CPU_CFS_QUOTA) { quota = MIN_CPU_CFS_QUOTA; } _cpu_ctrl->SetCpuQuota(quota); pid_t my_pid = getpid(); _mem_ctrl->AttachTask(my_pid); _cpu_ctrl->AttachTask(my_pid); _cpu_acct_ctrl->AttachTask(my_pid); } int ContainerTaskRunner::Start() { LOG(INFO, "start a task with id %d", m_task_info.task_id()); if (IsRunning() == 0) { LOG(WARNING, "task with id %d has been runing", m_task_info.task_id()); return -1; } int stdout_fd, stderr_fd; std::vector<int> fds; PrepareStart(fds, &stdout_fd, &stderr_fd); m_child_pid = fork(); if (m_child_pid == 0) { PutToCGroup(); StartTaskAfterFork(fds, stdout_fd, stderr_fd); } else { close(stdout_fd); close(stderr_fd); m_group_pid = m_child_pid; } return 0; } void ContainerTaskRunner::Status(TaskStatus* status) { if (collector_ != NULL) { status->set_cpu_usage(collector_->GetCpuUsage()); status->set_memory_usage(collector_->GetMemoryUsage()); LOG(WARNING, "cpu usage %f memory usage %ld", status->cpu_usage(), status->memory_usage()); } return; } void ContainerTaskRunner::StopPost() { if (collector_ != NULL) { collector_->Clear(); } return; } int ContainerTaskRunner::Stop(){ int status = AbstractTaskRunner::Stop(); LOG(INFO,"stop task %d with status %d",m_task_info.task_id(),status); if(status != 0 ){ return status; } //sleep 500 ms for cgroup clear tasks common::ThisThread::Sleep(500); StopPost(); status = _cg_ctrl->Destroy(m_task_info.task_id()); LOG(INFO,"destroy cgroup for task %d with status %d",m_task_info.task_id(),status); return status; } } <commit_msg>d -> ld<commit_after>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: wangtaize@baidu.com #include "agent/cgroup.h" #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include "common/logging.h" #include "common/util.h" #include "common/this_thread.h" #include "agent/downloader_manager.h" #include "agent/resource_collector.h" #include "agent/resource_collector_engine.h" namespace galaxy { static int CPU_CFS_PERIOD = 100000; static int MIN_CPU_CFS_QUOTA = 1000; int CGroupCtrl::Create(int64_t task_id, std::map<std::string, std::string>& sub_sys_map) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; int status = mkdir(ss.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (status != 0) { if (errno == EEXIST) { // TODO LOG(WARNING, "cgroup already there"); } else { LOG(FATAL, "fail to create subsystem %s ,status is %d", ss.str().c_str(), status); return status; } } sub_sys_map[*it] = ss.str(); LOG(INFO, "create subsystem %s successfully", ss.str().c_str()); } return 0; } //目前不支持递归删除 //删除前应该清空tasks文件 int CGroupCtrl::Destroy(int64_t task_id) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; int status = rmdir(ss.str().c_str()); if(status != 0 ){ LOG(FATAL,"fail to delete subsystem %s status %d",ss.str().c_str(),status); return status; } } return 0; } int AbstractCtrl::AttachTask(pid_t pid) { std::string task_file = _my_cg_root + "/" + "tasks"; int ret = common::util::WriteIntToFile(task_file, pid); if (ret < 0) { LOG(FATAL, "fail to attach pid %d for %s", pid, _my_cg_root.c_str()); return -1; }else{ LOG(INFO,"attach pid %d for %s successfully",pid, _my_cg_root.c_str()); } return 0; } int MemoryCtrl::SetLimit(int64_t limit) { std::string limit_file = _my_cg_root + "/" + "memory.limit_in_bytes"; int ret = common::util::WriteIntToFile(limit_file, limit); if (ret < 0) { LOG(FATAL, "fail to set limt %lld for %s", limit, _my_cg_root.c_str()); return -1; } return 0; } int MemoryCtrl::SetSoftLimit(int64_t soft_limit) { std::string soft_limit_file = _my_cg_root + "/" + "memory.soft_limit_in_bytes"; int ret = common::util::WriteIntToFile(soft_limit_file, soft_limit); if (ret < 0) { LOG(FATAL, "fail to set soft limt %lld for %s", soft_limit, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuShare(int64_t cpu_share) { std::string cpu_share_file = _my_cg_root + "/" + "cpu.shares"; int ret = common::util::WriteIntToFile(cpu_share_file, cpu_share); if (ret < 0) { LOG(FATAL, "fail to set cpu share %lld for %s", cpu_share, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuPeriod(int64_t cpu_period) { std::string cpu_period_file = _my_cg_root + "/" + "cpu.cfs_period_us"; int ret = common::util::WriteIntToFile(cpu_period_file, cpu_period); if (ret < 0) { LOG(FATAL, "fail to set cpu period %lld for %s", cpu_period, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuQuota(int64_t cpu_quota) { std::string cpu_quota_file = _my_cg_root + "/" + "cpu.cfs_quota_us"; int ret = common::util::WriteIntToFile(cpu_quota_file, cpu_quota); if (ret < 0) { LOG(FATAL, "fail to set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return -1; } LOG(INFO, "set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return 0; } ContainerTaskRunner::~ContainerTaskRunner() { if (collector_ != NULL) { ResourceCollectorEngine* engine = GetResourceCollectorEngine(); engine->DelCollector(collector_id_); delete collector_; collector_ = NULL; } delete _cg_ctrl; delete _mem_ctrl; delete _cpu_ctrl; delete _cpu_acct_ctrl; } int ContainerTaskRunner::Prepare() { LOG(INFO, "prepare container for task %ld", m_task_info.task_id()); //TODO std::vector<std::string> support_cg; support_cg.push_back("memory"); support_cg.push_back("cpu"); support_cg.push_back("cpuacct"); _cg_ctrl = new CGroupCtrl(_cg_root, support_cg); std::map<std::string, std::string> sub_sys_map; int status = _cg_ctrl->Create(m_task_info.task_id(), sub_sys_map); // NOTE multi thread safe if (collector_ == NULL) { std::string group_path = boost::lexical_cast<std::string>(m_task_info.task_id()); collector_ = new CGroupResourceCollector(group_path); ResourceCollectorEngine* engine = GetResourceCollectorEngine(); collector_id_ = engine->AddCollector(collector_); } else { collector_->ResetCgroupName( boost::lexical_cast<std::string>(m_task_info.task_id())); } if (status != 0) { LOG(FATAL, "fail to create subsystem for task %ld,status %d", m_task_info.task_id(), status); return status; } _mem_ctrl = new MemoryCtrl(sub_sys_map["memory"]); _cpu_ctrl = new CpuCtrl(sub_sys_map["cpu"]); _cpu_acct_ctrl = new CpuAcctCtrl(sub_sys_map["cpuacct"]); std::string uri = m_task_info.task_raw(); std::string path = m_workspace->GetPath(); path.append("/"); path.append("tmp.tar.gz"); DownloaderManager* downloader_handler = DownloaderManager::GetInstance(); downloader_handler->DownloadInThread( uri, path, boost::bind(&ContainerTaskRunner::StartAfterDownload, this, _1)); return 0; } void ContainerTaskRunner::StartAfterDownload(int ret) { if (ret == 0) { std::string tar_cmd = "cd " + m_workspace->GetPath() + " && tar -xzf tmp.tar.gz"; int status = system(tar_cmd.c_str()); if (status != 0) { LOG(WARNING, "tar -xf failed"); return; } Start(); } } void ContainerTaskRunner::PutToCGroup(){ int64_t mem_size = m_task_info.required_mem(); double cpu_core = m_task_info.required_cpu(); LOG(INFO, "resource limit cpu %f, mem %ld", cpu_core, mem_size); /* std::string mem_key = "memory"; std::string cpu_key = "cpu"; for (int i = 0; i< m_task_info.resource_list_size(); i++){ ResourceItem item = m_task_info.resource_list(i); if(mem_key.compare(item.name())==0 && item.value() > 0){ mem_size = item.value(); continue; } if(cpu_key.compare(item.name())==0 && item.value() >0){ cpu_share = item.value() * 512; } }*/ _mem_ctrl->SetLimit(mem_size); //_cpu_ctrl->SetCpuShare(cpu_share); int64_t quota = static_cast<int64_t>(cpu_core * CPU_CFS_PERIOD); if (quota < MIN_CPU_CFS_QUOTA) { quota = MIN_CPU_CFS_QUOTA; } _cpu_ctrl->SetCpuQuota(quota); pid_t my_pid = getpid(); _mem_ctrl->AttachTask(my_pid); _cpu_ctrl->AttachTask(my_pid); _cpu_acct_ctrl->AttachTask(my_pid); } int ContainerTaskRunner::Start() { LOG(INFO, "start a task with id %ld", m_task_info.task_id()); if (IsRunning() == 0) { LOG(WARNING, "task with id %ld has been runing", m_task_info.task_id()); return -1; } int stdout_fd, stderr_fd; std::vector<int> fds; PrepareStart(fds, &stdout_fd, &stderr_fd); m_child_pid = fork(); if (m_child_pid == 0) { PutToCGroup(); StartTaskAfterFork(fds, stdout_fd, stderr_fd); } else { close(stdout_fd); close(stderr_fd); m_group_pid = m_child_pid; } return 0; } void ContainerTaskRunner::Status(TaskStatus* status) { if (collector_ != NULL) { status->set_cpu_usage(collector_->GetCpuUsage()); status->set_memory_usage(collector_->GetMemoryUsage()); LOG(WARNING, "cpu usage %f memory usage %ld", status->cpu_usage(), status->memory_usage()); } return; } void ContainerTaskRunner::StopPost() { if (collector_ != NULL) { collector_->Clear(); } return; } int ContainerTaskRunner::Stop(){ int status = AbstractTaskRunner::Stop(); LOG(INFO,"stop task %ld with status %d",m_task_info.task_id(),status); if(status != 0 ){ return status; } //sleep 500 ms for cgroup clear tasks common::ThisThread::Sleep(500); StopPost(); status = _cg_ctrl->Destroy(m_task_info.task_id()); LOG(INFO,"destroy cgroup for task %ld with status %d",m_task_info.task_id(),status); return status; } } <|endoftext|>
<commit_before>#include <Bull/Graphics/Rendering/Transformable.hpp> namespace Bull { Transformable::Transformable() : m_scale(Vector3F::Unit) { /// Nothing } void Transformable::scale(const Vector3F& scale) { m_scale *= scale; } void Transformable::rotate(const EulerAnglesF& rotation) { m_rotation += rotation; } void Transformable::move(const Vector3F& translation) { m_translation += translation; } Matrix4F Transformable::getModelMatrix() const { Matrix4F scaling = Matrix4F::makeScale(m_scale); Matrix4F translation = Matrix4F::makeTranslation(m_translation); Matrix4F rotation = Matrix4F::makeRotation(QuaternionF(EulerAnglesF::normalize(m_rotation))); return translation * rotation * scaling; } } <commit_msg>[Graphics/Transformable] Normalize rotation<commit_after>#include <Bull/Graphics/Rendering/Transformable.hpp> namespace Bull { Transformable::Transformable() : m_scale(Vector3F::Unit) { /// Nothing } void Transformable::scale(const Vector3F& scale) { m_scale *= scale; } void Transformable::rotate(const EulerAnglesF& rotation) { m_rotation = EulerAnglesF::normalize(m_rotation += rotation); } void Transformable::move(const Vector3F& translation) { m_translation += translation; } Matrix4F Transformable::getModelMatrix() const { Matrix4F scaling = Matrix4F::makeScale(m_scale); Matrix4F translation = Matrix4F::makeTranslation(m_translation); Matrix4F rotation = Matrix4F::makeRotation(QuaternionF(EulerAnglesF::normalize(m_rotation))); return translation * rotation * scaling; } } <|endoftext|>
<commit_before>// Copyright Hugh Perkins 2016 // 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 "hostside_opencl_funcs.h" #include <iostream> #include <memory> #include <vector> #include <map> #include <set> #include "CL/cl.h" using namespace std; using namespace cocl; using namespace easycl; namespace cocl { class Context { public: Context() { cout << "Context " << this << endl; } ~Context() { cout << "~Context() " << this << endl; } }; typedef Context *PContext; Context *currentContext = 0; } extern "C" { size_t cuCtxSynchronize(void); size_t cuCtxCreate_v2(PContext *context, unsigned int flags, void *device); size_t cuCtxGetCurrent(PContext *context); size_t cuCtxSetCurrent(PContext context); } size_t cuCtxSynchronize(void) { cout << "cuCtxSynchronize redirected" << endl; cl->finish(); return 0; } size_t cuCtxGetCurrent(PContext *ppContext) { cout << "cuCtxGetCurrent redirected" << endl; *ppContext = currentContext; return 0; } size_t cuCtxSetCurrent(PContext pContext) { cout << "cuCtxSetCurrent redirected" << endl; currentContext = pContext; return 0; } size_t cuCtxCreate_v2 (PContext *ppContext, unsigned int flags, void *device) { cout << "cuCtxCreate_v2 redirected" << endl; Context *newContext = new Context(); currentContext = newContext; *ppContext = newContext; return 0; } <commit_msg>reduce spam a bit<commit_after>// Copyright Hugh Perkins 2016 // 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 "hostside_opencl_funcs.h" #include <iostream> #include <memory> #include <vector> #include <map> #include <set> #include "CL/cl.h" using namespace std; using namespace cocl; using namespace easycl; namespace cocl { class Context { public: Context() { cout << "Context " << this << endl; } ~Context() { cout << "~Context() " << this << endl; } }; typedef Context *PContext; Context *currentContext = 0; } extern "C" { size_t cuCtxSynchronize(void); size_t cuCtxCreate_v2(PContext *context, unsigned int flags, void *device); size_t cuCtxGetCurrent(PContext *context); size_t cuCtxSetCurrent(PContext context); } size_t cuCtxSynchronize(void) { cout << "cuCtxSynchronize redirected" << endl; cl->finish(); return 0; } size_t cuCtxGetCurrent(PContext *ppContext) { // cout << "cuCtxGetCurrent redirected" << endl; *ppContext = currentContext; return 0; } size_t cuCtxSetCurrent(PContext pContext) { cout << "cuCtxSetCurrent redirected" << endl; currentContext = pContext; return 0; } size_t cuCtxCreate_v2 (PContext *ppContext, unsigned int flags, void *device) { cout << "cuCtxCreate_v2 redirected" << endl; Context *newContext = new Context(); currentContext = newContext; *ppContext = newContext; return 0; } <|endoftext|>
<commit_before>/*++ Copyright (c) 2013 Microsoft Corporation Module Name: api_rcf.cpp Abstract: Additional APIs for handling elements of the Z3 real closed field that contains: - transcendental extensions - infinitesimal extensions - algebraic extensions Author: Leonardo de Moura (leonardo) 2012-01-05 Notes: --*/ #include<iostream> #include"z3.h" #include"api_log_macros.h" #include"api_context.h" #include"realclosure.h" static rcmanager & rcfm(Z3_context c) { return mk_c(c)->rcfm(); } static void reset_rcf_cancel(Z3_context c) { rcfm(c).reset_cancel(); } static Z3_rcf_num from_rcnumeral(rcnumeral a) { return reinterpret_cast<Z3_rcf_num>(a.c_ptr()); } static rcnumeral to_rcnumeral(Z3_rcf_num a) { return rcnumeral::mk(a); } extern "C" { void Z3_API Z3_rcf_del(Z3_context c, Z3_rcf_num a) { Z3_TRY; LOG_Z3_rcf_del(c, a); RESET_ERROR_CODE(); rcnumeral _a = to_rcnumeral(a); rcfm(c).del(_a); Z3_CATCH; } Z3_rcf_num Z3_API Z3_rcf_mk_rational(Z3_context c, Z3_string val) { Z3_TRY; LOG_Z3_rcf_mk_rational(c, val); RESET_ERROR_CODE(); reset_rcf_cancel(c); scoped_mpq q(rcfm(c).qm()); rcfm(c).qm().set(q, val); rcnumeral r; rcfm(c).set(r, q); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mk_small_int(Z3_context c, int val) { Z3_TRY; LOG_Z3_rcf_mk_small_int(c, val); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).set(r, val); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mk_pi(Z3_context c) { Z3_TRY; LOG_Z3_rcf_mk_pi(c); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).mk_pi(r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mk_e(Z3_context c) { Z3_TRY; LOG_Z3_rcf_mk_e(c); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).mk_e(r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mk_infinitesimal(Z3_context c, Z3_string name) { Z3_TRY; LOG_Z3_rcf_mk_infinitesimal(c, name); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).mk_infinitesimal(name, r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } unsigned Z3_API Z3_rcf_mk_roots(Z3_context c, unsigned n, Z3_rcf_num const a[], Z3_rcf_num roots[]) { Z3_TRY; LOG_Z3_rcf_mk_roots(c, n, a, roots); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral_vector av; unsigned rz = 0; for (unsigned i = 0; i < n; i++) { if (!rcfm(c).is_zero(to_rcnumeral(a[i]))) rz = i + 1; av.push_back(to_rcnumeral(a[i])); } if (rz == 0) { // it is the zero polynomial SET_ERROR_CODE(Z3_INVALID_ARG); return 0; } av.shrink(rz); rcnumeral_vector rs; rcfm(c).isolate_roots(av.size(), av.c_ptr(), rs); unsigned num_roots = rs.size(); for (unsigned i = 0; i < num_roots; i++) { roots[i] = from_rcnumeral(rs[i]); } RETURN_Z3_rcf_mk_roots num_roots; Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_add(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_add(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).add(to_rcnumeral(a), to_rcnumeral(b), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_sub(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_sub(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).sub(to_rcnumeral(a), to_rcnumeral(b), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mul(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_mul(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).mul(to_rcnumeral(a), to_rcnumeral(b), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_div(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_div(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).div(to_rcnumeral(a), to_rcnumeral(b), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_neg(Z3_context c, Z3_rcf_num a) { Z3_TRY; LOG_Z3_rcf_neg(c, a); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).neg(to_rcnumeral(a), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_inv(Z3_context c, Z3_rcf_num a) { Z3_TRY; LOG_Z3_rcf_inv(c, a); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).inv(to_rcnumeral(a), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_power(Z3_context c, Z3_rcf_num a, unsigned k) { Z3_TRY; LOG_Z3_rcf_power(c, a, k); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).power(to_rcnumeral(a), k, r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_bool Z3_API Z3_rcf_lt(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_lt(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).lt(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_gt(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_gt(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).gt(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_le(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_le(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).le(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_ge(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_ge(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).ge(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_eq(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_eq(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).eq(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_neq(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_neq(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).eq(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_string Z3_API Z3_rcf_num_to_string(Z3_context c, Z3_rcf_num a, Z3_bool compact) { Z3_TRY; LOG_Z3_rcf_num_to_string(c, a, compact); RESET_ERROR_CODE(); reset_rcf_cancel(c); std::ostringstream buffer; rcfm(c).display(buffer, to_rcnumeral(a), compact != 0); return mk_c(c)->mk_external_string(buffer.str()); Z3_CATCH_RETURN(""); } Z3_string Z3_API Z3_rcf_num_to_decimal_string(Z3_context c, Z3_rcf_num a, unsigned prec) { Z3_TRY; LOG_Z3_rcf_num_to_decimal_string(c, a, prec); RESET_ERROR_CODE(); reset_rcf_cancel(c); std::ostringstream buffer; rcfm(c).display_decimal(buffer, to_rcnumeral(a), prec); return mk_c(c)->mk_external_string(buffer.str()); Z3_CATCH_RETURN(""); } void Z3_API Z3_rcf_get_numerator_denominator(Z3_context c, Z3_rcf_num a, Z3_rcf_num * n, Z3_rcf_num * d) { Z3_TRY; LOG_Z3_rcf_get_numerator_denominator(c, a, n, d); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral _n, _d; rcfm(c).clean_denominators(to_rcnumeral(a), _n, _d); *n = from_rcnumeral(_n); *d = from_rcnumeral(_d); RETURN_Z3_rcf_get_numerator_denominator; Z3_CATCH; } }; <commit_msg>Fix typo<commit_after>/*++ Copyright (c) 2013 Microsoft Corporation Module Name: api_rcf.cpp Abstract: Additional APIs for handling elements of the Z3 real closed field that contains: - transcendental extensions - infinitesimal extensions - algebraic extensions Author: Leonardo de Moura (leonardo) 2012-01-05 Notes: --*/ #include<iostream> #include"z3.h" #include"api_log_macros.h" #include"api_context.h" #include"realclosure.h" static rcmanager & rcfm(Z3_context c) { return mk_c(c)->rcfm(); } static void reset_rcf_cancel(Z3_context c) { rcfm(c).reset_cancel(); } static Z3_rcf_num from_rcnumeral(rcnumeral a) { return reinterpret_cast<Z3_rcf_num>(a.c_ptr()); } static rcnumeral to_rcnumeral(Z3_rcf_num a) { return rcnumeral::mk(a); } extern "C" { void Z3_API Z3_rcf_del(Z3_context c, Z3_rcf_num a) { Z3_TRY; LOG_Z3_rcf_del(c, a); RESET_ERROR_CODE(); rcnumeral _a = to_rcnumeral(a); rcfm(c).del(_a); Z3_CATCH; } Z3_rcf_num Z3_API Z3_rcf_mk_rational(Z3_context c, Z3_string val) { Z3_TRY; LOG_Z3_rcf_mk_rational(c, val); RESET_ERROR_CODE(); reset_rcf_cancel(c); scoped_mpq q(rcfm(c).qm()); rcfm(c).qm().set(q, val); rcnumeral r; rcfm(c).set(r, q); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mk_small_int(Z3_context c, int val) { Z3_TRY; LOG_Z3_rcf_mk_small_int(c, val); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).set(r, val); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mk_pi(Z3_context c) { Z3_TRY; LOG_Z3_rcf_mk_pi(c); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).mk_pi(r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mk_e(Z3_context c) { Z3_TRY; LOG_Z3_rcf_mk_e(c); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).mk_e(r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mk_infinitesimal(Z3_context c, Z3_string name) { Z3_TRY; LOG_Z3_rcf_mk_infinitesimal(c, name); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).mk_infinitesimal(name, r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } unsigned Z3_API Z3_rcf_mk_roots(Z3_context c, unsigned n, Z3_rcf_num const a[], Z3_rcf_num roots[]) { Z3_TRY; LOG_Z3_rcf_mk_roots(c, n, a, roots); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral_vector av; unsigned rz = 0; for (unsigned i = 0; i < n; i++) { if (!rcfm(c).is_zero(to_rcnumeral(a[i]))) rz = i + 1; av.push_back(to_rcnumeral(a[i])); } if (rz == 0) { // it is the zero polynomial SET_ERROR_CODE(Z3_INVALID_ARG); return 0; } av.shrink(rz); rcnumeral_vector rs; rcfm(c).isolate_roots(av.size(), av.c_ptr(), rs); unsigned num_roots = rs.size(); for (unsigned i = 0; i < num_roots; i++) { roots[i] = from_rcnumeral(rs[i]); } RETURN_Z3_rcf_mk_roots num_roots; Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_add(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_add(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).add(to_rcnumeral(a), to_rcnumeral(b), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_sub(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_sub(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).sub(to_rcnumeral(a), to_rcnumeral(b), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_mul(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_mul(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).mul(to_rcnumeral(a), to_rcnumeral(b), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_div(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_div(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).div(to_rcnumeral(a), to_rcnumeral(b), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_neg(Z3_context c, Z3_rcf_num a) { Z3_TRY; LOG_Z3_rcf_neg(c, a); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).neg(to_rcnumeral(a), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_inv(Z3_context c, Z3_rcf_num a) { Z3_TRY; LOG_Z3_rcf_inv(c, a); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).inv(to_rcnumeral(a), r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_rcf_num Z3_API Z3_rcf_power(Z3_context c, Z3_rcf_num a, unsigned k) { Z3_TRY; LOG_Z3_rcf_power(c, a, k); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral r; rcfm(c).power(to_rcnumeral(a), k, r); RETURN_Z3(from_rcnumeral(r)); Z3_CATCH_RETURN(0); } Z3_bool Z3_API Z3_rcf_lt(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_lt(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).lt(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_gt(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_gt(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).gt(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_le(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_le(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).le(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_ge(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_ge(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).ge(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_eq(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_eq(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).eq(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_bool Z3_API Z3_rcf_neq(Z3_context c, Z3_rcf_num a, Z3_rcf_num b) { Z3_TRY; LOG_Z3_rcf_neq(c, a, b); RESET_ERROR_CODE(); reset_rcf_cancel(c); return rcfm(c).neq(to_rcnumeral(a), to_rcnumeral(b)); Z3_CATCH_RETURN(Z3_FALSE); } Z3_string Z3_API Z3_rcf_num_to_string(Z3_context c, Z3_rcf_num a, Z3_bool compact) { Z3_TRY; LOG_Z3_rcf_num_to_string(c, a, compact); RESET_ERROR_CODE(); reset_rcf_cancel(c); std::ostringstream buffer; rcfm(c).display(buffer, to_rcnumeral(a), compact != 0); return mk_c(c)->mk_external_string(buffer.str()); Z3_CATCH_RETURN(""); } Z3_string Z3_API Z3_rcf_num_to_decimal_string(Z3_context c, Z3_rcf_num a, unsigned prec) { Z3_TRY; LOG_Z3_rcf_num_to_decimal_string(c, a, prec); RESET_ERROR_CODE(); reset_rcf_cancel(c); std::ostringstream buffer; rcfm(c).display_decimal(buffer, to_rcnumeral(a), prec); return mk_c(c)->mk_external_string(buffer.str()); Z3_CATCH_RETURN(""); } void Z3_API Z3_rcf_get_numerator_denominator(Z3_context c, Z3_rcf_num a, Z3_rcf_num * n, Z3_rcf_num * d) { Z3_TRY; LOG_Z3_rcf_get_numerator_denominator(c, a, n, d); RESET_ERROR_CODE(); reset_rcf_cancel(c); rcnumeral _n, _d; rcfm(c).clean_denominators(to_rcnumeral(a), _n, _d); *n = from_rcnumeral(_n); *d = from_rcnumeral(_d); RETURN_Z3_rcf_get_numerator_denominator; Z3_CATCH; } }; <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/array.h> #include <af/defines.h> #include <af/arith.h> #include <af/data.h> #include <ArrayInfo.hpp> #include <optypes.hpp> #include <implicit.hpp> #include <err_common.hpp> #include <handle.hpp> #include <backend.hpp> #include <unary.hpp> #include <implicit.hpp> #include <complex.hpp> #include <logic.hpp> #include <cast.hpp> #include <arith.hpp> using namespace detail; template<typename T, af_op_t op> static inline af_array unaryOp(const af_array in) { af_array res = getHandle(unaryOp<T, op>(castArray<T>(in))); return res; } template<typename Tc, typename Tr, af_op_t op> struct unaryOpCplx; template<af_op_t op> static af_err af_unary(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); ARG_ASSERT(1, in_info.isReal()); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = unaryOp<float , op>(in); break; case f64 : res = unaryOp<double , op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } template<af_op_t op> static af_err af_unary_complex(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = unaryOp<float , op>(in); break; case f64 : res = unaryOp<double , op>(in); break; case c32 : res = unaryOpCplx<cfloat , float , op>(in); break; case c64 : res = unaryOpCplx<cdouble, double, op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } #define UNARY(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_unary<af_##fn##_t>(out, in); \ } #define UNARY_COMPLEX(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_unary_complex<af_##fn##_t>(out, in); \ } UNARY(sin) UNARY(cos) UNARY(tan) UNARY(asin) UNARY(acos) UNARY(atan) UNARY(sinh) UNARY(cosh) UNARY(tanh) UNARY(asinh) UNARY(acosh) UNARY(atanh) UNARY(trunc) UNARY(sign) UNARY(round) UNARY(floor) UNARY(ceil) UNARY(sigmoid) UNARY(expm1) UNARY(erf) UNARY(erfc) UNARY(log) UNARY(log10) UNARY(log1p) UNARY(log2) UNARY(cbrt) UNARY(tgamma) UNARY(lgamma) UNARY_COMPLEX(exp) UNARY_COMPLEX(sqrt) template<typename Tc, typename Tr> struct unaryOpCplx<Tc, Tr, af_exp_t> { af_array operator()(const af_array a) { Array<Tc> In = getArray<Tc>(a); Array<Tr> Real = real<Tr, Tc>(In); Array<Tr> Imag = imag<Tr, Tc>(In); Array<Tr> ExpReal = unaryOp<Tr, af_exp_t>(Real); Array<Tr> CosImag = unaryOp<Tr, af_cos_t>(Imag); Array<Tr> SinImag = unaryOp<Tr, af_sin_t>(Imag); Array<Tc> Unit = cplx<Tc, Tr>(CosImag, SinImag, CosImag.dims()); Array<Tc> Scale = cast<Tc, Tr>(ExpReal); Array<Tc> Result = arithOp<Tc, af_mul_t>(Scale, Unit, Scale.dims()); return getHandle(Result); } }; template<typename Tc, typename Tr> struct unaryOpCplx<Tc, Tr, af_sqrt_t> { af_array operator()(const af_array in) { // convert cartesian to polar Array<Tc> z = getArray<Tc>(a); Array<Tr> a = real<Tr, Tc>(In); Array<Tr> b = imag<Tr, Tc>(In); Array<Tr> r = arithOp<Tr, af_atan2_t>(b, a, b.dims()); Array<Tr> phi = abs<Tr>(z); // compute sqrt Array<Tr> two = createValueArray<Tr>(phi.dims(), 2.0); Array<Tr> r_out = unaryOp<Tr, af_sqrt_t>(r); Array<Tr> phi_out = arithOp<Tr, af_div_t>(phi, two, phi.dims()); // convert polar to cartesian Array<Tr> a_out_unit = unaryOp<Tr, af_cos_t>(phi_out); Array<Tr> b_out_unit = unaryOp<Tr, af_sin_t>(phi_out); Array<Tr> a_out = arithOp<Tc, af_mul_t>(r_out, a_out_unit, SqrtAbs.dims()); Array<Tr> b_out = arithOp<Tc, af_mul_t>(r_out, b_out_unit, SqrtAbs.dims()); Array<Tc> z_out = cplx<Tc, Tr>(a_out, b_out, a_out.dims()); return getHandle(z_out); } }; af_err af_not(af_array *out, const af_array in) { try { af_array tmp; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&tmp, 0, in_info.ndims(), in_info.dims().get(), in_info.getType())); AF_CHECK(af_eq(out, in, tmp, false)); AF_CHECK(af_release_array(tmp)); } CATCHALL; return AF_SUCCESS; } af_err af_arg(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); if (!in_info.isComplex()) { return af_constant(out, 0, in_info.ndims(), in_info.dims().get(), in_info.getType()); } af_array real; af_array imag; AF_CHECK(af_real(&real, in)); AF_CHECK(af_imag(&imag, in)); AF_CHECK(af_atan2(out, imag, real, false)); AF_CHECK(af_release_array(real)); AF_CHECK(af_release_array(imag)); } CATCHALL; return AF_SUCCESS; } af_err af_pow2(af_array *out, const af_array in) { try { af_array two; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&two, 2, in_info.ndims(), in_info.dims().get(), in_info.getType())); AF_CHECK(af_pow(out, two, in, false)); AF_CHECK(af_release_array(two)); } CATCHALL; return AF_SUCCESS; } af_err af_factorial(af_array *out, const af_array in) { try { af_array one; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&one, 1, in_info.ndims(), in_info.dims().get(), in_info.getType())); af_array inp1; AF_CHECK(af_add(&inp1, one, in, false)); AF_CHECK(af_tgamma(out, inp1)); AF_CHECK(af_release_array(one)); AF_CHECK(af_release_array(inp1)); } CATCHALL; return AF_SUCCESS; } template<typename T, af_op_t op> static inline af_array checkOp(const af_array in) { af_array res = getHandle(checkOp<T, op>(castArray<T>(in))); return res; } template<af_op_t op> struct cplxLogicOp { af_array operator()(Array<char> resR, Array<char> resI, dim4 dims) { return getHandle(logicOp<char, af_or_t>(resR, resI, dims)); } }; template <> struct cplxLogicOp<af_iszero_t> { af_array operator()(Array<char> resR, Array<char> resI, dim4 dims) { return getHandle(logicOp<char, af_and_t>(resR, resI, dims)); } }; template<typename T, typename BT, af_op_t op> static inline af_array checkOpCplx(const af_array in) { Array<BT> R = real<BT, T>(getArray<T>(in)); Array<BT> I = imag<BT, T>(getArray<T>(in)); Array<char> resR = checkOp<BT, op>(R); Array<char> resI = checkOp<BT, op>(I); ArrayInfo in_info = getInfo(in); dim4 dims = in_info.dims(); cplxLogicOp<op> cplxLogic; af_array res = cplxLogic(resR, resI, dims); return res; } template<af_op_t op> static af_err af_check(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles / complex af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = checkOp<float , op>(in); break; case f64 : res = checkOp<double , op>(in); break; case c32 : res = checkOpCplx<cfloat , float , op>(in); break; case c64 : res = checkOpCplx<cdouble, double, op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } #define CHECK(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_check<af_##fn##_t>(out, in); \ } CHECK(isinf) CHECK(isnan) CHECK(iszero) <commit_msg>Add complex log<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/array.h> #include <af/defines.h> #include <af/arith.h> #include <af/data.h> #include <ArrayInfo.hpp> #include <optypes.hpp> #include <implicit.hpp> #include <err_common.hpp> #include <handle.hpp> #include <backend.hpp> #include <unary.hpp> #include <implicit.hpp> #include <complex.hpp> #include <logic.hpp> #include <cast.hpp> #include <arith.hpp> using namespace detail; template<typename T, af_op_t op> static inline af_array unaryOp(const af_array in) { af_array res = getHandle(unaryOp<T, op>(castArray<T>(in))); return res; } template<typename Tc, typename Tr, af_op_t op> struct unaryOpCplx; template<af_op_t op> static af_err af_unary(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); ARG_ASSERT(1, in_info.isReal()); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = unaryOp<float , op>(in); break; case f64 : res = unaryOp<double , op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } template<af_op_t op> static af_err af_unary_complex(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = unaryOp<float , op>(in); break; case f64 : res = unaryOp<double , op>(in); break; case c32 : res = unaryOpCplx<cfloat , float , op>(in); break; case c64 : res = unaryOpCplx<cdouble, double, op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } #define UNARY(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_unary<af_##fn##_t>(out, in); \ } #define UNARY_COMPLEX(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_unary_complex<af_##fn##_t>(out, in); \ } UNARY(sin) UNARY(cos) UNARY(tan) UNARY(asin) UNARY(acos) UNARY(atan) UNARY(sinh) UNARY(cosh) UNARY(tanh) UNARY(asinh) UNARY(acosh) UNARY(atanh) UNARY(trunc) UNARY(sign) UNARY(round) UNARY(floor) UNARY(ceil) UNARY(sigmoid) UNARY(expm1) UNARY(erf) UNARY(erfc) UNARY(log) UNARY(log10) UNARY(log1p) UNARY(log2) UNARY(cbrt) UNARY(tgamma) UNARY(lgamma) UNARY_COMPLEX(exp) UNARY_COMPLEX(sqrt) template<typename Tc, typename Tr> struct unaryOpCplx<Tc, Tr, af_exp_t> { af_array operator()(const af_array a) { Array<Tc> In = getArray<Tc>(a); Array<Tr> Real = real<Tr, Tc>(In); Array<Tr> Imag = imag<Tr, Tc>(In); Array<Tr> ExpReal = unaryOp<Tr, af_exp_t>(Real); Array<Tr> CosImag = unaryOp<Tr, af_cos_t>(Imag); Array<Tr> SinImag = unaryOp<Tr, af_sin_t>(Imag); Array<Tc> Unit = cplx<Tc, Tr>(CosImag, SinImag, CosImag.dims()); Array<Tc> Scale = cast<Tc, Tr>(ExpReal); Array<Tc> Result = arithOp<Tc, af_mul_t>(Scale, Unit, Scale.dims()); return getHandle(Result); } }; template<typename Tc, typename Tr> struct unaryOpCplx<Tc, Tr, af_log_t> { af_array operator()(const af_array in) { // convert cartesian to polar Array<Tc> z = getArray<Tc>(a); Array<Tr> a = real<Tr, Tc>(In); Array<Tr> b = imag<Tr, Tc>(In); Array<Tr> r = arithOp<Tr, af_atan2_t>(b, a, b.dims()); Array<Tr> phi = abs<Tr>(z); // compute log Array<Tr> a_out = unaryOp<Tr, af_log_t>(r); Array<Tr> b_out = phi; Array<Tc> z_out = cplx<Tc, Tr>(a_out, b_out, a_out.dims()); return getHandle(z_out); } }; template<typename Tc, typename Tr> struct unaryOpCplx<Tc, Tr, af_sqrt_t> { af_array operator()(const af_array in) { // convert cartesian to polar Array<Tc> z = getArray<Tc>(a); Array<Tr> a = real<Tr, Tc>(In); Array<Tr> b = imag<Tr, Tc>(In); Array<Tr> r = arithOp<Tr, af_atan2_t>(b, a, b.dims()); Array<Tr> phi = abs<Tr>(z); // compute sqrt Array<Tr> two = createValueArray<Tr>(phi.dims(), 2.0); Array<Tr> r_out = unaryOp<Tr, af_sqrt_t>(r); Array<Tr> phi_out = arithOp<Tr, af_div_t>(phi, two, phi.dims()); // convert polar to cartesian Array<Tr> a_out_unit = unaryOp<Tr, af_cos_t>(phi_out); Array<Tr> b_out_unit = unaryOp<Tr, af_sin_t>(phi_out); Array<Tr> a_out = arithOp<Tc, af_mul_t>(r_out, a_out_unit, SqrtAbs.dims()); Array<Tr> b_out = arithOp<Tc, af_mul_t>(r_out, b_out_unit, SqrtAbs.dims()); Array<Tc> z_out = cplx<Tc, Tr>(a_out, b_out, a_out.dims()); return getHandle(z_out); } }; af_err af_not(af_array *out, const af_array in) { try { af_array tmp; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&tmp, 0, in_info.ndims(), in_info.dims().get(), in_info.getType())); AF_CHECK(af_eq(out, in, tmp, false)); AF_CHECK(af_release_array(tmp)); } CATCHALL; return AF_SUCCESS; } af_err af_arg(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); if (!in_info.isComplex()) { return af_constant(out, 0, in_info.ndims(), in_info.dims().get(), in_info.getType()); } af_array real; af_array imag; AF_CHECK(af_real(&real, in)); AF_CHECK(af_imag(&imag, in)); AF_CHECK(af_atan2(out, imag, real, false)); AF_CHECK(af_release_array(real)); AF_CHECK(af_release_array(imag)); } CATCHALL; return AF_SUCCESS; } af_err af_pow2(af_array *out, const af_array in) { try { af_array two; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&two, 2, in_info.ndims(), in_info.dims().get(), in_info.getType())); AF_CHECK(af_pow(out, two, in, false)); AF_CHECK(af_release_array(two)); } CATCHALL; return AF_SUCCESS; } af_err af_factorial(af_array *out, const af_array in) { try { af_array one; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&one, 1, in_info.ndims(), in_info.dims().get(), in_info.getType())); af_array inp1; AF_CHECK(af_add(&inp1, one, in, false)); AF_CHECK(af_tgamma(out, inp1)); AF_CHECK(af_release_array(one)); AF_CHECK(af_release_array(inp1)); } CATCHALL; return AF_SUCCESS; } template<typename T, af_op_t op> static inline af_array checkOp(const af_array in) { af_array res = getHandle(checkOp<T, op>(castArray<T>(in))); return res; } template<af_op_t op> struct cplxLogicOp { af_array operator()(Array<char> resR, Array<char> resI, dim4 dims) { return getHandle(logicOp<char, af_or_t>(resR, resI, dims)); } }; template <> struct cplxLogicOp<af_iszero_t> { af_array operator()(Array<char> resR, Array<char> resI, dim4 dims) { return getHandle(logicOp<char, af_and_t>(resR, resI, dims)); } }; template<typename T, typename BT, af_op_t op> static inline af_array checkOpCplx(const af_array in) { Array<BT> R = real<BT, T>(getArray<T>(in)); Array<BT> I = imag<BT, T>(getArray<T>(in)); Array<char> resR = checkOp<BT, op>(R); Array<char> resI = checkOp<BT, op>(I); ArrayInfo in_info = getInfo(in); dim4 dims = in_info.dims(); cplxLogicOp<op> cplxLogic; af_array res = cplxLogic(resR, resI, dims); return res; } template<af_op_t op> static af_err af_check(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles / complex af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = checkOp<float , op>(in); break; case f64 : res = checkOp<double , op>(in); break; case c32 : res = checkOpCplx<cfloat , float , op>(in); break; case c64 : res = checkOpCplx<cdouble, double, op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } #define CHECK(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_check<af_##fn##_t>(out, in); \ } CHECK(isinf) CHECK(isnan) CHECK(iszero) <|endoftext|>
<commit_before>/* * This file is part of the Objavi Renderer. * * Copyright (C) 2013 Borko Jandras <borko.jandras@sourcefabric.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "application.hpp" #include "renderer.hpp" #include "mainwindow.hpp" #include <QWebFrame> #include <QUrl> #include <QDir> #include <QFile> #include <QFileInfo> #include <QMetaEnum> #include <QTextStream> #include <QDebug> #include <iostream> namespace { QString takeOptionValue(QStringList * arguments, int index) { QString result; if (++index < arguments->count() && !arguments->at(index).startsWith("-")) { result = arguments->takeAt(index); } return result; } QUrl urlFromUserInput(QString input) { QFileInfo fi(input); if (fi.exists() && fi.isRelative()) { input = fi.absoluteFilePath(); } return QUrl::fromUserInput(input); } void initWebSettings() { QWebSettings::setMaximumPagesInCache(4); QWebSettings::setObjectCacheCapacities((16*1024*1024) / 8, (16*1024*1024) / 8, 16*1024*1024); QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); QWebSettings::globalSettings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); QWebSettings::globalSettings()->setAttribute(QWebSettings::CSSRegionsEnabled, true); QWebSettings::enablePersistentStorage(); } QString makeDefaultUrl() { QString default_file = QString("%1/%2").arg(QDir::homePath()).arg(QLatin1String("index.html")); if (QFile(default_file).exists()) { return QString("file://%1").arg(default_file); } else { return QString(); } } } // namespace namespace Objavi { Application::Application(int argc, char ** argv) : QApplication(argc, argv, QApplication::GuiServer) , m_gui(false) { setOrganizationName("Sourcefabric"); setApplicationName("Objavi Renderer"); setApplicationVersion("0.2"); // default options // m_rendererOptions.bookjsPath = QString(":/bookjs/"); m_rendererOptions.printTimeout = 10000; initWebSettings(); parseArguments(arguments()); QStringList urls = m_urls; if (urls.isEmpty()) { urls.append(makeDefaultUrl()); } if (m_gui) { m_window.reset(new MainWindow()); m_window->load(urls[0]); m_window->show(); } else { QString url = urls[0]; QUrl qurl = urlFromUserInput(url); if (qurl.scheme().isEmpty()) { qurl = QUrl("http://" + url + "/"); } m_renderer.reset(new Objavi::Renderer(qurl, m_rendererOptions)); QObject::connect(m_renderer.data(), SIGNAL(finished(bool)), this, SLOT(onRendererFinished(bool))); qDebug() << "rendering URL" << qurl.toString() << "to PDF file" << m_renderer->outputFilePath(); } } void Application::onRendererFinished(bool success) { QCoreApplication::exit(success ? 0 : -1); } void Application::parseArguments(QStringList args) { QFileInfo program(args.at(0)); QString programName("renderer"); if (program.exists()) programName = program.baseName(); if (args.contains("-h") || args.contains("-help") || args.contains("--help")) { std::cout << "Usage: " << programName.toLatin1().data() << " [-version]" << " [-gui]" << " [-bookjs path]" << " [-custom-css path]" << " [-output path]" << " [-page-config string]" << " [-print-timeout seconds]" << " URL" << std::endl; appQuit(0); } if (args.contains("-version")) { std::cout << applicationName().toLatin1().data() << " " << applicationVersion().toLatin1().data() #if defined(Q_PROCESSOR_X86_32) << " x86" #elif defined(Q_PROCESSOR_X86_64) << " amd64" #endif << std::endl; appQuit(0); } m_gui = args.contains("-gui"); int bookjsPathIndex = args.indexOf("-bookjs"); if (bookjsPathIndex != -1) { QString path = takeOptionValue(&args, bookjsPathIndex); QDir dir(path); if (! dir.exists()) { appQuit(1, QString("path does not point to a directory: %1").arg(path)); } m_rendererOptions.bookjsPath = dir.absolutePath(); } int cssPathIndex = args.indexOf("-custom-css"); if (cssPathIndex != -1) { QString path = takeOptionValue(&args, cssPathIndex); if (! QFileInfo(path).isReadable()) { appQuit(1, QString("file does not exist or is not readable: %1").arg(path)); } QFile file(path); if (! file.open(QFile::ReadOnly)) { appQuit(1, QString("could not open file: %1").arg(path)); } m_rendererOptions.customCSS = QTextStream(&file).readAll(); } int paginationConfigIndex = args.indexOf("-page-config"); if (paginationConfigIndex != -1) { QString paginationConfigText = takeOptionValue(&args, paginationConfigIndex); try { m_rendererOptions.paginationConfig = BookJS::PaginationConfig::parse(paginationConfigText); } catch (std::exception const & e) { appQuit(1, QString("error parsing page-config: %1").arg(e.what())); } } int printTimeoutIndex = args.indexOf("-print-timeout"); if (printTimeoutIndex != -1) { QString printTimeoutText = takeOptionValue(&args, printTimeoutIndex); bool ok; int printTimeout = printTimeoutText.toInt(&ok); if (ok == true) { m_rendererOptions.printTimeout = printTimeout * 1000; // to milli-seconds } else { appQuit(1, QString("invalid value for print-timeout: %1").arg(printTimeoutText)); } } int outputPathIndex = args.indexOf("-output"); if (outputPathIndex != -1) { m_rendererOptions.outputFilePath = takeOptionValue(&args, outputPathIndex); } int lastArg = args.lastIndexOf(QRegExp("^-.*")); m_urls = (lastArg != -1) ? args.mid(++lastArg) : args.mid(1); } void Application::appQuit(int exitCode, QString const & msg) { if (! msg.isEmpty()) { if (exitCode > 0) { qCritical("ERROR: %s", msg.toLatin1().data()); } else { qDebug("%s", msg.toLatin1().data()); } } disconnect(this); ::exit(exitCode); } } // namespace Objavi <commit_msg>Bumped the version number.<commit_after>/* * This file is part of the Objavi Renderer. * * Copyright (C) 2013 Borko Jandras <borko.jandras@sourcefabric.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "application.hpp" #include "renderer.hpp" #include "mainwindow.hpp" #include <QWebFrame> #include <QUrl> #include <QDir> #include <QFile> #include <QFileInfo> #include <QMetaEnum> #include <QTextStream> #include <QDebug> #include <iostream> namespace { QString takeOptionValue(QStringList * arguments, int index) { QString result; if (++index < arguments->count() && !arguments->at(index).startsWith("-")) { result = arguments->takeAt(index); } return result; } QUrl urlFromUserInput(QString input) { QFileInfo fi(input); if (fi.exists() && fi.isRelative()) { input = fi.absoluteFilePath(); } return QUrl::fromUserInput(input); } void initWebSettings() { QWebSettings::setMaximumPagesInCache(4); QWebSettings::setObjectCacheCapacities((16*1024*1024) / 8, (16*1024*1024) / 8, 16*1024*1024); QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); QWebSettings::globalSettings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); QWebSettings::globalSettings()->setAttribute(QWebSettings::CSSRegionsEnabled, true); QWebSettings::enablePersistentStorage(); } QString makeDefaultUrl() { QString default_file = QString("%1/%2").arg(QDir::homePath()).arg(QLatin1String("index.html")); if (QFile(default_file).exists()) { return QString("file://%1").arg(default_file); } else { return QString(); } } } // namespace namespace Objavi { Application::Application(int argc, char ** argv) : QApplication(argc, argv, QApplication::GuiServer) , m_gui(false) { setOrganizationName("Sourcefabric"); setApplicationName("Objavi Renderer"); setApplicationVersion("0.3"); // default options // m_rendererOptions.bookjsPath = QString(":/bookjs/"); m_rendererOptions.printTimeout = 10000; initWebSettings(); parseArguments(arguments()); QStringList urls = m_urls; if (urls.isEmpty()) { urls.append(makeDefaultUrl()); } if (m_gui) { m_window.reset(new MainWindow()); m_window->load(urls[0]); m_window->show(); } else { QString url = urls[0]; QUrl qurl = urlFromUserInput(url); if (qurl.scheme().isEmpty()) { qurl = QUrl("http://" + url + "/"); } m_renderer.reset(new Objavi::Renderer(qurl, m_rendererOptions)); QObject::connect(m_renderer.data(), SIGNAL(finished(bool)), this, SLOT(onRendererFinished(bool))); qDebug() << "rendering URL" << qurl.toString() << "to PDF file" << m_renderer->outputFilePath(); } } void Application::onRendererFinished(bool success) { QCoreApplication::exit(success ? 0 : -1); } void Application::parseArguments(QStringList args) { QFileInfo program(args.at(0)); QString programName("renderer"); if (program.exists()) programName = program.baseName(); if (args.contains("-h") || args.contains("-help") || args.contains("--help")) { std::cout << "Usage: " << programName.toLatin1().data() << " [-version]" << " [-gui]" << " [-bookjs path]" << " [-custom-css path]" << " [-output path]" << " [-page-config string]" << " [-print-timeout seconds]" << " URL" << std::endl; appQuit(0); } if (args.contains("-version")) { std::cout << applicationName().toLatin1().data() << " " << applicationVersion().toLatin1().data() #if defined(Q_PROCESSOR_X86_32) << " x86" #elif defined(Q_PROCESSOR_X86_64) << " amd64" #endif << std::endl; appQuit(0); } m_gui = args.contains("-gui"); int bookjsPathIndex = args.indexOf("-bookjs"); if (bookjsPathIndex != -1) { QString path = takeOptionValue(&args, bookjsPathIndex); QDir dir(path); if (! dir.exists()) { appQuit(1, QString("path does not point to a directory: %1").arg(path)); } m_rendererOptions.bookjsPath = dir.absolutePath(); } int cssPathIndex = args.indexOf("-custom-css"); if (cssPathIndex != -1) { QString path = takeOptionValue(&args, cssPathIndex); if (! QFileInfo(path).isReadable()) { appQuit(1, QString("file does not exist or is not readable: %1").arg(path)); } QFile file(path); if (! file.open(QFile::ReadOnly)) { appQuit(1, QString("could not open file: %1").arg(path)); } m_rendererOptions.customCSS = QTextStream(&file).readAll(); } int paginationConfigIndex = args.indexOf("-page-config"); if (paginationConfigIndex != -1) { QString paginationConfigText = takeOptionValue(&args, paginationConfigIndex); try { m_rendererOptions.paginationConfig = BookJS::PaginationConfig::parse(paginationConfigText); } catch (std::exception const & e) { appQuit(1, QString("error parsing page-config: %1").arg(e.what())); } } int printTimeoutIndex = args.indexOf("-print-timeout"); if (printTimeoutIndex != -1) { QString printTimeoutText = takeOptionValue(&args, printTimeoutIndex); bool ok; int printTimeout = printTimeoutText.toInt(&ok); if (ok == true) { m_rendererOptions.printTimeout = printTimeout * 1000; // to milli-seconds } else { appQuit(1, QString("invalid value for print-timeout: %1").arg(printTimeoutText)); } } int outputPathIndex = args.indexOf("-output"); if (outputPathIndex != -1) { m_rendererOptions.outputFilePath = takeOptionValue(&args, outputPathIndex); } int lastArg = args.lastIndexOf(QRegExp("^-.*")); m_urls = (lastArg != -1) ? args.mid(++lastArg) : args.mid(1); } void Application::appQuit(int exitCode, QString const & msg) { if (! msg.isEmpty()) { if (exitCode > 0) { qCritical("ERROR: %s", msg.toLatin1().data()); } else { qDebug("%s", msg.toLatin1().data()); } } disconnect(this); ::exit(exitCode); } } // namespace Objavi <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/pressure_pinning.h" // GRINS #include "grins/assembly_context.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/elem.h" #include "libmesh/fe_interface.h" #include "libmesh/mesh_base.h" #include "libmesh/parallel.h" namespace GRINS { PressurePinning::PressurePinning( const GetPot& input, const std::string& physics_name ) : _pinned_elem_id(libMesh::DofObject::invalid_id) { _pin_value = input("Physics/"+physics_name+"/pin_value", 0.0 ); unsigned int pin_loc_dim = input.vector_variable_size("Physics/"+physics_name+"/pin_location"); // If the user is specifying a pin_location, it had better be at least 2-dimensional if( pin_loc_dim > 0 && pin_loc_dim < 2 ) { std::cerr << "Error: pressure pin location must be at least 2 dimensional" << std::endl; libmesh_error(); } _pin_location(0) = input("Physics/"+physics_name+"/pin_location", 0.0, 0 ); _pin_location(1) = input("Physics/"+physics_name+"/pin_location", 0.0, 1 ); if( pin_loc_dim == 3 ) _pin_location(2) = input("Physics/"+physics_name+"/pin_location", 0.0, 2 ); return; } PressurePinning::~PressurePinning( ) { return; } void PressurePinning::check_pin_location( const libMesh::MeshBase& mesh ) { libMesh::MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const libMesh::MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { const libMesh::Elem* elem = *el; if( elem->contains_point(_pin_location) ) { _pinned_elem_id = elem->id(); break; } } // If we found the point on one of the processors, then we need // to tell all the others. invalid_id is exceedingly large, // so if we found an element, that id should be the smallest mesh.comm().min( _pinned_elem_id ); if( _pinned_elem_id == libMesh::DofObject::invalid_id ) { libMesh::err << "ERROR: Could not locate point " << _pin_location << " in mesh!" << std::endl; libmesh_error(); } } void PressurePinning::pin_value( libMesh::DiffContext &context, const bool request_jacobian, const VariableIndex var, const double penalty ) { // Make sure we've called check_pin_location() and that pin location // is in the mesh somewhere libmesh_assert_not_equal_to( _pinned_elem_id, libMesh::DofObject::invalid_id ); /** \todo pin_location needs to be const. Currently a libMesh restriction. */ AssemblyContext &c = libMesh::libmesh_cast_ref<AssemblyContext&>(context); if( c.get_elem().id() == _pinned_elem_id ) { // This is redundant for vast majority of cases, but we trying to // be prepared for cases involving, e.g. mesh motion that we're not // currently handling. if( !c.get_elem().contains_point(_pin_location) ) { libmesh_error_msg("ERROR: _pin_location not in the current element!"); } libMesh::DenseSubVector<libMesh::Number> &F_var = c.get_elem_residual(var); // residual libMesh::DenseSubMatrix<libMesh::Number> &K_var = c.get_elem_jacobian(var, var); // jacobian // The number of local degrees of freedom in p variable. const unsigned int n_var_dofs = c.get_dof_indices(var).size(); libMesh::Number var_value = c.point_value(var, _pin_location); libMesh::FEType fe_type = c.get_element_fe(var)->get_fe_type(); libMesh::Point point_loc_in_masterelem = libMesh::FEInterface::inverse_map(c.get_dim(), fe_type, &c.get_elem(), _pin_location); std::vector<libMesh::Real> phi(n_var_dofs); for (unsigned int i=0; i != n_var_dofs; i++) phi[i] = libMesh::FEInterface::shape( c.get_dim(), fe_type, &c.get_elem(), i, point_loc_in_masterelem ); for (unsigned int i=0; i != n_var_dofs; i++) { F_var(i) += penalty*(var_value - _pin_value)*phi[i]; /** \todo What the hell is the c.get_elem_solution_derivative() all about? */ if (request_jacobian && c.get_elem_solution_derivative()) { libmesh_assert (c.get_elem_solution_derivative() == 1.0); for (unsigned int j=0; j != n_var_dofs; j++) K_var(i,j) += penalty*phi[i]*phi[j]; } // End if request_jacobian } // End i loop } // End if pin_location return; } } // namespace GRINS <commit_msg>Need to reset cached elem pinning id<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/pressure_pinning.h" // GRINS #include "grins/assembly_context.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/elem.h" #include "libmesh/fe_interface.h" #include "libmesh/mesh_base.h" #include "libmesh/parallel.h" namespace GRINS { PressurePinning::PressurePinning( const GetPot& input, const std::string& physics_name ) : _pinned_elem_id(libMesh::DofObject::invalid_id) { _pin_value = input("Physics/"+physics_name+"/pin_value", 0.0 ); unsigned int pin_loc_dim = input.vector_variable_size("Physics/"+physics_name+"/pin_location"); // If the user is specifying a pin_location, it had better be at least 2-dimensional if( pin_loc_dim > 0 && pin_loc_dim < 2 ) { std::cerr << "Error: pressure pin location must be at least 2 dimensional" << std::endl; libmesh_error(); } _pin_location(0) = input("Physics/"+physics_name+"/pin_location", 0.0, 0 ); _pin_location(1) = input("Physics/"+physics_name+"/pin_location", 0.0, 1 ); if( pin_loc_dim == 3 ) _pin_location(2) = input("Physics/"+physics_name+"/pin_location", 0.0, 2 ); return; } PressurePinning::~PressurePinning( ) { return; } void PressurePinning::check_pin_location( const libMesh::MeshBase& mesh ) { // We need to reset to invalid_id since this may not be the first time called _pinned_elem_id = libMesh::DofObject::invalid_id; libMesh::MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const libMesh::MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { const libMesh::Elem* elem = *el; if( elem->contains_point(_pin_location) ) { _pinned_elem_id = elem->id(); break; } } // If we found the point on one of the processors, then we need // to tell all the others. invalid_id is exceedingly large, // so if we found an element, that id should be the smallest mesh.comm().min( _pinned_elem_id ); if( _pinned_elem_id == libMesh::DofObject::invalid_id ) { libMesh::err << "ERROR: Could not locate point " << _pin_location << " in mesh!" << std::endl; libmesh_error(); } } void PressurePinning::pin_value( libMesh::DiffContext &context, const bool request_jacobian, const VariableIndex var, const double penalty ) { // Make sure we've called check_pin_location() and that pin location // is in the mesh somewhere libmesh_assert_not_equal_to( _pinned_elem_id, libMesh::DofObject::invalid_id ); /** \todo pin_location needs to be const. Currently a libMesh restriction. */ AssemblyContext &c = libMesh::libmesh_cast_ref<AssemblyContext&>(context); if( c.get_elem().id() == _pinned_elem_id ) { // This is redundant for vast majority of cases, but we trying to // be prepared for cases involving, e.g. mesh motion that we're not // currently handling. if( !c.get_elem().contains_point(_pin_location) ) { libmesh_error_msg("ERROR: _pin_location not in the current element!"); } libMesh::DenseSubVector<libMesh::Number> &F_var = c.get_elem_residual(var); // residual libMesh::DenseSubMatrix<libMesh::Number> &K_var = c.get_elem_jacobian(var, var); // jacobian // The number of local degrees of freedom in p variable. const unsigned int n_var_dofs = c.get_dof_indices(var).size(); libMesh::Number var_value = c.point_value(var, _pin_location); libMesh::FEType fe_type = c.get_element_fe(var)->get_fe_type(); libMesh::Point point_loc_in_masterelem = libMesh::FEInterface::inverse_map(c.get_dim(), fe_type, &c.get_elem(), _pin_location); std::vector<libMesh::Real> phi(n_var_dofs); for (unsigned int i=0; i != n_var_dofs; i++) phi[i] = libMesh::FEInterface::shape( c.get_dim(), fe_type, &c.get_elem(), i, point_loc_in_masterelem ); for (unsigned int i=0; i != n_var_dofs; i++) { F_var(i) += penalty*(var_value - _pin_value)*phi[i]; /** \todo What the hell is the c.get_elem_solution_derivative() all about? */ if (request_jacobian && c.get_elem_solution_derivative()) { libmesh_assert (c.get_elem_solution_derivative() == 1.0); for (unsigned int j=0; j != n_var_dofs; j++) K_var(i,j) += penalty*phi[i]*phi[j]; } // End if request_jacobian } // End i loop } // End if pin_location return; } } // namespace GRINS <|endoftext|>
<commit_before>// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // XGL tests // // Copyright (C) 2014 LunarG, Inc. // // 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. // Basic rendering tests #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include <xgl.h> #include "gtest-1.7.0/include/gtest/gtest.h" #include "xgldevice.h" class XglRenderTest : public ::testing::Test { public: void CreateImage(XGL_UINT w, XGL_UINT h); void DestroyImage(); void CreateImageView(XGL_IMAGE_VIEW_CREATE_INFO* pCreateInfo, XGL_IMAGE_VIEW* pView); void DestroyImageView(XGL_IMAGE_VIEW imageView); XGL_DEVICE device() {return m_device->device();} protected: XGL_APPLICATION_INFO app_info; XGL_PHYSICAL_GPU objs[MAX_GPUS]; XGL_UINT gpu_count; XGL_IMAGE m_image; XGL_GPU_MEMORY m_image_mem; XglDevice *m_device; virtual void SetUp() { XGL_RESULT err; this->app_info.sType = XGL_STRUCTURE_TYPE_APPLICATION_INFO; this->app_info.pNext = NULL; this->app_info.pAppName = (const XGL_CHAR *) "base"; this->app_info.appVersion = 1; this->app_info.pEngineName = (const XGL_CHAR *) "unittest"; this->app_info.engineVersion = 1; this->app_info.apiVersion = XGL_MAKE_VERSION(0, 22, 0); err = xglInitAndEnumerateGpus(&app_info, NULL, MAX_GPUS, &this->gpu_count, objs); ASSERT_XGL_SUCCESS(err); ASSERT_GE(1, this->gpu_count) << "No GPU available"; m_device = new XglDevice(0, objs[0]); m_device->get_device_queue(); } virtual void TearDown() { xglInitAndEnumerateGpus(&this->app_info, XGL_NULL_HANDLE, 0, &gpu_count, XGL_NULL_HANDLE); } }; void XglRenderTest::CreateImage(XGL_UINT w, XGL_UINT h) { XGL_RESULT err; XGL_IMAGE image; XGL_UINT mipCount; XGL_SIZE size; XGL_FORMAT fmt; XGL_FORMAT_PROPERTIES image_fmt; mipCount = 0; XGL_UINT _w = w; XGL_UINT _h = h; while( ( _w > 0 ) || ( _h > 0 ) ) { _w >>= 1; _h >>= 1; mipCount++; } fmt.channelFormat = XGL_CH_FMT_R8G8B8A8; fmt.numericFormat = XGL_NUM_FMT_UINT; // TODO: Pick known good format rather than just expect common format /* * XXX: What should happen if given NULL HANDLE for the pData argument? * We're not requesting XGL_INFO_TYPE_MEMORY_REQUIREMENTS so there is * an expectation that pData is a valid pointer. * However, why include a returned size value? That implies that the * amount of data may vary and that doesn't work well for using a * fixed structure. */ err = xglGetFormatInfo(this->m_device->device(), fmt, XGL_INFO_TYPE_FORMAT_PROPERTIES, &size, &image_fmt); ASSERT_XGL_SUCCESS(err); // typedef struct _XGL_IMAGE_CREATE_INFO // { // XGL_STRUCTURE_TYPE sType; // Must be XGL_STRUCTURE_TYPE_IMAGE_CREATE_INFO // const XGL_VOID* pNext; // Pointer to next structure. // XGL_IMAGE_TYPE imageType; // XGL_FORMAT format; // XGL_EXTENT3D extent; // XGL_UINT mipLevels; // XGL_UINT arraySize; // XGL_UINT samples; // XGL_IMAGE_TILING tiling; // XGL_FLAGS usage; // XGL_IMAGE_USAGE_FLAGS // XGL_FLAGS flags; // XGL_IMAGE_CREATE_FLAGS // } XGL_IMAGE_CREATE_INFO; XGL_IMAGE_CREATE_INFO imageCreateInfo = {}; imageCreateInfo.sType = XGL_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageCreateInfo.imageType = XGL_IMAGE_2D; imageCreateInfo.format = fmt; imageCreateInfo.arraySize = 1; imageCreateInfo.extent.width = w; imageCreateInfo.extent.height = h; imageCreateInfo.extent.depth = 1; imageCreateInfo.mipLevels = mipCount; imageCreateInfo.samples = 1; imageCreateInfo.tiling = XGL_LINEAR_TILING; // Image usage flags // typedef enum _XGL_IMAGE_USAGE_FLAGS // { // XGL_IMAGE_USAGE_SHADER_ACCESS_READ_BIT = 0x00000001, // XGL_IMAGE_USAGE_SHADER_ACCESS_WRITE_BIT = 0x00000002, // XGL_IMAGE_USAGE_COLOR_ATTACHMENT_BIT = 0x00000004, // XGL_IMAGE_USAGE_DEPTH_STENCIL_BIT = 0x00000008, // } XGL_IMAGE_USAGE_FLAGS; imageCreateInfo.usage = XGL_IMAGE_USAGE_SHADER_ACCESS_WRITE_BIT | XGL_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // XGL_RESULT XGLAPI xglCreateImage( // XGL_DEVICE device, // const XGL_IMAGE_CREATE_INFO* pCreateInfo, // XGL_IMAGE* pImage); err = xglCreateImage(device(), &imageCreateInfo, &m_image); ASSERT_XGL_SUCCESS(err); XGL_MEMORY_REQUIREMENTS mem_req; XGL_UINT data_size; err = xglGetObjectInfo(image, XGL_INFO_TYPE_MEMORY_REQUIREMENTS, &data_size, &mem_req); ASSERT_XGL_SUCCESS(err); ASSERT_EQ(data_size, sizeof(mem_req)); ASSERT_NE(0, mem_req.size) << "xglGetObjectInfo (Event): Failed - expect images to require memory"; // XGL_RESULT XGLAPI xglAllocMemory( // XGL_DEVICE device, // const XGL_MEMORY_ALLOC_INFO* pAllocInfo, // XGL_GPU_MEMORY* pMem); XGL_MEMORY_ALLOC_INFO mem_info; memset(&mem_info, 0, sizeof(mem_info)); mem_info.sType = XGL_STRUCTURE_TYPE_MEMORY_ALLOC_INFO; mem_info.allocationSize = mem_req.size; mem_info.alignment = mem_req.alignment; mem_info.heapCount = mem_req.heapCount; memcpy(mem_info.heaps, mem_req.heaps, sizeof(XGL_UINT)*XGL_MAX_MEMORY_HEAPS); mem_info.memPriority = XGL_MEMORY_PRIORITY_NORMAL; mem_info.flags = XGL_MEMORY_ALLOC_SHAREABLE_BIT; err = xglAllocMemory(device(), &mem_info, &m_image_mem); ASSERT_XGL_SUCCESS(err); err = xglBindObjectMemory(image, m_image_mem, 0); ASSERT_XGL_SUCCESS(err); } void XglRenderTest::DestroyImage() { // All done with image memory, clean up ASSERT_XGL_SUCCESS(xglBindObjectMemory(m_image, XGL_NULL_HANDLE, 0)); ASSERT_XGL_SUCCESS(xglFreeMemory(m_image_mem)); ASSERT_XGL_SUCCESS(xglDestroyObject(m_image)); } void XglRenderTest::CreateImageView(XGL_IMAGE_VIEW_CREATE_INFO *pCreateInfo, XGL_IMAGE_VIEW *pView) { pCreateInfo->image = this->m_image; ASSERT_XGL_SUCCESS(xglCreateImageView(device(), pCreateInfo, pView)); } void XglRenderTest::DestroyImageView(XGL_IMAGE_VIEW imageView) { ASSERT_XGL_SUCCESS(xglDestroyObject(imageView)); } TEST_F(XglRenderTest, DrawTriangleTest) { XGL_FORMAT fmt; XGL_IMAGE_VIEW imageView; XGL_RESULT err; fmt.channelFormat = XGL_CH_FMT_R8G8B8A8; fmt.numericFormat = XGL_NUM_FMT_UINT; CreateImage(512, 256); // typedef struct _XGL_IMAGE_VIEW_CREATE_INFO // { // XGL_STRUCTURE_TYPE sType; // Must be XGL_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO // const XGL_VOID* pNext; // Pointer to next structure // XGL_IMAGE image; // XGL_IMAGE_VIEW_TYPE viewType; // XGL_FORMAT format; // XGL_CHANNEL_MAPPING channels; // XGL_IMAGE_SUBRESOURCE_RANGE subresourceRange; // XGL_FLOAT minLod; // } XGL_IMAGE_VIEW_CREATE_INFO; XGL_IMAGE_VIEW_CREATE_INFO viewInfo = {}; viewInfo.sType = XGL_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; viewInfo.viewType = XGL_IMAGE_VIEW_2D; viewInfo.format = fmt; viewInfo.channels.r = XGL_CHANNEL_SWIZZLE_R; viewInfo.channels.g = XGL_CHANNEL_SWIZZLE_G; viewInfo.channels.b = XGL_CHANNEL_SWIZZLE_B; viewInfo.channels.a = XGL_CHANNEL_SWIZZLE_A; viewInfo.subresourceRange.baseArraySlice = 0; viewInfo.subresourceRange.arraySize = 1; viewInfo.subresourceRange.baseMipLevel = 0; viewInfo.subresourceRange.mipLevels = 1; viewInfo.subresourceRange.aspect = XGL_IMAGE_ASPECT_COLOR; // XGL_RESULT XGLAPI xglCreateImageView( // XGL_DEVICE device, // const XGL_IMAGE_VIEW_CREATE_INFO* pCreateInfo, // XGL_IMAGE_VIEW* pView); CreateImageView(&viewInfo, &imageView); DestroyImageView(imageView); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>tests: Add pipeline init to render test.<commit_after>// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // XGL tests // // Copyright (C) 2014 LunarG, Inc. // // 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. // Basic rendering tests #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include <xgl.h> #include "gtest-1.7.0/include/gtest/gtest.h" #include "xgldevice.h" #include "shader_il.h" class XglRenderTest : public ::testing::Test { public: void CreateImage(XGL_UINT w, XGL_UINT h); void DestroyImage(); void CreateImageView(XGL_IMAGE_VIEW_CREATE_INFO* pCreateInfo, XGL_IMAGE_VIEW* pView); void DestroyImageView(XGL_IMAGE_VIEW imageView); XGL_DEVICE device() {return m_device->device();} void CreateShader(XGL_SHADER *pshader); void InitPipeline(); protected: XGL_APPLICATION_INFO app_info; XGL_PHYSICAL_GPU objs[MAX_GPUS]; XGL_UINT gpu_count; XGL_IMAGE m_image; XGL_GPU_MEMORY m_image_mem; XglDevice *m_device; XGL_CMD_BUFFER m_cmdBuffer; virtual void SetUp() { XGL_RESULT err; this->app_info.sType = XGL_STRUCTURE_TYPE_APPLICATION_INFO; this->app_info.pNext = NULL; this->app_info.pAppName = (const XGL_CHAR *) "base"; this->app_info.appVersion = 1; this->app_info.pEngineName = (const XGL_CHAR *) "unittest"; this->app_info.engineVersion = 1; this->app_info.apiVersion = XGL_MAKE_VERSION(0, 22, 0); err = xglInitAndEnumerateGpus(&app_info, NULL, MAX_GPUS, &this->gpu_count, objs); ASSERT_XGL_SUCCESS(err); ASSERT_GE(1, this->gpu_count) << "No GPU available"; m_device = new XglDevice(0, objs[0]); m_device->get_device_queue(); XGL_CMD_BUFFER_CREATE_INFO info = {}; info.sType = XGL_STRUCTURE_TYPE_CMD_BUFFER_CREATE_INFO; info.queueType = XGL_QUEUE_TYPE_GRAPHICS; err = xglCreateCommandBuffer(device(), &info, &m_cmdBuffer); ASSERT_XGL_SUCCESS(err) << "xglCreateCommandBuffer failed"; } virtual void TearDown() { xglInitAndEnumerateGpus(&this->app_info, XGL_NULL_HANDLE, 0, &gpu_count, XGL_NULL_HANDLE); } }; void XglRenderTest::CreateImage(XGL_UINT w, XGL_UINT h) { XGL_RESULT err; XGL_IMAGE image; XGL_UINT mipCount; XGL_SIZE size; XGL_FORMAT fmt; XGL_FORMAT_PROPERTIES image_fmt; mipCount = 0; XGL_UINT _w = w; XGL_UINT _h = h; while( ( _w > 0 ) || ( _h > 0 ) ) { _w >>= 1; _h >>= 1; mipCount++; } fmt.channelFormat = XGL_CH_FMT_R8G8B8A8; fmt.numericFormat = XGL_NUM_FMT_UINT; // TODO: Pick known good format rather than just expect common format /* * XXX: What should happen if given NULL HANDLE for the pData argument? * We're not requesting XGL_INFO_TYPE_MEMORY_REQUIREMENTS so there is * an expectation that pData is a valid pointer. * However, why include a returned size value? That implies that the * amount of data may vary and that doesn't work well for using a * fixed structure. */ err = xglGetFormatInfo(this->m_device->device(), fmt, XGL_INFO_TYPE_FORMAT_PROPERTIES, &size, &image_fmt); ASSERT_XGL_SUCCESS(err); // typedef struct _XGL_IMAGE_CREATE_INFO // { // XGL_STRUCTURE_TYPE sType; // Must be XGL_STRUCTURE_TYPE_IMAGE_CREATE_INFO // const XGL_VOID* pNext; // Pointer to next structure. // XGL_IMAGE_TYPE imageType; // XGL_FORMAT format; // XGL_EXTENT3D extent; // XGL_UINT mipLevels; // XGL_UINT arraySize; // XGL_UINT samples; // XGL_IMAGE_TILING tiling; // XGL_FLAGS usage; // XGL_IMAGE_USAGE_FLAGS // XGL_FLAGS flags; // XGL_IMAGE_CREATE_FLAGS // } XGL_IMAGE_CREATE_INFO; XGL_IMAGE_CREATE_INFO imageCreateInfo = {}; imageCreateInfo.sType = XGL_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageCreateInfo.imageType = XGL_IMAGE_2D; imageCreateInfo.format = fmt; imageCreateInfo.arraySize = 1; imageCreateInfo.extent.width = w; imageCreateInfo.extent.height = h; imageCreateInfo.extent.depth = 1; imageCreateInfo.mipLevels = mipCount; imageCreateInfo.samples = 1; imageCreateInfo.tiling = XGL_LINEAR_TILING; // Image usage flags // typedef enum _XGL_IMAGE_USAGE_FLAGS // { // XGL_IMAGE_USAGE_SHADER_ACCESS_READ_BIT = 0x00000001, // XGL_IMAGE_USAGE_SHADER_ACCESS_WRITE_BIT = 0x00000002, // XGL_IMAGE_USAGE_COLOR_ATTACHMENT_BIT = 0x00000004, // XGL_IMAGE_USAGE_DEPTH_STENCIL_BIT = 0x00000008, // } XGL_IMAGE_USAGE_FLAGS; imageCreateInfo.usage = XGL_IMAGE_USAGE_SHADER_ACCESS_WRITE_BIT | XGL_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // XGL_RESULT XGLAPI xglCreateImage( // XGL_DEVICE device, // const XGL_IMAGE_CREATE_INFO* pCreateInfo, // XGL_IMAGE* pImage); err = xglCreateImage(device(), &imageCreateInfo, &m_image); ASSERT_XGL_SUCCESS(err); XGL_MEMORY_REQUIREMENTS mem_req; XGL_UINT data_size; err = xglGetObjectInfo(image, XGL_INFO_TYPE_MEMORY_REQUIREMENTS, &data_size, &mem_req); ASSERT_XGL_SUCCESS(err); ASSERT_EQ(data_size, sizeof(mem_req)); ASSERT_NE(0, mem_req.size) << "xglGetObjectInfo (Event): Failed - expect images to require memory"; // XGL_RESULT XGLAPI xglAllocMemory( // XGL_DEVICE device, // const XGL_MEMORY_ALLOC_INFO* pAllocInfo, // XGL_GPU_MEMORY* pMem); XGL_MEMORY_ALLOC_INFO mem_info; memset(&mem_info, 0, sizeof(mem_info)); mem_info.sType = XGL_STRUCTURE_TYPE_MEMORY_ALLOC_INFO; mem_info.allocationSize = mem_req.size; mem_info.alignment = mem_req.alignment; mem_info.heapCount = mem_req.heapCount; memcpy(mem_info.heaps, mem_req.heaps, sizeof(XGL_UINT)*XGL_MAX_MEMORY_HEAPS); mem_info.memPriority = XGL_MEMORY_PRIORITY_NORMAL; mem_info.flags = XGL_MEMORY_ALLOC_SHAREABLE_BIT; err = xglAllocMemory(device(), &mem_info, &m_image_mem); ASSERT_XGL_SUCCESS(err); err = xglBindObjectMemory(image, m_image_mem, 0); ASSERT_XGL_SUCCESS(err); } void XglRenderTest::DestroyImage() { // All done with image memory, clean up ASSERT_XGL_SUCCESS(xglBindObjectMemory(m_image, XGL_NULL_HANDLE, 0)); ASSERT_XGL_SUCCESS(xglFreeMemory(m_image_mem)); ASSERT_XGL_SUCCESS(xglDestroyObject(m_image)); } void XglRenderTest::CreateImageView(XGL_IMAGE_VIEW_CREATE_INFO *pCreateInfo, XGL_IMAGE_VIEW *pView) { pCreateInfo->image = this->m_image; ASSERT_XGL_SUCCESS(xglCreateImageView(device(), pCreateInfo, pView)); } void XglRenderTest::DestroyImageView(XGL_IMAGE_VIEW imageView) { ASSERT_XGL_SUCCESS(xglDestroyObject(imageView)); } void XglRenderTest::CreateShader(XGL_SHADER *pshader) { void *code; uint32_t codeSize; struct bil_header *pBIL; XGL_RESULT err; codeSize = sizeof(struct bil_header) + 100; code = malloc(codeSize); ASSERT_TRUE(NULL != code) << "malloc failed!"; memset(code, 0, codeSize); // Indicate that this is BIL data. pBIL = (struct bil_header *) code; pBIL->bil_magic = BILMagicNumber; pBIL->bil_version = BILVersion; XGL_SHADER_CREATE_INFO createInfo; XGL_SHADER shader; createInfo.sType = XGL_STRUCTURE_TYPE_SHADER_CREATE_INFO; createInfo.pNext = NULL; createInfo.pCode = code; createInfo.codeSize = codeSize; createInfo.flags = 0; err = xglCreateShader(device(), &createInfo, &shader); ASSERT_XGL_SUCCESS(err); ASSERT_XGL_SUCCESS(xglDestroyObject(shader)); *pshader = shader; } TEST_F(XglRenderTest, DrawTriangleTest) { XGL_RESULT err; XGL_GRAPHICS_PIPELINE_CREATE_INFO info = {}; XGL_SHADER vs, ps; XGL_PIPELINE_SHADER_STAGE_CREATE_INFO vs_stage; XGL_PIPELINE_SHADER_STAGE_CREATE_INFO ps_stage; XGL_PIPELINE pipeline; /* * Define descriptor slots for vertex shader. */ XGL_DESCRIPTOR_SLOT_INFO ds_vs = { XGL_SLOT_SHADER_RESOURCE, // XGL_DESCRIPTOR_SET_SLOT_TYPE 1 // shaderEntityIndex }; CreateShader(&vs); vs_stage.sType = XGL_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; vs_stage.pNext = XGL_NULL_HANDLE; vs_stage.shader.stage = XGL_SHADER_STAGE_VERTEX; vs_stage.shader.shader = vs; vs_stage.shader.descriptorSetMapping[0].descriptorCount = 1; vs_stage.shader.descriptorSetMapping[0].pDescriptorInfo = &ds_vs; vs_stage.shader.linkConstBufferCount = 0; vs_stage.shader.pLinkConstBufferInfo = XGL_NULL_HANDLE; vs_stage.shader.dynamicMemoryViewMapping.slotObjectType = XGL_SLOT_SHADER_RESOURCE; vs_stage.shader.dynamicMemoryViewMapping.shaderEntityIndex = 0; CreateShader(&ps); ps_stage.sType = XGL_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; ps_stage.pNext = &vs_stage; ps_stage.shader.stage = XGL_SHADER_STAGE_FRAGMENT; ps_stage.shader.shader = ps; ps_stage.shader.descriptorSetMapping[0].descriptorCount = 1; // TODO: Do we need a descriptor set mapping for fragment? ps_stage.shader.descriptorSetMapping[0].pDescriptorInfo = &ds_vs; ps_stage.shader.linkConstBufferCount = 0; ps_stage.shader.pLinkConstBufferInfo = XGL_NULL_HANDLE; ps_stage.shader.dynamicMemoryViewMapping.slotObjectType = XGL_SLOT_SHADER_RESOURCE; ps_stage.shader.dynamicMemoryViewMapping.shaderEntityIndex = 0; XGL_PIPELINE_IA_STATE_CREATE_INFO ia_state = { XGL_STRUCTURE_TYPE_PIPELINE_IA_STATE_CREATE_INFO, // sType &ps_stage, // pNext XGL_TOPOLOGY_TRIANGLE_LIST, // XGL_PRIMITIVE_TOPOLOGY XGL_FALSE, // disableVertexReuse XGL_PROVOKING_VERTEX_LAST, // XGL_PROVOKING_VERTEX_CONVENTION XGL_FALSE, // primitiveRestartEnable 0 // primitiveRestartIndex }; XGL_PIPELINE_RS_STATE_CREATE_INFO rs_state = { XGL_STRUCTURE_TYPE_PIPELINE_RS_STATE_CREATE_INFO, &ia_state, XGL_FALSE, // depthClipEnable XGL_FALSE, // rasterizerDiscardEnable 1.0 // pointSize }; XGL_PIPELINE_CB_STATE cb_state = { XGL_STRUCTURE_TYPE_PIPELINE_CB_STATE_CREATE_INFO, &rs_state, XGL_FALSE, // alphaToCoverageEnable XGL_FALSE, // dualSourceBlendEnable XGL_LOGIC_OP_COPY, // XGL_LOGIC_OP { // XGL_PIPELINE_CB_ATTACHMENT_STATE { XGL_FALSE, // blendEnable {XGL_CH_FMT_R8G8B8A8, XGL_NUM_FMT_UINT}, // XGL_FORMAT 0xF // channelWriteMask } } }; // TODO: Should take depth buffer format from queried formats XGL_PIPELINE_DB_STATE_CREATE_INFO db_state = { XGL_STRUCTURE_TYPE_PIPELINE_DB_STATE_CREATE_INFO, &cb_state, {XGL_CH_FMT_R32, XGL_NUM_FMT_DS} // XGL_FORMAT }; info.sType = XGL_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; info.pNext = &db_state; info.flags = 0; err = xglCreateGraphicsPipeline(device(), &info, &pipeline); ASSERT_XGL_SUCCESS(err); ASSERT_XGL_SUCCESS(xglDestroyObject(pipeline)); ASSERT_XGL_SUCCESS(xglDestroyObject(ps)); ASSERT_XGL_SUCCESS(xglDestroyObject(vs)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief ポート定義クラス @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "port.hpp" #include "common/port_map.hpp" // ポートの配置 // P4_2(1): LCD_SCK ,SD_CLK(5) // P3_7(2): LCD_/CS // /RES(3): (System reset) // P4_7(4): ,SD_DO/DAT0(7) // VSS:(5) (Power GND) // P4_6(6): XIN (高精度なクロック用) // VCC(7): (Power +V) // MODE(8): (System mode) // P3_5(9): I2C_SDA // P3_4(10): ,SD_/CS(1) // P1_0(20): AN0 (keep) // P1_1(19): AN1 (keep) // P1_2(18): AN2 (keep) // P1_3(17): AN3 (keep) // P1_4(16): TXD0 (keep) // P1_5(15): RXD0 (keep) // P1_6(14): LCD_A0 (share) // P1_7(13): TRJIO (keep) // P4_5(12): LCD_SDA ,SD_DI/CMD(2) // P3_3(11): I2C_SCL // I2C ポートの定義クラス struct scl_sda { void init() const { // オープン・ドレイン設定 utils::PORT_MAP(utils::port_map::P35::PORT); utils::PORT_MAP(utils::port_map::P33::PORT); device::POD3.B5 = 1; // SDA device::POD3.B3 = 1; // SCL } void scl_dir(bool b) const { device::PD3.B3 = b; } // SCL 方向 (0:in, 1:out) void scl_out(bool b) const { device::P3.B3 = b; } // SCL 出力 bool scl_inp() const { return device::P3.B3(); } // SCL 入力 void sda_dir(bool b) const { device::PD3.B5 = b; } // SDA 方向 (0:in, 1:out) void sda_out(bool b) const { device::P3.B5 = b; } // SDA 出力 bool sda_inp() const { return device::P3.B5(); } // SDA 入力 }; // SPI ベース・ポートの定義クラス struct spi_base { void init() const { utils::PORT_MAP(utils::port_map::P42::PORT); utils::PORT_MAP(utils::port_map::P45::PORT); utils::PORT_MAP(utils::port_map::P47::PORT); device::PD4.B2 = 1; // LCD_SCK ,SD_CLK device::PD4.B5 = 1; // LCD_SDA ,SD_DI/CMD device::PD4.B7 = 0; // ,SD_DO/DAT0 } void scl_out(bool b) const { device::P4.B2 = b; } void sda_out(bool b) const { device::P4.B5 = b; } bool sda_inp() const { return device::P4.B7(); } }; // SPI コントロール・ポートの定義クラス struct spi_ctrl { void init() const { utils::PORT_MAP(utils::port_map::P16::PORT); utils::PORT_MAP(utils::port_map::P37::PORT); utils::PORT_MAP(utils::port_map::P34::PORT); device::PD1.B6 = 1; // LCD_A0 device::PD3.B7 = 1; // LCD_/CS device::PD3.B4 = 1; // ,SD_/CS } void a0_out(bool b) const { device::P1.B6 = b; } void lcd_sel(bool b) const { device::P3.B7 = b; } void sd_sel(bool b) const { device::P3.B4 = b; } }; <commit_msg>remove file<commit_after><|endoftext|>
<commit_before>// @(#)root/graf:$Id$ // Author: Rene Brun 17/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TStyle.h" #include "TPaveLabel.h" #include "TLatex.h" #include "TVirtualPad.h" ClassImp(TPaveLabel) //______________________________________________________________________________ //* A PaveLabel is a Pave (see TPave) with a text centered in the Pave. //Begin_Html /* <img src="gif/pavelabel.gif"> */ //End_Html // //______________________________________________________________________________ TPaveLabel::TPaveLabel(): TPave(), TAttText() { // Pavelabel default constructor. } //______________________________________________________________________________ TPaveLabel::TPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label, Option_t *option) :TPave(x1,y1,x2,y2,3,option), TAttText(22,0,1,gStyle->GetTextFont(),0.99) { // Pavelabel normal constructor. // // a PaveLabel is a Pave with a label centered in the Pave // The Pave is by default defined bith bordersize=5 and option ="br". // The text size is automatically computed as a function of the pave size. // // IMPORTANT NOTE: // Because TPave objects (and objects deriving from TPave) have their // master coordinate system in NDC, one cannot use the TBox functions // SetX1,SetY1,SetX2,SetY2 to change the corner coordinates. One should use // instead SetX1NDC, SetY1NDC, SetX2NDC, SetY2NDC. fLabel = label; } //______________________________________________________________________________ TPaveLabel::~TPaveLabel() { // Pavelabel default destructor. } //______________________________________________________________________________ TPaveLabel::TPaveLabel(const TPaveLabel &pavelabel) : TPave(pavelabel), TAttText(pavelabel) { // Pavelabel copy constructor. ((TPaveLabel&)pavelabel).Copy(*this); } //______________________________________________________________________________ void TPaveLabel::Copy(TObject &obj) const { // Copy this pavelabel to pavelabel. TPave::Copy(obj); TAttText::Copy(((TPaveLabel&)obj)); ((TPaveLabel&)obj).fLabel = fLabel; } //______________________________________________________________________________ void TPaveLabel::Draw(Option_t *option) { // Draw this pavelabel with its current attributes. Option_t *opt; if (option && strlen(option)) opt = option; else opt = GetOption(); AppendPad(opt); } //______________________________________________________________________________ void TPaveLabel::DrawPaveLabel(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char *label, Option_t *option) { // Draw this pavelabel with new coordinates. TPaveLabel *newpavelabel = new TPaveLabel(x1,y1,x2,y2,label,option); newpavelabel->SetBit(kCanDelete); newpavelabel->AppendPad(); } //______________________________________________________________________________ void TPaveLabel::Paint(Option_t *option) { // Paint this pavelabel with its current attributes. // Convert from NDC to pad coordinates TPave::ConvertNDCtoPad(); PaintPaveLabel(fX1, fY1, fX2, fY2, GetLabel(), strlen(option)?option:GetOption()); } //______________________________________________________________________________ void TPaveLabel::PaintPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label ,Option_t *option) { // Draw this pavelabel with new coordinates. Int_t nch = strlen(label); // Draw the pave TPave::PaintPave(x1,y1,x2,y2,GetBorderSize(),option); Float_t nspecials = 0; for (Int_t i=0;i<nch;i++) { if (label[i] == '!') nspecials += 1; if (label[i] == '?') nspecials += 1.5; if (label[i] == '#') nspecials += 1; if (label[i] == '`') nspecials += 1; if (label[i] == '^') nspecials += 1.5; if (label[i] == '~') nspecials += 1; if (label[i] == '&') nspecials += 2; if (label[i] == '\\') nspecials += 3; // octal characters very likely } nch -= Int_t(nspecials + 0.5); if (nch <= 0) return; // Draw label Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2()); Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1()); Double_t labelsize, textsize = GetTextSize(); Int_t automat = 0; if (GetTextFont()%10 > 2) { // fixed size font specified in pixels labelsize = GetTextSize(); } else { if (TMath::Abs(textsize -0.99) < 0.001) automat = 1; if (textsize == 0) { textsize = 0.99; automat = 1;} Int_t ypixel = TMath::Abs(gPad->YtoPixel(y1) - gPad->YtoPixel(y2)); labelsize = textsize*ypixel/hh; if (wh < hh) labelsize *= hh/wh; } TLatex latex; latex.SetTextAngle(GetTextAngle()); latex.SetTextFont(GetTextFont()); latex.SetTextAlign(GetTextAlign()); latex.SetTextColor(GetTextColor()); latex.SetTextSize(labelsize); if (automat) { UInt_t w=0,h=0,w1=0; latex.GetTextExtent(w,h,GetTitle()); labelsize = h/hh; Double_t wxlabel = TMath::Abs(gPad->XtoPixel(x2) - gPad->XtoPixel(x1)); latex.GetTextExtent(w1,h,GetTitle()); while (w > 0.99*wxlabel) { labelsize *= 0.99*wxlabel/w; latex.SetTextSize(labelsize); latex.GetTextExtent(w,h,GetTitle()); if (w==w1) break; else w1=w; } if (h < 1) h = 1; if (h==1) { labelsize = Double_t(h)/hh; if (wh < hh) labelsize *= hh/wh; latex.SetTextSize(labelsize); } } Int_t halign = GetTextAlign()/10; Int_t valign = GetTextAlign()%10; Double_t x = 0.5*(x1+x2); if (halign == 1) x = x1 + 0.02*(x2-x1); if (halign == 3) x = x2 - 0.02*(x2-x1); Double_t y = 0.5*(y1+y2); if (valign == 1) y = y1 + 0.02*(y2-y1); if (valign == 3) y = y2 - 0.02*(y2-y1); latex.PaintLatex(x, y, GetTextAngle(),labelsize,GetLabel()); } //______________________________________________________________________________ void TPaveLabel::SavePrimitive(ostream &out, Option_t * /*= ""*/) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TPaveLabel::Class())) { out<<" "; } else { out<<" TPaveLabel *"; } TString s = fLabel.Data(); s.ReplaceAll("\"","\\\""); if (fOption.Contains("NDC")) { out<<"pl = new TPaveLabel("<<fX1NDC<<","<<fY1NDC<<","<<fX2NDC<<","<<fY2NDC <<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl; } else { out<<"pl = new TPaveLabel("<<gPad->PadtoX(fX1)<<","<<gPad->PadtoY(fY1)<<","<<gPad->PadtoX(fX2)<<","<<gPad->PadtoY(fY2) <<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl; } if (fBorderSize != 3) { out<<" pl->SetBorderSize("<<fBorderSize<<");"<<endl; } SaveFillAttributes(out,"pl",19,1001); SaveLineAttributes(out,"pl",1,1,1); SaveTextAttributes(out,"pl",22,0,1,62,0); out<<" pl->Draw();"<<endl; } <commit_msg>Fix coverity report DIVIDE_BY_ZERO<commit_after>// @(#)root/graf:$Id$ // Author: Rene Brun 17/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TStyle.h" #include "TPaveLabel.h" #include "TLatex.h" #include "TVirtualPad.h" ClassImp(TPaveLabel) //______________________________________________________________________________ //* A PaveLabel is a Pave (see TPave) with a text centered in the Pave. //Begin_Html /* <img src="gif/pavelabel.gif"> */ //End_Html // //______________________________________________________________________________ TPaveLabel::TPaveLabel(): TPave(), TAttText() { // Pavelabel default constructor. } //______________________________________________________________________________ TPaveLabel::TPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label, Option_t *option) :TPave(x1,y1,x2,y2,3,option), TAttText(22,0,1,gStyle->GetTextFont(),0.99) { // Pavelabel normal constructor. // // a PaveLabel is a Pave with a label centered in the Pave // The Pave is by default defined bith bordersize=5 and option ="br". // The text size is automatically computed as a function of the pave size. // // IMPORTANT NOTE: // Because TPave objects (and objects deriving from TPave) have their // master coordinate system in NDC, one cannot use the TBox functions // SetX1,SetY1,SetX2,SetY2 to change the corner coordinates. One should use // instead SetX1NDC, SetY1NDC, SetX2NDC, SetY2NDC. fLabel = label; } //______________________________________________________________________________ TPaveLabel::~TPaveLabel() { // Pavelabel default destructor. } //______________________________________________________________________________ TPaveLabel::TPaveLabel(const TPaveLabel &pavelabel) : TPave(pavelabel), TAttText(pavelabel) { // Pavelabel copy constructor. ((TPaveLabel&)pavelabel).Copy(*this); } //______________________________________________________________________________ void TPaveLabel::Copy(TObject &obj) const { // Copy this pavelabel to pavelabel. TPave::Copy(obj); TAttText::Copy(((TPaveLabel&)obj)); ((TPaveLabel&)obj).fLabel = fLabel; } //______________________________________________________________________________ void TPaveLabel::Draw(Option_t *option) { // Draw this pavelabel with its current attributes. Option_t *opt; if (option && strlen(option)) opt = option; else opt = GetOption(); AppendPad(opt); } //______________________________________________________________________________ void TPaveLabel::DrawPaveLabel(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char *label, Option_t *option) { // Draw this pavelabel with new coordinates. TPaveLabel *newpavelabel = new TPaveLabel(x1,y1,x2,y2,label,option); newpavelabel->SetBit(kCanDelete); newpavelabel->AppendPad(); } //______________________________________________________________________________ void TPaveLabel::Paint(Option_t *option) { // Paint this pavelabel with its current attributes. // Convert from NDC to pad coordinates TPave::ConvertNDCtoPad(); PaintPaveLabel(fX1, fY1, fX2, fY2, GetLabel(), strlen(option)?option:GetOption()); } //______________________________________________________________________________ void TPaveLabel::PaintPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label ,Option_t *option) { // Draw this pavelabel with new coordinates. Int_t nch = strlen(label); // Draw the pave TPave::PaintPave(x1,y1,x2,y2,GetBorderSize(),option); Float_t nspecials = 0; for (Int_t i=0;i<nch;i++) { if (label[i] == '!') nspecials += 1; if (label[i] == '?') nspecials += 1.5; if (label[i] == '#') nspecials += 1; if (label[i] == '`') nspecials += 1; if (label[i] == '^') nspecials += 1.5; if (label[i] == '~') nspecials += 1; if (label[i] == '&') nspecials += 2; if (label[i] == '\\') nspecials += 3; // octal characters very likely } nch -= Int_t(nspecials + 0.5); if (nch <= 0) return; // Draw label Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2()); Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1()); Double_t labelsize, textsize = GetTextSize(); Int_t automat = 0; if (GetTextFont()%10 > 2) { // fixed size font specified in pixels labelsize = GetTextSize(); } else { if (TMath::Abs(textsize -0.99) < 0.001) automat = 1; if (textsize == 0) { textsize = 0.99; automat = 1;} Int_t ypixel = TMath::Abs(gPad->YtoPixel(y1) - gPad->YtoPixel(y2)); labelsize = textsize*ypixel/hh; if (wh < hh) labelsize *= hh/wh; } TLatex latex; latex.SetTextAngle(GetTextAngle()); latex.SetTextFont(GetTextFont()); latex.SetTextAlign(GetTextAlign()); latex.SetTextColor(GetTextColor()); latex.SetTextSize(labelsize); if (automat) { UInt_t w=0,h=0,w1=0; latex.GetTextExtent(w,h,GetTitle()); if (!w) return; labelsize = h/hh; Double_t wxlabel = TMath::Abs(gPad->XtoPixel(x2) - gPad->XtoPixel(x1)); latex.GetTextExtent(w1,h,GetTitle()); while (w > 0.99*wxlabel) { labelsize *= 0.99*wxlabel/w; latex.SetTextSize(labelsize); latex.GetTextExtent(w,h,GetTitle()); if (w==w1) break; else w1=w; } if (h < 1) h = 1; if (h==1) { labelsize = Double_t(h)/hh; if (wh < hh) labelsize *= hh/wh; latex.SetTextSize(labelsize); } } Int_t halign = GetTextAlign()/10; Int_t valign = GetTextAlign()%10; Double_t x = 0.5*(x1+x2); if (halign == 1) x = x1 + 0.02*(x2-x1); if (halign == 3) x = x2 - 0.02*(x2-x1); Double_t y = 0.5*(y1+y2); if (valign == 1) y = y1 + 0.02*(y2-y1); if (valign == 3) y = y2 - 0.02*(y2-y1); latex.PaintLatex(x, y, GetTextAngle(),labelsize,GetLabel()); } //______________________________________________________________________________ void TPaveLabel::SavePrimitive(ostream &out, Option_t * /*= ""*/) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TPaveLabel::Class())) { out<<" "; } else { out<<" TPaveLabel *"; } TString s = fLabel.Data(); s.ReplaceAll("\"","\\\""); if (fOption.Contains("NDC")) { out<<"pl = new TPaveLabel("<<fX1NDC<<","<<fY1NDC<<","<<fX2NDC<<","<<fY2NDC <<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl; } else { out<<"pl = new TPaveLabel("<<gPad->PadtoX(fX1)<<","<<gPad->PadtoY(fY1)<<","<<gPad->PadtoX(fX2)<<","<<gPad->PadtoY(fY2) <<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl; } if (fBorderSize != 3) { out<<" pl->SetBorderSize("<<fBorderSize<<");"<<endl; } SaveFillAttributes(out,"pl",19,1001); SaveLineAttributes(out,"pl",1,1,1); SaveTextAttributes(out,"pl",22,0,1,62,0); out<<" pl->Draw();"<<endl; } <|endoftext|>
<commit_before>/****************************************************************************** Copyright 2019 Allied Telesis Labs Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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 <buildsys.h> static bool directory_exists(const std::string & dir) { struct stat info; if(stat(dir.c_str(), &info) != 0) { /* Nothing here */ return false; } else if(S_ISDIR(info.st_mode)) { /* Actually a directory */ return true; } /* Something other than a directory */ return false; } static bool refspec_is_commitid(const std::string & refspec) { if(refspec.length() != 40) { return false; } for(char const &c:refspec) { if(!isxdigit(c)) { return false; } } return true; } static std::string git_hash_ref(const std::string & gdir, const std::string & refspec) { std::string cmd = string_format("cd %s && git rev-parse %s", gdir.c_str(), refspec.c_str()); FILE *f = popen(cmd.c_str(), "r"); if(f == NULL) { throw CustomException("git rev-parse ref failed"); } char *commit = (char *) calloc(41, sizeof(char)); fread(commit, sizeof(char), 40, f); pclose(f); std::string ret = std::string(commit); free(commit); return ret; } static std::string git_hash(const std::string & gdir) { return git_hash_ref(gdir, "HEAD"); } static std::string git_diff_hash(const std::string & gdir) { std::string cmd = string_format("cd %s && git diff HEAD | sha1sum", gdir.c_str()); FILE *f = popen(cmd.c_str(), "r"); if(f == NULL) { throw CustomException("git diff | sha1sum failed"); } char *delta_hash = (char *) calloc(41, sizeof(char)); fread(delta_hash, sizeof(char), 40, f); pclose(f); std::string ret(delta_hash); free(delta_hash); return ret; } static std::string git_remote(const std::string & gdir, const std::string & remote) { std::string cmd = string_format("cd %s && git config --local --get remote.%s.url", gdir.c_str(), remote.c_str()); FILE *f = popen(cmd.c_str(), "r"); if(f == NULL) { throw CustomException("git config --local --get remote. .url failed"); } char *Remote = (char *) calloc(1025, sizeof(char)); fread(Remote, sizeof(char), 1024, f); pclose(f); std::string ret(Remote); free(Remote); return ret; } GitDirExtractionUnit::GitDirExtractionUnit(const std::string & git_dir, const std::string & to_dir) { this->uri = git_dir; this->hash = git_hash(this->uri); this->toDir = to_dir; } GitDirExtractionUnit::GitDirExtractionUnit() { } bool GitDirExtractionUnit::isDirty() { if(!directory_exists(this->localPath())) { /* If the source directory doesn't exist, then it can't be dirty */ return false; } std::string cmd = string_format("cd %s && git diff --quiet HEAD", this->localPath().c_str()); int res = std::system(cmd.c_str()); return (res != 0); } std::string GitDirExtractionUnit::dirtyHash() { return git_diff_hash(this->localPath()); } GitExtractionUnit::GitExtractionUnit(const std::string & remote, const std::string & local, std::string refspec, Package * P) { this->uri = remote; this->local = P->getWorld()->getWorkingDir() + "/source/" + local; this->refspec = refspec; this->P = P; this->fetched = false; } bool GitExtractionUnit::updateOrigin() { std::string location = this->uri; std::string source_dir = this->local; std::string remote_url = git_remote(source_dir, "origin"); if(strcmp(remote_url.c_str(), location.c_str()) != 0) { std::unique_ptr < PackageCmd > pc(new PackageCmd(source_dir.c_str(), "git")); pc->addArg("remote"); // If the remote doesn't exist, add it if(strcmp(remote_url.c_str(), "") == 0) { pc->addArg("add"); } else { pc->addArg("set-url"); } pc->addArg("origin"); pc->addArg(location.c_str()); if(!pc->Run(this->P)) { throw CustomException("Failed: git remote set-url origin"); } // Forcibly fetch if the remote url has change, // if the ref is origin the user wont get what they wanted otherwise pc.reset(new PackageCmd(source_dir.c_str(), "git")); pc->addArg("fetch"); pc->addArg("origin"); pc->addArg("--tags"); if(!pc->Run(this->P)) { throw CustomException("Failed: git fetch origin --tags"); } } return true; } bool GitExtractionUnit::fetch(BuildDir * d) { std::string location = this->uri; std::string source_dir = this->local; const char *cwd = d->getWorld()->getWorkingDir().c_str(); bool exists = directory_exists(source_dir); std::unique_ptr < PackageCmd > pc(new PackageCmd(exists ? source_dir.c_str() : cwd, "git")); if(exists) { /* Update the origin */ this->updateOrigin(); /* Check if the commit is already present */ std::string cmd = "cd " + source_dir + "; git cat-file -e " + this->refspec + " 2>/dev/null"; if(std::system(cmd.c_str()) != 0) { /* If not, fetch everything from origin */ pc->addArg("fetch"); pc->addArg("origin"); pc->addArg("--tags"); if(!pc->Run(this->P)) { throw CustomException("Failed: git fetch origin --tags"); } } } else { pc->addArg("clone"); pc->addArg("-n"); pc->addArg(location.c_str()); pc->addArg(source_dir.c_str()); if(!pc->Run(this->P)) throw CustomException("Failed to git clone"); } if(this->refspec.compare("HEAD") == 0) { // Don't touch it } else { std::string cmd = "cd " + source_dir + "; git show-ref --quiet --verify -- refs/heads/" + this->refspec; if(std::system(cmd.c_str()) == 0) { std::string head_hash = git_hash_ref(source_dir, "HEAD"); std::string branch_hash = git_hash_ref(source_dir, this->refspec); if(strcmp(head_hash.c_str(), branch_hash.c_str())) { throw CustomException("Asked to use branch: " + this->refspec + ", but " + source_dir + " is off somewhere else"); } } else { pc.reset(new PackageCmd(source_dir.c_str(), "git")); // switch to refspec pc->addArg("checkout"); pc->addArg("-q"); pc->addArg("--detach"); pc->addArg(this->refspec.c_str()); if(!pc->Run(this->P)) throw CustomException("Failed to checkout"); } } bool res = true; std::string hash = git_hash(source_dir); if(!this->hash.empty()) { if(strcmp(this->hash.c_str(), hash.c_str()) != 0) { log(this->P, "Hash mismatch for %s\n(committed to %s, providing %s)\n", this->uri.c_str(), this->hash.c_str(), hash.c_str()); res = false; } } else { this->hash = hash; } this->fetched = res; return res; } std::string GitExtractionUnit::HASH() { if(refspec_is_commitid(this->refspec)) { this->hash = std::string(this->refspec); } else { std::string digest_name = string_format("%s#%s", this->uri.c_str(), this->refspec.c_str()); /* Check if the package contains pre-computed hashes */ std::string Hash = P->getFileHash(digest_name); if(Hash.empty()) { this->fetch(P->builddir()); } else { this->hash = Hash; } } return this->hash; } bool GitExtractionUnit::extract(Package * P, BuildDir * bd) { // make sure it has been fetched if(!this->fetched) { if(!this->fetch(bd)) { return false; } } // copy to work dir std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "cp")); pc->addArg("-dpRuf"); pc->addArg(this->localPath()); pc->addArg("."); if(!pc->Run(P)) throw CustomException("Failed to checkout"); return true; } bool LinkGitDirExtractionUnit::extract(Package * P, BuildDir * bd) { std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "ln")); pc->addArg("-sfT"); if(this->uri[0] == '.') { std::string arg = P->getWorld()->getWorkingDir() + "/" + this->uri; pc->addArg(arg); } else { pc->addArg(this->uri); } pc->addArg(this->toDir); if(!pc->Run(P)) { throw CustomException("Operation failed"); } return true; } bool CopyGitDirExtractionUnit::extract(Package * P, BuildDir * bd) { std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "cp")); pc->addArg("-dpRuf"); if(this->uri[0] == '.') { std::string arg = P->getWorld()->getWorkingDir() + "/" + this->uri; pc->addArg(arg); } else { pc->addArg(this->uri); } pc->addArg(this->toDir); if(!pc->Run(P)) { throw CustomException("Operation failed"); } return true; } <commit_msg>git: Use string rather than 'char *'<commit_after>/****************************************************************************** Copyright 2019 Allied Telesis Labs Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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 <buildsys.h> static bool directory_exists(const std::string & dir) { struct stat info; if(stat(dir.c_str(), &info) != 0) { /* Nothing here */ return false; } else if(S_ISDIR(info.st_mode)) { /* Actually a directory */ return true; } /* Something other than a directory */ return false; } static bool refspec_is_commitid(const std::string & refspec) { if(refspec.length() != 40) { return false; } for(char const &c:refspec) { if(!isxdigit(c)) { return false; } } return true; } static std::string git_hash_ref(const std::string & gdir, const std::string & refspec) { std::string cmd = string_format("cd %s && git rev-parse %s", gdir.c_str(), refspec.c_str()); FILE *f = popen(cmd.c_str(), "r"); if(f == NULL) { throw CustomException("git rev-parse ref failed"); } char *commit = (char *) calloc(41, sizeof(char)); fread(commit, sizeof(char), 40, f); pclose(f); std::string ret = std::string(commit); free(commit); return ret; } static std::string git_hash(const std::string & gdir) { return git_hash_ref(gdir, "HEAD"); } static std::string git_diff_hash(const std::string & gdir) { std::string cmd = string_format("cd %s && git diff HEAD | sha1sum", gdir.c_str()); FILE *f = popen(cmd.c_str(), "r"); if(f == NULL) { throw CustomException("git diff | sha1sum failed"); } char *delta_hash = (char *) calloc(41, sizeof(char)); fread(delta_hash, sizeof(char), 40, f); pclose(f); std::string ret(delta_hash); free(delta_hash); return ret; } static std::string git_remote(const std::string & gdir, const std::string & remote) { std::string cmd = string_format("cd %s && git config --local --get remote.%s.url", gdir.c_str(), remote.c_str()); FILE *f = popen(cmd.c_str(), "r"); if(f == NULL) { throw CustomException("git config --local --get remote. .url failed"); } char *Remote = (char *) calloc(1025, sizeof(char)); fread(Remote, sizeof(char), 1024, f); pclose(f); std::string ret(Remote); free(Remote); return ret; } GitDirExtractionUnit::GitDirExtractionUnit(const std::string & git_dir, const std::string & to_dir) { this->uri = git_dir; this->hash = git_hash(this->uri); this->toDir = to_dir; } GitDirExtractionUnit::GitDirExtractionUnit() { } bool GitDirExtractionUnit::isDirty() { if(!directory_exists(this->localPath())) { /* If the source directory doesn't exist, then it can't be dirty */ return false; } std::string cmd = string_format("cd %s && git diff --quiet HEAD", this->localPath().c_str()); int res = std::system(cmd.c_str()); return (res != 0); } std::string GitDirExtractionUnit::dirtyHash() { return git_diff_hash(this->localPath()); } GitExtractionUnit::GitExtractionUnit(const std::string & remote, const std::string & local, std::string refspec, Package * P) { this->uri = remote; this->local = P->getWorld()->getWorkingDir() + "/source/" + local; this->refspec = refspec; this->P = P; this->fetched = false; } bool GitExtractionUnit::updateOrigin() { std::string location = this->uri; std::string source_dir = this->local; std::string remote_url = git_remote(source_dir, "origin"); if(strcmp(remote_url.c_str(), location.c_str()) != 0) { std::unique_ptr < PackageCmd > pc(new PackageCmd(source_dir.c_str(), "git")); pc->addArg("remote"); // If the remote doesn't exist, add it if(strcmp(remote_url.c_str(), "") == 0) { pc->addArg("add"); } else { pc->addArg("set-url"); } pc->addArg("origin"); pc->addArg(location.c_str()); if(!pc->Run(this->P)) { throw CustomException("Failed: git remote set-url origin"); } // Forcibly fetch if the remote url has change, // if the ref is origin the user wont get what they wanted otherwise pc.reset(new PackageCmd(source_dir.c_str(), "git")); pc->addArg("fetch"); pc->addArg("origin"); pc->addArg("--tags"); if(!pc->Run(this->P)) { throw CustomException("Failed: git fetch origin --tags"); } } return true; } bool GitExtractionUnit::fetch(BuildDir * d) { std::string location = this->uri; std::string source_dir = this->local; std::string cwd = d->getWorld()->getWorkingDir(); bool exists = directory_exists(source_dir); std::unique_ptr < PackageCmd > pc(new PackageCmd(exists ? source_dir : cwd, "git")); if(exists) { /* Update the origin */ this->updateOrigin(); /* Check if the commit is already present */ std::string cmd = "cd " + source_dir + "; git cat-file -e " + this->refspec + " 2>/dev/null"; if(std::system(cmd.c_str()) != 0) { /* If not, fetch everything from origin */ pc->addArg("fetch"); pc->addArg("origin"); pc->addArg("--tags"); if(!pc->Run(this->P)) { throw CustomException("Failed: git fetch origin --tags"); } } } else { pc->addArg("clone"); pc->addArg("-n"); pc->addArg(location.c_str()); pc->addArg(source_dir.c_str()); if(!pc->Run(this->P)) throw CustomException("Failed to git clone"); } if(this->refspec.compare("HEAD") == 0) { // Don't touch it } else { std::string cmd = "cd " + source_dir + "; git show-ref --quiet --verify -- refs/heads/" + this->refspec; if(std::system(cmd.c_str()) == 0) { std::string head_hash = git_hash_ref(source_dir, "HEAD"); std::string branch_hash = git_hash_ref(source_dir, this->refspec); if(strcmp(head_hash.c_str(), branch_hash.c_str())) { throw CustomException("Asked to use branch: " + this->refspec + ", but " + source_dir + " is off somewhere else"); } } else { pc.reset(new PackageCmd(source_dir.c_str(), "git")); // switch to refspec pc->addArg("checkout"); pc->addArg("-q"); pc->addArg("--detach"); pc->addArg(this->refspec.c_str()); if(!pc->Run(this->P)) throw CustomException("Failed to checkout"); } } bool res = true; std::string hash = git_hash(source_dir); if(!this->hash.empty()) { if(strcmp(this->hash.c_str(), hash.c_str()) != 0) { log(this->P, "Hash mismatch for %s\n(committed to %s, providing %s)\n", this->uri.c_str(), this->hash.c_str(), hash.c_str()); res = false; } } else { this->hash = hash; } this->fetched = res; return res; } std::string GitExtractionUnit::HASH() { if(refspec_is_commitid(this->refspec)) { this->hash = std::string(this->refspec); } else { std::string digest_name = string_format("%s#%s", this->uri.c_str(), this->refspec.c_str()); /* Check if the package contains pre-computed hashes */ std::string Hash = P->getFileHash(digest_name); if(Hash.empty()) { this->fetch(P->builddir()); } else { this->hash = Hash; } } return this->hash; } bool GitExtractionUnit::extract(Package * P, BuildDir * bd) { // make sure it has been fetched if(!this->fetched) { if(!this->fetch(bd)) { return false; } } // copy to work dir std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "cp")); pc->addArg("-dpRuf"); pc->addArg(this->localPath()); pc->addArg("."); if(!pc->Run(P)) throw CustomException("Failed to checkout"); return true; } bool LinkGitDirExtractionUnit::extract(Package * P, BuildDir * bd) { std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "ln")); pc->addArg("-sfT"); if(this->uri[0] == '.') { std::string arg = P->getWorld()->getWorkingDir() + "/" + this->uri; pc->addArg(arg); } else { pc->addArg(this->uri); } pc->addArg(this->toDir); if(!pc->Run(P)) { throw CustomException("Operation failed"); } return true; } bool CopyGitDirExtractionUnit::extract(Package * P, BuildDir * bd) { std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "cp")); pc->addArg("-dpRuf"); if(this->uri[0] == '.') { std::string arg = P->getWorld()->getWorkingDir() + "/" + this->uri; pc->addArg(arg); } else { pc->addArg(this->uri); } pc->addArg(this->toDir); if(!pc->Run(P)) { throw CustomException("Operation failed"); } return true; } <|endoftext|>
<commit_before>#include "configuration.h" void Configuration::initialize(ConfigManager* manager) { manager->registerConfig(this); } bool Configuration::loadConfig(const std::string& filename, Json::Value& value) { _filename = filename; std::ios::sync_with_stdio(false); std::ifstream fs; fs.open(filename, std::ios::in); if (!fs.is_open()) { error_log("failed to open configuration file : %s", filename.c_str()); return false; } fs.seekg(0, ios::end); std::streamsize filesize = fs.tellg(); fs.seekg(0, ios::beg); char* configBuffer = new char[filesize]; memset(configBuffer, 0, filesize); fs.read(configBuffer, filesize); bool parseResult = Json::Reader::parse(configBuffer, value, false); SAFE_DELETE_ARR(configBuffer); return parseResult; } <commit_msg>[*] 去掉一个警告<commit_after>#include "configuration.h" void Configuration::initialize(ConfigManager* manager) { manager->registerConfig(this); } bool Configuration::loadConfig(const std::string& filename, Json::Value& value) { _filename = filename; std::ios::sync_with_stdio(false); std::ifstream fs; fs.open(filename, std::ios::in); if (!fs.is_open()) { error_log("failed to open configuration file : %s", filename.c_str()); return false; } fs.seekg(0, ios::end); size_t filesize = static_cast<size_t>(fs.tellg()); fs.seekg(0, ios::beg); char* configBuffer = new char[filesize]; memset(configBuffer, 0, filesize); fs.read(configBuffer, filesize); bool parseResult = Json::Reader::parse(configBuffer, value, false); SAFE_DELETE_ARR(configBuffer); return parseResult; } <|endoftext|>
<commit_before>/* * * The MIT License (MIT) * * Copyright (c) 2013 Paul Holden et al. (See AUTHORS) * * 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 <bakge/Bakge.h> namespace bakge { Byte* LoadFileContents(const char* Path) { FILE* fp; long length; Byte* content; fp = fopen(Path, "rb"); if (fp != NULL) { fseek(fp, 0, SEEK_END); length = ftell(fp); fseek(fp, 0, SEEK_SET); content = (Byte*)malloc(length); fread(content, length, 1, fp); fclose(fp); return content; } else { return NULL; } } } /* bakge */ <commit_msg>Tweaks to FunkyCat LoadFileContents<commit_after>/* * * The MIT License (MIT) * * Copyright (c) 2013 Paul Holden et al. (See AUTHORS) * * 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 <bakge/Bakge.h> namespace bakge { Byte* LoadFileContents(const char* Path) { FILE* FileHandle; long Length; Byte* FileContent; FileHandle = fopen(Path, "rb"); if (FileHandle != NULL) { /* Get character count of file */ fseek(FileHandle, 0, SEEK_END); Length = ftell(FileHandle); fseek(FileHandle, 0, SEEK_SET); /* Allocate memory and read in file contents */ FileContent = (Byte*)malloc(Length); fread(FileContent, Length, 1, FileHandle); fclose(FileHandle); return FileContent; } else { return NULL; } } } /* bakge */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * XPLC - Cross-Platform Lightweight Components * Copyright (C) 2000, Pierre Phaneuf * * 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., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "../test.h" #include <xplc/xplc.h> #include <xplc/utils.h> #include "../xplc/statichandler.h" /* * test003 * * Verifies the static service handler; */ void test() { IStaticServiceHandler* handler; TestObject* test; IObject* obj; ITestInterface *itest; handler = StaticServiceHandler::create(); ASSERT(handler, "could not instantiate static service handler"); handler->addRef(); test = new TestObject; ASSERT(test, "could not instantiate test object"); test->addRef(); VERIFY(test->getRefCount() == 1, "the test object has an incorrect refcount"); handler->addObject(TestObject::CID, test); VERIFY(test->getRefCount() == 2, "static service handler did not addRef the test component"); obj = handler->getObject(TestObject::CID); ASSERT(obj, "could not get test component from static service handler"); itest = mutateInterface<ITestInterface>(obj); ASSERT(itest, "test component does not have the expected interface"); VERIFY(test->getRefCount() == 3, "the test object has an incorrect refcount"); itest->setRefCount(10); itest->addRef(); VERIFY(itest->getRefCount() == 11, "test component has unexpected behavior"); itest->setRefCount(3); VERIFY(itest->release() == 2, "test component has incorrect refcount"); handler->removeObject(TestObject::CID); VERIFY(test->getRefCount() == 1, "static service handler did not release the test component"); obj = handler->getObject(TestObject::CID); VERIFY(!obj, "static service handler did not remove the test component"); if(obj) obj->release(); VERIFY(handler->release() == 0, "static service handler has non-zero refcount after release"); VERIFY(test->release() == 0, "test object has non-zero refcount after release"); } <commit_msg>Forgot a small detail that the unit tests *did* get, but I had forgot to run them, so that's what happen...<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * XPLC - Cross-Platform Lightweight Components * Copyright (C) 2000, Pierre Phaneuf * * 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., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include "../test.h" #include <xplc/xplc.h> #include <xplc/utils.h> #include "../xplc/statichandler.h" /* * test003 * * Verifies the static service handler; */ void test() { IStaticServiceHandler* handler; TestObject* test; IObject* obj; ITestInterface *itest; handler = StaticServiceHandler::create(); ASSERT(handler, "could not instantiate static service handler"); handler->addRef(); test = new TestObject; ASSERT(test, "could not instantiate test object"); test->addRef(); VERIFY(test->getRefCount() == 1, "the test object has an incorrect refcount"); handler->addObject(TestObject_CID, test); VERIFY(test->getRefCount() == 2, "static service handler did not addRef the test component"); obj = handler->getObject(TestObject_CID); ASSERT(obj, "could not get test component from static service handler"); itest = mutateInterface<ITestInterface>(obj); ASSERT(itest, "test component does not have the expected interface"); VERIFY(test->getRefCount() == 3, "the test object has an incorrect refcount"); itest->setRefCount(10); itest->addRef(); VERIFY(itest->getRefCount() == 11, "test component has unexpected behavior"); itest->setRefCount(3); VERIFY(itest->release() == 2, "test component has incorrect refcount"); handler->removeObject(TestObject_CID); VERIFY(test->getRefCount() == 1, "static service handler did not release the test component"); obj = handler->getObject(TestObject_CID); VERIFY(!obj, "static service handler did not remove the test component"); if(obj) obj->release(); VERIFY(handler->release() == 0, "static service handler has non-zero refcount after release"); VERIFY(test->release() == 0, "test object has non-zero refcount after release"); } <|endoftext|>
<commit_before>#include "BigFix/DataRef.h" #include "BigFix/InflateStream.h" #include "TestUtility.h" #include <gtest/gtest.h> using namespace BigFix; TEST( InflateStreamTest, ShortRaw ) { StringStream stringStream; InflateStream inflateStream( stringStream ); DataRef data( "hello" ); WriteOneByOne( inflateStream, data ); inflateStream.End(); EXPECT_EQ( "hello", stringStream.output ); EXPECT_TRUE( stringStream.ended ); } TEST( InflateStreamTest, LongRaw ) { StringStream stringStream; InflateStream inflateStream( stringStream ); DataRef data( "hello, world! blah blah blah" ); WriteOneByOne( inflateStream, data ); inflateStream.End(); EXPECT_EQ( "hello, world! blah blah blah", stringStream.output ); EXPECT_TRUE( stringStream.ended ); } TEST( InflateStreamTest, Compressed ) { StringStream stringStream; InflateStream inflateStream( stringStream ); uint8_t data[] = { 0x23, 0x23, 0x53, 0x43, 0x30, 0x30, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x9c, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0xd7, 0x51, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0x04, 0x00, 0x20, 0x5e, 0x04, 0x8a }; WriteOneByOne( inflateStream, DataRef( data, data + sizeof( data ) ) ); inflateStream.End(); EXPECT_EQ( "Hello, world!", stringStream.output ); EXPECT_TRUE( stringStream.ended ); } <commit_msg>Add a test for inflating an empty file<commit_after>#include "BigFix/DataRef.h" #include "BigFix/InflateStream.h" #include "TestUtility.h" #include <gtest/gtest.h> using namespace BigFix; TEST( InflateStreamTest, ShortRaw ) { StringStream stringStream; InflateStream inflateStream( stringStream ); DataRef data( "hello" ); WriteOneByOne( inflateStream, data ); inflateStream.End(); EXPECT_EQ( "hello", stringStream.output ); EXPECT_TRUE( stringStream.ended ); } TEST( InflateStreamTest, LongRaw ) { StringStream stringStream; InflateStream inflateStream( stringStream ); DataRef data( "hello, world! blah blah blah" ); WriteOneByOne( inflateStream, data ); inflateStream.End(); EXPECT_EQ( "hello, world! blah blah blah", stringStream.output ); EXPECT_TRUE( stringStream.ended ); } TEST( InflateStreamTest, DecompressHelloWorld ) { StringStream stringStream; InflateStream inflateStream( stringStream ); uint8_t data[] = { 0x23, 0x23, 0x53, 0x43, 0x30, 0x30, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x9c, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0xd7, 0x51, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0x04, 0x00, 0x20, 0x5e, 0x04, 0x8a }; WriteOneByOne( inflateStream, DataRef( data, data + sizeof( data ) ) ); inflateStream.End(); EXPECT_EQ( "Hello, world!", stringStream.output ); EXPECT_TRUE( stringStream.ended ); } TEST( InflateStreamTest, DecompressEmpty ) { StringStream stringStream; InflateStream inflateStream( stringStream ); uint8_t data[] = { 0x23, 0x23, 0x53, 0x43, 0x30, 0x30, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01 }; WriteOneByOne( inflateStream, DataRef( data, data + sizeof( data ) ) ); inflateStream.End(); EXPECT_EQ( "", stringStream.output ); EXPECT_TRUE( stringStream.ended ); } <|endoftext|>
<commit_before>/* This file is part of the Grantlee template system. Copyright (c) 2009 Stephen Kelly <steveire@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 only, 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 version 3 for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "util_p.h" Util::Util() { } QString Util::unescapeStringLiteral( const QString &input ) { return input.mid( 1, input.size() - 2 ) .replace( "\\\'", "'" ) .replace( "\\\"", "\"" ) .replace( "\\\\", "\\" ); } bool Util::variantIsTrue( const QVariant &variant ) { if ( !variant.isValid() ) return false; switch ( variant.userType() ) { case QVariant::Bool: { return variant.toBool(); } case QVariant::Int: { return ( variant.toInt() > 0 ); } case QVariant::Double: { return ( variant.toDouble() > 0 ); } case QMetaType::QObjectStar: { QObject *obj = variant.value<QObject *>(); if ( !obj ) return false; if ( obj->property( "__true__" ).isValid() ) { return obj->property( "__true__" ).toBool(); } return true; } case QVariant::List: { return ( variant.toList().size() > 0 ); } case QVariant::Map: { return ( variant.toMap().size() > 0 ); } } Grantlee::SafeString str = getSafeString( variant ); return !str.rawString().isEmpty(); } QVariantList Util::variantToList( const QVariant &var ) { if ( !var.isValid() ) return QVariantList(); if ( var.type() == QVariant::List ) { return var.toList(); } if ( var.type() == QVariant::Hash ) { QVariantHash varHash = var.toHash(); QVariantList list; foreach( QString key, varHash.keys() ) list << key; return list; } if ( var.userType() == QMetaType::QObjectStar ) { QObject *obj = var.value<QObject*>(); if ( obj->property( "__list__" ).isValid() ) { return obj->property( "__list__" ).toList(); } } else { return QVariantList() << var; } } Grantlee::SafeString Util::conditionalEscape( const Grantlee::SafeString &input ) { Grantlee::SafeString temp = input; if ( !temp.isSafe() ) return escape( temp ); return temp; } Grantlee::SafeString Util::markSafe( const Grantlee::SafeString &input ) { Grantlee::SafeString sret = input; sret.setSafety( Grantlee::SafeString::IsSafe ); return sret; } Grantlee::SafeString Util::markForEscaping( const Grantlee::SafeString &input ) { Grantlee::SafeString temp = input; temp.setNeedsEscape( true ); return temp; } // This should probably take a QString instead. Grantlee::SafeString Util::escape( const Grantlee::SafeString &input ) { QString temp = input; temp.replace( "&", "&amp;" ); temp.replace( "<", "&lt;" ); temp.replace( ">", "&gt;" ); return temp; } Grantlee::SafeString Util::getSafeString( const QVariant &input ) { if ( input.userType() == qMetaTypeId<Grantlee::SafeString>() ) { return input.value<Grantlee::SafeString>(); } else { return input.toString(); } } bool Util::isSafeString( const QVariant &input ) { int type = input.userType(); return (( type == qMetaTypeId<Grantlee::SafeString>() ) || type == QVariant::String ); } bool Util::supportedOutputType( const QVariant &input ) { QList<int> primitives; primitives << qMetaTypeId<Grantlee::SafeString>() << QVariant::Bool << QVariant::Int << QVariant::Double; return primitives.contains( input.userType() ); } bool Util::equals( const QVariant &lhs, const QVariant &rhs ) { // QVariant doesn't use operator== to compare its held data, so we do it manually instead for SafeString. bool equal = false; if ( lhs.userType() == qMetaTypeId<Grantlee::SafeString>() ) { if ( rhs.userType() == qMetaTypeId<Grantlee::SafeString>() ) { equal = ( lhs.value<Grantlee::SafeString>() == rhs.value<Grantlee::SafeString>() ); } else if ( rhs.userType() == QVariant::String ) { equal = ( lhs.value<Grantlee::SafeString>().rawString() == rhs.toString() ); } } else if ( rhs.userType() == qMetaTypeId<Grantlee::SafeString>() && lhs.userType() == QVariant::String ) { equal = ( rhs.value<Grantlee::SafeString>().rawString() == lhs.toString() ); } else { equal = (( lhs == rhs ) && ( lhs.userType() == rhs.userType() ) ); } return equal; } <commit_msg>Fix logic error in markForEscaping<commit_after>/* This file is part of the Grantlee template system. Copyright (c) 2009 Stephen Kelly <steveire@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 only, 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 version 3 for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "util_p.h" Util::Util() { } QString Util::unescapeStringLiteral( const QString &input ) { return input.mid( 1, input.size() - 2 ) .replace( "\\\'", "'" ) .replace( "\\\"", "\"" ) .replace( "\\\\", "\\" ); } bool Util::variantIsTrue( const QVariant &variant ) { if ( !variant.isValid() ) return false; switch ( variant.userType() ) { case QVariant::Bool: { return variant.toBool(); } case QVariant::Int: { return ( variant.toInt() > 0 ); } case QVariant::Double: { return ( variant.toDouble() > 0 ); } case QMetaType::QObjectStar: { QObject *obj = variant.value<QObject *>(); if ( !obj ) return false; if ( obj->property( "__true__" ).isValid() ) { return obj->property( "__true__" ).toBool(); } return true; } case QVariant::List: { return ( variant.toList().size() > 0 ); } case QVariant::Map: { return ( variant.toMap().size() > 0 ); } } Grantlee::SafeString str = getSafeString( variant ); return !str.rawString().isEmpty(); } QVariantList Util::variantToList( const QVariant &var ) { if ( !var.isValid() ) return QVariantList(); if ( var.type() == QVariant::List ) { return var.toList(); } if ( var.type() == QVariant::Hash ) { QVariantHash varHash = var.toHash(); QVariantList list; foreach( QString key, varHash.keys() ) list << key; return list; } if ( var.userType() == QMetaType::QObjectStar ) { QObject *obj = var.value<QObject*>(); if ( obj->property( "__list__" ).isValid() ) { return obj->property( "__list__" ).toList(); } } else { return QVariantList() << var; } } Grantlee::SafeString Util::conditionalEscape( const Grantlee::SafeString &input ) { Grantlee::SafeString temp = input; if ( !temp.isSafe() ) return escape( temp ); return temp; } Grantlee::SafeString Util::markSafe( const Grantlee::SafeString &input ) { Grantlee::SafeString sret = input; sret.setSafety( Grantlee::SafeString::IsSafe ); return sret; } Grantlee::SafeString Util::markForEscaping( const Grantlee::SafeString &input ) { Grantlee::SafeString temp = input; if ( input.isSafe() || input.needsEscape() ) return input; temp.setNeedsEscape( true ); return temp; } // This should probably take a QString instead. Grantlee::SafeString Util::escape( const Grantlee::SafeString &input ) { QString temp = input; temp.replace( "&", "&amp;" ); temp.replace( "<", "&lt;" ); temp.replace( ">", "&gt;" ); return temp; } Grantlee::SafeString Util::getSafeString( const QVariant &input ) { if ( input.userType() == qMetaTypeId<Grantlee::SafeString>() ) { return input.value<Grantlee::SafeString>(); } else { return input.toString(); } } bool Util::isSafeString( const QVariant &input ) { int type = input.userType(); return (( type == qMetaTypeId<Grantlee::SafeString>() ) || type == QVariant::String ); } bool Util::supportedOutputType( const QVariant &input ) { QList<int> primitives; primitives << qMetaTypeId<Grantlee::SafeString>() << QVariant::Bool << QVariant::Int << QVariant::Double; return primitives.contains( input.userType() ); } bool Util::equals( const QVariant &lhs, const QVariant &rhs ) { // QVariant doesn't use operator== to compare its held data, so we do it manually instead for SafeString. bool equal = false; if ( lhs.userType() == qMetaTypeId<Grantlee::SafeString>() ) { if ( rhs.userType() == qMetaTypeId<Grantlee::SafeString>() ) { equal = ( lhs.value<Grantlee::SafeString>() == rhs.value<Grantlee::SafeString>() ); } else if ( rhs.userType() == QVariant::String ) { equal = ( lhs.value<Grantlee::SafeString>().rawString() == rhs.toString() ); } } else if ( rhs.userType() == qMetaTypeId<Grantlee::SafeString>() && lhs.userType() == QVariant::String ) { equal = ( rhs.value<Grantlee::SafeString>().rawString() == lhs.toString() ); } else { equal = (( lhs == rhs ) && ( lhs.userType() == rhs.userType() ) ); } return equal; } <|endoftext|>
<commit_before>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "perf.h" #include <iomanip> #include <iostream> #include <sys/time.h> using namespace benchmark; std::map<std::string, BenchFunction> BenchRunner::benchmarks; static double gettimedouble(void) { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_usec * 0.000001 + tv.tv_sec; } BenchRunner::BenchRunner(std::string name, BenchFunction func) { benchmarks.insert(std::make_pair(name, func)); } void BenchRunner::RunAll(double elapsedTimeForOne) { perf_init(); std::cout << "#Benchmark" << "," << "count" << "," << "min" << "," << "max" << "," << "average" << "," << "min_cycles" << "," << "max_cycles" << "," << "average_cycles" << "\n"; for (std::map<std::string,BenchFunction>::iterator it = benchmarks.begin(); it != benchmarks.end(); ++it) { State state(it->first, elapsedTimeForOne); BenchFunction& func = it->second; func(state); } perf_fini(); } bool State::KeepRunning() { if (count & countMask) { ++count; return true; } double now; uint64_t nowCycles; if (count == 0) { beginTime = now = gettimedouble(); lastCycles = beginCycles = nowCycles = perf_cpucycles(); } else { now = gettimedouble(); double elapsed = now - lastTime; double elapsedOne = elapsed * countMaskInv; if (elapsedOne < minTime) minTime = elapsedOne; if (elapsedOne > maxTime) maxTime = elapsedOne; // We only use relative values, so don't have to handle 64-bit wrap-around specially nowCycles = perf_cpucycles(); uint64_t elapsedOneCycles = (nowCycles - lastCycles) * countMaskInv; if (elapsedOneCycles < minCycles) minCycles = elapsedOneCycles; if (elapsedOneCycles > maxCycles) maxCycles = elapsedOneCycles; if (elapsed*128 < maxElapsed) { // If the execution was much too fast (1/128th of maxElapsed), increase the count mask by 8x and restart timing. // The restart avoids including the overhead of this code in the measurement. countMask = ((countMask<<3)|7) & ((1LL<<60)-1); countMaskInv = 1./(countMask+1); count = 0; minTime = std::numeric_limits<double>::max(); maxTime = std::numeric_limits<double>::min(); minCycles = std::numeric_limits<uint64_t>::max(); maxCycles = std::numeric_limits<uint64_t>::min(); return true; } if (elapsed*16 < maxElapsed) { uint64_t newCountMask = ((countMask<<1)|1) & ((1LL<<60)-1); if ((count & newCountMask)==0) { countMask = newCountMask; countMaskInv = 1./(countMask+1); } } } lastTime = now; lastCycles = nowCycles; ++count; if (now - beginTime < maxElapsed) return true; // Keep going --count; // Output results double average = (now-beginTime)/count; int64_t averageCycles = (nowCycles-beginCycles)/count; std::cout << std::fixed << std::setprecision(15) << name << "," << count << "," << minTime << "," << maxTime << "," << average << "," << minCycles << "," << maxCycles << "," << averageCycles << "\n"; return false; } <commit_msg>[Refactoring] Removed using namespace <xxx> from bench/ sources<commit_after>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "perf.h" #include <iomanip> #include <iostream> #include <sys/time.h> std::map<std::string, benchmark::BenchFunction> benchmark::BenchRunner::benchmarks; static double gettimedouble(void) { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_usec * 0.000001 + tv.tv_sec; } benchmark::BenchRunner::BenchRunner(std::string name, benchmark::BenchFunction func) { benchmarks.insert(std::make_pair(name, func)); } void benchmark::BenchRunner::RunAll(double elapsedTimeForOne) { perf_init(); std::cout << "#Benchmark" << "," << "count" << "," << "min" << "," << "max" << "," << "average" << "," << "min_cycles" << "," << "max_cycles" << "," << "average_cycles" << "\n"; for (std::map<std::string,BenchFunction>::iterator it = benchmarks.begin(); it != benchmarks.end(); ++it) { State state(it->first, elapsedTimeForOne); BenchFunction& func = it->second; func(state); } perf_fini(); } bool benchmark::State::KeepRunning() { if (count & countMask) { ++count; return true; } double now; uint64_t nowCycles; if (count == 0) { beginTime = now = gettimedouble(); lastCycles = beginCycles = nowCycles = perf_cpucycles(); } else { now = gettimedouble(); double elapsed = now - lastTime; double elapsedOne = elapsed * countMaskInv; if (elapsedOne < minTime) minTime = elapsedOne; if (elapsedOne > maxTime) maxTime = elapsedOne; // We only use relative values, so don't have to handle 64-bit wrap-around specially nowCycles = perf_cpucycles(); uint64_t elapsedOneCycles = (nowCycles - lastCycles) * countMaskInv; if (elapsedOneCycles < minCycles) minCycles = elapsedOneCycles; if (elapsedOneCycles > maxCycles) maxCycles = elapsedOneCycles; if (elapsed*128 < maxElapsed) { // If the execution was much too fast (1/128th of maxElapsed), increase the count mask by 8x and restart timing. // The restart avoids including the overhead of this code in the measurement. countMask = ((countMask<<3)|7) & ((1LL<<60)-1); countMaskInv = 1./(countMask+1); count = 0; minTime = std::numeric_limits<double>::max(); maxTime = std::numeric_limits<double>::min(); minCycles = std::numeric_limits<uint64_t>::max(); maxCycles = std::numeric_limits<uint64_t>::min(); return true; } if (elapsed*16 < maxElapsed) { uint64_t newCountMask = ((countMask<<1)|1) & ((1LL<<60)-1); if ((count & newCountMask)==0) { countMask = newCountMask; countMaskInv = 1./(countMask+1); } } } lastTime = now; lastCycles = nowCycles; ++count; if (now - beginTime < maxElapsed) return true; // Keep going --count; // Output results double average = (now-beginTime)/count; int64_t averageCycles = (nowCycles-beginCycles)/count; std::cout << std::fixed << std::setprecision(15) << name << "," << count << "," << minTime << "," << maxTime << "," << average << "," << minCycles << "," << maxCycles << "," << averageCycles << "\n"; return false; } <|endoftext|>
<commit_before>/* Copyright 2016 Mitchell Young 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. */ #pragma once #include <vector> #include "util/blitz_typedefs.hpp" #include "util/fp_utils.hpp" #include "util/global_config.hpp" #include "core_mesh.hpp" #include "output_interface.hpp" #include "xs_mesh_region.hpp" namespace mocc { class XSMesh : public HasOutput { public: // XSMesh provides its own facility to initialize itself from a \ref // CoreMesh XSMesh(const CoreMesh &mesh, MeshTreatment treatment); // Return the number of energy groups size_t n_group() const { return ng_; } // Iterators to the underlying vector const std::vector<XSMeshRegion>::const_iterator begin() const { return regions_.cbegin(); } const std::vector<XSMeshRegion>::const_iterator end() const { return regions_.cend(); } const XSMeshRegion &operator[](size_t i) const { assert(i >= 0); assert(i < regions_.size()); return regions_[i]; } size_t size() const { return regions_.size(); } const VecF &eubounds() const { return eubounds_; } /** * \brief Update macroscopic cross sections if needed * * Since the stock XSMesh only deals in un-homogenized, macroscopic * cross sections, this does nothing. When support for microscopic cross * sections is added, this will need to start doing some work. * * For right now, this is overridden in the \ref XSMeshHomogenized class * to calculate new homoginzed cross sections given a new state of the * FM scalar flux. */ virtual void update() { // Do nothing for the regular XS Mesh... for now return; } virtual void output(H5Node &file) const { // Not really implementing for the general XS Mesh type. assert(false); } bool operator==(const XSMesh &other) const { if (regions_ != other.regions_) { return false; } return true; } bool operator!=(const XSMesh &other) const { return !(*this == other); } /** * \brief Return the number of regions that this XSMesh would expand into * * This is essentially the same as n_reg() for the sweeper with which the * XSMesh is associated. */ int n_reg_expanded() const { return n_reg_expanded_; } /** * \brief Return the encoded state */ int state() const { return state_; } protected: /** * \brief Allocate space to store the actual cross sections. * * \param nxs the number of cross section mesh materials * \param ng the number of energy groups * * This is identical for all cross-section mesh types, so might as well * have it in one place. */ void allocate_xs(int nxs, int ng) { auto shape = blitz::shape(nxs, ng); xstr_.resize(shape); xsnf_.resize(shape); xsch_.resize(shape); xsf_.resize(shape); xsrm_.resize(shape); auto test_slice(xstr_(0, blitz::Range::all())); assert(test_slice.isStorageContiguous()); } size_t ng_; // Vector of xs mesh regions std::vector<XSMeshRegion> regions_; // Actual cross-section data ArrayB2 xstr_; ArrayB2 xsnf_; ArrayB2 xsch_; ArrayB2 xsf_; ArrayB2 xsrm_; // Energy group upper bounds VecF eubounds_; // Number of regions in the associated computational mesh int n_reg_expanded_; // This is used to somehow encode the state of the cross sections, any time // the cross sections change, this shall assume a new value, unique to the // history of the XSMesh object int state_; }; typedef std::shared_ptr<XSMesh> SP_XSMesh_t; /** * \brief Storage class for cross sections mapped from the XS mesh regions to * computational mesh * * This class maintains an array of one-group cross sections, sized to the * number of regions in a mesh, along with the state necessary to determine * whether cross sections need to be expanded under requested circumstances. * This is useful in cases where it is convenient to share expanded cross * sections bewteen different parts of the code without having to * - duplicate the data, * - redundantly expand the cross sections, or * - worry about the order of operations and whether following a certain code * path will find the appropriate cross sections in the array. * * A concrete example of when this is especially useful is in the CDD sweeper, * where both the Sn sweeper and the correction worker on the MoC sweeper need * cross sections expanded to the Sn mesh. Having both classes share a reference * to and instance of this class allows for them to both have access to the * cross sections without having to store them twice. They can both call * expand() right before they need up-to-date cross sections, and the actual * expansion will take place only if needed. */ class ExpandedXS { public: ExpandedXS() : xs_mesh_(nullptr) { return; } ExpandedXS(const XSMesh *xs_mesh) : xstr_(xs_mesh->n_reg_expanded(), 0.0), xs_mesh_(xs_mesh), group_(-1), state_(-1) { return; } real_t operator[](int i) const { return xstr_[i]; } void expand(int group) { // only update if the group has canged or the cross sections have been // updated if ((group != group_) || (xs_mesh_->state() != state_)) { group_ = group; state_ = xs_mesh_->state(); for (const auto &xsr : *xs_mesh_) { real_t xs = xsr.xsmactr(group); for (const int ireg : xsr.reg()) { xstr_[ireg] = xs; } } } return; } private: VecF xstr_; const XSMesh *xs_mesh_; int group_; int state_; }; } <commit_msg>Refine ExpandXS class<commit_after>/* Copyright 2016 Mitchell Young 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. */ #pragma once #include <vector> #include "util/blitz_typedefs.hpp" #include "util/fp_utils.hpp" #include "util/global_config.hpp" #include "core_mesh.hpp" #include "output_interface.hpp" #include "xs_mesh_region.hpp" namespace mocc { class XSMesh : public HasOutput { public: // XSMesh provides its own facility to initialize itself from a \ref // CoreMesh XSMesh(const CoreMesh &mesh, MeshTreatment treatment); // Return the number of energy groups size_t n_group() const { return ng_; } // Iterators to the underlying vector const std::vector<XSMeshRegion>::const_iterator begin() const { return regions_.cbegin(); } const std::vector<XSMeshRegion>::const_iterator end() const { return regions_.cend(); } const XSMeshRegion &operator[](size_t i) const { assert(i >= 0); assert(i < regions_.size()); return regions_[i]; } size_t size() const { return regions_.size(); } const VecF &eubounds() const { return eubounds_; } /** * \brief Update macroscopic cross sections if needed * * Since the stock XSMesh only deals in un-homogenized, macroscopic * cross sections, this does nothing. When support for microscopic cross * sections is added, this will need to start doing some work. * * For right now, this is overridden in the \ref XSMeshHomogenized class * to calculate new homoginzed cross sections given a new state of the * FM scalar flux. */ virtual void update() { // Do nothing for the regular XS Mesh... for now return; } virtual void output(H5Node &file) const { // Not really implementing for the general XS Mesh type. assert(false); } bool operator==(const XSMesh &other) const { if (regions_ != other.regions_) { return false; } return true; } bool operator!=(const XSMesh &other) const { return !(*this == other); } /** * \brief Return the number of regions that this XSMesh would expand into * * This is essentially the same as n_reg() for the sweeper with which the * XSMesh is associated. */ int n_reg_expanded() const { return n_reg_expanded_; } /** * \brief Return the encoded state */ int state() const { return state_; } protected: /** * \brief Allocate space to store the actual cross sections. * * \param nxs the number of cross section mesh materials * \param ng the number of energy groups * * This is identical for all cross-section mesh types, so might as well * have it in one place. */ void allocate_xs(int nxs, int ng) { auto shape = blitz::shape(nxs, ng); xstr_.resize(shape); xsnf_.resize(shape); xsch_.resize(shape); xsf_.resize(shape); xsrm_.resize(shape); auto test_slice(xstr_(0, blitz::Range::all())); assert(test_slice.isStorageContiguous()); } size_t ng_; // Vector of xs mesh regions std::vector<XSMeshRegion> regions_; // Actual cross-section data ArrayB2 xstr_; ArrayB2 xsnf_; ArrayB2 xsch_; ArrayB2 xsf_; ArrayB2 xsrm_; // Energy group upper bounds VecF eubounds_; // Number of regions in the associated computational mesh int n_reg_expanded_; // This is used to somehow encode the state of the cross sections, any time // the cross sections change, this shall assume a new value, unique to the // history of the XSMesh object int state_; }; typedef std::shared_ptr<XSMesh> SP_XSMesh_t; /** * \brief Storage class for cross sections mapped from the XS mesh regions to * computational mesh * * This class maintains an array of one-group cross sections, sized to the * number of regions in a mesh, along with the state necessary to determine * whether cross sections need to be expanded under requested circumstances. * This is useful in cases where it is convenient to share expanded cross * sections bewteen different parts of the code without having to * - duplicate the data, * - redundantly expand the cross sections, or * - worry about the order of operations and whether following a certain code * path will find the appropriate cross sections in the array. * * A concrete example of when this is especially useful is in the CDD sweeper, * where both the Sn sweeper and the correction worker on the MoC sweeper need * cross sections expanded to the Sn mesh. Having both classes share a reference * to and instance of this class allows for them to both have access to the * cross sections without having to store them twice. They can both call * expand() right before they need up-to-date cross sections, and the actual * expansion will take place only if needed. * * \note Care is taken to keep access to the underlying cross sections * efficient. A blitz array is used to store the cross sections themselves, so * that we can take advantage of the aliasing functionality. The subscript * operator under sane compiler treatment should be elided, and the use of the * \c shared_ptr for storing the other state allows for full instances of the * class (referring to the same data) to be used where a reference or pointer * would otherwise be used, removing a level of indirection. */ class ExpandedXS { public: ExpandedXS() : xs_mesh_(nullptr), state_(nullptr) { return; } ExpandedXS(const XSMesh *xs_mesh) : xstr_(xs_mesh->n_reg_expanded()), xs_mesh_(xs_mesh), state_(std::make_shared<std::pair<int, int>>(-1, -1)) { return; } ExpandedXS(ExpandedXS &other) : xstr_(other.xstr_), xs_mesh_(other.xs_mesh_), state_(other.state_) { return; } ExpandedXS &operator=(const ExpandedXS &other) { if(this == &other) { return *this; } xstr_.reference(other.xstr_); xs_mesh_ = other.xs_mesh_; state_ = other.state_; return *this; } real_t operator[](int i) const { return xstr_(i); } int size() const { return xstr_.size(); } void expand(int group) { // only update if the group has canged or the cross sections have been // updated if ((group != state_->first) || (xs_mesh_->state() != state_->second)) { state_->first = group; state_->second = xs_mesh_->state(); for (const auto &xsr : *xs_mesh_) { real_t xs = xsr.xsmactr(group); for (const int ireg : xsr.reg()) { xstr_(ireg) = xs; } } } return; } /** * \brief Expand cross sections, optionally performing source splitting if * provided. */ void expand(int group, const ArrayB1 split) { if (split.size() > 0) { // If we are doing splitting, skip the checks on group, etc. and // always expand assert((int)split.size() == xs_mesh_->n_reg_expanded()); for (const auto &xsr : *xs_mesh_) { real_t xs = xsr.xsmactr(group); for (const int ireg : xsr.reg()) { xstr_(ireg) = xs + split(ireg); } } } else { this->expand(group); } return; } const ArrayB1 &xs() const { return xstr_; } private: ArrayB1 xstr_; const XSMesh *xs_mesh_; // State of the cross sections. First is the energy group, second is the // state of the XS mesh from which the cross sections were extracted. This // is stored in a shared pointer so that multiple instances of ExpandedXS // can share state. std::shared_ptr<std::pair<int, int>> state_; }; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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. */ /** \file GLFBOTex.cpp \author Jens Krueger SCI Institute University of Utah Jens Schneider tum.3D, Muenchen \date August 2008 */ #include "GLFBOTex.h" #include <Controller/Controller.h> #ifdef WIN32 #ifndef DEBUG #pragma warning( disable : 4189 ) // disable unused var warning #endif #endif using namespace tuvok; GLuint GLFBOTex::m_hFBO = 0; int GLFBOTex::m_iCount = 0; bool GLFBOTex::m_bInitialized = true; /** * Constructor: on first instantiation, generate an FBO. * In any case a new dummy texture according to the parameters is generated. */ GLFBOTex::GLFBOTex(MasterController* pMasterController, GLenum minfilter, GLenum magfilter, GLenum wrapmode, GLsizei width, GLsizei height, GLenum intformat, unsigned int iSizePerElement, bool bHaveDepth, int iNumBuffers) : m_pMasterController(pMasterController), m_iSizePerElement(iSizePerElement), m_iSizeX(width), m_iSizeY(height), m_hTexture(new GLuint[iNumBuffers]), m_LastDepthTextUnit(0), m_iNumBuffers(iNumBuffers) { if (width<1) width=1; if (height<1) height=1; if (!m_bInitialized) { if (GLEW_OK!=glewInit()) { T_ERROR("failed to initialize GLEW!"); return; } if (!glewGetExtension("GL_EXT_framebuffer_object")) { T_ERROR("GL_EXT_framebuffer_object not supported!"); return; } m_bInitialized=true; } glGetError(); assert(iNumBuffers>0); assert(iNumBuffers<5); m_LastTexUnit=new GLenum[iNumBuffers]; m_LastAttachment=new GLenum[iNumBuffers]; for (int i=0; i<m_iNumBuffers; i++) { m_LastTexUnit[i]=0; m_LastAttachment[i]=GL_COLOR_ATTACHMENT0_EXT+i; m_hTexture[i]=0; } if (m_hFBO==0) initFBO(); { GLenum glerr = glGetError(); if(GL_NO_ERROR != glerr) { T_ERROR("Error '%d' during FBO creation!", static_cast<int>(glerr)); glDeleteFramebuffersEXT(1,&m_hFBO); m_hFBO=0; return; } } initTextures(minfilter,magfilter,wrapmode,width,height,intformat); { GLenum glerr = glGetError(); if(GL_NO_ERROR != glerr) { T_ERROR("Error '%d' during texture creation!", static_cast<int>(glerr)); glDeleteTextures(m_iNumBuffers,m_hTexture); delete[] m_hTexture; m_hTexture=NULL; return; } } if (bHaveDepth) { #ifdef GLFBOTEX_DEPTH_RENDERBUFFER glGenRenderbuffersEXT(1,&m_hDepthBuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24,width,height); #else glGenTextures(1,&m_hDepthBuffer); glBindTexture(GL_TEXTURE_2D,m_hDepthBuffer); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT,width,height,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL); #endif } else m_hDepthBuffer=0; ++m_iCount; } /** * Destructor: Delete texture object. If no more instances of * GLFBOTex are around, the FBO is deleted as well. */ GLFBOTex::~GLFBOTex(void) { if (m_hTexture) { glDeleteTextures(m_iNumBuffers,m_hTexture); delete[] m_hTexture; m_hTexture=NULL; } if (m_LastTexUnit) { delete[] m_LastTexUnit; m_LastTexUnit=NULL; } if (m_LastAttachment) { delete[] m_LastAttachment; m_LastAttachment=NULL; } #ifdef GLFBOTEX_DEPTH_RENDERBUFFER if (m_hDepthBuffer) glDeleteRenderbuffersEXT(1,&m_hDepthBuffer); #else if (m_hDepthBuffer) glDeleteTextures(1,&m_hDepthBuffer); #endif m_hDepthBuffer=0; --m_iCount; if (m_iCount==0) { m_pMasterController->DebugOut()->Message(_func_, "FBO released via " "destructor call."); glDeleteFramebuffersEXT(1,&m_hFBO); m_hFBO=0; } } /** * Build a dummy texture according to the parameters. */ void GLFBOTex::initTextures(GLenum minfilter, GLenum magfilter, GLenum wrapmode, GLsizei width, GLsizei height, GLenum intformat) { MESSAGE("Initializing 2D texture of dimensions: %ux%u", static_cast<unsigned>(width), static_cast<unsigned>(height)); glDeleteTextures(m_iNumBuffers,m_hTexture); glGenTextures(m_iNumBuffers,m_hTexture); for (int i=0; i<m_iNumBuffers; i++) { glBindTexture(GL_TEXTURE_2D, m_hTexture[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapmode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapmode); int level=0; switch (minfilter) { case GL_NEAREST_MIPMAP_NEAREST: case GL_LINEAR_MIPMAP_NEAREST: case GL_NEAREST_MIPMAP_LINEAR: case GL_LINEAR_MIPMAP_LINEAR: do { glTexImage2D(GL_TEXTURE_2D, level, intformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); width/=2; height/=2; if (width==0 && height>0) width=1; if (width>0 && height==0) height=1; ++level; } while (width>=1 && height>=1); break; default: glTexImage2D(GL_TEXTURE_2D, 0, intformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); } } } /** * Build a new FBO. */ void GLFBOTex::initFBO(void) { MESSAGE("Initializing FBO..."); glGenFramebuffersEXT(1, &m_hFBO); } /** * Check the FBO for consistency. */ bool GLFBOTex::CheckFBO(const char* method) { GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch(status) { case GL_FRAMEBUFFER_COMPLETE_EXT: return true; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: T_ERROR("%s() - Unsupported Format!",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: T_ERROR("%s() - Incomplete attachment",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: T_ERROR("%s() - Incomplete missing attachment",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: T_ERROR("%s() - Incomplete dimensions",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: T_ERROR("%s() - Incomplete formats",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: T_ERROR("%s() - Incomplete draw buffer",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: T_ERROR("%s() - Incomplete read buffer",method); return false; default: return false; } } /** * Lock texture for writing. Texture may not be bound any more! */ void GLFBOTex::Write(unsigned int iTargetBuffer, int iBuffer, bool bCheckBuffer) { GLenum target = GL_COLOR_ATTACHMENT0_EXT + iTargetBuffer; #ifdef _DEBUG if (!m_hFBO) { T_ERROR("FBO not initialized!"); return; } #endif glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,m_hFBO); assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); m_LastAttachment[iBuffer]=target; glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, target, GL_TEXTURE_2D, m_hTexture[iBuffer], 0); if (m_hDepthBuffer) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,GL_DEPTH_ATTACHMENT_EXT,GL_TEXTURE_2D,m_hDepthBuffer,0); if (bCheckBuffer) { #ifdef _DEBUG if (!CheckFBO("Write")) return; #endif } } void GLFBOTex::FinishWrite(int iBuffer) { glGetError(); assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,m_LastAttachment[iBuffer],GL_TEXTURE_2D,0,0); if (m_hDepthBuffer) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,GL_DEPTH_ATTACHMENT_EXT,GL_TEXTURE_2D,0,0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0); } void GLFBOTex::Read(unsigned int iTargetUnit, int iBuffer) { GLenum texunit = GL_TEXTURE0 + iTargetUnit; #ifdef _DEBUG if (m_LastTexUnit[iBuffer]!=0) { T_ERROR("Missing FinishRead()!"); } #endif assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); m_LastTexUnit[iBuffer]=texunit; glActiveTextureARB(texunit); glBindTexture(GL_TEXTURE_2D,m_hTexture[iBuffer]); } void GLFBOTex::ReadDepth(unsigned int iTargetUnit) { GLenum texunit = GL_TEXTURE0 + iTargetUnit; #ifdef _DEBUG if (m_LastDepthTextUnit!=0) { T_ERROR("Missing FinishDepthRead()!"); } #endif m_LastDepthTextUnit=texunit; glActiveTextureARB(texunit); glBindTexture(GL_TEXTURE_2D,m_hDepthBuffer); } // Finish reading from the depth texture void GLFBOTex::FinishDepthRead() { glActiveTextureARB(m_LastDepthTextUnit); glBindTexture(GL_TEXTURE_2D,0); m_LastDepthTextUnit=0; } void GLFBOTex::NoDrawBuffer() { glDrawBuffer(GL_NONE); } void GLFBOTex::OneDrawBuffer() { glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); } void GLFBOTex::TwoDrawBuffers() { GLenum twobuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT }; glDrawBuffers(2, twobuffers); } void GLFBOTex::ThreeDrawBuffers() { GLenum threebuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT}; glDrawBuffers(3, threebuffers); } void GLFBOTex::FourDrawBuffers() { GLenum fourbuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_COLOR_ATTACHMENT3_EXT}; glDrawBuffers(4, fourbuffers); } // Finish reading from this texture void GLFBOTex::FinishRead(int iBuffer) { assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); glActiveTextureARB(m_LastTexUnit[iBuffer]); glBindTexture(GL_TEXTURE_2D,0); m_LastTexUnit[iBuffer]=0; } <commit_msg>wrap long lines.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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. */ /** \file GLFBOTex.cpp \author Jens Krueger SCI Institute University of Utah Jens Schneider tum.3D, Muenchen \date August 2008 */ #include "GLFBOTex.h" #include <Controller/Controller.h> #ifdef WIN32 #ifndef DEBUG #pragma warning( disable : 4189 ) // disable unused var warning #endif #endif using namespace tuvok; GLuint GLFBOTex::m_hFBO = 0; int GLFBOTex::m_iCount = 0; bool GLFBOTex::m_bInitialized = true; /** * Constructor: on first instantiation, generate an FBO. * In any case a new dummy texture according to the parameters is generated. */ GLFBOTex::GLFBOTex(MasterController* pMasterController, GLenum minfilter, GLenum magfilter, GLenum wrapmode, GLsizei width, GLsizei height, GLenum intformat, unsigned int iSizePerElement, bool bHaveDepth, int iNumBuffers) : m_pMasterController(pMasterController), m_iSizePerElement(iSizePerElement), m_iSizeX(width), m_iSizeY(height), m_hTexture(new GLuint[iNumBuffers]), m_LastDepthTextUnit(0), m_iNumBuffers(iNumBuffers) { if (width<1) width=1; if (height<1) height=1; if (!m_bInitialized) { if (GLEW_OK!=glewInit()) { T_ERROR("failed to initialize GLEW!"); return; } if (!glewGetExtension("GL_EXT_framebuffer_object")) { T_ERROR("GL_EXT_framebuffer_object not supported!"); return; } m_bInitialized=true; } glGetError(); assert(iNumBuffers>0); assert(iNumBuffers<5); m_LastTexUnit=new GLenum[iNumBuffers]; m_LastAttachment=new GLenum[iNumBuffers]; for (int i=0; i<m_iNumBuffers; i++) { m_LastTexUnit[i]=0; m_LastAttachment[i]=GL_COLOR_ATTACHMENT0_EXT+i; m_hTexture[i]=0; } if (m_hFBO==0) initFBO(); { GLenum glerr = glGetError(); if(GL_NO_ERROR != glerr) { T_ERROR("Error '%d' during FBO creation!", static_cast<int>(glerr)); glDeleteFramebuffersEXT(1,&m_hFBO); m_hFBO=0; return; } } initTextures(minfilter,magfilter,wrapmode,width,height,intformat); { GLenum glerr = glGetError(); if(GL_NO_ERROR != glerr) { T_ERROR("Error '%d' during texture creation!", static_cast<int>(glerr)); glDeleteTextures(m_iNumBuffers,m_hTexture); delete[] m_hTexture; m_hTexture=NULL; return; } } if (bHaveDepth) { #ifdef GLFBOTEX_DEPTH_RENDERBUFFER glGenRenderbuffersEXT(1,&m_hDepthBuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24,width,height); #else glGenTextures(1,&m_hDepthBuffer); glBindTexture(GL_TEXTURE_2D,m_hDepthBuffer); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); #endif } else m_hDepthBuffer=0; ++m_iCount; } /** * Destructor: Delete texture object. If no more instances of * GLFBOTex are around, the FBO is deleted as well. */ GLFBOTex::~GLFBOTex(void) { if (m_hTexture) { glDeleteTextures(m_iNumBuffers,m_hTexture); delete[] m_hTexture; m_hTexture=NULL; } if (m_LastTexUnit) { delete[] m_LastTexUnit; m_LastTexUnit=NULL; } if (m_LastAttachment) { delete[] m_LastAttachment; m_LastAttachment=NULL; } #ifdef GLFBOTEX_DEPTH_RENDERBUFFER if (m_hDepthBuffer) glDeleteRenderbuffersEXT(1,&m_hDepthBuffer); #else if (m_hDepthBuffer) glDeleteTextures(1,&m_hDepthBuffer); #endif m_hDepthBuffer=0; --m_iCount; if (m_iCount==0) { m_pMasterController->DebugOut()->Message(_func_, "FBO released via " "destructor call."); glDeleteFramebuffersEXT(1,&m_hFBO); m_hFBO=0; } } /** * Build a dummy texture according to the parameters. */ void GLFBOTex::initTextures(GLenum minfilter, GLenum magfilter, GLenum wrapmode, GLsizei width, GLsizei height, GLenum intformat) { MESSAGE("Initializing 2D texture of dimensions: %ux%u", static_cast<unsigned>(width), static_cast<unsigned>(height)); glDeleteTextures(m_iNumBuffers,m_hTexture); glGenTextures(m_iNumBuffers,m_hTexture); for (int i=0; i<m_iNumBuffers; i++) { glBindTexture(GL_TEXTURE_2D, m_hTexture[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapmode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapmode); int level=0; switch (minfilter) { case GL_NEAREST_MIPMAP_NEAREST: case GL_LINEAR_MIPMAP_NEAREST: case GL_NEAREST_MIPMAP_LINEAR: case GL_LINEAR_MIPMAP_LINEAR: do { glTexImage2D(GL_TEXTURE_2D, level, intformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); width/=2; height/=2; if (width==0 && height>0) width=1; if (width>0 && height==0) height=1; ++level; } while (width>=1 && height>=1); break; default: glTexImage2D(GL_TEXTURE_2D, 0, intformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); } } } /** * Build a new FBO. */ void GLFBOTex::initFBO(void) { MESSAGE("Initializing FBO..."); glGenFramebuffersEXT(1, &m_hFBO); } /** * Check the FBO for consistency. */ bool GLFBOTex::CheckFBO(const char* method) { GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch(status) { case GL_FRAMEBUFFER_COMPLETE_EXT: return true; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: T_ERROR("%s() - Unsupported Format!",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: T_ERROR("%s() - Incomplete attachment",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: T_ERROR("%s() - Incomplete missing attachment",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: T_ERROR("%s() - Incomplete dimensions",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: T_ERROR("%s() - Incomplete formats",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: T_ERROR("%s() - Incomplete draw buffer",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: T_ERROR("%s() - Incomplete read buffer",method); return false; default: return false; } } /** * Lock texture for writing. Texture may not be bound any more! */ void GLFBOTex::Write(unsigned int iTargetBuffer, int iBuffer, bool bCheckBuffer) { GLenum target = GL_COLOR_ATTACHMENT0_EXT + iTargetBuffer; #ifdef _DEBUG if (!m_hFBO) { T_ERROR("FBO not initialized!"); return; } #endif glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,m_hFBO); assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); m_LastAttachment[iBuffer]=target; glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, target, GL_TEXTURE_2D, m_hTexture[iBuffer], 0); if (m_hDepthBuffer) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, m_hDepthBuffer, 0); if (bCheckBuffer) { #ifdef _DEBUG if (!CheckFBO("Write")) return; #endif } } void GLFBOTex::FinishWrite(int iBuffer) { glGetError(); assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, m_LastAttachment[iBuffer], GL_TEXTURE_2D, 0, 0); if (m_hDepthBuffer) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } void GLFBOTex::Read(unsigned int iTargetUnit, int iBuffer) { GLenum texunit = GL_TEXTURE0 + iTargetUnit; #ifdef _DEBUG if (m_LastTexUnit[iBuffer]!=0) { T_ERROR("Missing FinishRead()!"); } #endif assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); m_LastTexUnit[iBuffer]=texunit; glActiveTextureARB(texunit); glBindTexture(GL_TEXTURE_2D,m_hTexture[iBuffer]); } void GLFBOTex::ReadDepth(unsigned int iTargetUnit) { GLenum texunit = GL_TEXTURE0 + iTargetUnit; #ifdef _DEBUG if (m_LastDepthTextUnit!=0) { T_ERROR("Missing FinishDepthRead()!"); } #endif m_LastDepthTextUnit=texunit; glActiveTextureARB(texunit); glBindTexture(GL_TEXTURE_2D,m_hDepthBuffer); } // Finish reading from the depth texture void GLFBOTex::FinishDepthRead() { glActiveTextureARB(m_LastDepthTextUnit); glBindTexture(GL_TEXTURE_2D,0); m_LastDepthTextUnit=0; } void GLFBOTex::NoDrawBuffer() { glDrawBuffer(GL_NONE); } void GLFBOTex::OneDrawBuffer() { glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); } void GLFBOTex::TwoDrawBuffers() { GLenum twobuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT }; glDrawBuffers(2, twobuffers); } void GLFBOTex::ThreeDrawBuffers() { GLenum threebuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT}; glDrawBuffers(3, threebuffers); } void GLFBOTex::FourDrawBuffers() { GLenum fourbuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_COLOR_ATTACHMENT3_EXT}; glDrawBuffers(4, fourbuffers); } // Finish reading from this texture void GLFBOTex::FinishRead(int iBuffer) { assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); glActiveTextureARB(m_LastTexUnit[iBuffer]); glBindTexture(GL_TEXTURE_2D,0); m_LastTexUnit[iBuffer]=0; } <|endoftext|>
<commit_before>/// \file ROOT/RError.h /// \ingroup Base ROOT7 /// \author Jakob Blomer <jblomer@cern.ch> /// \date 2019-12-11 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_RError #define ROOT7_RError #include <ROOT/RConfig.hxx> // for R__[un]likely #include <ROOT/RLogger.hxx> // for R__LOG_PRETTY_FUNCTION #include <cstddef> #include <memory> #include <new> #include <stdexcept> #include <string> #include <type_traits> #include <utility> #include <vector> // The RResult<T> class and their related classes are used for call chains that can throw exceptions, // such as I/O code paths. Throwing of the exception is deferred to allow for `if (result)` style error // checking where it makes sense. // // A function returning an RResult might look like this: // // RResult<int> MyIOFunc() // { // int rv = syscall(...); // if (rv == -1) // R__FAIL("user-facing error message"); // if (rv == kShortcut) // return 42; // R__FORWARD_RESULT(FuncThatReturnsRResultOfInt()); // } // // Code using MyIOFunc might look like this: // // auto result = MyIOOperation(); // if (!result) { // /* custom error handling or result.Throw() */ // } // switch (result.Get()) { // ... // } // // Note that RResult<void> can be used for a function without return value, like this // // RResult<void> DoSomething() // { // if (failure) // R__FAIL("user-facing error messge"); // R__SUCCESS // } namespace ROOT { namespace Experimental { // clang-format off /** \class ROOT::Experimental::RError \ingroup Base \brief Captures diagnostics related to a ROOT runtime error */ // clang-format on class RError { public: struct RLocation { RLocation() = default; RLocation(const std::string &func, const std::string &file, int line) : fFunction(func), fSourceFile(file), fSourceLine(line) {} // TODO(jblomer) use std::source_location once available std::string fFunction; std::string fSourceFile; int fSourceLine; }; private: /// User-facing error message std::string fMessage; /// The location of the error related to fMessage plus upper frames if the error is forwarded through the call stack std::vector<RLocation> fStackTrace; public: /// Used by R__FAIL RError(const std::string &message, RLocation &&sourceLocation); /// Used by R__FORWARD_RESULT void AddFrame(RLocation &&sourceLocation); /// Add more information to the diagnostics void AppendToMessage(const std::string &info) { fMessage += info; } /// Format a dignostics report, e.g. for an exception message std::string GetReport() const; const std::vector<RLocation> &GetStackTrace() const { return fStackTrace; } }; // clang-format off /** \class ROOT::Experimental::RException \ingroup Base \brief Base class for all ROOT issued exceptions */ // clang-format on class RException : public std::runtime_error { RError fError; public: explicit RException(const RError &error) : std::runtime_error(error.GetReport()), fError(error) {} const RError &GetError() const { return fError; } }; /// Wrapper class that generates a data member of type T in RResult<T> for all Ts except T == void namespace Internal { template <typename T> struct RResultType { RResultType() = default; explicit RResultType(const T &value) : fValue(value) {} T fValue; }; template <> struct RResultType<void> {}; } // namespace Internal // clang-format off /** \class ROOT::Experimental::RResult \ingroup Base \brief The class is used as a return type for operations that can fail; wraps a value of type T or an RError RResult enforces checking whether it contains a valid value or an error state. If the RResult leaves the scope unchecked, it will throw an exception. RResult should only be allocated on the stack, which is helped by deleting the new operator. RResult is movable but not copyable to avoid throwing multiple exceptions about the same failure. */ // clang-format on template <typename T> class RResult : public Internal::RResultType<T> { private: /// This is the nullptr for an RResult representing success std::unique_ptr<RError> fError; /// This is safe because checking an RResult is not a multi-threaded operation mutable bool fIsChecked{false}; public: /// Constructor is _not_ explicit in order to allow for `return T();` for functions returning RResult<T> /// Only available if T is not void template <typename Dummy = T, typename = typename std::enable_if_t<!std::is_void<T>::value, Dummy>> RResult(const Dummy &value) : Internal::RResultType<T>(value) {} /// Constructor is _not_ explicit such that the RError returned by R__FAIL can be converted into an RResult<T> /// for any T RResult(const RError &error) : fError(std::make_unique<RError>(error)) {} /// RResult<void> has a default contructor that creates an object representing success template <typename Dummy = T, typename = typename std::enable_if_t<std::is_void<T>::value, Dummy>> RResult() {} RResult(const RResult &other) = delete; RResult(RResult &&other) = default; RResult &operator =(const RResult &other) = delete; RResult &operator =(RResult &&other) = default; ~RResult() noexcept(false) { if (R__unlikely(fError && !fIsChecked)) { // Prevent from throwing if the object is deconstructed in the course of stack unwinding for another exception #if __cplusplus >= 201703L if (std::uncaught_exceptions() == 0) #else if (!std::uncaught_exception()) #endif { throw RException(*fError); } } } /// Only available if T is not void template <typename Dummy = T> typename std::enable_if_t<!std::is_void<T>::value, const Dummy &> Get() { if (R__unlikely(fError)) { fError->AppendToMessage(" (invalid access)"); throw RException(*fError); } return Internal::RResultType<T>::fValue; } explicit operator bool() const { fIsChecked = true; return !fError; } RError *GetError() { return fError.get(); } void Throw() { throw RException(*fError); } // Help to prevent heap construction of RResult objects. Unchecked RResult objects in failure state should throw // an exception close to the error location. For stack allocated RResult objects, an exception is thrown // the latest when leaving the scope. Heap allocated ill RResult objects can live much longer making it difficult // to trace back the original failure. void *operator new(std::size_t size) = delete; void *operator new(std::size_t, void *) = delete; void *operator new[](std::size_t) = delete; void *operator new[](std::size_t, void *) = delete; }; /// Short-hand to return an RResult<void> indicating success #define R__SUCCESS return ROOT::Experimental::RResult<void>(); /// Short-hand to return an RResult<T> in an error state; the RError is implicitly converted into RResult<T> #define R__FAIL(msg) return ROOT::Experimental::RError(msg, {R__LOG_PRETTY_FUNCTION, __FILE__, __LINE__}) /// Short-hand to return an RResult<T> value from a subroutine to the calling stack frame #define R__FORWARD_RESULT(res) if (res.GetError()) \ { res.GetError()->AddFrame({R__LOG_PRETTY_FUNCTION, __FILE__, __LINE__}); } \ return res } // namespace Experimental } // namespace ROOT #endif <commit_msg>[v7, excpetions] don't lie about const-ness<commit_after>/// \file ROOT/RError.h /// \ingroup Base ROOT7 /// \author Jakob Blomer <jblomer@cern.ch> /// \date 2019-12-11 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_RError #define ROOT7_RError #include <ROOT/RConfig.hxx> // for R__[un]likely #include <ROOT/RLogger.hxx> // for R__LOG_PRETTY_FUNCTION #include <cstddef> #include <memory> #include <new> #include <stdexcept> #include <string> #include <type_traits> #include <utility> #include <vector> // The RResult<T> class and their related classes are used for call chains that can throw exceptions, // such as I/O code paths. Throwing of the exception is deferred to allow for `if (result)` style error // checking where it makes sense. // // A function returning an RResult might look like this: // // RResult<int> MyIOFunc() // { // int rv = syscall(...); // if (rv == -1) // R__FAIL("user-facing error message"); // if (rv == kShortcut) // return 42; // R__FORWARD_RESULT(FuncThatReturnsRResultOfInt()); // } // // Code using MyIOFunc might look like this: // // auto result = MyIOOperation(); // if (!result) { // /* custom error handling or result.Throw() */ // } // switch (result.Get()) { // ... // } // // Note that RResult<void> can be used for a function without return value, like this // // RResult<void> DoSomething() // { // if (failure) // R__FAIL("user-facing error messge"); // R__SUCCESS // } namespace ROOT { namespace Experimental { // clang-format off /** \class ROOT::Experimental::RError \ingroup Base \brief Captures diagnostics related to a ROOT runtime error */ // clang-format on class RError { public: struct RLocation { RLocation() = default; RLocation(const std::string &func, const std::string &file, int line) : fFunction(func), fSourceFile(file), fSourceLine(line) {} // TODO(jblomer) use std::source_location once available std::string fFunction; std::string fSourceFile; int fSourceLine; }; private: /// User-facing error message std::string fMessage; /// The location of the error related to fMessage plus upper frames if the error is forwarded through the call stack std::vector<RLocation> fStackTrace; public: /// Used by R__FAIL RError(const std::string &message, RLocation &&sourceLocation); /// Used by R__FORWARD_RESULT void AddFrame(RLocation &&sourceLocation); /// Add more information to the diagnostics void AppendToMessage(const std::string &info) { fMessage += info; } /// Format a dignostics report, e.g. for an exception message std::string GetReport() const; const std::vector<RLocation> &GetStackTrace() const { return fStackTrace; } }; // clang-format off /** \class ROOT::Experimental::RException \ingroup Base \brief Base class for all ROOT issued exceptions */ // clang-format on class RException : public std::runtime_error { RError fError; public: explicit RException(const RError &error) : std::runtime_error(error.GetReport()), fError(error) {} const RError &GetError() const { return fError; } }; /// Wrapper class that generates a data member of type T in RResult<T> for all Ts except T == void namespace Internal { template <typename T> struct RResultType { RResultType() = default; explicit RResultType(const T &value) : fValue(value) {} T fValue; }; template <> struct RResultType<void> {}; } // namespace Internal // clang-format off /** \class ROOT::Experimental::RResult \ingroup Base \brief The class is used as a return type for operations that can fail; wraps a value of type T or an RError RResult enforces checking whether it contains a valid value or an error state. If the RResult leaves the scope unchecked, it will throw an exception. RResult should only be allocated on the stack, which is helped by deleting the new operator. RResult is movable but not copyable to avoid throwing multiple exceptions about the same failure. */ // clang-format on template <typename T> class RResult : public Internal::RResultType<T> { private: /// This is the nullptr for an RResult representing success std::unique_ptr<RError> fError; /// Switches to true once the user of an RResult object checks the object status bool fIsChecked{false}; public: /// Constructor is _not_ explicit in order to allow for `return T();` for functions returning RResult<T> /// Only available if T is not void template <typename Dummy = T, typename = typename std::enable_if_t<!std::is_void<T>::value, Dummy>> RResult(const Dummy &value) : Internal::RResultType<T>(value) {} /// Constructor is _not_ explicit such that the RError returned by R__FAIL can be converted into an RResult<T> /// for any T RResult(const RError &error) : fError(std::make_unique<RError>(error)) {} /// RResult<void> has a default contructor that creates an object representing success template <typename Dummy = T, typename = typename std::enable_if_t<std::is_void<T>::value, Dummy>> RResult() {} RResult(const RResult &other) = delete; RResult(RResult &&other) = default; RResult &operator =(const RResult &other) = delete; RResult &operator =(RResult &&other) = default; ~RResult() noexcept(false) { if (R__unlikely(fError && !fIsChecked)) { // Prevent from throwing if the object is deconstructed in the course of stack unwinding for another exception #if __cplusplus >= 201703L if (std::uncaught_exceptions() == 0) #else if (!std::uncaught_exception()) #endif { throw RException(*fError); } } } /// Only available if T is not void template <typename Dummy = T> typename std::enable_if_t<!std::is_void<T>::value, const Dummy &> Get() { if (R__unlikely(fError)) { fError->AppendToMessage(" (invalid access)"); throw RException(*fError); } return Internal::RResultType<T>::fValue; } explicit operator bool() { fIsChecked = true; return !fError; } RError *GetError() { return fError.get(); } void Throw() { throw RException(*fError); } // Help to prevent heap construction of RResult objects. Unchecked RResult objects in failure state should throw // an exception close to the error location. For stack allocated RResult objects, an exception is thrown // the latest when leaving the scope. Heap allocated ill RResult objects can live much longer making it difficult // to trace back the original failure. void *operator new(std::size_t size) = delete; void *operator new(std::size_t, void *) = delete; void *operator new[](std::size_t) = delete; void *operator new[](std::size_t, void *) = delete; }; /// Short-hand to return an RResult<void> indicating success #define R__SUCCESS return ROOT::Experimental::RResult<void>(); /// Short-hand to return an RResult<T> in an error state; the RError is implicitly converted into RResult<T> #define R__FAIL(msg) return ROOT::Experimental::RError(msg, {R__LOG_PRETTY_FUNCTION, __FILE__, __LINE__}) /// Short-hand to return an RResult<T> value from a subroutine to the calling stack frame #define R__FORWARD_RESULT(res) if (res.GetError()) \ { res.GetError()->AddFrame({R__LOG_PRETTY_FUNCTION, __FILE__, __LINE__}); } \ return res } // namespace Experimental } // namespace ROOT #endif <|endoftext|>
<commit_before>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2020, Marcus Rowe <undisbeliever@gmail.com>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "imgui-filebrowser.h" #include "vendor/imgui-filebrowser/imfilebrowser.h" #include "vendor/imgui/imgui_internal.h" namespace ImGui { std::pair<bool, std::optional<std::filesystem::path>> SaveFileDialog(const char* strId, const std::string& title, const char* extension) { static ImGuiID fileDialogId = 0; static FileBrowser fileDialog(ImGuiFileBrowserFlags_EnterNewFilename | ImGuiFileBrowserFlags_CloseOnEsc); const ImGuiID id = GetID(strId); if (fileDialogId != id || !fileDialog.IsOpened()) { fileDialogId = id; fileDialog.SetTitle(title); fileDialog.SetTypeFilters({ extension }); fileDialog.Open(); } fileDialog.Display(); if (!fileDialog.IsOpened()) { if (fileDialog.HasSelected()) { auto fn = fileDialog.GetSelected(); fileDialog.ClearSelected(); if (fn.extension().empty()) { fn += extension; } return { true, std::filesystem::absolute(fn) }; } else { return { true, std::nullopt }; } } else { return { false, std::nullopt }; } } std::pair<bool, std::optional<std::filesystem::path>> OpenFileDialog(const char* strId, const std::string& title, const char* extension) { static ImGuiID fileDialogId = 0; static FileBrowser fileDialog(ImGuiFileBrowserFlags_CloseOnEsc); const ImGuiID id = GetID(strId); if (fileDialogId != id || !fileDialog.IsOpened()) { fileDialogId = id; fileDialog.SetTitle(title); fileDialog.SetTypeFilters({ extension }); fileDialog.Open(); } fileDialog.Display(); if (!fileDialog.IsOpened()) { if (fileDialog.HasSelected()) { const auto fn = fileDialog.GetSelected(); fileDialog.ClearSelected(); return { true, std::filesystem::absolute(fn) }; } else { return { true, std::nullopt }; } } else { return { false, std::nullopt }; } } std::optional<std::filesystem::path> SaveFileDialogButton(const char* label, const std::string& title, const char* extension, const ImVec2& size) { static FileBrowser fileDialog(ImGuiFileBrowserFlags_EnterNewFilename | ImGuiFileBrowserFlags_CloseOnEsc); PushID(label); if (Button(label, size)) { fileDialog.SetTitle(title); fileDialog.SetTypeFilters({ extension }); fileDialog.Open(); } fileDialog.Display(); PopID(); if (fileDialog.HasSelected()) { auto fn = fileDialog.GetSelected(); if (fn.extension().empty()) { fn += extension; } fileDialog.ClearSelected(); return std::filesystem::absolute(fn); } return std::nullopt; } std::optional<std::filesystem::path> OpenFileDialogButton(const char* label, const std::string& title, const char* extension, const ImVec2& size) { static FileBrowser fileDialog(ImGuiFileBrowserFlags_CloseOnEsc); PushID(label); if (Button(label, size)) { fileDialog.SetTitle(title); fileDialog.SetTypeFilters({ extension }); fileDialog.Open(); } fileDialog.Display(); PopID(); if (fileDialog.HasSelected()) { auto fn = fileDialog.GetSelected(); fileDialog.ClearSelected(); return std::filesystem::absolute(fn); } return std::nullopt; } bool InputPngImageFilename(const char* label, std::filesystem::path* path) { static ImGuiID activeDialogId; static ImGui::FileBrowser fileDialog = []() { ImGui::FileBrowser d(ImGuiFileBrowserFlags_CloseOnEsc); d.SetTitle("Select PNG Image"); d.SetTypeFilters({ ".png" }); return d; }(); const auto innerSpacingX = ImGui::GetStyle().ItemInnerSpacing.x; bool pathEdited = false; const ImGuiID id = GetID(label); BeginGroup(); PushID(label); const float buttonWidth = CalcItemWidth(); std::string basename = path->filename().u8string(); if (Button(basename.data(), ImVec2(buttonWidth, 0))) { if (!path->empty()) { auto p = std::filesystem::absolute(path->parent_path()).lexically_normal(); fileDialog.SetPwd(p); } fileDialog.Open(); activeDialogId = id; } if (activeDialogId == id) { fileDialog.Display(); if (fileDialog.HasSelected()) { auto fn = std::filesystem::absolute(fileDialog.GetSelected()).lexically_normal(); if (*path != fn) { *path = std::move(fn); pathEdited = true; } fileDialog.ClearSelected(); } } const char* label_end = FindRenderedTextEnd(label); if (label != label_end) { SameLine(0.0f, innerSpacingX); TextEx(label, label_end); } PopID(); EndGroup(); return pathEdited; } } <commit_msg>Cleanup imgui-filebrowser.cpp<commit_after>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2020, Marcus Rowe <undisbeliever@gmail.com>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "imgui-filebrowser.h" #include "vendor/imgui-filebrowser/imfilebrowser.h" #include "vendor/imgui/imgui_internal.h" namespace ImGui { static ImGuiID saveDialogId = 0; static FileBrowser saveDialog(ImGuiFileBrowserFlags_EnterNewFilename | ImGuiFileBrowserFlags_CloseOnEsc); static ImGuiID openDialogId = 0; static FileBrowser openDialog(ImGuiFileBrowserFlags_CloseOnEsc); static void openSaveDialog(const ImGuiID id, const std::string& title, const char* extension) { if (saveDialogId != id || !saveDialog.IsOpened()) { saveDialogId = id; saveDialog.SetTitle(title); saveDialog.SetTypeFilters({ extension }); saveDialog.Open(); } } static std::pair<bool, std::optional<std::filesystem::path>> processSaveDialog(const ImGuiID id, const char* extension) { if (saveDialogId == id) { saveDialog.Display(); if (!saveDialog.IsOpened()) { if (saveDialog.HasSelected()) { auto fn = saveDialog.GetSelected(); saveDialog.ClearSelected(); if (fn.extension().empty()) { fn += extension; } fn = std::filesystem::absolute(fn).lexically_normal(); return { true, fn }; } return { true, std::nullopt }; } } return { false, std::nullopt }; } static void openOpenDialog(const ImGuiID id, const std::string& title, const char* extension) { if (openDialogId != id || !openDialog.IsOpened()) { openDialogId = id; openDialog.SetTitle(title); openDialog.SetTypeFilters({ extension }); openDialog.Open(); } } static std::pair<bool, std::optional<std::filesystem::path>> processOpenDialog(const ImGuiID id) { if (openDialogId == id) { openDialog.Display(); if (!openDialog.IsOpened()) { if (openDialog.HasSelected()) { auto fn = openDialog.GetSelected(); openDialog.ClearSelected(); fn = std::filesystem::absolute(fn).lexically_normal(); return { true, fn }; } return { true, std::nullopt }; } } return { false, std::nullopt }; } std::pair<bool, std::optional<std::filesystem::path>> SaveFileDialog(const char* strId, const std::string& title, const char* extension) { const ImGuiID id = GetID(strId); openSaveDialog(id, title, extension); return processSaveDialog(id, extension); } std::pair<bool, std::optional<std::filesystem::path>> OpenFileDialog(const char* strId, const std::string& title, const char* extension) { const ImGuiID id = GetID(strId); openOpenDialog(id, title, extension); return processOpenDialog(id); } std::optional<std::filesystem::path> SaveFileDialogButton(const char* label, const std::string& title, const char* extension, const ImVec2& size) { const ImGuiID id = GetID(label); if (Button(label, size)) { openSaveDialog(id, title, extension); } const auto [closed, fn] = processSaveDialog(id, extension); return fn; } std::optional<std::filesystem::path> OpenFileDialogButton(const char* label, const std::string& title, const char* extension, const ImVec2& size) { const ImGuiID id = GetID(label); if (Button(label, size)) { openOpenDialog(id, title, extension); } const auto [closed, fn] = processOpenDialog(id); return fn; } bool InputPngImageFilename(const char* label, std::filesystem::path* path) { const auto innerSpacingX = ImGui::GetStyle().ItemInnerSpacing.x; bool pathEdited = false; const ImGuiID id = GetID(label); BeginGroup(); PushID(label); const float buttonWidth = CalcItemWidth(); std::string basename = path->filename().u8string(); if (Button(basename.data(), ImVec2(buttonWidth, 0))) { if (!path->empty()) { auto p = std::filesystem::absolute(path->parent_path()).lexically_normal(); openDialog.SetPwd(p); } openOpenDialog(id, "Select PNG Image", ".png"); } const auto [closed, fn] = processOpenDialog(id); if (fn) { if (*path != fn) { *path = std::move(*fn); pathEdited = true; } } const char* label_end = FindRenderedTextEnd(label); if (label != label_end) { SameLine(0.0f, innerSpacingX); TextEx(label, label_end); } PopID(); EndGroup(); return pathEdited; } } <|endoftext|>
<commit_before>// IVSHMEM-test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #define TEST_START(name) printf("Test: %s...", name) #define TEST_PASS() printf("PASS\n") #define TEST_FAIL(reason) printf("FAIL - %s\n", reason) int main() { HDEVINFO deviceInfoSet; DWORD deviceIndex; PSP_DEVICE_INTERFACE_DETAIL_DATA infData = NULL; HANDLE devHandle = INVALID_HANDLE_VALUE; deviceInfoSet = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_PRESENT | DIGCF_ALLCLASSES | DIGCF_DEVICEINTERFACE); SP_DEVICE_INTERFACE_DATA deviceInterfaceData; ZeroMemory(&deviceInterfaceData, sizeof(SP_DEVICE_INTERFACE_DATA)); deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); deviceIndex = 0; while (1) { TEST_START("Find device"); if (SetupDiEnumDeviceInterfaces(deviceInfoSet, NULL, &GUID_DEVINTERFACE_IVSHMEM, 0, &deviceInterfaceData) == FALSE) { DWORD error = GetLastError(); if (error == ERROR_NO_MORE_ITEMS) { TEST_FAIL("Unable to enumerate the device, is it attached?"); break; } TEST_FAIL("SetupDiEnumDeviceInterfaces failed"); break; } TEST_PASS(); TEST_START("Get device name length"); DWORD reqSize = 0; // this returns false even though we succeed in getting the size SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, NULL, 0, &reqSize, NULL); if (!reqSize) { TEST_FAIL("SetupDiGetDeviceInterfaceDetail"); break; } TEST_PASS(); TEST_START("Get device name"); infData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(reqSize); infData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); if (!SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, infData, reqSize, NULL, NULL)) { TEST_FAIL("SetupDiGetDeviceInterfaceDetail"); break; } TEST_PASS(); TEST_START("Open device"); devHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0); if (devHandle == INVALID_HANDLE_VALUE) { TEST_FAIL("CreateFile returned INVALID_HANDLE_VALUE"); break; } TEST_PASS(); TEST_START("IOCTL_IVSHMEM_REQUEST_PEERID"); IVSHMEM_PEERID peer = 0; ULONG ulReturnedLength = 0; if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_PEERID, NULL, 0, &peer, sizeof(IVSHMEM_PEERID), &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); printf("Error 0x%x\n", GetLastError()); break; } TEST_PASS(); printf("Peer: %u\n", peer); TEST_START("IOCTL_IVSHMEM_REQUEST_SIZE"); IVSHMEM_SIZE size = 0; if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_SIZE, NULL, 0, &size, sizeof(IVSHMEM_SIZE), &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); break; } if (size == 0) { TEST_FAIL("Size should not be zero"); break; } TEST_PASS(); printf("Size: %I64u\n", size); TEST_START("IOCTL_IVSHMEM_REQUEST_MMAP"); IVSHMEM_MMAP_CONFIG config; config.cacheMode = IVSHMEM_CACHE_NONCACHED; IVSHMEM_MMAP map; ZeroMemory(&map, sizeof(IVSHMEM_MMAP)); if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &config, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); break; } if (!map.ptr) { TEST_FAIL("NULL pointer to mapping returned"); break; } if (map.size != size) { TEST_FAIL("Incorrect size"); break; } TEST_PASS(); TEST_START("Mapping more then once fails"); if (DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, NULL, 0, &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("mapping succeeded, this should not happen!"); break; } TEST_PASS(); TEST_START("Mapping from another handle fails"); HANDLE devHandle2 = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0); if (!devHandle2) { TEST_FAIL("Failed to open second handle"); break; } if (DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, NULL, 0, &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("mapping succeeded, this should not happen!"); break; } CloseHandle(devHandle2); TEST_PASS(); TEST_START("IOCTL_IVSHMEM_RING_DOORBELL"); IVSHMEM_RING ring; ring.peerID = 0; ring.vector = 0; if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_RING_DOORBELL, &ring, sizeof(IVSHMEM_RING), NULL, 0, &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); break; } TEST_PASS(); TEST_START("IOCTL_IVSHMEM_RELEASE_MMAP"); if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_RELEASE_MMAP, NULL, 0, NULL, 0, &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); break; } TEST_PASS(); TEST_START("Closing handle releases mapping"); CloseHandle(devHandle); devHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0); if (devHandle == INVALID_HANDLE_VALUE) { TEST_FAIL("Failed to re-open handle"); break; } if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, NULL, 0, &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("Mapping failed!"); break; } TEST_PASS(); TEST_START("Shared memory actually works"); memset(map.ptr, 0xAA, (size_t)map.size); CloseHandle(devHandle); devHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0); if (devHandle == INVALID_HANDLE_VALUE) { TEST_FAIL("Failed to re-open handle"); break; } if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, NULL, 0, &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("Mapping failed!"); break; } bool fail = false; unsigned char *data = (unsigned char *)map.ptr; for (UINT64 i = 0; i < map.size; ++i) if (data[i] != 0xAA) { TEST_FAIL("Invalid data read back"); fail = true; break; } if (fail) break; TEST_PASS(); if (map.vectors > 0) { TEST_START("Check events work, send interrupt 0 to this peer"); IVSHMEM_EVENT event; event.event = CreateEvent(NULL, TRUE, FALSE, L"TEST_EVENT"); event.vector = 0; event.singleShot = TRUE; if (event.event == INVALID_HANDLE_VALUE) { TEST_FAIL("Failed to create the event"); break; } if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REGISTER_EVENT, &event, sizeof(IVSHMEM_EVENT), NULL, 0, &ulReturnedLength, NULL)) { TEST_FAIL("Register event failed!"); CloseHandle(event.event); break; } if (WaitForSingleObject(event.event, INFINITE) != WAIT_OBJECT_0) { TEST_FAIL("WaitForSingleObject failed!"); CloseHandle(event.event); break; } CloseHandle(event.event); TEST_PASS(); } break; } if (devHandle != INVALID_HANDLE_VALUE) CloseHandle(devHandle); if (infData) free(infData); SetupDiDestroyDeviceInfoList(deviceInfoSet); return 0; } <commit_msg>ivshmem: fix main() declaration<commit_after>// IVSHMEM-test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #define TEST_START(name) printf("Test: %s...", name) #define TEST_PASS() printf("PASS\n") #define TEST_FAIL(reason) printf("FAIL - %s\n", reason) int __cdecl main() { HDEVINFO deviceInfoSet; DWORD deviceIndex; PSP_DEVICE_INTERFACE_DETAIL_DATA infData = NULL; HANDLE devHandle = INVALID_HANDLE_VALUE; deviceInfoSet = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_PRESENT | DIGCF_ALLCLASSES | DIGCF_DEVICEINTERFACE); SP_DEVICE_INTERFACE_DATA deviceInterfaceData; ZeroMemory(&deviceInterfaceData, sizeof(SP_DEVICE_INTERFACE_DATA)); deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); deviceIndex = 0; while (1) { TEST_START("Find device"); if (SetupDiEnumDeviceInterfaces(deviceInfoSet, NULL, &GUID_DEVINTERFACE_IVSHMEM, 0, &deviceInterfaceData) == FALSE) { DWORD error = GetLastError(); if (error == ERROR_NO_MORE_ITEMS) { TEST_FAIL("Unable to enumerate the device, is it attached?"); break; } TEST_FAIL("SetupDiEnumDeviceInterfaces failed"); break; } TEST_PASS(); TEST_START("Get device name length"); DWORD reqSize = 0; // this returns false even though we succeed in getting the size SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, NULL, 0, &reqSize, NULL); if (!reqSize) { TEST_FAIL("SetupDiGetDeviceInterfaceDetail"); break; } TEST_PASS(); TEST_START("Get device name"); infData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(reqSize); infData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); if (!SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, infData, reqSize, NULL, NULL)) { TEST_FAIL("SetupDiGetDeviceInterfaceDetail"); break; } TEST_PASS(); TEST_START("Open device"); devHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0); if (devHandle == INVALID_HANDLE_VALUE) { TEST_FAIL("CreateFile returned INVALID_HANDLE_VALUE"); break; } TEST_PASS(); TEST_START("IOCTL_IVSHMEM_REQUEST_PEERID"); IVSHMEM_PEERID peer = 0; ULONG ulReturnedLength = 0; if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_PEERID, NULL, 0, &peer, sizeof(IVSHMEM_PEERID), &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); printf("Error 0x%x\n", GetLastError()); break; } TEST_PASS(); printf("Peer: %u\n", peer); TEST_START("IOCTL_IVSHMEM_REQUEST_SIZE"); IVSHMEM_SIZE size = 0; if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_SIZE, NULL, 0, &size, sizeof(IVSHMEM_SIZE), &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); break; } if (size == 0) { TEST_FAIL("Size should not be zero"); break; } TEST_PASS(); printf("Size: %I64u\n", size); TEST_START("IOCTL_IVSHMEM_REQUEST_MMAP"); IVSHMEM_MMAP_CONFIG config; config.cacheMode = IVSHMEM_CACHE_NONCACHED; IVSHMEM_MMAP map; ZeroMemory(&map, sizeof(IVSHMEM_MMAP)); if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &config, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); break; } if (!map.ptr) { TEST_FAIL("NULL pointer to mapping returned"); break; } if (map.size != size) { TEST_FAIL("Incorrect size"); break; } TEST_PASS(); TEST_START("Mapping more then once fails"); if (DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, NULL, 0, &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("mapping succeeded, this should not happen!"); break; } TEST_PASS(); TEST_START("Mapping from another handle fails"); HANDLE devHandle2 = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0); if (!devHandle2) { TEST_FAIL("Failed to open second handle"); break; } if (DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, NULL, 0, &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("mapping succeeded, this should not happen!"); break; } CloseHandle(devHandle2); TEST_PASS(); TEST_START("IOCTL_IVSHMEM_RING_DOORBELL"); IVSHMEM_RING ring; ring.peerID = 0; ring.vector = 0; if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_RING_DOORBELL, &ring, sizeof(IVSHMEM_RING), NULL, 0, &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); break; } TEST_PASS(); TEST_START("IOCTL_IVSHMEM_RELEASE_MMAP"); if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_RELEASE_MMAP, NULL, 0, NULL, 0, &ulReturnedLength, NULL)) { TEST_FAIL("DeviceIoControl"); break; } TEST_PASS(); TEST_START("Closing handle releases mapping"); CloseHandle(devHandle); devHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0); if (devHandle == INVALID_HANDLE_VALUE) { TEST_FAIL("Failed to re-open handle"); break; } if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, NULL, 0, &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("Mapping failed!"); break; } TEST_PASS(); TEST_START("Shared memory actually works"); memset(map.ptr, 0xAA, (size_t)map.size); CloseHandle(devHandle); devHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0); if (devHandle == INVALID_HANDLE_VALUE) { TEST_FAIL("Failed to re-open handle"); break; } if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, NULL, 0, &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL)) { TEST_FAIL("Mapping failed!"); break; } bool fail = false; unsigned char *data = (unsigned char *)map.ptr; for (UINT64 i = 0; i < map.size; ++i) if (data[i] != 0xAA) { TEST_FAIL("Invalid data read back"); fail = true; break; } if (fail) break; TEST_PASS(); if (map.vectors > 0) { TEST_START("Check events work, send interrupt 0 to this peer"); IVSHMEM_EVENT event; event.event = CreateEvent(NULL, TRUE, FALSE, L"TEST_EVENT"); event.vector = 0; event.singleShot = TRUE; if (event.event == INVALID_HANDLE_VALUE) { TEST_FAIL("Failed to create the event"); break; } if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REGISTER_EVENT, &event, sizeof(IVSHMEM_EVENT), NULL, 0, &ulReturnedLength, NULL)) { TEST_FAIL("Register event failed!"); CloseHandle(event.event); break; } if (WaitForSingleObject(event.event, INFINITE) != WAIT_OBJECT_0) { TEST_FAIL("WaitForSingleObject failed!"); CloseHandle(event.event); break; } CloseHandle(event.event); TEST_PASS(); } break; } if (devHandle != INVALID_HANDLE_VALUE) CloseHandle(devHandle); if (infData) free(infData); SetupDiDestroyDeviceInfoList(deviceInfoSet); return 0; } <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <csql/defaults.h> using namespace stx; namespace csql { void installDefaultSymbols(SymbolTable* rt) { /* expressions/aggregate.h */ rt->registerFunction("count", expressions::kCountExpr); rt->registerFunction("sum", expressions::kSumExpr); //rt->registerSymbol( // "mean", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "avg", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "average", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "min", // &expressions::minExpr, // expressions::minExprScratchpadSize(), // &expressions::minExprFree); //rt->registerSymbol( // "max", // &expressions::maxExpr, // expressions::maxExprScratchpadSize(), // &expressions::maxExprFree); /* expressions/boolean.h */ rt->registerFunction("eq", PureFunction(&expressions::eqExpr)); rt->registerFunction("neq", PureFunction(&expressions::neqExpr)); rt->registerFunction("and", PureFunction(&expressions::andExpr)); rt->registerFunction("or", PureFunction(&expressions::orExpr)); rt->registerFunction("neg", PureFunction(&expressions::negExpr)); rt->registerFunction("lt", PureFunction(&expressions::ltExpr)); rt->registerFunction("lte", PureFunction(&expressions::lteExpr)); rt->registerFunction("gt", PureFunction(&expressions::gtExpr)); rt->registerFunction("gte", PureFunction(&expressions::gteExpr)); /* expressions/UnixTime.h */ rt->registerFunction( "FROM_TIMESTAMP", PureFunction(&expressions::fromTimestamp)); /* expressions/math.h */ rt->registerFunction("add", PureFunction(&expressions::addExpr)); rt->registerFunction("sub", PureFunction(&expressions::subExpr)); rt->registerFunction("mul", PureFunction(&expressions::mulExpr)); rt->registerFunction("div", PureFunction(&expressions::divExpr)); rt->registerFunction("mod", PureFunction(&expressions::modExpr)); rt->registerFunction("pow", PureFunction(&expressions::powExpr)); } } // namespace csql <commit_msg>update deps<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <csql/defaults.h> using namespace stx; namespace csql { void installDefaultSymbols(SymbolTable* rt) { /* expressions/aggregate.h */ rt->registerFunction("count", expressions::kCountExpr); rt->registerFunction("sum", expressions::kSumExpr); rt->registerFunction("mean", expressions::kMeanExpr); //rt->registerSymbol( // "mean", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "avg", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "average", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "min", // &expressions::minExpr, // expressions::minExprScratchpadSize(), // &expressions::minExprFree); //rt->registerSymbol( // "max", // &expressions::maxExpr, // expressions::maxExprScratchpadSize(), // &expressions::maxExprFree); /* expressions/boolean.h */ rt->registerFunction("eq", PureFunction(&expressions::eqExpr)); rt->registerFunction("neq", PureFunction(&expressions::neqExpr)); rt->registerFunction("and", PureFunction(&expressions::andExpr)); rt->registerFunction("or", PureFunction(&expressions::orExpr)); rt->registerFunction("neg", PureFunction(&expressions::negExpr)); rt->registerFunction("lt", PureFunction(&expressions::ltExpr)); rt->registerFunction("lte", PureFunction(&expressions::lteExpr)); rt->registerFunction("gt", PureFunction(&expressions::gtExpr)); rt->registerFunction("gte", PureFunction(&expressions::gteExpr)); /* expressions/UnixTime.h */ rt->registerFunction( "FROM_TIMESTAMP", PureFunction(&expressions::fromTimestamp)); /* expressions/math.h */ rt->registerFunction("add", PureFunction(&expressions::addExpr)); rt->registerFunction("sub", PureFunction(&expressions::subExpr)); rt->registerFunction("mul", PureFunction(&expressions::mulExpr)); rt->registerFunction("div", PureFunction(&expressions::divExpr)); rt->registerFunction("mod", PureFunction(&expressions::modExpr)); rt->registerFunction("pow", PureFunction(&expressions::powExpr)); } } // namespace csql <|endoftext|>
<commit_before>#include <iostream> #include "ctvm.h" #include "ctvm_util.h" int main(int argc, char **argv){ /* Program: ctvm-recover <sinogram-image> <tilt-angles> <recovered-output> ----------- */ using namespace std; /* Test Inputs */ if(argc != 4){ cout<<"Usage: ctvm-recover <sinogram-image> <tilt-angles> <recovered-output>"<<endl; return 0; } /* Get Filenames */ char* SinogramFile = argv[1]; char* TiltAngleFile = argv[2]; char* RecoveredOutput = argv[3]; /* Debugging */ cout<<"SinogramFile: "<<SinogramFile<<endl; cout<<"TiltAngleFile: "<<TiltAngleFile<<endl; cout<<"RecoveredOutput: "<<RecoveredOutput<<endl; cout<<endl; /* Load Tilt Anlges */ cout<<"Loading Tilt Angles."<<endl; BoostDoubleVector TiltAngles = ReadTiltAngles(TiltAngleFile); cout<<TiltAngles<<endl; /* Load Sinogram */ cout<<"Loading Sinogram."<<endl; BoostDoubleMatrix Sinogram = LoadImage(SinogramFile); return 0; }<commit_msg>Reconstruction Call<commit_after>#include <iostream> #include "ctvm.h" #include "ctvm_util.h" int main(int argc, char **argv){ /* Program: ctvm-recover <sinogram-image> <tilt-angles> <recovered-output> ----------- */ using namespace std; /* Test Inputs */ if(argc != 4){ cout<<"Usage: ctvm-recover <sinogram-image> <tilt-angles> <recovered-output>"<<endl; return 0; } /* Get Filenames */ char* SinogramFile = argv[1]; char* TiltAngleFile = argv[2]; char* RecoveredOutput = argv[3]; /* Debugging */ cout<<"SinogramFile: "<<SinogramFile<<endl; cout<<"TiltAngleFile: "<<TiltAngleFile<<endl; cout<<"RecoveredOutput: "<<RecoveredOutput<<endl; cout<<endl; /* Load Tilt Anlges */ cout<<"Loading Tilt Angles."<<endl; BoostDoubleVector TiltAngles = ReadTiltAngles(TiltAngleFile); cout<<TiltAngles<<endl; /* Load Sinogram */ cout<<"Loading Sinogram."<<endl; BoostDoubleMatrix Sinogram = LoadImage(SinogramFile); /* Call Reconstruction */ BoostDoubleMatrix Reconstruction = tval3_reconstruction(Sinogram,TiltAngles); return 0; }<|endoftext|>
<commit_before>// @(#)root/cont:$Id$ // Author: Fons Rademakers 04/08/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSeqCollection // // // // Sequenceable collection abstract base class. TSeqCollection's have // // an ordering relation, i.e. there is a first and last element. // // // ////////////////////////////////////////////////////////////////////////// #include "TSeqCollection.h" #include "TCollection.h" #include "TVirtualMutex.h" #include "TClass.h" #include "TMethodCall.h" ClassImp(TSeqCollection) //______________________________________________________________________________ Int_t TSeqCollection::IndexOf(const TObject *obj) const { // Return index of object in collection. Returns -1 when object not found. // Uses member IsEqual() to find object. Int_t idx = 0; TIter next(this); TObject *ob; while ((ob = next())) { if (ob->IsEqual(obj)) return idx; idx++; } return -1; } //______________________________________________________________________________ Int_t TSeqCollection::ObjCompare(TObject *a, TObject *b) { // Compare to objects in the collection. Use member Compare() of object a. if (a == 0 && b == 0) return 0; if (a == 0) return 1; if (b == 0) return -1; return a->Compare(b); } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t first, Int_t last) { // Sort array of TObject pointers using a quicksort algorithm. // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp; static int i; // "static" to save stack space int j; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) ; while (--j > first && ObjCompare(a[j], a[first]) > 0) ; if (i >= j) break; tmp = a[i]; a[i] = a[j]; a[j] = tmp; } if (j == first) { ++first; continue; } tmp = a[first]; a[first] = a[j]; a[j] = tmp; if (j - first < last - (j + 1)) { QSort(a, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, j + 1, last); last = j; // QSort(first, j); } } } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t nBs, TObject ***b, Int_t first, Int_t last) { // Sort array a of TObject pointers using a quicksort algorithm. // Arrays b will be sorted just like a (a determines the sort). // nBs is the number of TObject** arrays in b. // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp1, **tmp2; static int i; // "static" to save stack space int j,k; static int depth = 0; if(depth == 0 && nBs > 0) tmp2 = new TObject*[nBs]; depth++; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) {} while (--j > first && ObjCompare(a[j], a[first]) > 0) {} if (i >= j) break; tmp1 = a[i]; for(k=0;k<nBs;k++) tmp2[k] = b[k][i]; a[i] = a[j]; for(k=0;k<nBs;k++) b[k][i] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; } if (j == first) { ++first; continue; } tmp1 = a[first]; for(k=0;k<nBs;k++) tmp2[k] = b[k][first]; a[first] = a[j]; for(k=0;k<nBs;k++) b[k][first] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; if (j - first < last - (j + 1)) { QSort(a, nBs, b, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, nBs, b, j + 1, last); last = j; // QSort(first, j); } } depth--; if(depth == 0 && nBs > 0) delete [] tmp2; } //______________________________________________________________________________ Long64_t TSeqCollection::Merge(TCollection *list) { // Merge this collection with all collections coming in the input list. The // input list must contain other collections of objects compatible with the // ones in this collection and ordered in the same manner. For example, if this // collection contains a TH1 object and a tree, all collections in the input // list have to contain a histogram and a tree. In case the list contains // collections, the objects in the input lists must also be collections with // the same structure and number of objects. // // Example // ========= // this list // ____________ ---------------------| // | A (TH1F) | __________ | L1 (TSeqCollection)|- [A1, B1(C1,D1,E1)] // | B (TList)|-| C (TTree)| | L1 (TSeqCollection)|- [A2, B2(C2,D2,E2)] // |__________| | D (TH1F) | | ... |- [...] // | E (TH1F) | |____________________| // |__________| Long64_t nmerged = 0; if (IsEmpty() || !list) { Warning("Merge", "list is empty - nothing to merge"); return 0; } if (list->IsEmpty()) { Warning("Merge", "input list is empty - nothing to merge with"); return 0; } TIter nextobject(this); TIter nextlist(list); TObject *object; TObject *objtomerge; TObject *collcrt; TSeqCollection *templist; TMethodCall callEnv; Int_t indobj = 0; while ((object = nextobject())) { // loop objects in this collection // If current object is not mergeable just skip it if (!object->IsA()) { indobj++; // current object non-mergeable, go to next object continue; } callEnv.InitWithPrototype(object->IsA(), "Merge", "TCollection*"); if (!callEnv.IsValid()) { indobj++; // no Merge() interface, go to next object continue; } // Current object mergeable - get corresponding objects in input lists templist = (TSeqCollection*)IsA()->New(); nextlist.Reset(); Int_t indcoll = 0; while ((collcrt = nextlist())) { // loop input lists if (!collcrt->InheritsFrom(TSeqCollection::Class())) { Error("Merge", "some objects in the input list are not collections - merging aborted"); delete templist; return 0; } // The next object to be merged with is a collection // the iterator skips the 'holes' the collections, we also need to do so. objtomerge = ((TSeqCollection*)collcrt)->At(indobj); if (!objtomerge) { Warning("Merge", "Object of type %s (position %d in list) not found in list %d. Continuing...", object->ClassName(), indobj, indcoll); continue; } /* // Dangerous - may try to merge non-corresponding histograms (A.G) while (objtomerge == 0 && indobj < ((TSeqCollection*)collcrt)->LastIndex() ) { ++indobj; objtomerge = ((TSeqCollection*)collcrt)->At(indobj); } */ if (object->IsA() != objtomerge->IsA()) { Error("Merge", "object of type %s at index %d not matching object of type %s in input list", object->ClassName(), indobj, objtomerge->ClassName()); delete templist; return 0; } // Add object at index indobj in the temporary list templist->Add(objtomerge); nmerged++; } // Merge current object with objects in the temporary list callEnv.SetParam((Long_t) templist); callEnv.Execute(object); delete templist; indobj++; } return nmerged; } <commit_msg>add comment that QSort uses a non-stable algorithm, i.e. the order of already sorted elements might be switched/changed. Fixes issue 76111.<commit_after>// @(#)root/cont:$Id$ // Author: Fons Rademakers 04/08/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSeqCollection // // // // Sequenceable collection abstract base class. TSeqCollection's have // // an ordering relation, i.e. there is a first and last element. // // // ////////////////////////////////////////////////////////////////////////// #include "TSeqCollection.h" #include "TCollection.h" #include "TVirtualMutex.h" #include "TClass.h" #include "TMethodCall.h" ClassImp(TSeqCollection) //______________________________________________________________________________ Int_t TSeqCollection::IndexOf(const TObject *obj) const { // Return index of object in collection. Returns -1 when object not found. // Uses member IsEqual() to find object. Int_t idx = 0; TIter next(this); TObject *ob; while ((ob = next())) { if (ob->IsEqual(obj)) return idx; idx++; } return -1; } //______________________________________________________________________________ Int_t TSeqCollection::ObjCompare(TObject *a, TObject *b) { // Compare to objects in the collection. Use member Compare() of object a. if (a == 0 && b == 0) return 0; if (a == 0) return 1; if (b == 0) return -1; return a->Compare(b); } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t first, Int_t last) { // Sort array of TObject pointers using a quicksort algorithm. // The algorithm used is a non stable sort (i.e. already sorted // elements might switch/change places). // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp; static int i; // "static" to save stack space int j; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) ; while (--j > first && ObjCompare(a[j], a[first]) > 0) ; if (i >= j) break; tmp = a[i]; a[i] = a[j]; a[j] = tmp; } if (j == first) { ++first; continue; } tmp = a[first]; a[first] = a[j]; a[j] = tmp; if (j - first < last - (j + 1)) { QSort(a, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, j + 1, last); last = j; // QSort(first, j); } } } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t nBs, TObject ***b, Int_t first, Int_t last) { // Sort array a of TObject pointers using a quicksort algorithm. // Arrays b will be sorted just like a (a determines the sort). // Argument nBs is the number of TObject** arrays in b. // The algorithm used is a non stable sort (i.e. already sorted // elements might switch/change places). // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp1, **tmp2; static int i; // "static" to save stack space int j,k; static int depth = 0; if (depth == 0 && nBs > 0) tmp2 = new TObject*[nBs]; depth++; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) {} while (--j > first && ObjCompare(a[j], a[first]) > 0) {} if (i >= j) break; tmp1 = a[i]; for(k=0;k<nBs;k++) tmp2[k] = b[k][i]; a[i] = a[j]; for(k=0;k<nBs;k++) b[k][i] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; } if (j == first) { ++first; continue; } tmp1 = a[first]; for(k=0;k<nBs;k++) tmp2[k] = b[k][first]; a[first] = a[j]; for(k=0;k<nBs;k++) b[k][first] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; if (j - first < last - (j + 1)) { QSort(a, nBs, b, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, nBs, b, j + 1, last); last = j; // QSort(first, j); } } depth--; if (depth == 0 && nBs > 0) delete [] tmp2; } //______________________________________________________________________________ Long64_t TSeqCollection::Merge(TCollection *list) { // Merge this collection with all collections coming in the input list. The // input list must contain other collections of objects compatible with the // ones in this collection and ordered in the same manner. For example, if this // collection contains a TH1 object and a tree, all collections in the input // list have to contain a histogram and a tree. In case the list contains // collections, the objects in the input lists must also be collections with // the same structure and number of objects. // // Example // ========= // this list // ____________ ---------------------| // | A (TH1F) | __________ | L1 (TSeqCollection)|- [A1, B1(C1,D1,E1)] // | B (TList)|-| C (TTree)| | L1 (TSeqCollection)|- [A2, B2(C2,D2,E2)] // |__________| | D (TH1F) | | ... |- [...] // | E (TH1F) | |____________________| // |__________| Long64_t nmerged = 0; if (IsEmpty() || !list) { Warning("Merge", "list is empty - nothing to merge"); return 0; } if (list->IsEmpty()) { Warning("Merge", "input list is empty - nothing to merge with"); return 0; } TIter nextobject(this); TIter nextlist(list); TObject *object; TObject *objtomerge; TObject *collcrt; TSeqCollection *templist; TMethodCall callEnv; Int_t indobj = 0; while ((object = nextobject())) { // loop objects in this collection // If current object is not mergeable just skip it if (!object->IsA()) { indobj++; // current object non-mergeable, go to next object continue; } callEnv.InitWithPrototype(object->IsA(), "Merge", "TCollection*"); if (!callEnv.IsValid()) { indobj++; // no Merge() interface, go to next object continue; } // Current object mergeable - get corresponding objects in input lists templist = (TSeqCollection*)IsA()->New(); nextlist.Reset(); Int_t indcoll = 0; while ((collcrt = nextlist())) { // loop input lists if (!collcrt->InheritsFrom(TSeqCollection::Class())) { Error("Merge", "some objects in the input list are not collections - merging aborted"); delete templist; return 0; } // The next object to be merged with is a collection // the iterator skips the 'holes' the collections, we also need to do so. objtomerge = ((TSeqCollection*)collcrt)->At(indobj); if (!objtomerge) { Warning("Merge", "Object of type %s (position %d in list) not found in list %d. Continuing...", object->ClassName(), indobj, indcoll); continue; } /* // Dangerous - may try to merge non-corresponding histograms (A.G) while (objtomerge == 0 && indobj < ((TSeqCollection*)collcrt)->LastIndex() ) { ++indobj; objtomerge = ((TSeqCollection*)collcrt)->At(indobj); } */ if (object->IsA() != objtomerge->IsA()) { Error("Merge", "object of type %s at index %d not matching object of type %s in input list", object->ClassName(), indobj, objtomerge->ClassName()); delete templist; return 0; } // Add object at index indobj in the temporary list templist->Add(objtomerge); nmerged++; } // Merge current object with objects in the temporary list callEnv.SetParam((Long_t) templist); callEnv.Execute(object); delete templist; indobj++; } return nmerged; } <|endoftext|>
<commit_before>// // Copyright (c) 2008-2018 the Urho3D project. // // 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 "../Precompiled.h" #include "../Core/Context.h" #include "../Core/CoreEvents.h" #include "../Core/ProcessUtils.h" #include "../Core/Profiler.h" #include "../Core/Thread.h" #include "../Core/Timer.h" #include "../IO/File.h" #include "../IO/IOEvents.h" #include "../IO/Log.h" #include <cstdio> #ifdef __ANDROID__ #include <android/log.h> #endif #if defined(IOS) || defined(TVOS) extern "C" void SDL_IOS_LogMessage(const char* message); #endif #include "../DebugNew.h" namespace Urho3D { const char* logLevelPrefixes[] = { "TRACE", "DEBUG", "INFO", "WARNING", "ERROR", nullptr }; static Log* logInstance = nullptr; static bool threadErrorDisplayed = false; Log::Log(Context* context) : Object(context), #ifdef _DEBUG level_(LOG_DEBUG), #else level_(LOG_INFO), #endif timeStamp_(true), inWrite_(false), quiet_(false) { logInstance = this; SubscribeToEvent(E_ENDFRAME, URHO3D_HANDLER(Log, HandleEndFrame)); } Log::~Log() { logInstance = nullptr; } void Log::Open(const String& fileName) { #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS) if (fileName.Empty()) return; if (logFile_ && logFile_->IsOpen()) { if (logFile_->GetName() == fileName) return; else Close(); } logFile_ = new File(context_); if (logFile_->Open(fileName, FILE_WRITE)) Write(LOG_INFO, "Opened log file " + fileName); else { logFile_.Reset(); Write(LOG_ERROR, "Failed to create log file " + fileName); } #endif } void Log::Close() { #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS) if (logFile_ && logFile_->IsOpen()) { logFile_->Close(); logFile_.Reset(); } #endif } void Log::SetLevel(LogLevel level) { if (level < LOG_TRACE || level > LOG_NONE) { URHO3D_LOGERRORF("Attempted to set erroneous log level %d", level); return; } level_ = level; } void Log::SetTimeStamp(bool enable) { timeStamp_ = enable; } void Log::SetQuiet(bool quiet) { quiet_ = quiet; } void Log::Write(LogLevel level, const String& message) { // Special case for LOG_RAW level if (level == LOG_RAW) { WriteRaw(message, false); return; } // No-op if illegal level if (level < LOG_TRACE || level >= LOG_NONE) return; // If not in the main thread, store message for later processing if (!Thread::IsMainThread()) { if (logInstance) { MutexLock lock(logInstance->logMutex_); logInstance->threadMessages_.Push(StoredLogMessage(message, level, false)); } return; } // Do not log if message level excluded or if currently sending a log event if (!logInstance || logInstance->level_ > level || logInstance->inWrite_) return; String formattedMessage = logLevelPrefixes[level]; formattedMessage += ": "; formattedMessage += String(' ', 9 - formattedMessage.Length()); formattedMessage += message; logInstance->lastMessage_ = message; if (logInstance->timeStamp_) formattedMessage = "[" + Time::GetTimeStamp() + "] " + formattedMessage; URHO3D_PROFILE_MESSAGE(formattedMessage.CString(), formattedMessage.Length()); #if defined(__ANDROID__) int androidLevel = ANDROID_LOG_VERBOSE + level;int __android_log_print(androidLevel, "Urho3D", "%s", message.CString()); #elif defined(IOS) || defined(TVOS) SDL_IOS_LogMessage(message.CString()); #else if (logInstance->quiet_) { // If in quiet mode, still print the error message to the standard error stream if (level == LOG_ERROR) PrintUnicodeLine(formattedMessage, true); } else PrintUnicodeLine(formattedMessage, level == LOG_ERROR); #endif if (logInstance->logFile_) { logInstance->logFile_->WriteLine(formattedMessage); logInstance->logFile_->Flush(); } logInstance->inWrite_ = true; using namespace LogMessage; VariantMap& eventData = logInstance->GetEventDataMap(); eventData[P_MESSAGE] = formattedMessage; eventData[P_LEVEL] = level; logInstance->SendEvent(E_LOGMESSAGE, eventData); logInstance->inWrite_ = false; } void Log::WriteRaw(const String& message, bool error) { // If not in the main thread, store message for later processing if (!Thread::IsMainThread()) { if (logInstance) { MutexLock lock(logInstance->logMutex_); logInstance->threadMessages_.Push(StoredLogMessage(message, LOG_RAW, error)); } return; } // Prevent recursion during log event if (!logInstance || logInstance->inWrite_) return; logInstance->lastMessage_ = message; #if defined(__ANDROID__) if (logInstance->quiet_) { if (error) __android_log_print(ANDROID_LOG_ERROR, "Urho3D", "%s", message.CString()); } else __android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "Urho3D", "%s", message.CString()); #elif defined(IOS) || defined(TVOS) SDL_IOS_LogMessage(message.CString()); #else if (logInstance->quiet_) { // If in quiet mode, still print the error message to the standard error stream if (error) PrintUnicode(message, true); } else PrintUnicode(message, error); #endif if (logInstance->logFile_) { logInstance->logFile_->Write(message.CString(), message.Length()); logInstance->logFile_->Flush(); } logInstance->inWrite_ = true; using namespace LogMessage; VariantMap& eventData = logInstance->GetEventDataMap(); eventData[P_MESSAGE] = message; eventData[P_LEVEL] = error ? LOG_ERROR : LOG_INFO; logInstance->SendEvent(E_LOGMESSAGE, eventData); logInstance->inWrite_ = false; } void Log::HandleEndFrame(StringHash eventType, VariantMap& eventData) { // If the MainThreadID is not valid, processing this loop can potentially be endless if (!Thread::IsMainThread()) { if (!threadErrorDisplayed) { fprintf(stderr, "Thread::mainThreadID is not setup correctly! Threaded log handling disabled\n"); threadErrorDisplayed = true; } return; } MutexLock lock(logMutex_); // Process messages accumulated from other threads (if any) while (!threadMessages_.Empty()) { const StoredLogMessage& stored = threadMessages_.Front(); if (stored.level_ != LOG_RAW) Write(stored.level_, stored.message_); else WriteRaw(stored.message_, stored.error_); threadMessages_.PopFront(); } } } <commit_msg>IO: Fix build error on android.<commit_after>// // Copyright (c) 2008-2018 the Urho3D project. // // 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 "../Precompiled.h" #include "../Core/Context.h" #include "../Core/CoreEvents.h" #include "../Core/ProcessUtils.h" #include "../Core/Profiler.h" #include "../Core/Thread.h" #include "../Core/Timer.h" #include "../IO/File.h" #include "../IO/IOEvents.h" #include "../IO/Log.h" #include <cstdio> #ifdef __ANDROID__ #include <android/log.h> #endif #if defined(IOS) || defined(TVOS) extern "C" void SDL_IOS_LogMessage(const char* message); #endif #include "../DebugNew.h" namespace Urho3D { const char* logLevelPrefixes[] = { "TRACE", "DEBUG", "INFO", "WARNING", "ERROR", nullptr }; static Log* logInstance = nullptr; static bool threadErrorDisplayed = false; Log::Log(Context* context) : Object(context), #ifdef _DEBUG level_(LOG_DEBUG), #else level_(LOG_INFO), #endif timeStamp_(true), inWrite_(false), quiet_(false) { logInstance = this; SubscribeToEvent(E_ENDFRAME, URHO3D_HANDLER(Log, HandleEndFrame)); } Log::~Log() { logInstance = nullptr; } void Log::Open(const String& fileName) { #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS) if (fileName.Empty()) return; if (logFile_ && logFile_->IsOpen()) { if (logFile_->GetName() == fileName) return; else Close(); } logFile_ = new File(context_); if (logFile_->Open(fileName, FILE_WRITE)) Write(LOG_INFO, "Opened log file " + fileName); else { logFile_.Reset(); Write(LOG_ERROR, "Failed to create log file " + fileName); } #endif } void Log::Close() { #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS) if (logFile_ && logFile_->IsOpen()) { logFile_->Close(); logFile_.Reset(); } #endif } void Log::SetLevel(LogLevel level) { if (level < LOG_TRACE || level > LOG_NONE) { URHO3D_LOGERRORF("Attempted to set erroneous log level %d", level); return; } level_ = level; } void Log::SetTimeStamp(bool enable) { timeStamp_ = enable; } void Log::SetQuiet(bool quiet) { quiet_ = quiet; } void Log::Write(LogLevel level, const String& message) { // Special case for LOG_RAW level if (level == LOG_RAW) { WriteRaw(message, false); return; } // No-op if illegal level if (level < LOG_TRACE || level >= LOG_NONE) return; // If not in the main thread, store message for later processing if (!Thread::IsMainThread()) { if (logInstance) { MutexLock lock(logInstance->logMutex_); logInstance->threadMessages_.Push(StoredLogMessage(message, level, false)); } return; } // Do not log if message level excluded or if currently sending a log event if (!logInstance || logInstance->level_ > level || logInstance->inWrite_) return; String formattedMessage = logLevelPrefixes[level]; formattedMessage += ": "; formattedMessage += String(' ', 9 - formattedMessage.Length()); formattedMessage += message; logInstance->lastMessage_ = message; if (logInstance->timeStamp_) formattedMessage = "[" + Time::GetTimeStamp() + "] " + formattedMessage; URHO3D_PROFILE_MESSAGE(formattedMessage.CString(), formattedMessage.Length()); #if defined(__ANDROID__) int androidLevel = ANDROID_LOG_VERBOSE + level; __android_log_print(androidLevel, "Urho3D", "%s", message.CString()); #elif defined(IOS) || defined(TVOS) SDL_IOS_LogMessage(message.CString()); #else if (logInstance->quiet_) { // If in quiet mode, still print the error message to the standard error stream if (level == LOG_ERROR) PrintUnicodeLine(formattedMessage, true); } else PrintUnicodeLine(formattedMessage, level == LOG_ERROR); #endif if (logInstance->logFile_) { logInstance->logFile_->WriteLine(formattedMessage); logInstance->logFile_->Flush(); } logInstance->inWrite_ = true; using namespace LogMessage; VariantMap& eventData = logInstance->GetEventDataMap(); eventData[P_MESSAGE] = formattedMessage; eventData[P_LEVEL] = level; logInstance->SendEvent(E_LOGMESSAGE, eventData); logInstance->inWrite_ = false; } void Log::WriteRaw(const String& message, bool error) { // If not in the main thread, store message for later processing if (!Thread::IsMainThread()) { if (logInstance) { MutexLock lock(logInstance->logMutex_); logInstance->threadMessages_.Push(StoredLogMessage(message, LOG_RAW, error)); } return; } // Prevent recursion during log event if (!logInstance || logInstance->inWrite_) return; logInstance->lastMessage_ = message; #if defined(__ANDROID__) if (logInstance->quiet_) { if (error) __android_log_print(ANDROID_LOG_ERROR, "Urho3D", "%s", message.CString()); } else __android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "Urho3D", "%s", message.CString()); #elif defined(IOS) || defined(TVOS) SDL_IOS_LogMessage(message.CString()); #else if (logInstance->quiet_) { // If in quiet mode, still print the error message to the standard error stream if (error) PrintUnicode(message, true); } else PrintUnicode(message, error); #endif if (logInstance->logFile_) { logInstance->logFile_->Write(message.CString(), message.Length()); logInstance->logFile_->Flush(); } logInstance->inWrite_ = true; using namespace LogMessage; VariantMap& eventData = logInstance->GetEventDataMap(); eventData[P_MESSAGE] = message; eventData[P_LEVEL] = error ? LOG_ERROR : LOG_INFO; logInstance->SendEvent(E_LOGMESSAGE, eventData); logInstance->inWrite_ = false; } void Log::HandleEndFrame(StringHash eventType, VariantMap& eventData) { // If the MainThreadID is not valid, processing this loop can potentially be endless if (!Thread::IsMainThread()) { if (!threadErrorDisplayed) { fprintf(stderr, "Thread::mainThreadID is not setup correctly! Threaded log handling disabled\n"); threadErrorDisplayed = true; } return; } MutexLock lock(logMutex_); // Process messages accumulated from other threads (if any) while (!threadMessages_.Empty()) { const StoredLogMessage& stored = threadMessages_.Front(); if (stored.level_ != LOG_RAW) Write(stored.level_, stored.message_); else WriteRaw(stored.message_, stored.error_); threadMessages_.PopFront(); } } } <|endoftext|>
<commit_before>#include "ROOT/TThreadExecutor.hxx" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #include "tbb/tbb.h" #pragma GCC diagnostic pop ////////////////////////////////////////////////////////////////////////// /// /// \class ROOT::TThreadExecutor /// \ingroup Parallelism /// \brief This class provides a simple interface to execute the same task /// multiple times in parallel, possibly with different arguments every /// time. This mimics the behaviour of python's pool.Map method. /// /// ### ROOT::TThreadExecutor::Map /// This class inherits its interfaces from ROOT::TExecutor\n. /// The two possible usages of the Map method are:\n /// * Map(F func, unsigned nTimes): func is executed nTimes with no arguments /// * Map(F func, T& args): func is executed on each element of the collection of arguments args /// /// For either signature, func is executed as many times as needed by a pool of /// nThreads threads; It defaults to the number of cores.\n /// A collection containing the result of each execution is returned.\n /// **Note:** the user is responsible for the deletion of any object that might /// be created upon execution of func, returned objects included: ROOT::TThreadExecutor never /// deletes what it returns, it simply forgets it.\n /// /// \param func /// \parblock /// a lambda expression, an std::function, a loaded macro, a /// functor class or a function that takes zero arguments (for the first signature) /// or one (for the second signature). /// \endparblock /// \param args /// \parblock /// a standard vector, a ROOT::TSeq of integer type or an initializer list for the second signature. /// An integer only for the first. /// \endparblock /// **Note:** in cases where the function to be executed takes more than /// zero/one argument but all are fixed except zero/one, the function can be wrapped /// in a lambda or via std::bind to give it the right signature.\n /// /// #### Return value: /// An std::vector. The elements in the container /// will be the objects returned by func. /// /// /// #### Examples: /// /// ~~~{.cpp} /// root[] ROOT::TThreadExecutor pool; auto hists = pool.Map(CreateHisto, 10); /// root[] ROOT::TThreadExecutor pool(2); auto squares = pool.Map([](int a) { return a*a; }, {1,2,3}); /// ~~~ /// /// ### ROOT::TThreadExecutor::MapReduce /// This set of methods behaves exactly like Map, but takes an additional /// function as a third argument. This function is applied to the set of /// objects returned by the corresponding Map execution to "squash" them /// to a single object. This function should be independent of the size of /// the vector returned by Map due to optimization of the number of chunks. /// /// If this function is a binary operator, the "squashing" will be performed in parallel. /// This is exclusive to ROOT::TThreadExecutor and not any other ROOT::TExecutor-derived classes.\n /// An integer can be passed as the fourth argument indicating the number of chunks we want to divide our work in. /// This may be useful to avoid the overhead introduced when running really short tasks. /// /// #### Examples: /// ~~~{.cpp} /// root[] ROOT::TThreadExecutor pool; auto ten = pool.MapReduce([]() { return 1; }, 10, [](std::vector<int> v) { return std::accumulate(v.begin(), v.end(), 0); }) /// root[] ROOT::TThreadExecutor pool; auto hist = pool.MapReduce(CreateAndFillHists, 10, PoolUtils::ReduceObjects); /// ~~~ /// ////////////////////////////////////////////////////////////////////////// /* VERY IMPORTANT NOTE ABOUT WORK ISOLATION We enclose the parallel_for and parallel_reduce invocations in a task_arena::isolate because we want to prevent a thread to start executing an outer task when the task it's running spawned subtasks, e.g. with a parallel_for, and is waiting on inner tasks to be completed. While this change has a negligible performance impact, it has benefits for several applications, for example big parallelised HEP frameworks and RDataFrame analyses. - For HEP Frameworks, without work isolation, it can happen that a huge framework task is pulled by a yielding ROOT task. This causes to delay the processing of the event which is interrupted by the long task. For example, work isolation avoids that during the wait due to the parallel flushing of baskets, a very long simulation task is pulled in by the idle task. - For RDataFrame analyses we want to guarantee that each entry is processed from the beginning to the end without TBB interrupting it to pull in other work items. As a corollary, the usage of ROOT (or TBB in work isolation mode) in actions and transformations guarantee that each entry is processed from the beginning to the end without being interrupted by the processing of outer tasks. */ namespace ROOT { namespace Internal { /// A helper function to implement the TThreadExecutor::ParallelReduce methods template<typename T> static T ParallelReduceHelper(const std::vector<T> &objs, const std::function<T(T a, T b)> &redfunc) { using BRange_t = tbb::blocked_range<decltype(objs.begin())>; auto pred = [redfunc](BRange_t const & range, T init) { return std::accumulate(range.begin(), range.end(), init, redfunc); }; BRange_t objRange(objs.begin(), objs.end()); return tbb::this_task_arena::isolate([&]{ return tbb::parallel_reduce(objRange, T{}, pred, redfunc); }); } } // End NS Internal } // End NS ROOT namespace ROOT { ////////////////////////////////////////////////////////////////////////// /// Class constructor. /// If the scheduler is active, gets a pointer to it. /// If not, initializes the pool of threads with the number of logical threads supported by the hardware. TThreadExecutor::TThreadExecutor(): TThreadExecutor::TThreadExecutor(tbb::task_scheduler_init::default_num_threads()) {} ////////////////////////////////////////////////////////////////////////// /// Class constructor. /// nThreads is the number of threads that will be spawned. If the scheduler is active (ImplicitMT enabled, another TThreadExecutor instance), /// it won't change the number of threads. TThreadExecutor::TThreadExecutor(UInt_t nThreads) { fSched = ROOT::Internal::GetPoolManager(nThreads); } void TThreadExecutor::ParallelFor(unsigned int start, unsigned int end, unsigned step, const std::function<void(unsigned int i)> &f) { tbb::this_task_arena::isolate([&]{ tbb::parallel_for(start, end, step, f); }); } double TThreadExecutor::ParallelReduce(const std::vector<double> &objs, const std::function<double(double a, double b)> &redfunc) { return ROOT::Internal::ParallelReduceHelper<double>(objs, redfunc); } float TThreadExecutor::ParallelReduce(const std::vector<float> &objs, const std::function<float(float a, float b)> &redfunc) { return ROOT::Internal::ParallelReduceHelper<float>(objs, redfunc); } unsigned TThreadExecutor::GetPoolSize(){ return ROOT::Internal::TPoolManager::GetPoolSize(); } } <commit_msg>Fix "unknown pragma" compiler warning on Windows<commit_after>#include "ROOT/TThreadExecutor.hxx" #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #endif #include "tbb/tbb.h" #if defined(__GNUC__) #pragma GCC diagnostic pop #endif ////////////////////////////////////////////////////////////////////////// /// /// \class ROOT::TThreadExecutor /// \ingroup Parallelism /// \brief This class provides a simple interface to execute the same task /// multiple times in parallel, possibly with different arguments every /// time. This mimics the behaviour of python's pool.Map method. /// /// ### ROOT::TThreadExecutor::Map /// This class inherits its interfaces from ROOT::TExecutor\n. /// The two possible usages of the Map method are:\n /// * Map(F func, unsigned nTimes): func is executed nTimes with no arguments /// * Map(F func, T& args): func is executed on each element of the collection of arguments args /// /// For either signature, func is executed as many times as needed by a pool of /// nThreads threads; It defaults to the number of cores.\n /// A collection containing the result of each execution is returned.\n /// **Note:** the user is responsible for the deletion of any object that might /// be created upon execution of func, returned objects included: ROOT::TThreadExecutor never /// deletes what it returns, it simply forgets it.\n /// /// \param func /// \parblock /// a lambda expression, an std::function, a loaded macro, a /// functor class or a function that takes zero arguments (for the first signature) /// or one (for the second signature). /// \endparblock /// \param args /// \parblock /// a standard vector, a ROOT::TSeq of integer type or an initializer list for the second signature. /// An integer only for the first. /// \endparblock /// **Note:** in cases where the function to be executed takes more than /// zero/one argument but all are fixed except zero/one, the function can be wrapped /// in a lambda or via std::bind to give it the right signature.\n /// /// #### Return value: /// An std::vector. The elements in the container /// will be the objects returned by func. /// /// /// #### Examples: /// /// ~~~{.cpp} /// root[] ROOT::TThreadExecutor pool; auto hists = pool.Map(CreateHisto, 10); /// root[] ROOT::TThreadExecutor pool(2); auto squares = pool.Map([](int a) { return a*a; }, {1,2,3}); /// ~~~ /// /// ### ROOT::TThreadExecutor::MapReduce /// This set of methods behaves exactly like Map, but takes an additional /// function as a third argument. This function is applied to the set of /// objects returned by the corresponding Map execution to "squash" them /// to a single object. This function should be independent of the size of /// the vector returned by Map due to optimization of the number of chunks. /// /// If this function is a binary operator, the "squashing" will be performed in parallel. /// This is exclusive to ROOT::TThreadExecutor and not any other ROOT::TExecutor-derived classes.\n /// An integer can be passed as the fourth argument indicating the number of chunks we want to divide our work in. /// This may be useful to avoid the overhead introduced when running really short tasks. /// /// #### Examples: /// ~~~{.cpp} /// root[] ROOT::TThreadExecutor pool; auto ten = pool.MapReduce([]() { return 1; }, 10, [](std::vector<int> v) { return std::accumulate(v.begin(), v.end(), 0); }) /// root[] ROOT::TThreadExecutor pool; auto hist = pool.MapReduce(CreateAndFillHists, 10, PoolUtils::ReduceObjects); /// ~~~ /// ////////////////////////////////////////////////////////////////////////// /* VERY IMPORTANT NOTE ABOUT WORK ISOLATION We enclose the parallel_for and parallel_reduce invocations in a task_arena::isolate because we want to prevent a thread to start executing an outer task when the task it's running spawned subtasks, e.g. with a parallel_for, and is waiting on inner tasks to be completed. While this change has a negligible performance impact, it has benefits for several applications, for example big parallelised HEP frameworks and RDataFrame analyses. - For HEP Frameworks, without work isolation, it can happen that a huge framework task is pulled by a yielding ROOT task. This causes to delay the processing of the event which is interrupted by the long task. For example, work isolation avoids that during the wait due to the parallel flushing of baskets, a very long simulation task is pulled in by the idle task. - For RDataFrame analyses we want to guarantee that each entry is processed from the beginning to the end without TBB interrupting it to pull in other work items. As a corollary, the usage of ROOT (or TBB in work isolation mode) in actions and transformations guarantee that each entry is processed from the beginning to the end without being interrupted by the processing of outer tasks. */ namespace ROOT { namespace Internal { /// A helper function to implement the TThreadExecutor::ParallelReduce methods template<typename T> static T ParallelReduceHelper(const std::vector<T> &objs, const std::function<T(T a, T b)> &redfunc) { using BRange_t = tbb::blocked_range<decltype(objs.begin())>; auto pred = [redfunc](BRange_t const & range, T init) { return std::accumulate(range.begin(), range.end(), init, redfunc); }; BRange_t objRange(objs.begin(), objs.end()); return tbb::this_task_arena::isolate([&]{ return tbb::parallel_reduce(objRange, T{}, pred, redfunc); }); } } // End NS Internal } // End NS ROOT namespace ROOT { ////////////////////////////////////////////////////////////////////////// /// Class constructor. /// If the scheduler is active, gets a pointer to it. /// If not, initializes the pool of threads with the number of logical threads supported by the hardware. TThreadExecutor::TThreadExecutor(): TThreadExecutor::TThreadExecutor(tbb::task_scheduler_init::default_num_threads()) {} ////////////////////////////////////////////////////////////////////////// /// Class constructor. /// nThreads is the number of threads that will be spawned. If the scheduler is active (ImplicitMT enabled, another TThreadExecutor instance), /// it won't change the number of threads. TThreadExecutor::TThreadExecutor(UInt_t nThreads) { fSched = ROOT::Internal::GetPoolManager(nThreads); } void TThreadExecutor::ParallelFor(unsigned int start, unsigned int end, unsigned step, const std::function<void(unsigned int i)> &f) { tbb::this_task_arena::isolate([&]{ tbb::parallel_for(start, end, step, f); }); } double TThreadExecutor::ParallelReduce(const std::vector<double> &objs, const std::function<double(double a, double b)> &redfunc) { return ROOT::Internal::ParallelReduceHelper<double>(objs, redfunc); } float TThreadExecutor::ParallelReduce(const std::vector<float> &objs, const std::function<float(float a, float b)> &redfunc) { return ROOT::Internal::ParallelReduceHelper<float>(objs, redfunc); } unsigned TThreadExecutor::GetPoolSize(){ return ROOT::Internal::TPoolManager::GetPoolSize(); } } <|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 "util.h" #include "init.h" #include "bitcoinrpc.h" #include "ui_interface.h" /* for _(...) */ #include "chainparams.h" #include <boost/filesystem/operations.hpp> ////////////////////////////////////////////////////////////////////////////// // // Start // static bool AppInitRPC(int argc, char* argv[]) { // // Parameters // ParseParameters(argc, argv); if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } ReadConfigFile(mapArgs, mapMultiArgs); // Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); return false; } if (argc<2 || mapArgs.count("-?") || mapArgs.count("--help")) { // First part of help message is specific to RPC client std::string strUsage = _("Bitcoin RPC client version") + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " bitcoin-cli [options] <command> [params] " + _("Send command to Bitcoin server") + "\n" + " bitcoin-cli [options] help " + _("List commands") + "\n" + " bitcoin-cli [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessageCli(true); fprintf(stdout, "%s", strUsage.c_str()); return false; } return true; } int main(int argc, char* argv[]) { try { if(!AppInitRPC(argc, argv)) return abs(RPC_MISC_ERROR); } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInitRPC()"); return abs(RPC_MISC_ERROR); } catch (...) { PrintExceptionContinue(NULL, "AppInitRPC()"); return abs(RPC_MISC_ERROR); } int ret = abs(RPC_MISC_ERROR); try { ret = CommandLineRPC(argc, argv); } catch (std::exception& e) { PrintExceptionContinue(&e, "CommandLineRPC()"); } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); } return ret; } <commit_msg>new march 24<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 "util.h" #include "init.h" #include "bitcoinrpc.h" #include "ui_interface.h" /* for _(...) */ #include "chainparams.h" #include <boost/filesystem/operations.hpp> ////////////////////////////////////////////////////////////////////////////// // // Start // static bool AppInitRPC(int argc, char* argv[]) { // // Parameters // ParseParameters(argc, argv); if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } ReadConfigFile(mapArgs, mapMultiArgs); // Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); return false; } if (argc<2 || mapArgs.count("-?") || mapArgs.count("--help")) { // First part of help message is specific to RPC client std::string strUsage = _("Bitcoin RPC client version") + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " bitcoin-cli [options] <command> [params] " + _("Send command to Bitcoin server") + "\n" + " bitcoin-cli [options] help " + _("List commands") + "\n" + " bitcoin-cli [options] help <command> " + _("Get help for a command") + "\n"; fprintf(stdout, "%s", strUsage.c_str()); return false; } return true; } int main(int argc, char* argv[]) { try { if(!AppInitRPC(argc, argv)) return abs(RPC_MISC_ERROR); } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInitRPC()"); return abs(RPC_MISC_ERROR); } catch (...) { PrintExceptionContinue(NULL, "AppInitRPC()"); return abs(RPC_MISC_ERROR); } int ret = abs(RPC_MISC_ERROR); try { ret = CommandLineRPC(argc, argv); } catch (std::exception& e) { PrintExceptionContinue(&e, "CommandLineRPC()"); } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); } return ret; } <|endoftext|>
<commit_before>/* explosive-c4 Copyright (C) 2014-2022 Salvo "LtWorf" Tomaselli This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it> */ #include <QMap> #include <QPair> #include <QPainter> #include <QMouseEvent> #include <QColor> #include <QBrush> #include "boardwidget.h" #include "boardai.h" // map cell type to pen and brush color static QMap<cell_t, QPair<QColor, QColor> > cell_color; BoardWidget::BoardWidget(boardwidget_t board_type) { QWidget(); this->board_type = board_type; // initialize color table if (cell_color.empty()) { cell_color[CELL_RED] = qMakePair(QColor("#ff4500"), Qt::red); cell_color[CELL_YELLOW] = qMakePair(Qt::yellow, QColor("#ffd700")); cell_color[CELL_EMPTY] = qMakePair(Qt::white, Qt::white); } init(); } void BoardWidget::init() { if (board!=NULL) { delete board; } switch (board_type) { case BOARD_WIDGET_LOCAL: board = new Board(); break; case BOARD_WIDGET_AI: board = new BoardAI(); break; case BOARD_WIDGET_NETWORK: //TODO something about this break; } connect(board, SIGNAL(changed(int,int)), this, SLOT(changed(int,int)) ); connect(board, SIGNAL(winner(player_t,int, int)), this, SLOT(winner(player_t, int, int)) ); QSize size = this->size(); update(0,0,size.width(),size.height()); } BoardWidget::~BoardWidget() { delete board; } void BoardWidget::winner(player_t winner, int row, int col) { winner_row = row; winner_col = col; } void BoardWidget::newgame() { winner_col = winner_row = -1; init(); } void BoardWidget::paintEvent(QPaintEvent * p) { QWidget::paintEvent(p); QPainter painter(this); QSize size = this->size(); static const QColor board_color0 = QColor("#434343"); static const QColor board_color1 = QColor("#333333"); static const QColor win_color0 = QColor("#f3f3f3"); static const QColor win_color1 = QColor("#030303"); QLinearGradient board_gradient(0.73, 0.92, 0.4, 0.06); board_gradient.setCoordinateMode(QGradient::ObjectMode); board_gradient.setColorAt(0, board_color0); board_gradient.setColorAt(1, board_color1); QLinearGradient ring_gradient(board_gradient); ring_gradient.setColorAt(0, board_color1); ring_gradient.setColorAt(1, board_color0); QLinearGradient win_gradient(board_gradient); win_gradient.setColorAt(0, win_color0); win_gradient.setColorAt(1, win_color1); QLinearGradient ring_win_gradient(win_gradient); ring_win_gradient.setColorAt(0, win_color1); ring_win_gradient.setColorAt(1, win_color0); painter.fillRect(0,0,size.width(),size.height(),board_gradient); int rows; int cols; board->get_size(&rows,&cols); int w_max = size.width() / cols; int h_max = size.height() / rows; diameter = w_max < h_max ? w_max : h_max; int hole_diam = diameter - 2; if (diameter > 8) { hole_diam = diameter*3/4; } int hole_offset = (diameter - hole_diam)/2; int ring_offset = hole_offset/2; int ring_diam = diameter - hole_offset; painter.setRenderHint(QPainter::Antialiasing, true); for (int r=0; r<rows;r++){ for (int c=0; c<cols;c++) { bool winner_pos = (c==winner_col and r==winner_row); if (winner_pos) painter.fillRect(diameter*c,diameter*r,diameter,diameter,win_gradient); cell_t cell = board->get_content(r,c); painter.setPen( QPen((winner_pos ? ring_win_gradient : ring_gradient), ring_offset) ); painter.drawEllipse(diameter*c + ring_offset, diameter*r + ring_offset, ring_diam, ring_diam); painter.setPen(QPen(cell_color[cell].first, ring_offset)); painter.setBrush(QBrush(cell_color[cell].second, Qt::SolidPattern)); painter.drawEllipse(diameter*c+hole_offset,diameter*r+hole_offset,hole_diam,hole_diam); } } } void BoardWidget::changed(int row, int col) { update(col*diameter,row*diameter,diameter,diameter); } void BoardWidget::mousePressEvent(QMouseEvent *ev) { QWidget::mousePressEvent(ev); int column = ev->x() / diameter; int rows; int cols; board->get_size(&rows,&cols); if (column >= cols) return; player_t t = board->get_turn(); board->place(column,t); } QSize BoardWidget::minimumSizeHint() { int rows; int cols; board->get_size(&rows,&cols); return QSize(cols*30,rows*30); } QSize BoardWidget::sizeHint() { int rows; int cols; board->get_size(&rows,&cols); return QSize(cols*diameter,rows*diameter); } <commit_msg>Move gradient init to board widget init<commit_after>/* explosive-c4 Copyright (C) 2014-2022 Salvo "LtWorf" Tomaselli This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it> */ #include <QMap> #include <QPair> #include <QPainter> #include <QMouseEvent> #include <QColor> #include <QBrush> #include "boardwidget.h" #include "boardai.h" // map cell type to pen and brush color static QMap<cell_t, QPair<QColor, QColor> > cell_color; static const QColor board_color0 = QColor("#434343"); static const QColor board_color1 = QColor("#333333"); static const QColor win_color0 = QColor("#f3f3f3"); static const QColor win_color1 = QColor("#030303"); static QLinearGradient board_gradient, ring_gradient; static QLinearGradient win_gradient, ring_win_gradient; BoardWidget::BoardWidget(boardwidget_t board_type) { QWidget(); this->board_type = board_type; // initialize color table and gradients if (cell_color.empty()) { cell_color[CELL_RED] = qMakePair(QColor("#ff4500"), Qt::red); cell_color[CELL_YELLOW] = qMakePair(Qt::yellow, QColor("#ffd700")); cell_color[CELL_EMPTY] = qMakePair(Qt::white, Qt::white); board_gradient.setStart(0.73, 0.92); board_gradient.setFinalStop(0.4, 0.6); board_gradient.setCoordinateMode(QGradient::ObjectMode); board_gradient.setColorAt(0, board_color0); board_gradient.setColorAt(1, board_color1); ring_gradient = board_gradient; ring_gradient.setColorAt(0, board_color1); ring_gradient.setColorAt(1, board_color0); win_gradient = board_gradient; win_gradient.setColorAt(0, win_color0); win_gradient.setColorAt(1, win_color1); ring_win_gradient = win_gradient; ring_win_gradient.setColorAt(0, win_color1); ring_win_gradient.setColorAt(1, win_color0); } init(); } void BoardWidget::init() { if (board!=NULL) { delete board; } switch (board_type) { case BOARD_WIDGET_LOCAL: board = new Board(); break; case BOARD_WIDGET_AI: board = new BoardAI(); break; case BOARD_WIDGET_NETWORK: //TODO something about this break; } connect(board, SIGNAL(changed(int,int)), this, SLOT(changed(int,int)) ); connect(board, SIGNAL(winner(player_t,int, int)), this, SLOT(winner(player_t, int, int)) ); QSize size = this->size(); update(0,0,size.width(),size.height()); } BoardWidget::~BoardWidget() { delete board; } void BoardWidget::winner(player_t winner, int row, int col) { winner_row = row; winner_col = col; } void BoardWidget::newgame() { winner_col = winner_row = -1; init(); } void BoardWidget::paintEvent(QPaintEvent * p) { QWidget::paintEvent(p); QPainter painter(this); QSize size = this->size(); painter.fillRect(0,0,size.width(),size.height(),board_gradient); int rows; int cols; board->get_size(&rows,&cols); int w_max = size.width() / cols; int h_max = size.height() / rows; diameter = w_max < h_max ? w_max : h_max; int hole_diam = diameter - 2; if (diameter > 8) { hole_diam = diameter*3/4; } int hole_offset = (diameter - hole_diam)/2; int ring_offset = hole_offset/2; int ring_diam = diameter - hole_offset; painter.setRenderHint(QPainter::Antialiasing, true); for (int r=0; r<rows;r++){ for (int c=0; c<cols;c++) { bool winner_pos = (c==winner_col and r==winner_row); if (winner_pos) painter.fillRect(diameter*c,diameter*r,diameter,diameter,win_gradient); cell_t cell = board->get_content(r,c); painter.setPen( QPen((winner_pos ? ring_win_gradient : ring_gradient), ring_offset) ); painter.drawEllipse(diameter*c + ring_offset, diameter*r + ring_offset, ring_diam, ring_diam); painter.setPen(QPen(cell_color[cell].first, ring_offset)); painter.setBrush(QBrush(cell_color[cell].second, Qt::SolidPattern)); painter.drawEllipse(diameter*c+hole_offset,diameter*r+hole_offset,hole_diam,hole_diam); } } } void BoardWidget::changed(int row, int col) { update(col*diameter,row*diameter,diameter,diameter); } void BoardWidget::mousePressEvent(QMouseEvent *ev) { QWidget::mousePressEvent(ev); int column = ev->x() / diameter; int rows; int cols; board->get_size(&rows,&cols); if (column >= cols) return; player_t t = board->get_turn(); board->place(column,t); } QSize BoardWidget::minimumSizeHint() { int rows; int cols; board->get_size(&rows,&cols); return QSize(cols*30,rows*30); } QSize BoardWidget::sizeHint() { int rows; int cols; board->get_size(&rows,&cols); return QSize(cols*diameter,rows*diameter); } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "context/standard_uri_resolvers.h" #include <fstream> #include <sstream> #include "util/web/web.h" #include "store/api/item.h" #include "store/api/collection.h" #include "store/api/store.h" #include "system/globalenv.h" #include "zorbatypes/URI.h" #include "zorbaerrors/error_manager.h" #include "context/static_context.h" namespace zorba { store::Item_t StandardDocumentURIResolver::resolve(const store::Item_t& aURI, static_context* aStaticContext) { store::Item_t lResultDoc; if (aURI == NULL) return NULL; xqpStringStore_t lUriString = aURI->getStringValue(); store::Store& lStore = GENV.getStore(); xqpString lURIString = xqpString(&*aURI->getStringValue()); URI lURI(lURIString); lResultDoc = lStore.getDocument(lURI.toString().getStore()); if (lResultDoc != NULL) return lResultDoc; if (lURI.get_scheme() == "file") { #ifdef ZORBA_WITH_FILE_ACCESS // maybe we don't want to allow file access for security reasons (e.g. in a webapp) std::ifstream lInStream; xqpStringStore_t decodedURI = URI::decode_file_URI(lURI.toString().getStore()); lInStream.open(decodedURI->c_str(), std::ios::in); if (lInStream.is_open() == false) { ZORBA_ERROR_DESC_OSS(FODC0002, "File not found or accessible " << decodedURI); } // parse exception must be caught by the caller lResultDoc = lStore.loadDocument(lURI.toString().getStore(), lInStream); // result can't be null, because we already asked the store if he has it ZORBA_ASSERT(lResultDoc != NULL); #else ZORBA_ERROR_DESC_OSS(FODC0002, "Can't retrieve a file:// URI " << lURI.toString()); #endif } if (lURI.get_scheme() == "http") { #ifdef ZORBA_HAVE_CURL_H // retrieve web file xqp_string xmlString; int result = http_get(lURI.toString().c_str(), xmlString); if (result != 0) { ZORBA_ERROR_DESC_OSS(FODC0002, "File not found or accessible. Could not make HTTP call"); } std::istringstream iss(xmlString.c_str()); // parse exception must be caught by the caller lResultDoc = lStore.loadDocument(lURI.toString().getStore(), iss); // result can't be null, because we already asked the store if he has it ZORBA_ASSERT(lResultDoc != NULL); #else ZORBA_ERROR_DESC_OSS(FODC0002, "Can't retrieve a http:// URI " << lURI.toString()); #endif } if (lResultDoc == NULL) { ZORBA_ERROR_DESC_OSS(FODC0002, "Couldn't retrieve document with URI " << lURI.toString()); } return lResultDoc; } store::Collection_t StandardCollectionURIResolver::resolve(const store::Item_t& aURI, static_context* aStaticContext) { store::Collection_t lResultCol; xqpStringStore_t lUriString = aURI->getStringValue(); store::Store& lStore = GENV.getStore(); // maybe the document is stored with the uri that is given by the user lResultCol = lStore.getCollection(lUriString); if (lResultCol != NULL) return lResultCol; // check and eventually resolve URI // throw FODC0004 if the URI is not valid URI lURI; try { lURI = URI(&*lUriString); if (!lURI.is_absolute()) { URI lBaseURI(aStaticContext->final_baseuri()); lURI = URI(lBaseURI, &*lUriString); } } catch (error::ZorbaError& e) { ZORBA_ERROR_DESC_OSS(FODC0004, "URI " << lUriString << " is not valid or could not be resolved. Reason: " << e.theDescription); } // try to get it from the store again lResultCol = lStore.getCollection(lURI.toString().getStore()); return lResultCol; } std::istream* StandardSchemaURIResolver::resolve(const store::Item_t& aURI, const std::vector<store::Item_t>& aLocationHints, static_context* aStaticContext) { xqpStringStore_t lResolvedURI = aURI->getStringValue(); std::auto_ptr<std::istream> schemafile( new std::ifstream(URI::decode_file_URI (lResolvedURI)->c_str())); // we transfer ownership to the caller return schemafile.release(); } std::istream* StandardModuleURIResolver::resolve(const store::Item_t& aURI, static_context* aStaticContext) { xqpStringStore_t lResolvedURI = aURI->getStringValue(); std::auto_ptr<std::istream> modfile( new std::ifstream(URI::decode_file_URI (lResolvedURI)->c_str())); // we transfer ownership to the caller return modfile.release(); } } /* namespace zorba */ <commit_msg>fix in StandardCollectionURIResolver<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "context/standard_uri_resolvers.h" #include <fstream> #include <sstream> #include "util/web/web.h" #include "store/api/item.h" #include "store/api/collection.h" #include "store/api/store.h" #include "system/globalenv.h" #include "zorbatypes/URI.h" #include "zorbaerrors/error_manager.h" #include "context/static_context.h" namespace zorba { store::Item_t StandardDocumentURIResolver::resolve(const store::Item_t& aURI, static_context* aStaticContext) { store::Item_t lResultDoc; if (aURI == NULL) return NULL; xqpStringStore_t lUriString = aURI->getStringValue(); store::Store& lStore = GENV.getStore(); xqpString lURIString = xqpString(&*aURI->getStringValue()); URI lURI(lURIString); lResultDoc = lStore.getDocument(lURI.toString().getStore()); if (lResultDoc != NULL) return lResultDoc; if (lURI.get_scheme() == "file") { #ifdef ZORBA_WITH_FILE_ACCESS // maybe we don't want to allow file access for security reasons (e.g. in a webapp) std::ifstream lInStream; xqpStringStore_t decodedURI = URI::decode_file_URI(lURI.toString().getStore()); lInStream.open(decodedURI->c_str(), std::ios::in); if (lInStream.is_open() == false) { ZORBA_ERROR_DESC_OSS(FODC0002, "File not found or accessible " << decodedURI); } // parse exception must be caught by the caller lResultDoc = lStore.loadDocument(lURI.toString().getStore(), lInStream); // result can't be null, because we already asked the store if he has it ZORBA_ASSERT(lResultDoc != NULL); #else ZORBA_ERROR_DESC_OSS(FODC0002, "Can't retrieve a file:// URI " << lURI.toString()); #endif } if (lURI.get_scheme() == "http") { #ifdef ZORBA_HAVE_CURL_H // retrieve web file xqp_string xmlString; int result = http_get(lURI.toString().c_str(), xmlString); if (result != 0) { ZORBA_ERROR_DESC_OSS(FODC0002, "File not found or accessible. Could not make HTTP call"); } std::istringstream iss(xmlString.c_str()); // parse exception must be caught by the caller lResultDoc = lStore.loadDocument(lURI.toString().getStore(), iss); // result can't be null, because we already asked the store if he has it ZORBA_ASSERT(lResultDoc != NULL); #else ZORBA_ERROR_DESC_OSS(FODC0002, "Can't retrieve a http:// URI " << lURI.toString()); #endif } if (lResultDoc == NULL) { ZORBA_ERROR_DESC_OSS(FODC0002, "Couldn't retrieve document with URI " << lURI.toString()); } return lResultDoc; } store::Collection_t StandardCollectionURIResolver::resolve(const store::Item_t& aURI, static_context* aStaticContext) { store::Collection_t lResultCol; xqpStringStore_t lUriString = aURI->getStringValue(); store::Store& lStore = GENV.getStore(); // TODO to be removed as soon as create-collection implement correct uri resolving // maybe the document is stored with the uri that is given by the user try { lResultCol = lStore.getCollection(lUriString); if (lResultCol != NULL) return lResultCol; } catch (error::ZorbaError& e) { } // check and eventually resolve URI // throw FODC0004 if the URI is not valid URI lURI; try { lURI = URI(&*lUriString); if (!lURI.is_absolute()) { URI lBaseURI(aStaticContext->final_baseuri()); lURI = URI(lBaseURI, &*lUriString); } } catch (error::ZorbaError& e) { ZORBA_ERROR_DESC_OSS(FODC0004, "URI " << lUriString << " is not valid or could not be resolved. Reason: " << e.theDescription); } // try to get it from the store again lResultCol = lStore.getCollection(lURI.toString().getStore()); return lResultCol; } std::istream* StandardSchemaURIResolver::resolve(const store::Item_t& aURI, const std::vector<store::Item_t>& aLocationHints, static_context* aStaticContext) { xqpStringStore_t lResolvedURI = aURI->getStringValue(); std::auto_ptr<std::istream> schemafile( new std::ifstream(URI::decode_file_URI (lResolvedURI)->c_str())); // we transfer ownership to the caller return schemafile.release(); } std::istream* StandardModuleURIResolver::resolve(const store::Item_t& aURI, static_context* aStaticContext) { xqpStringStore_t lResolvedURI = aURI->getStringValue(); std::auto_ptr<std::istream> modfile( new std::ifstream(URI::decode_file_URI (lResolvedURI)->c_str())); // we transfer ownership to the caller return modfile.release(); } } /* namespace zorba */ <|endoftext|>
<commit_before>#include "bufferstream.h" #include <node_buffer.h> #include "taglib.h" using namespace v8; using namespace node; using namespace node_taglib; namespace node_taglib { BufferStream::BufferStream(Handle<Object> buffer) : TagLib::IOStream() , m_data(Buffer::Data(buffer)) , m_length(Buffer::Length(buffer)) , m_offset(0) { } BufferStream::~BufferStream() { } TagLib::ByteVector BufferStream::readBlock(TagLib::ulong length) { long start = m_offset; m_offset += length; return TagLib::ByteVector(m_data, m_length).mid(start, length); } void BufferStream::writeBlock(const TagLib::ByteVector &data) { fprintf(stderr, "writeBlock called aborting\n"); abort(); } void BufferStream::insert(const TagLib::ByteVector &data, TagLib::ulong start, TagLib::ulong replace) { fprintf(stderr, "insert called aborting\n"); abort(); } void BufferStream::removeBlock(TagLib::ulong start, TagLib::ulong length) { fprintf(stderr, "removeBlock called aborting\n"); abort(); } void BufferStream::seek(long offset, TagLib::IOStream::Position p) { if (p == TagLib::IOStream::Beginning) { m_offset = offset; } else if (p == TagLib::IOStream::Current) { m_offset += offset; } else if (p == TagLib::IOStream::End) { m_offset = length() + offset; } assert(m_offset >= 0); } void BufferStream::clear() { } long BufferStream::tell() const { return m_offset; } long BufferStream::length() { return m_length; } void BufferStream::truncate(long length) { fprintf(stderr, "truncate called aborting\n"); abort(); } } <commit_msg>remove assertion from seek<commit_after>#include "bufferstream.h" #include <node_buffer.h> #include "taglib.h" using namespace v8; using namespace node; using namespace node_taglib; namespace node_taglib { BufferStream::BufferStream(Handle<Object> buffer) : TagLib::IOStream() , m_data(Buffer::Data(buffer)) , m_length(Buffer::Length(buffer)) , m_offset(0) { } BufferStream::~BufferStream() { } TagLib::ByteVector BufferStream::readBlock(TagLib::ulong length) { long start = m_offset; m_offset += length; return TagLib::ByteVector(m_data, m_length).mid(start, length); } void BufferStream::writeBlock(const TagLib::ByteVector &data) { fprintf(stderr, "writeBlock called aborting\n"); abort(); } void BufferStream::insert(const TagLib::ByteVector &data, TagLib::ulong start, TagLib::ulong replace) { fprintf(stderr, "insert called aborting\n"); abort(); } void BufferStream::removeBlock(TagLib::ulong start, TagLib::ulong length) { fprintf(stderr, "removeBlock called aborting\n"); abort(); } void BufferStream::seek(long offset, TagLib::IOStream::Position p) { if (p == TagLib::IOStream::Beginning) { m_offset = offset; } else if (p == TagLib::IOStream::Current) { m_offset += offset; } else if (p == TagLib::IOStream::End) { m_offset = length() + offset; } } void BufferStream::clear() { } long BufferStream::tell() const { return m_offset; } long BufferStream::length() { return m_length; } void BufferStream::truncate(long length) { fprintf(stderr, "truncate called aborting\n"); abort(); } } <|endoftext|>
<commit_before>#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <set> #include "Coords.h" #include "LevelDetect.h" #include "Drawer.h" using namespace std; using namespace cv; #define MIN_RADIUS 25 #define MAX_RADIUS 50 #define MIN_LINE_LENGTH 50 #define MAX_LINE_GAP 50 #define LIMIT_GAP 80 Scalar PIECE_COLOR = CV_RGB(65, 33, 145); vector<Vec3f> detectCircles(Mat& img, int offset) { vector<Vec3f> circles; HoughCircles(img(Rect(0, offset, img.cols, img.rows - offset)), circles, CV_HOUGH_GRADIENT, 1, img.rows / 32, 30, 30, MIN_RADIUS, MAX_RADIUS); return circles; } bool near_border(int x, int limit, int threshold = 2) { return abs(x - limit) < threshold; } vector<int> detectPieces(Mat& img, Mat& img_gray) { vector<Vec4i> lines; Mat img_gray_d; Canny(img_gray, img_gray_d, 30, 100); HoughLinesP(img_gray_d, lines, 1, CV_PI / 180 * 30, 30, MIN_LINE_LENGTH, MAX_LINE_GAP); Vec3b v = img.at<Vec3b>(img.cols / 2, img.rows / 2); Scalar centerColor = Scalar(v[0], v[1], v[2]); set<int> dirs; if (norm(centerColor - PIECE_COLOR) < 10) { for (Vec4i c : lines) { line(img, Point2i(c[0], c[1]), Point2i(c[2], c[3]), CV_RGB(0, 255, 0)); if (near_border(c[0], 0) && near_border(c[2], 0)) continue; if (near_border(c[0], img.cols) && near_border(c[2], img.cols)) continue; if (near_border(c[1], 0) && near_border(c[3], 0)) continue; if (near_border(c[1], img.rows) && near_border(c[3], img.rows)) continue; float m = static_cast<float>(c[3] - c[1]) / (c[2] - c[0]); if (isfinite(m)) { if (fabs(m) < 1e-8) { dirs.insert(get_dir_index("w")); dirs.insert(get_dir_index("e")); } else if (m < 0) { dirs.insert(get_dir_index("sw")); dirs.insert(get_dir_index("ne")); } else { dirs.insert(get_dir_index("nw")); dirs.insert(get_dir_index("se")); } } } } //if (!dirs.empty()) { //imshow("Piece", img); waitKey(0); //} return vector<int>(dirs.begin(), dirs.end()); } /** @function main */ std::pair<Grid, PieceVec> detectLevel(std::string fname, float factor = 2.0f) { Mat src, src_gray; /// Read the image src = imread(fname, 1); if (!src.data) throw std::logic_error("Invalid image"); int offset = 0; int limit = src.rows / 4 - LIMIT_GAP; /// Convert it to gray cvtColor(src, src_gray, CV_BGR2GRAY); /// Reduce the noise so we avoid false circle detection GaussianBlur(src_gray, src_gray, Size(9, 9), 2, 2); vector<Vec3f> circles = detectCircles(src_gray, offset); Vec3f start; float avg_radius = 0; int n = 0; for (Vec3f p : circles) if (p[1] > limit) { //if (n == 0) start = p; avg_radius += p[2]; ++n; } avg_radius /= n; avg_radius *= factor; Grid grid; PieceVec pv; for (Vec3f p : circles) { if (p[1] > limit) { Point2d center(p[0], p[1]); Point2d size(avg_radius, avg_radius); p -= start; double q = (p[0] * sqrt(3.0) / 3 - p[1] / 3.0) / avg_radius; double r = p[1] * 2.0 / 3 / avg_radius; grid.set_el(Coords(q, r), GRID_EMPTY_CELL); //draw_hex(src, center, (int) size.x, Point2d(0, offset)); //draw_text(src, center - Point2d(10, 0), repr, Point2d(0, offset)); } else { Point2d center(p[0], p[1]); int radius = static_cast<int>(p[2]); circle(src, center, radius, 0); Rect bounding_rect(center - Point2d(radius, radius), Size(2 * radius, 2 * radius)); vector<int> dirs = detectPieces(src(bounding_rect), src_gray(bounding_rect)); if (!dirs.empty()) { Piece p = make_piece(dirs); pv.push_back(p); } } } return make_pair(grid, pv); }<commit_msg>Fixed border detection<commit_after>#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <set> #include "Coords.h" #include "LevelDetect.h" #include "Drawer.h" using namespace std; using namespace cv; #define MIN_RADIUS 25 #define MAX_RADIUS 50 #define MIN_LINE_LENGTH 50 #define MAX_LINE_GAP 50 #define LIMIT_GAP 80 Scalar PIECE_COLOR = CV_RGB(65, 33, 145); vector<Vec3f> detectCircles(Mat& img, int offset) { vector<Vec3f> circles; HoughCircles(img(Rect(0, offset, img.cols, img.rows - offset)), circles, CV_HOUGH_GRADIENT, 1, img.rows / 32, 30, 30, MIN_RADIUS, MAX_RADIUS); return circles; } bool near_border(int x, int limit, int threshold = 10) { return abs(x - limit) < threshold; } vector<int> detectPieces(Mat& img, Mat& img_gray) { vector<Vec4i> lines; Mat img_gray_d; Canny(img_gray, img_gray_d, 40, 120); HoughLinesP(img_gray_d, lines, 1, CV_PI / 180 * 30, 25, MIN_LINE_LENGTH, MAX_LINE_GAP); Vec3b v = img.at<Vec3b>(img.cols / 2, img.rows / 2); Scalar centerColor = Scalar(v[0], v[1], v[2]); set<int> dirs; if (norm(centerColor - PIECE_COLOR) < 10) { for (Vec4i c : lines) { bool in_border = false; if (near_border(c[0], 0) && near_border(c[2], 0)) in_border = true; if (near_border(c[0], img.cols) && near_border(c[2], img.cols)) in_border = true; if (near_border(c[1], 0) && near_border(c[3], 0)) in_border = true; if (near_border(c[1], img.rows) && near_border(c[3], img.rows)) in_border = true; auto color = in_border ? CV_RGB(255, 0, 0) : CV_RGB(0, 255, 0); line(img, Point2i(c[0], c[1]), Point2i(c[2], c[3]), color); if (in_border) continue; float m = static_cast<float>(c[3] - c[1]) / (c[2] - c[0]); if (isfinite(m)) { if (fabs(m) < 1e-8) { dirs.insert(get_dir_index("w")); dirs.insert(get_dir_index("e")); } else if (m < 0) { dirs.insert(get_dir_index("sw")); dirs.insert(get_dir_index("ne")); } else { dirs.insert(get_dir_index("nw")); dirs.insert(get_dir_index("se")); } } } } if (!dirs.empty()) { imshow("Piece", img); waitKey(0); } return vector<int>(dirs.begin(), dirs.end()); } /** @function main */ std::pair<Grid, PieceVec> detectLevel(std::string fname, float factor = 2.0f) { Mat src, src_gray; /// Read the image src = imread(fname, 1); if (!src.data) throw std::logic_error("Invalid image"); int offset = 0; int limit = src.rows / 4 - LIMIT_GAP; /// Convert it to gray cvtColor(src, src_gray, CV_BGR2GRAY); /// Reduce the noise so we avoid false circle detection GaussianBlur(src_gray, src_gray, Size(9, 9), 2, 2); vector<Vec3f> circles = detectCircles(src_gray, offset); Vec3f start; float avg_radius = 0; int n = 0; for (Vec3f p : circles) if (p[1] > limit) { //if (n == 0) start = p; avg_radius += p[2]; ++n; } avg_radius /= n; avg_radius *= factor; Grid grid; PieceVec pv; for (Vec3f p : circles) { if (p[1] > limit) { Point2d center(p[0], p[1]); Point2d size(avg_radius, avg_radius); p -= start; double q = (p[0] * sqrt(3.0) / 3 - p[1] / 3.0) / avg_radius; double r = p[1] * 2.0 / 3 / avg_radius; grid.set_el(Coords(q, r), GRID_EMPTY_CELL); //draw_hex(src, center, (int) size.x, Point2d(0, offset)); } else { Point2d center(p[0], p[1]); int radius = static_cast<int>(p[2]); circle(src, center, radius, 0); Rect bounding_rect(center - Point2d(radius, radius), Size(2 * radius, 2 * radius)); vector<int> dirs = detectPieces(src(bounding_rect), src_gray(bounding_rect)); if (!dirs.empty()) { Piece p = make_piece(dirs); pv.push_back(p); } } } return make_pair(grid, pv); }<|endoftext|>
<commit_before>#include "includes.h" #include <spdlog/sinks/systemd_sink.h> namespace { const char *tested_logger_name = "main"; } void run(spdlog::logger &logger) { logger.debug("test debug"); logger.error("test error"); logger.info("test info"); } // std::shared_ptr<spdlog::logger> create_stdout_and_systemd_logger( // std::string name="", // spdlog::level::level_enum level_stdout=spdlog::level::level_enum::debug, // spdlog::level::level_enum level_systemd=spdlog::level::level_enum::err // ) { // auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); // console_sink->set_level(level_stdout); // auto systemd_sink = std::make_shared<spdlog::sinks::systemd_sink_st>(); // systemd_sink->set_level(level_systemd); // return std::make_shared<spdlog::logger>(name, {console_sink, systemd_sink}); // } TEST_CASE("systemd", "[all]") { auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); console_sink->set_level(spdlog::level::level_enum::debug); auto systemd_sink = std::make_shared<spdlog::sinks::systemd_sink_st>(); systemd_sink->set_level(spdlog::level::level_enum::err); spdlog::logger logger("spdlog_systemd_test", {console_sink, systemd_sink}); run(logger); } <commit_msg>Cleaned systemd test<commit_after>#include "includes.h" #include <spdlog/sinks/systemd_sink.h> TEST_CASE("systemd", "[all]") { auto systemd_sink = std::make_shared<spdlog::sinks::systemd_sink_st>(); systemd_sink->set_level(spdlog::level::level_enum::err); spdlog::logger logger("spdlog_systemd_test", systemd_sink); logger.debug("test debug"); logger.error("test error"); logger.info("test info"); } <|endoftext|>
<commit_before>/* * Copyright (c) 2000 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) && !defined(macintosh) #ident "$Id: link_const.cc,v 1.6 2000/11/20 00:58:40 steve Exp $" #endif # include "netlist.h" # include "netmisc.h" /* * Scan the link for drivers. If there are only constant drivers, then * the nexus has a known constant value. If there is a supply net, * then the nexus again has a known constant value. */ bool link_drivers_constant(const Link&lnk) { const Nexus*nex = lnk.nexus(); bool flag = true; for (const Link*cur = nex->first_nlink() ; cur ; cur = cur->next_nlink()) { if (cur == &lnk) continue; if (cur->get_dir() == Link::INPUT) continue; /* If the link is PASSIVE then it doesn't count as a driver if its initial value is Vz. This is pertinant because REGs are PASSIVE but can receive values from procedural assignments. */ if ((cur->get_dir() == Link::PASSIVE) && (cur->get_init() == verinum::Vz)) continue; if (! dynamic_cast<const NetConst*>(cur->get_obj())) flag = false; /* If there is a supply net, then this nexus will have a constant value independent of any drivers. */ if (const NetNet*sig = dynamic_cast<const NetNet*>(cur->get_obj())) switch (sig->type()) { case NetNet::SUPPLY0: case NetNet::SUPPLY1: return true; default: break; } } return flag; } verinum::V driven_value(const Link&lnk) { verinum::V val = verinum::Vx; const Nexus*nex = lnk.nexus(); for (const Link*cur = nex->first_nlink() ; cur ; cur = cur->next_nlink()) { const NetConst*obj; const NetNet*sig; if (obj = dynamic_cast<const NetConst*>(cur->get_obj())) { val = obj->value(cur->get_pin()); } else if (sig = dynamic_cast<const NetNet*>(cur->get_obj())) { if (sig->type() == NetNet::SUPPLY0) return verinum::V0; if (sig->type() == NetNet::SUPPLY1) return verinum::V1; } } return lnk.get_init(); } /* * $Log: link_const.cc,v $ * Revision 1.6 2000/11/20 00:58:40 steve * Add support for supply nets (PR#17) * * Revision 1.5 2000/07/14 06:12:57 steve * Move inital value handling from NetNet to Nexus * objects. This allows better propogation of inital * values. * * Clean up constant propagation a bit to account * for regs that are not really values. * * Revision 1.4 2000/06/25 19:59:42 steve * Redesign Links to include the Nexus class that * carries properties of the connected set of links. * * Revision 1.3 2000/05/14 17:55:04 steve * Support initialization of FF Q value. * * Revision 1.2 2000/05/07 04:37:56 steve * Carry strength values from Verilog source to the * pform and netlist for gates. * * Change vvm constants to use the driver_t to drive * a constant value. This works better if there are * multiple drivers on a signal. * * Revision 1.1 2000/04/20 00:28:03 steve * Catch some simple identity compareoptimizations. * */ <commit_msg> Whoops, return the calculated constant value rom driven_value.<commit_after>/* * Copyright (c) 2000 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) && !defined(macintosh) #ident "$Id: link_const.cc,v 1.7 2000/11/20 01:41:12 steve Exp $" #endif # include "netlist.h" # include "netmisc.h" /* * Scan the link for drivers. If there are only constant drivers, then * the nexus has a known constant value. If there is a supply net, * then the nexus again has a known constant value. */ bool link_drivers_constant(const Link&lnk) { const Nexus*nex = lnk.nexus(); bool flag = true; for (const Link*cur = nex->first_nlink() ; cur ; cur = cur->next_nlink()) { if (cur == &lnk) continue; if (cur->get_dir() == Link::INPUT) continue; /* If the link is PASSIVE then it doesn't count as a driver if its initial value is Vz. This is pertinant because REGs are PASSIVE but can receive values from procedural assignments. */ if ((cur->get_dir() == Link::PASSIVE) && (cur->get_init() == verinum::Vz)) continue; if (! dynamic_cast<const NetConst*>(cur->get_obj())) flag = false; /* If there is a supply net, then this nexus will have a constant value independent of any drivers. */ if (const NetNet*sig = dynamic_cast<const NetNet*>(cur->get_obj())) switch (sig->type()) { case NetNet::SUPPLY0: case NetNet::SUPPLY1: return true; default: break; } } return flag; } verinum::V driven_value(const Link&lnk) { verinum::V val = lnk.get_init(); const Nexus*nex = lnk.nexus(); for (const Link*cur = nex->first_nlink() ; cur ; cur = cur->next_nlink()) { const NetConst*obj; const NetNet*sig; if (obj = dynamic_cast<const NetConst*>(cur->get_obj())) { val = obj->value(cur->get_pin()); } else if (sig = dynamic_cast<const NetNet*>(cur->get_obj())) { if (sig->type() == NetNet::SUPPLY0) return verinum::V0; if (sig->type() == NetNet::SUPPLY1) return verinum::V1; } } return val; } /* * $Log: link_const.cc,v $ * Revision 1.7 2000/11/20 01:41:12 steve * Whoops, return the calculated constant value rom driven_value. * * Revision 1.6 2000/11/20 00:58:40 steve * Add support for supply nets (PR#17) * * Revision 1.5 2000/07/14 06:12:57 steve * Move inital value handling from NetNet to Nexus * objects. This allows better propogation of inital * values. * * Clean up constant propagation a bit to account * for regs that are not really values. * * Revision 1.4 2000/06/25 19:59:42 steve * Redesign Links to include the Nexus class that * carries properties of the connected set of links. * * Revision 1.3 2000/05/14 17:55:04 steve * Support initialization of FF Q value. * * Revision 1.2 2000/05/07 04:37:56 steve * Carry strength values from Verilog source to the * pform and netlist for gates. * * Change vvm constants to use the driver_t to drive * a constant value. This works better if there are * multiple drivers on a signal. * * Revision 1.1 2000/04/20 00:28:03 steve * Catch some simple identity compareoptimizations. * */ <|endoftext|>
<commit_before>// // Copyright (c) 2008-2018 the Urho3D project. // // 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 "../Precompiled.h" #include "../Core/Context.h" #include "../Core/CoreEvents.h" #include "../Core/ProcessUtils.h" #include "../Core/Thread.h" #include "../Core/Timer.h" #include "../IO/File.h" #include "../IO/IOEvents.h" #include "../IO/Log.h" #include <cstdio> #ifdef __ANDROID__ #include <android/log.h> #endif #if defined(IOS) || defined(TVOS) extern "C" void SDL_IOS_LogMessage(const char* message); #endif #include "../DebugNew.h" namespace Urho3D { const char* logLevelPrefixes[] = { "TRACE", "DEBUG", "INFO", "WARNING", "ERROR", nullptr }; static Log* logInstance = nullptr; static bool threadErrorDisplayed = false; Log::Log(Context* context) : Object(context), #ifdef _DEBUG level_(LOG_DEBUG), #else level_(LOG_INFO), #endif timeStamp_(true), inWrite_(false), quiet_(false) { logInstance = this; SubscribeToEvent(E_ENDFRAME, URHO3D_HANDLER(Log, HandleEndFrame)); } Log::~Log() { logInstance = nullptr; } void Log::Open(const String& fileName) { #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS) if (fileName.Empty()) return; if (logFile_ && logFile_->IsOpen()) { if (logFile_->GetName() == fileName) return; else Close(); } logFile_ = new File(context_); if (logFile_->Open(fileName, FILE_WRITE)) Write(LOG_INFO, "Opened log file " + fileName); else { logFile_.Reset(); Write(LOG_ERROR, "Failed to create log file " + fileName); } #endif } void Log::Close() { #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS) if (logFile_ && logFile_->IsOpen()) { logFile_->Close(); logFile_.Reset(); } #endif } void Log::SetLevel(int level) { if (level < LOG_TRACE || level > LOG_NONE) { URHO3D_LOGERRORF("Attempted to set erroneous log level %d", level); return; } level_ = level; } void Log::SetTimeStamp(bool enable) { timeStamp_ = enable; } void Log::SetQuiet(bool quiet) { quiet_ = quiet; } void Log::Write(int level, const String& message) { // Special case for LOG_RAW level if (level == LOG_RAW) { WriteRaw(message, false); return; } // No-op if illegal level if (level < LOG_TRACE || level >= LOG_NONE) return; // If not in the main thread, store message for later processing if (!Thread::IsMainThread()) { if (logInstance) { MutexLock lock(logInstance->logMutex_); logInstance->threadMessages_.Push(StoredLogMessage(message, level, false)); } return; } // Do not log if message level excluded or if currently sending a log event if (!logInstance || logInstance->level_ > level || logInstance->inWrite_) return; String formattedMessage = logLevelPrefixes[level]; formattedMessage += ": " + message; logInstance->lastMessage_ = message; if (logInstance->timeStamp_) formattedMessage = "[" + Time::GetTimeStamp() + "] " + formattedMessage; #if defined(__ANDROID__) int androidLevel = ANDROID_LOG_VERBOSE + level; __android_log_print(androidLevel, "Urho3D", "%s", message.CString()); #elif defined(IOS) || defined(TVOS) SDL_IOS_LogMessage(message.CString()); #else if (logInstance->quiet_) { // If in quiet mode, still print the error message to the standard error stream if (level == LOG_ERROR) PrintUnicodeLine(formattedMessage, true); } else PrintUnicodeLine(formattedMessage, level == LOG_ERROR); #endif if (logInstance->logFile_) { logInstance->logFile_->WriteLine(formattedMessage); logInstance->logFile_->Flush(); } logInstance->inWrite_ = true; using namespace LogMessage; VariantMap& eventData = logInstance->GetEventDataMap(); eventData[P_MESSAGE] = formattedMessage; eventData[P_LEVEL] = level; logInstance->SendEvent(E_LOGMESSAGE, eventData); logInstance->inWrite_ = false; } void Log::WriteRaw(const String& message, bool error) { // If not in the main thread, store message for later processing if (!Thread::IsMainThread()) { if (logInstance) { MutexLock lock(logInstance->logMutex_); logInstance->threadMessages_.Push(StoredLogMessage(message, LOG_RAW, error)); } return; } // Prevent recursion during log event if (!logInstance || logInstance->inWrite_) return; logInstance->lastMessage_ = message; #if defined(__ANDROID__) if (logInstance->quiet_) { if (error) __android_log_print(ANDROID_LOG_ERROR, "Urho3D", "%s", message.CString()); } else __android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "Urho3D", "%s", message.CString()); #elif defined(IOS) || defined(TVOS) SDL_IOS_LogMessage(message.CString()); #else if (logInstance->quiet_) { // If in quiet mode, still print the error message to the standard error stream if (error) PrintUnicode(message, true); } else PrintUnicode(message, error); #endif if (logInstance->logFile_) { logInstance->logFile_->Write(message.CString(), message.Length()); logInstance->logFile_->Flush(); } logInstance->inWrite_ = true; using namespace LogMessage; VariantMap& eventData = logInstance->GetEventDataMap(); eventData[P_MESSAGE] = message; eventData[P_LEVEL] = error ? LOG_ERROR : LOG_INFO; logInstance->SendEvent(E_LOGMESSAGE, eventData); logInstance->inWrite_ = false; } void Log::HandleEndFrame(StringHash eventType, VariantMap& eventData) { // If the MainThreadID is not valid, processing this loop can potentially be endless if (!Thread::IsMainThread()) { if (!threadErrorDisplayed) { fprintf(stderr, "Thread::mainThreadID is not setup correctly! Threaded log handling disabled\n"); threadErrorDisplayed = true; } return; } MutexLock lock(logMutex_); // Process messages accumulated from other threads (if any) while (!threadMessages_.Empty()) { const StoredLogMessage& stored = threadMessages_.Front(); if (stored.level_ != LOG_RAW) Write(stored.level_, stored.message_); else WriteRaw(stored.message_, stored.error_); threadMessages_.PopFront(); } } } <commit_msg>Logging: pad log messages after message type so that message text aligns.<commit_after>// // Copyright (c) 2008-2018 the Urho3D project. // // 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 "../Precompiled.h" #include "../Core/Context.h" #include "../Core/CoreEvents.h" #include "../Core/ProcessUtils.h" #include "../Core/Thread.h" #include "../Core/Timer.h" #include "../IO/File.h" #include "../IO/IOEvents.h" #include "../IO/Log.h" #include <cstdio> #ifdef __ANDROID__ #include <android/log.h> #endif #if defined(IOS) || defined(TVOS) extern "C" void SDL_IOS_LogMessage(const char* message); #endif #include "../DebugNew.h" namespace Urho3D { const char* logLevelPrefixes[] = { "TRACE", "DEBUG", "INFO", "WARNING", "ERROR", nullptr }; static Log* logInstance = nullptr; static bool threadErrorDisplayed = false; Log::Log(Context* context) : Object(context), #ifdef _DEBUG level_(LOG_DEBUG), #else level_(LOG_INFO), #endif timeStamp_(true), inWrite_(false), quiet_(false) { logInstance = this; SubscribeToEvent(E_ENDFRAME, URHO3D_HANDLER(Log, HandleEndFrame)); } Log::~Log() { logInstance = nullptr; } void Log::Open(const String& fileName) { #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS) if (fileName.Empty()) return; if (logFile_ && logFile_->IsOpen()) { if (logFile_->GetName() == fileName) return; else Close(); } logFile_ = new File(context_); if (logFile_->Open(fileName, FILE_WRITE)) Write(LOG_INFO, "Opened log file " + fileName); else { logFile_.Reset(); Write(LOG_ERROR, "Failed to create log file " + fileName); } #endif } void Log::Close() { #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS) if (logFile_ && logFile_->IsOpen()) { logFile_->Close(); logFile_.Reset(); } #endif } void Log::SetLevel(int level) { if (level < LOG_TRACE || level > LOG_NONE) { URHO3D_LOGERRORF("Attempted to set erroneous log level %d", level); return; } level_ = level; } void Log::SetTimeStamp(bool enable) { timeStamp_ = enable; } void Log::SetQuiet(bool quiet) { quiet_ = quiet; } void Log::Write(int level, const String& message) { // Special case for LOG_RAW level if (level == LOG_RAW) { WriteRaw(message, false); return; } // No-op if illegal level if (level < LOG_TRACE || level >= LOG_NONE) return; // If not in the main thread, store message for later processing if (!Thread::IsMainThread()) { if (logInstance) { MutexLock lock(logInstance->logMutex_); logInstance->threadMessages_.Push(StoredLogMessage(message, level, false)); } return; } // Do not log if message level excluded or if currently sending a log event if (!logInstance || logInstance->level_ > level || logInstance->inWrite_) return; String formattedMessage = logLevelPrefixes[level]; formattedMessage += ": "; formattedMessage += String(' ', 9 - formattedMessage.Length()); formattedMessage += message; logInstance->lastMessage_ = message; if (logInstance->timeStamp_) formattedMessage = "[" + Time::GetTimeStamp() + "] " + formattedMessage; #if defined(__ANDROID__) int androidLevel = ANDROID_LOG_VERBOSE + level; __android_log_print(androidLevel, "Urho3D", "%s", message.CString()); #elif defined(IOS) || defined(TVOS) SDL_IOS_LogMessage(message.CString()); #else if (logInstance->quiet_) { // If in quiet mode, still print the error message to the standard error stream if (level == LOG_ERROR) PrintUnicodeLine(formattedMessage, true); } else PrintUnicodeLine(formattedMessage, level == LOG_ERROR); #endif if (logInstance->logFile_) { logInstance->logFile_->WriteLine(formattedMessage); logInstance->logFile_->Flush(); } logInstance->inWrite_ = true; using namespace LogMessage; VariantMap& eventData = logInstance->GetEventDataMap(); eventData[P_MESSAGE] = formattedMessage; eventData[P_LEVEL] = level; logInstance->SendEvent(E_LOGMESSAGE, eventData); logInstance->inWrite_ = false; } void Log::WriteRaw(const String& message, bool error) { // If not in the main thread, store message for later processing if (!Thread::IsMainThread()) { if (logInstance) { MutexLock lock(logInstance->logMutex_); logInstance->threadMessages_.Push(StoredLogMessage(message, LOG_RAW, error)); } return; } // Prevent recursion during log event if (!logInstance || logInstance->inWrite_) return; logInstance->lastMessage_ = message; #if defined(__ANDROID__) if (logInstance->quiet_) { if (error) __android_log_print(ANDROID_LOG_ERROR, "Urho3D", "%s", message.CString()); } else __android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "Urho3D", "%s", message.CString()); #elif defined(IOS) || defined(TVOS) SDL_IOS_LogMessage(message.CString()); #else if (logInstance->quiet_) { // If in quiet mode, still print the error message to the standard error stream if (error) PrintUnicode(message, true); } else PrintUnicode(message, error); #endif if (logInstance->logFile_) { logInstance->logFile_->Write(message.CString(), message.Length()); logInstance->logFile_->Flush(); } logInstance->inWrite_ = true; using namespace LogMessage; VariantMap& eventData = logInstance->GetEventDataMap(); eventData[P_MESSAGE] = message; eventData[P_LEVEL] = error ? LOG_ERROR : LOG_INFO; logInstance->SendEvent(E_LOGMESSAGE, eventData); logInstance->inWrite_ = false; } void Log::HandleEndFrame(StringHash eventType, VariantMap& eventData) { // If the MainThreadID is not valid, processing this loop can potentially be endless if (!Thread::IsMainThread()) { if (!threadErrorDisplayed) { fprintf(stderr, "Thread::mainThreadID is not setup correctly! Threaded log handling disabled\n"); threadErrorDisplayed = true; } return; } MutexLock lock(logMutex_); // Process messages accumulated from other threads (if any) while (!threadMessages_.Empty()) { const StoredLogMessage& stored = threadMessages_.Front(); if (stored.level_ != LOG_RAW) Write(stored.level_, stored.message_); else WriteRaw(stored.message_, stored.error_); threadMessages_.PopFront(); } } } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2014 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "burst.hpp" #include <string> #include <vector> #include <map> #include "../framework/mixable.hpp" namespace jubatus { namespace core { namespace driver { void burst::init_(jubatus::util::lang::shared_ptr<model_t>& model) { burst_.swap(model); mixable_burst_.set_model(burst_); holder_ = mixable_holder(); // just to be safe register_mixable(&mixable_burst_); } bool burst::add_keyword(const std::string& keyword, const keyword_params& params, bool processed_in_this_server) { return burst_->add_keyword(keyword, params, processed_in_this_server); } bool burst::remove_keyword(const std::string& keyword) { return burst_->remove_keyword(keyword); } bool burst::remove_all_keywords() { return burst_->remove_all_keywords(); } burst::keyword_list burst::get_all_keywords() const { return burst_->get_all_keywords(); } bool burst::add_document(const std::string& str, double pos) { return burst_->add_document(str, pos); } void burst::calculate_results() { burst_->calculate_results(); } burst::result_t burst::get_result(const std::string& keyword) const { return burst_->get_result(keyword); } burst::result_t burst::get_result_at( const std::string& keyword, double pos) const { return burst_->get_result_at(keyword, pos); } burst::result_map burst::get_all_bursted_results() const { return burst_->get_all_bursted_results(); } burst::result_map burst::get_all_bursted_results_at(double pos) const { return burst_->get_all_bursted_results_at(pos); } void burst::get_status(std::map<std::string, std::string>& status) const { // TODO(gintenlabo) implement } bool burst::has_been_mixed() const { return burst_->has_been_mixed(); } void burst::set_processed_keywords(const std::vector<std::string>& keywords) { return burst_->set_processed_keywords(keywords); } void burst::pack(framework::packer& pk) const { burst_->pack(pk); } void burst::unpack(msgpack::object o) { burst_->unpack(o); } void burst::clear() { burst_->clear(); } } // namespace driver } // namespace core } // namespace jubatus <commit_msg>Implement get_status<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2014 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "burst.hpp" #include <string> #include <vector> #include <map> #include "../framework/mixable.hpp" namespace jubatus { namespace core { namespace driver { namespace { std::string keywords_to_string(const burst::keyword_list& keywords) { size_t n = keywords.size(); if (n == 0) { return ""; } std::string result = keywords[0].keyword; for (size_t i = 1; i < n; ++i) { result += ','; result += keywords[i].keyword; } return result; } } // namespace void burst::init_(jubatus::util::lang::shared_ptr<model_t>& model) { burst_.swap(model); mixable_burst_.set_model(burst_); holder_ = mixable_holder(); // just to be safe register_mixable(&mixable_burst_); } bool burst::add_keyword(const std::string& keyword, const keyword_params& params, bool processed_in_this_server) { return burst_->add_keyword(keyword, params, processed_in_this_server); } bool burst::remove_keyword(const std::string& keyword) { return burst_->remove_keyword(keyword); } bool burst::remove_all_keywords() { return burst_->remove_all_keywords(); } burst::keyword_list burst::get_all_keywords() const { return burst_->get_all_keywords(); } bool burst::add_document(const std::string& str, double pos) { return burst_->add_document(str, pos); } void burst::calculate_results() { burst_->calculate_results(); } burst::result_t burst::get_result(const std::string& keyword) const { return burst_->get_result(keyword); } burst::result_t burst::get_result_at( const std::string& keyword, double pos) const { return burst_->get_result_at(keyword, pos); } burst::result_map burst::get_all_bursted_results() const { return burst_->get_all_bursted_results(); } burst::result_map burst::get_all_bursted_results_at(double pos) const { return burst_->get_all_bursted_results_at(pos); } void burst::get_status(std::map<std::string, std::string>& status) const { status["all_keywords"] = keywords_to_string(burst_->get_all_keywords()); status["processed_keywords"] = keywords_to_string(burst_->get_processed_keywords()); } bool burst::has_been_mixed() const { return burst_->has_been_mixed(); } void burst::set_processed_keywords(const std::vector<std::string>& keywords) { return burst_->set_processed_keywords(keywords); } void burst::pack(framework::packer& pk) const { burst_->pack(pk); } void burst::unpack(msgpack::object o) { burst_->unpack(o); } void burst::clear() { burst_->clear(); } } // namespace driver } // namespace core } // namespace jubatus <|endoftext|>
<commit_before>#include <tiramisu/auto_scheduler/search_method.h> #include <random> namespace tiramisu::auto_scheduler { void beam_search::search(syntax_tree& ast) { ast.print_ast(); if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0) ast.clear_new_optimizations(); std::vector<syntax_tree*> children; // Look for an optimization that can be applied int nb_optims_tried = 0; int nb_explored_optims = ast.nb_explored_optims; while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth) { optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS]; children = states_gen->generate_states(ast, optim_type); nb_explored_optims++; nb_optims_tried++; } // Stop if no more optimizations can be applied if (children.size() == 0) return ; // Evaluate children and sort them from smallest to highest evaluation for (syntax_tree *child : children) { child->nb_explored_optims = nb_explored_optims; if (eval_func->should_transform_ast(*child)) child->transform_ast(); child->evaluation = eval_func->evaluate(*child); if (child->evaluation < best_evaluation) { best_evaluation = child->evaluation; best_ast = child; } nb_explored_schedules++; } // Stop if we reached the maximum depth if (nb_explored_optims >= max_depth) return ; // Add the current AST to the list of children syntax_tree *ast_copy = ast.copy_ast(); ast_copy->nb_explored_optims = nb_explored_optims; children.push_back(ast_copy); // Sort children from smallest evaluation to largest std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) { return a->evaluation < b->evaluation; }); // Search recursively on the best children for (int i = beam_size; i < children.size(); ++i) delete children[i]; children.resize(std::min(beam_size, (int)children.size())); for (syntax_tree *child : children) { child->search_depth = ast.search_depth + 1; search(*child); } } void beam_search_accuracy_evaluator::search(syntax_tree& ast) { ast.print_ast(); if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0) ast.clear_new_optimizations(); std::vector<syntax_tree*> children; // Look for an optimization that can be applied int nb_optims_tried = 0; int nb_explored_optims = ast.nb_explored_optims; while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth) { optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS]; children = states_gen->generate_states(ast, optim_type); nb_explored_optims++; nb_optims_tried++; } // Stop if no more optimizations can be applied if (children.size() == 0) return ; // Evaluate children and sort them from smallest to highest evaluation for (syntax_tree *child : children) { child->nb_explored_optims = nb_explored_optims; if (eval_func->should_transform_ast(*child)) child->transform_ast(); child->evaluation = eval_func->evaluate(*child); model_evals_list.push_back(child->evaluation); exec_evals_list.push_back(exec_eval->evaluate(*child)); if (child->evaluation < best_evaluation) { best_evaluation = child->evaluation; best_ast = child; } nb_explored_schedules++; } // Stop if we reached the maximum depth if (nb_explored_optims >= max_depth) return ; // Add the current AST to the list of children syntax_tree *ast_copy = ast.copy_ast(); ast_copy->nb_explored_optims = nb_explored_optims; children.push_back(ast_copy); // Sort children from smallest evaluation to largest std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) { return a->evaluation < b->evaluation; }); // Search recursively on the best children for (int i = beam_size; i < children.size(); ++i) delete children[i]; children.resize(std::min(beam_size, (int)children.size())); for (syntax_tree *child : children) { child->search_depth = ast.search_depth + 1; search(*child); } } void simple_mcts::search(syntax_tree& ast) { std::default_random_engine rand_generator; std::vector<syntax_tree*> samples; std::vector<syntax_tree*> children; std::vector<double> softmax_values; for (int epoch = 0; epoch < nb_samples; ++epoch) { syntax_tree *ast_sample = &ast; for (int depth = 0; depth < max_depth; ++depth) { optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[depth % NB_OPTIMIZATIONS]; children = states_gen->generate_states(*ast_sample, optim_type); depth++; if (children.empty()) continue; for (syntax_tree *child : children) { if (eval_func->should_transform_ast(*child)) child->transform_ast(); child->evaluation = eval_func->evaluate(*child); nb_explored_schedules++; } children.push_back(ast_sample->copy_ast()); softmax_values = compute_softmax(children); std::discrete_distribution<int> dist(softmax_values.begin(), softmax_values.end()); ast_sample = children[dist(rand_generator)]; samples.push_back(ast_sample); ast_sample->print_ast(); } } if (samples.empty()) return ; std::sort(samples.begin(), samples.end(), [](syntax_tree *a, syntax_tree *b) { return a->evaluation < b->evaluation; }); for (int i = 0; i < topk; ++i) { float exec_time = exec_eval->evaluate(*samples[i]); if (exec_time < best_evaluation) { best_evaluation = exec_time; best_ast = samples[i]; } } } } <commit_msg>Autoscheduler : fix error<commit_after>#include <tiramisu/auto_scheduler/search_method.h> #include <random> namespace tiramisu::auto_scheduler { void beam_search::search(syntax_tree& ast) { ast.print_ast(); if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0) ast.clear_new_optimizations(); std::vector<syntax_tree*> children; // Look for an optimization that can be applied int nb_optims_tried = 0; int nb_explored_optims = ast.nb_explored_optims; while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth) { optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS]; children = states_gen->generate_states(ast, optim_type); nb_explored_optims++; nb_optims_tried++; } // Stop if no more optimizations can be applied if (children.size() == 0) return ; // Evaluate children and sort them from smallest to highest evaluation for (syntax_tree *child : children) { child->nb_explored_optims = nb_explored_optims; if (eval_func->should_transform_ast(*child)) child->transform_ast(); child->evaluation = eval_func->evaluate(*child); if (child->evaluation < best_evaluation) { best_evaluation = child->evaluation; best_ast = child; } nb_explored_schedules++; } // Stop if we reached the maximum depth if (nb_explored_optims >= max_depth) return ; // Add the current AST to the list of children syntax_tree *ast_copy = ast.copy_ast(); ast_copy->nb_explored_optims = nb_explored_optims; children.push_back(ast_copy); // Sort children from smallest evaluation to largest std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) { return a->evaluation < b->evaluation; }); // Search recursively on the best children for (int i = beam_size; i < children.size(); ++i) delete children[i]; children.resize(std::min(beam_size, (int)children.size())); for (syntax_tree *child : children) { child->search_depth = ast.search_depth + 1; search(*child); } } void beam_search_accuracy_evaluator::search(syntax_tree& ast) { ast.print_ast(); if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0) ast.clear_new_optimizations(); std::vector<syntax_tree*> children; // Look for an optimization that can be applied int nb_optims_tried = 0; int nb_explored_optims = ast.nb_explored_optims; while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth) { optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS]; children = states_gen->generate_states(ast, optim_type); nb_explored_optims++; nb_optims_tried++; } // Stop if no more optimizations can be applied if (children.size() == 0) return ; // Evaluate children and sort them from smallest to highest evaluation for (syntax_tree *child : children) { child->nb_explored_optims = nb_explored_optims; if (eval_func->should_transform_ast(*child)) child->transform_ast(); child->evaluation = eval_func->evaluate(*child); model_evals_list.push_back(child->evaluation); exec_evals_list.push_back(exec_eval->evaluate(*child)); if (child->evaluation < best_evaluation) { best_evaluation = child->evaluation; best_ast = child; } nb_explored_schedules++; } // Stop if we reached the maximum depth if (nb_explored_optims >= max_depth) return ; // Add the current AST to the list of children syntax_tree *ast_copy = ast.copy_ast(); ast_copy->nb_explored_optims = nb_explored_optims; children.push_back(ast_copy); // Sort children from smallest evaluation to largest std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) { return a->evaluation < b->evaluation; }); // Search recursively on the best children for (int i = beam_size; i < children.size(); ++i) delete children[i]; children.resize(std::min(beam_size, (int)children.size())); for (syntax_tree *child : children) { child->search_depth = ast.search_depth + 1; search(*child); } } void simple_mcts::search(syntax_tree& ast) { std::default_random_engine rand_generator; std::vector<syntax_tree*> samples; std::vector<syntax_tree*> children; std::vector<double> softmax_values; for (int epoch = 0; epoch < nb_samples; ++epoch) { syntax_tree *ast_sample = &ast; for (int depth = 0; depth < max_depth; ++depth) { optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[depth % NB_OPTIMIZATIONS]; children = states_gen->generate_states(*ast_sample, optim_type); if (children.empty()) continue; for (syntax_tree *child : children) { if (eval_func->should_transform_ast(*child)) child->transform_ast(); child->evaluation = eval_func->evaluate(*child); nb_explored_schedules++; } children.push_back(ast_sample->copy_ast()); softmax_values = compute_softmax(children); std::discrete_distribution<int> dist(softmax_values.begin(), softmax_values.end()); ast_sample = children[dist(rand_generator)]; samples.push_back(ast_sample); ast_sample->print_ast(); } } if (samples.empty()) return ; std::sort(samples.begin(), samples.end(), [](syntax_tree *a, syntax_tree *b) { return a->evaluation < b->evaluation; }); for (int i = 0; i < topk; ++i) { float exec_time = exec_eval->evaluate(*samples[i]); if (exec_time < best_evaluation) { best_evaluation = exec_time; best_ast = samples[i]; } } } } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786) #endif #include "motd.h" #include "URLManager.h" #include "TextUtils.h" MessageOfTheDay::MessageOfTheDay() { } MessageOfTheDay::~MessageOfTheDay() { } const std::string& MessageOfTheDay::get ( const std::string URL ) { data = ""; return data; // get all up on the internet and go get the thing if (!URLManager::instance().getURL(URL,data)) { data = "Default MOTD"; } else { // trim trailing whitespace int l = data.size() - 1; while (TextUtils::isWhitespace(data[l])) { data.erase(l, 1); l--; } } return data; } <commit_msg>undisable motd for testing/fixing<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786) #endif #include "motd.h" #include "URLManager.h" #include "TextUtils.h" MessageOfTheDay::MessageOfTheDay() { } MessageOfTheDay::~MessageOfTheDay() { } const std::string& MessageOfTheDay::get ( const std::string URL ) { // get all up on the internet and go get the thing if (!URLManager::instance().getURL(URL,data)) { data = "Default MOTD"; } else { // trim trailing whitespace int l = data.size() - 1; while (TextUtils::isWhitespace(data[l])) { data.erase(l, 1); l--; } } return data; } <|endoftext|>
<commit_before>/* Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "midend.h" #include "lower.h" #include "inlining.h" #include "eliminateVerify.h" #include "frontends/common/constantFolding.h" #include "frontends/common/resolveReferences/resolveReferences.h" #include "frontends/p4/evaluator/evaluator.h" #include "frontends/p4/fromv1.0/v1model.h" #include "frontends/p4/moveDeclarations.h" #include "frontends/p4/simplify.h" #include "frontends/p4/simplifyParsers.h" #include "frontends/p4/strengthReduction.h" #include "frontends/p4/typeChecking/typeChecker.h" #include "frontends/p4/typeMap.h" #include "frontends/p4/uniqueNames.h" #include "frontends/p4/unusedDeclarations.h" #include "midend/actionsInlining.h" #include "midend/actionSynthesis.h" #include "midend/convertEnums.h" #include "midend/copyStructures.h" #include "midend/eliminateTuples.h" #include "midend/local_copyprop.h" #include "midend/localizeActions.h" #include "midend/moveConstructors.h" #include "midend/nestedStructs.h" #include "midend/removeLeftSlices.h" #include "midend/removeParameters.h" #include "midend/removeReturns.h" #include "midend/simplifyKey.h" #include "midend/simplifySelect.h" #include "midend/validateProperties.h" #include "midend/compileTimeOps.h" namespace BMV2 { #if 0 void MidEnd::setup_for_P4_14(CompilerOptions&) { auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap); // Inlining is simpler for P4 v1.0/1.1 programs, so we have a // specialized code path, which also generates slighly nicer // human-readable results. addPasses({ evaluator, new P4::DiscoverInlining(&controlsToInline, &refMap, &typeMap, evaluator), new P4::InlineDriver(&controlsToInline, new SimpleControlsInliner(&refMap)), new P4::RemoveAllUnusedDeclarations(&refMap), new P4::TypeChecking(&refMap, &typeMap), new P4::DiscoverActionsInlining(&actionsToInline, &refMap, &typeMap), new P4::InlineActionsDriver(&actionsToInline, new SimpleActionsInliner(&refMap)), new P4::RemoveAllUnusedDeclarations(&refMap), }); } #endif class EnumOn32Bits : public P4::ChooseEnumRepresentation { bool convert(const IR::Type_Enum* type) const override { if (type->srcInfo.isValid()) { unsigned line = type->srcInfo.getStart().getLineNumber(); auto sfl = Util::InputSources::instance->getSourceLine(line); cstring sourceFile = sfl.fileName; if (sourceFile.endsWith(P4V1::V1Model::instance.file.name)) // Don't convert any of the standard enums return false; } return true; } unsigned enumSize(unsigned) const override { return 32; } }; void MidEnd::setup_for_P4_16(CompilerOptions&) { // we may come through this path even if the program is actually a P4 v1.0 program auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap); addPasses({ new P4::ConvertEnums(&refMap, &typeMap, new EnumOn32Bits()), new P4::RemoveReturns(&refMap), new P4::MoveConstructors(&refMap), new P4::RemoveAllUnusedDeclarations(&refMap), new P4::ClearTypeMap(&typeMap), evaluator, new VisitFunctor([evaluator](const IR::Node *root) -> const IR::Node * { auto toplevel = evaluator->getToplevelBlock(); if (toplevel->getMain() == nullptr) // nothing further to do return nullptr; return root; }), new P4::Inline(&refMap, &typeMap, evaluator), new P4::InlineActions(&refMap, &typeMap), new P4::LocalizeAllActions(&refMap), new P4::UniqueNames(&refMap), new P4::UniqueParameters(&refMap, &typeMap), new P4::SimplifyControlFlow(&refMap, &typeMap), new P4::RemoveTableParameters(&refMap, &typeMap), new P4::RemoveActionParameters(&refMap, &typeMap), new P4::SimplifyKey(&refMap, &typeMap, new P4::NonLeftValue(&refMap, &typeMap)), new P4::ConstantFolding(&refMap, &typeMap), new P4::StrengthReduction(), new P4::SimplifySelect(&refMap, &typeMap, true), // require constant keysets new P4::SimplifyParsers(&refMap), new P4::StrengthReduction(), new P4::EliminateTuples(&refMap, &typeMap), new P4::CopyStructures(&refMap, &typeMap), new P4::NestedStructs(&refMap, &typeMap), new P4::LocalCopyPropagation(&refMap, &typeMap), new P4::MoveDeclarations(), new P4::ValidateTableProperties({ "implementation", "size", "counters", "meters", "size", "support_timeout" }), new P4::SimplifyControlFlow(&refMap, &typeMap), new P4::CompileTimeOperations(), new P4::SynthesizeActions(&refMap, &typeMap), new P4::MoveActionsToTables(&refMap, &typeMap), }); } MidEnd::MidEnd(CompilerOptions& options) { bool isv1 = options.isv1(); setName("MidEnd"); refMap.setIsV1(isv1); // must be done BEFORE creating passes #if 0 if (isv1) // TODO: This path should be eventually deprecated setup_for_P4_14(options); else #endif setup_for_P4_16(options); // BMv2-specific passes auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap); addPasses({ new P4::TypeChecking(&refMap, &typeMap), new EliminateVerify(&refMap, &typeMap), new P4::SimplifyControlFlow(&refMap, &typeMap), new P4::RemoveLeftSlices(&refMap, &typeMap), new P4::TypeChecking(&refMap, &typeMap), new LowerExpressions(&typeMap), new P4::ConstantFolding(&refMap, &typeMap, false), evaluator, new VisitFunctor([this, evaluator]() { toplevel = evaluator->getToplevelBlock(); }) }); } } // namespace BMV2 <commit_msg>Enable predication for BMv2 back-end<commit_after>/* Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "midend.h" #include "lower.h" #include "inlining.h" #include "eliminateVerify.h" #include "frontends/common/constantFolding.h" #include "frontends/common/resolveReferences/resolveReferences.h" #include "frontends/p4/evaluator/evaluator.h" #include "frontends/p4/fromv1.0/v1model.h" #include "frontends/p4/moveDeclarations.h" #include "frontends/p4/simplify.h" #include "frontends/p4/simplifyParsers.h" #include "frontends/p4/strengthReduction.h" #include "frontends/p4/typeChecking/typeChecker.h" #include "frontends/p4/typeMap.h" #include "frontends/p4/uniqueNames.h" #include "frontends/p4/unusedDeclarations.h" #include "midend/actionsInlining.h" #include "midend/actionSynthesis.h" #include "midend/convertEnums.h" #include "midend/copyStructures.h" #include "midend/eliminateTuples.h" #include "midend/local_copyprop.h" #include "midend/localizeActions.h" #include "midend/moveConstructors.h" #include "midend/nestedStructs.h" #include "midend/removeLeftSlices.h" #include "midend/removeParameters.h" #include "midend/removeReturns.h" #include "midend/simplifyKey.h" #include "midend/simplifySelect.h" #include "midend/validateProperties.h" #include "midend/compileTimeOps.h" #include "midend/predication.h" namespace BMV2 { #if 0 void MidEnd::setup_for_P4_14(CompilerOptions&) { auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap); // Inlining is simpler for P4 v1.0/1.1 programs, so we have a // specialized code path, which also generates slighly nicer // human-readable results. addPasses({ evaluator, new P4::DiscoverInlining(&controlsToInline, &refMap, &typeMap, evaluator), new P4::InlineDriver(&controlsToInline, new SimpleControlsInliner(&refMap)), new P4::RemoveAllUnusedDeclarations(&refMap), new P4::TypeChecking(&refMap, &typeMap), new P4::DiscoverActionsInlining(&actionsToInline, &refMap, &typeMap), new P4::InlineActionsDriver(&actionsToInline, new SimpleActionsInliner(&refMap)), new P4::RemoveAllUnusedDeclarations(&refMap), }); } #endif class EnumOn32Bits : public P4::ChooseEnumRepresentation { bool convert(const IR::Type_Enum* type) const override { if (type->srcInfo.isValid()) { unsigned line = type->srcInfo.getStart().getLineNumber(); auto sfl = Util::InputSources::instance->getSourceLine(line); cstring sourceFile = sfl.fileName; if (sourceFile.endsWith(P4V1::V1Model::instance.file.name)) // Don't convert any of the standard enums return false; } return true; } unsigned enumSize(unsigned) const override { return 32; } }; void MidEnd::setup_for_P4_16(CompilerOptions&) { // we may come through this path even if the program is actually a P4 v1.0 program auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap); addPasses({ new P4::ConvertEnums(&refMap, &typeMap, new EnumOn32Bits()), new P4::RemoveReturns(&refMap), new P4::MoveConstructors(&refMap), new P4::RemoveAllUnusedDeclarations(&refMap), new P4::ClearTypeMap(&typeMap), evaluator, new VisitFunctor([evaluator](const IR::Node *root) -> const IR::Node * { auto toplevel = evaluator->getToplevelBlock(); if (toplevel->getMain() == nullptr) // nothing further to do return nullptr; return root; }), new P4::Inline(&refMap, &typeMap, evaluator), new P4::InlineActions(&refMap, &typeMap), new P4::LocalizeAllActions(&refMap), new P4::UniqueNames(&refMap), new P4::UniqueParameters(&refMap, &typeMap), new P4::SimplifyControlFlow(&refMap, &typeMap), new P4::RemoveTableParameters(&refMap, &typeMap), new P4::RemoveActionParameters(&refMap, &typeMap), new P4::SimplifyKey(&refMap, &typeMap, new P4::NonLeftValue(&refMap, &typeMap)), new P4::ConstantFolding(&refMap, &typeMap), new P4::StrengthReduction(), new P4::SimplifySelect(&refMap, &typeMap, true), // require constant keysets new P4::SimplifyParsers(&refMap), new P4::StrengthReduction(), new P4::Predication(&refMap), new P4::EliminateTuples(&refMap, &typeMap), new P4::CopyStructures(&refMap, &typeMap), new P4::NestedStructs(&refMap, &typeMap), new P4::LocalCopyPropagation(&refMap, &typeMap), new P4::MoveDeclarations(), new P4::ValidateTableProperties({ "implementation", "size", "counters", "meters", "size", "support_timeout" }), new P4::SimplifyControlFlow(&refMap, &typeMap), new P4::CompileTimeOperations(), new P4::SynthesizeActions(&refMap, &typeMap), new P4::MoveActionsToTables(&refMap, &typeMap), }); } MidEnd::MidEnd(CompilerOptions& options) { bool isv1 = options.isv1(); setName("MidEnd"); refMap.setIsV1(isv1); // must be done BEFORE creating passes #if 0 if (isv1) // TODO: This path should be eventually deprecated setup_for_P4_14(options); else #endif setup_for_P4_16(options); // BMv2-specific passes auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap); addPasses({ new P4::TypeChecking(&refMap, &typeMap), new EliminateVerify(&refMap, &typeMap), new P4::SimplifyControlFlow(&refMap, &typeMap), new P4::RemoveLeftSlices(&refMap, &typeMap), new P4::TypeChecking(&refMap, &typeMap), new LowerExpressions(&typeMap), new P4::ConstantFolding(&refMap, &typeMap, false), evaluator, new VisitFunctor([this, evaluator]() { toplevel = evaluator->getToplevelBlock(); }) }); } } // namespace BMV2 <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QStringList> #include <QtCore/QTextStream> #include <QtGui/QGuiApplication> #include <QtDeclarative/QDeclarativeEngine> #include <QtDeclarative/QDeclarativeContext> #include <QtQuick/QQuickView> #include <QtQuick/QQuickItem> static bool parseArgs(QStringList& args, QVariantMap& parameters) { while (!args.isEmpty()) { QString param = args.takeFirst(); if (param.startsWith("--help")) { QTextStream out(stdout); out << "Usage: " << endl; out << "--plugin.<parameter_name> <parameter_value> - Sets parameter = value for plugin" << endl; out.flush(); return true; } if (param.startsWith("--plugin.")) { param.remove(0, 9); if (args.isEmpty() || args.first().startsWith("--")) { parameters[param] = true; } else { QString value = args.takeFirst(); if (value == "true" || value == "on" || value == "enabled") { parameters[param] = true; } else if (value == "false" || value == "off" || value == "disable") { parameters[param] = false; } else { parameters[param] = value; } } } } return false; } int main(int argc, char *argv[]) { QGuiApplication application(argc, argv); QVariantMap parameters; QStringList args(QCoreApplication::arguments()); if (parseArgs(args, parameters)) return 0; const QString mainQmlApp = QLatin1String("qrc:///places.qml"); QQuickView view; view.engine()->addImportPath(QLatin1String(":/")); view.rootContext()->setContextProperty(QLatin1String("pluginParameters"), parameters); view.rootContext()->setContextProperty(QLatin1String("_mobileUi"), false); view.setSource(QUrl(mainQmlApp)); view.setResizeMode(QQuickView::SizeRootObjectToView); QObject::connect(view.engine(), SIGNAL(quit()), qApp, SLOT(quit())); view.setGeometry(QRect(100, 100, 360, 640)); view.show(); return application.exec(); } <commit_msg>Fix wrong overloaded function is being called.<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QStringList> #include <QtCore/QTextStream> #include <QtGui/QGuiApplication> #include <QtDeclarative/QDeclarativeEngine> #include <QtDeclarative/QDeclarativeContext> #include <QtQuick/QQuickView> #include <QtQuick/QQuickItem> static bool parseArgs(QStringList& args, QVariantMap& parameters) { while (!args.isEmpty()) { QString param = args.takeFirst(); if (param.startsWith("--help")) { QTextStream out(stdout); out << "Usage: " << endl; out << "--plugin.<parameter_name> <parameter_value> - Sets parameter = value for plugin" << endl; out.flush(); return true; } if (param.startsWith("--plugin.")) { param.remove(0, 9); if (args.isEmpty() || args.first().startsWith("--")) { parameters[param] = true; } else { QString value = args.takeFirst(); if (value == "true" || value == "on" || value == "enabled") { parameters[param] = true; } else if (value == "false" || value == "off" || value == "disable") { parameters[param] = false; } else { parameters[param] = value; } } } } return false; } int main(int argc, char *argv[]) { QGuiApplication application(argc, argv); QVariantMap parameters; QStringList args(QCoreApplication::arguments()); if (parseArgs(args, parameters)) return 0; const QString mainQmlApp = QLatin1String("qrc:///places.qml"); QQuickView view; view.engine()->addImportPath(QLatin1String(":/")); view.rootContext()->setContextProperty(QLatin1String("pluginParameters"), parameters); view.rootContext()->setContextProperty(QLatin1String("_mobileUi"), QVariant::fromValue(false)); view.setSource(QUrl(mainQmlApp)); view.setResizeMode(QQuickView::SizeRootObjectToView); QObject::connect(view.engine(), SIGNAL(quit()), qApp, SLOT(quit())); view.setGeometry(QRect(100, 100, 360, 640)); view.show(); return application.exec(); } <|endoftext|>
<commit_before>/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * * 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/dom/Text.h" #include "SVGNames.h" #include "core/css/resolver/StyleResolver.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExceptionCodePlaceholder.h" #include "core/dom/NodeRenderingContext.h" #include "core/dom/ScopedEventQueue.h" #include "core/dom/shadow/ShadowRoot.h" #include "core/rendering/RenderCombineText.h" #include "core/rendering/RenderText.h" #include "core/rendering/svg/RenderSVGInlineText.h" #include "wtf/text/CString.h" #include "wtf/text/StringBuilder.h" using namespace std; namespace WebCore { PassRefPtr<Text> Text::create(Document* document, const String& data) { return adoptRef(new Text(document, data, CreateText)); } PassRefPtr<Text> Text::create(ScriptExecutionContext* context, const String& data) { return adoptRef(new Text(toDocument(context), data, CreateText)); } PassRefPtr<Text> Text::createEditingText(Document* document, const String& data) { return adoptRef(new Text(document, data, CreateEditingText)); } PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionCode& ec) { ec = 0; // INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than // the number of 16-bit units in data. if (offset > length()) { ec = INDEX_SIZE_ERR; return 0; } EventQueueScope scope; String oldStr = data(); RefPtr<Text> newText = cloneWithData(oldStr.substring(offset)); setDataWithoutUpdate(oldStr.substring(0, offset)); didModifyData(oldStr); if (parentNode()) parentNode()->insertBefore(newText.get(), nextSibling(), ec); if (ec) return 0; if (parentNode()) document()->textNodeSplit(this); if (renderer()) toRenderText(renderer())->setTextWithOffset(dataImpl(), 0, oldStr.length()); return newText.release(); } static const Text* earliestLogicallyAdjacentTextNode(const Text* t) { const Node* n = t; while ((n = n->previousSibling())) { Node::NodeType type = n->nodeType(); if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) { t = static_cast<const Text*>(n); continue; } break; } return t; } static const Text* latestLogicallyAdjacentTextNode(const Text* t) { const Node* n = t; while ((n = n->nextSibling())) { Node::NodeType type = n->nodeType(); if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) { t = static_cast<const Text*>(n); continue; } break; } return t; } String Text::wholeText() const { const Text* startText = earliestLogicallyAdjacentTextNode(this); const Text* endText = latestLogicallyAdjacentTextNode(this); Node* onePastEndText = endText->nextSibling(); unsigned resultLength = 0; for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) { if (!n->isTextNode()) continue; const Text* t = static_cast<const Text*>(n); const String& data = t->data(); if (std::numeric_limits<unsigned>::max() - data.length() < resultLength) CRASH(); resultLength += data.length(); } StringBuilder result; result.reserveCapacity(resultLength); for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) { if (!n->isTextNode()) continue; const Text* t = static_cast<const Text*>(n); result.append(t->data()); } ASSERT(result.length() == resultLength); return result.toString(); } PassRefPtr<Text> Text::replaceWholeText(const String& newText) { // Remove all adjacent text nodes, and replace the contents of this one. // Protect startText and endText against mutation event handlers removing the last ref RefPtr<Text> startText = const_cast<Text*>(earliestLogicallyAdjacentTextNode(this)); RefPtr<Text> endText = const_cast<Text*>(latestLogicallyAdjacentTextNode(this)); RefPtr<Text> protectedThis(this); // Mutation event handlers could cause our last ref to go away RefPtr<ContainerNode> parent = parentNode(); // Protect against mutation handlers moving this node during traversal for (RefPtr<Node> n = startText; n && n != this && n->isTextNode() && n->parentNode() == parent;) { RefPtr<Node> nodeToRemove(n.release()); n = nodeToRemove->nextSibling(); parent->removeChild(nodeToRemove.get(), IGNORE_EXCEPTION); } if (this != endText) { Node* onePastEndText = endText->nextSibling(); for (RefPtr<Node> n = nextSibling(); n && n != onePastEndText && n->isTextNode() && n->parentNode() == parent;) { RefPtr<Node> nodeToRemove(n.release()); n = nodeToRemove->nextSibling(); parent->removeChild(nodeToRemove.get(), IGNORE_EXCEPTION); } } if (newText.isEmpty()) { if (parent && parentNode() == parent) parent->removeChild(this, IGNORE_EXCEPTION); return 0; } setData(newText); return protectedThis.release(); } String Text::nodeName() const { return textAtom.string(); } Node::NodeType Text::nodeType() const { return TEXT_NODE; } PassRefPtr<Node> Text::cloneNode(bool /*deep*/) { return cloneWithData(data()); } bool Text::textRendererIsNeeded(const NodeRenderingContext& context) { if (isEditingText()) return true; if (!length()) return false; if (context.style()->display() == NONE) return false; bool onlyWS = containsOnlyWhitespace(); if (!onlyWS) return true; RenderObject* parent = context.parentRenderer(); if (parent->isTable() || parent->isTableRow() || parent->isTableSection() || parent->isRenderTableCol() || parent->isFrameSet()) return false; if (context.style()->preserveNewline()) // pre/pre-wrap/pre-line always make renderers. return true; RenderObject* prev = context.previousRenderer(); if (prev && prev->isBR()) // <span><br/> <br/></span> return false; if (parent->isRenderInline()) { // <span><div/> <div/></span> if (prev && !prev->isInline()) return false; } else { if (parent->isRenderBlock() && !parent->childrenInline() && (!prev || !prev->isInline())) return false; RenderObject* first = parent->firstChild(); while (first && first->isFloatingOrOutOfFlowPositioned()) first = first->nextSibling(); RenderObject* next = context.nextRenderer(); if (!first || next == first) // Whitespace at the start of a block just goes away. Don't even // make a render object for this text. return false; } return true; } static bool isSVGShadowText(Text* text) { Node* parentNode = text->parentNode(); return parentNode->isShadowRoot() && toShadowRoot(parentNode)->host()->hasTagName(SVGNames::trefTag); } static bool isSVGText(Text* text) { Node* parentOrShadowHostNode = text->parentOrShadowHostNode(); return parentOrShadowHostNode->isSVGElement() && !parentOrShadowHostNode->hasTagName(SVGNames::foreignObjectTag); } void Text::createTextRendererIfNeeded() { NodeRenderingContext(this).createRendererForTextIfNeeded(); } RenderText* Text::createTextRenderer(RenderArena* arena, RenderStyle* style) { if (isSVGText(this) || isSVGShadowText(this)) return new (arena) RenderSVGInlineText(this, dataImpl()); if (style->hasTextCombine()) return new (arena) RenderCombineText(this, dataImpl()); return new (arena) RenderText(this, dataImpl()); } void Text::attach(const AttachContext& context) { createTextRendererIfNeeded(); CharacterData::attach(context); } void Text::recalcTextStyle(StyleChange change) { RenderText* renderer = toRenderText(this->renderer()); if (!renderer) { if (needsStyleRecalc()) reattach(); clearNeedsStyleRecalc(); return; } if (needsStyleRecalc()) { renderer->setStyle(document()->styleResolver()->styleForText(this)); renderer->setText(dataImpl()); } else if (change != NoChange) { renderer->setStyle(document()->styleResolver()->styleForText(this)); } clearNeedsStyleRecalc(); } void Text::updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData) { if (!attached()) return; RenderText* textRenderer = toRenderText(renderer()); if (!textRenderer || !textRendererIsNeeded(NodeRenderingContext(this, textRenderer->style()))) { reattach(); return; } textRenderer->setTextWithOffset(dataImpl(), offsetOfReplacedData, lengthOfReplacedData); } bool Text::childTypeAllowed(NodeType) const { return false; } PassRefPtr<Text> Text::cloneWithData(const String& data) { return create(document(), data); } PassRefPtr<Text> Text::createWithLengthLimit(Document* document, const String& data, unsigned start, unsigned lengthLimit) { unsigned dataLength = data.length(); if (!start && dataLength <= lengthLimit) return create(document, data); RefPtr<Text> result = Text::create(document, String()); result->parserAppendData(data, start, lengthLimit); return result; } #ifndef NDEBUG void Text::formatForDebugger(char *buffer, unsigned length) const { StringBuilder result; String s; result.append(nodeName()); s = data(); if (s.length() > 0) { if (result.length()) result.appendLiteral("; "); result.appendLiteral("value="); result.append(s); } strncpy(buffer, result.toString().utf8().data(), length - 1); } #endif } // namespace WebCore <commit_msg>Remove code duplication in Text::recalcTextStyle<commit_after>/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * * 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/dom/Text.h" #include "SVGNames.h" #include "core/css/resolver/StyleResolver.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExceptionCodePlaceholder.h" #include "core/dom/NodeRenderingContext.h" #include "core/dom/ScopedEventQueue.h" #include "core/dom/shadow/ShadowRoot.h" #include "core/rendering/RenderCombineText.h" #include "core/rendering/RenderText.h" #include "core/rendering/svg/RenderSVGInlineText.h" #include "wtf/text/CString.h" #include "wtf/text/StringBuilder.h" using namespace std; namespace WebCore { PassRefPtr<Text> Text::create(Document* document, const String& data) { return adoptRef(new Text(document, data, CreateText)); } PassRefPtr<Text> Text::create(ScriptExecutionContext* context, const String& data) { return adoptRef(new Text(toDocument(context), data, CreateText)); } PassRefPtr<Text> Text::createEditingText(Document* document, const String& data) { return adoptRef(new Text(document, data, CreateEditingText)); } PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionCode& ec) { ec = 0; // INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than // the number of 16-bit units in data. if (offset > length()) { ec = INDEX_SIZE_ERR; return 0; } EventQueueScope scope; String oldStr = data(); RefPtr<Text> newText = cloneWithData(oldStr.substring(offset)); setDataWithoutUpdate(oldStr.substring(0, offset)); didModifyData(oldStr); if (parentNode()) parentNode()->insertBefore(newText.get(), nextSibling(), ec); if (ec) return 0; if (parentNode()) document()->textNodeSplit(this); if (renderer()) toRenderText(renderer())->setTextWithOffset(dataImpl(), 0, oldStr.length()); return newText.release(); } static const Text* earliestLogicallyAdjacentTextNode(const Text* t) { const Node* n = t; while ((n = n->previousSibling())) { Node::NodeType type = n->nodeType(); if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) { t = static_cast<const Text*>(n); continue; } break; } return t; } static const Text* latestLogicallyAdjacentTextNode(const Text* t) { const Node* n = t; while ((n = n->nextSibling())) { Node::NodeType type = n->nodeType(); if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) { t = static_cast<const Text*>(n); continue; } break; } return t; } String Text::wholeText() const { const Text* startText = earliestLogicallyAdjacentTextNode(this); const Text* endText = latestLogicallyAdjacentTextNode(this); Node* onePastEndText = endText->nextSibling(); unsigned resultLength = 0; for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) { if (!n->isTextNode()) continue; const Text* t = static_cast<const Text*>(n); const String& data = t->data(); if (std::numeric_limits<unsigned>::max() - data.length() < resultLength) CRASH(); resultLength += data.length(); } StringBuilder result; result.reserveCapacity(resultLength); for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) { if (!n->isTextNode()) continue; const Text* t = static_cast<const Text*>(n); result.append(t->data()); } ASSERT(result.length() == resultLength); return result.toString(); } PassRefPtr<Text> Text::replaceWholeText(const String& newText) { // Remove all adjacent text nodes, and replace the contents of this one. // Protect startText and endText against mutation event handlers removing the last ref RefPtr<Text> startText = const_cast<Text*>(earliestLogicallyAdjacentTextNode(this)); RefPtr<Text> endText = const_cast<Text*>(latestLogicallyAdjacentTextNode(this)); RefPtr<Text> protectedThis(this); // Mutation event handlers could cause our last ref to go away RefPtr<ContainerNode> parent = parentNode(); // Protect against mutation handlers moving this node during traversal for (RefPtr<Node> n = startText; n && n != this && n->isTextNode() && n->parentNode() == parent;) { RefPtr<Node> nodeToRemove(n.release()); n = nodeToRemove->nextSibling(); parent->removeChild(nodeToRemove.get(), IGNORE_EXCEPTION); } if (this != endText) { Node* onePastEndText = endText->nextSibling(); for (RefPtr<Node> n = nextSibling(); n && n != onePastEndText && n->isTextNode() && n->parentNode() == parent;) { RefPtr<Node> nodeToRemove(n.release()); n = nodeToRemove->nextSibling(); parent->removeChild(nodeToRemove.get(), IGNORE_EXCEPTION); } } if (newText.isEmpty()) { if (parent && parentNode() == parent) parent->removeChild(this, IGNORE_EXCEPTION); return 0; } setData(newText); return protectedThis.release(); } String Text::nodeName() const { return textAtom.string(); } Node::NodeType Text::nodeType() const { return TEXT_NODE; } PassRefPtr<Node> Text::cloneNode(bool /*deep*/) { return cloneWithData(data()); } bool Text::textRendererIsNeeded(const NodeRenderingContext& context) { if (isEditingText()) return true; if (!length()) return false; if (context.style()->display() == NONE) return false; bool onlyWS = containsOnlyWhitespace(); if (!onlyWS) return true; RenderObject* parent = context.parentRenderer(); if (parent->isTable() || parent->isTableRow() || parent->isTableSection() || parent->isRenderTableCol() || parent->isFrameSet()) return false; if (context.style()->preserveNewline()) // pre/pre-wrap/pre-line always make renderers. return true; RenderObject* prev = context.previousRenderer(); if (prev && prev->isBR()) // <span><br/> <br/></span> return false; if (parent->isRenderInline()) { // <span><div/> <div/></span> if (prev && !prev->isInline()) return false; } else { if (parent->isRenderBlock() && !parent->childrenInline() && (!prev || !prev->isInline())) return false; RenderObject* first = parent->firstChild(); while (first && first->isFloatingOrOutOfFlowPositioned()) first = first->nextSibling(); RenderObject* next = context.nextRenderer(); if (!first || next == first) // Whitespace at the start of a block just goes away. Don't even // make a render object for this text. return false; } return true; } static bool isSVGShadowText(Text* text) { Node* parentNode = text->parentNode(); return parentNode->isShadowRoot() && toShadowRoot(parentNode)->host()->hasTagName(SVGNames::trefTag); } static bool isSVGText(Text* text) { Node* parentOrShadowHostNode = text->parentOrShadowHostNode(); return parentOrShadowHostNode->isSVGElement() && !parentOrShadowHostNode->hasTagName(SVGNames::foreignObjectTag); } void Text::createTextRendererIfNeeded() { NodeRenderingContext(this).createRendererForTextIfNeeded(); } RenderText* Text::createTextRenderer(RenderArena* arena, RenderStyle* style) { if (isSVGText(this) || isSVGShadowText(this)) return new (arena) RenderSVGInlineText(this, dataImpl()); if (style->hasTextCombine()) return new (arena) RenderCombineText(this, dataImpl()); return new (arena) RenderText(this, dataImpl()); } void Text::attach(const AttachContext& context) { createTextRendererIfNeeded(); CharacterData::attach(context); } void Text::recalcTextStyle(StyleChange change) { RenderText* renderer = toRenderText(this->renderer()); if (renderer) { if (change != NoChange || needsStyleRecalc()) renderer->setStyle(document()->styleResolver()->styleForText(this)); if (needsStyleRecalc()) renderer->setText(dataImpl()); } else if (needsStyleRecalc()) { reattach(); } clearNeedsStyleRecalc(); } void Text::updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData) { if (!attached()) return; RenderText* textRenderer = toRenderText(renderer()); if (!textRenderer || !textRendererIsNeeded(NodeRenderingContext(this, textRenderer->style()))) { reattach(); return; } textRenderer->setTextWithOffset(dataImpl(), offsetOfReplacedData, lengthOfReplacedData); } bool Text::childTypeAllowed(NodeType) const { return false; } PassRefPtr<Text> Text::cloneWithData(const String& data) { return create(document(), data); } PassRefPtr<Text> Text::createWithLengthLimit(Document* document, const String& data, unsigned start, unsigned lengthLimit) { unsigned dataLength = data.length(); if (!start && dataLength <= lengthLimit) return create(document, data); RefPtr<Text> result = Text::create(document, String()); result->parserAppendData(data, start, lengthLimit); return result; } #ifndef NDEBUG void Text::formatForDebugger(char *buffer, unsigned length) const { StringBuilder result; String s; result.append(nodeName()); s = data(); if (s.length() > 0) { if (result.length()) result.appendLiteral("; "); result.appendLiteral("value="); result.append(s); } strncpy(buffer, result.toString().utf8().data(), length - 1); } #endif } // namespace WebCore <|endoftext|>
<commit_before><commit_msg>coverity#441125 Dereference after null check<commit_after><|endoftext|>
<commit_before>#ifndef MLT_MODELS_REGRESSORS_RIDGE_REGRESSION_HPP #define MLT_MODELS_REGRESSORS_RIDGE_REGRESSION_HPP #include <Eigen/Core> #include "../linear_model.hpp" #include "../../utils/linalg.hpp" namespace mlt { namespace models { namespace regressors { class RidgeRegression : public LinearModel { public: explicit RidgeRegression(double regularization, bool fit_intercept) : _regularization(regularization), LinearModel(fit_intercept) {} RidgeRegression& fit(const Eigen::MatrixXd& input, const Eigen::MatrixXd& target) { // Closed-form solution of Ridge Linear Regression: pinv((input' * input) + I * regularization) * input' * target Eigen::MatrixXd input_prime(input.rows(), input.cols() + (_fit_intercept ? 1 : 0)); input_prime.leftCols(input.cols()) << input; if (_fit_intercept) { input_prime.rightCols<1>() = Eigen::VectorXd::Ones(input.rows()); } Eigen::MatrixXd coeffs = utils::linalg::pseudo_inverse( (input_prime.transpose() * input_prime) + Eigen::MatrixXd::Identity(input_prime.cols(), input_prime.cols()) * _regularization) * input_prime.transpose() * target; if (_fit_intercept) { _set_coefficients_and_intercepts(coeffs.topRows(coeffs.rows() - 1), coeffs.bottomRows<1>()); } else { _set_coefficients(coeffs); } return *this; } protected: // TODO: Implement different training methods inline double _cost_internal(const Eigen::MatrixXd& beta, const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const { double loss = ((input * beta) - result).array().pow(2).sum() / (2 * input.rows()); loss += _regularization * (beta.array().pow(2)).sum(); return loss; } inline std::tuple<double, Eigen::MatrixXd> _cost_and_gradient_internal(const Eigen::MatrixXd& beta, const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const { Eigen::MatrixXd diff = input * beta - result; double loss = diff.array().pow(2).sum() / (2 * input.rows()); loss += _regularization * (beta.array().pow(2)).sum(); Eigen::MatrixXd d_beta = (input.transpose() * diff) / input.rows(); d_beta += _regularization * 2 * beta; return std::make_tuple(loss, d_beta); } double _regularization; }; } } } #endif<commit_msg>Not applying regularization to intercept terms<commit_after>#ifndef MLT_MODELS_REGRESSORS_RIDGE_REGRESSION_HPP #define MLT_MODELS_REGRESSORS_RIDGE_REGRESSION_HPP #include <Eigen/Core> #include "../linear_model.hpp" #include "../../utils/linalg.hpp" namespace mlt { namespace models { namespace regressors { class RidgeRegression : public LinearModel { public: explicit RidgeRegression(double regularization, bool fit_intercept) : _regularization(regularization), LinearModel(fit_intercept) {} RidgeRegression& fit(const Eigen::MatrixXd& input, const Eigen::MatrixXd& target) { // Closed-form solution of Ridge Linear Regression: pinv((input' * input) + I * regularization) * input' * target Eigen::MatrixXd input_prime(input.rows(), input.cols() + (_fit_intercept ? 1 : 0)); input_prime.leftCols(input.cols()) << input; if (_fit_intercept) { input_prime.rightCols<1>() = Eigen::VectorXd::Ones(input.rows()); } Eigen::MatrixXd reg = Eigen::MatrixXd::Identity(input_prime.cols(), input_prime.cols()) * _regularization; reg(reg.rows() -1, reg.cols() - 1) = 0; Eigen::MatrixXd coeffs = utils::linalg::pseudo_inverse( (input_prime.transpose() * input_prime) + reg) * input_prime.transpose() * target; if (_fit_intercept) { _set_coefficients_and_intercepts(coeffs.topRows(coeffs.rows() - 1), coeffs.bottomRows<1>()); } else { _set_coefficients(coeffs); } return *this; } protected: // TODO: Implement different training methods inline double _cost_internal(const Eigen::MatrixXd& beta, const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const { double loss = ((input * beta) - result).array().pow(2).sum() / (2 * input.rows()); loss += _regularization * (beta.array().pow(2)).sum(); return loss; } inline std::tuple<double, Eigen::MatrixXd> _cost_and_gradient_internal(const Eigen::MatrixXd& beta, const Eigen::MatrixXd& input, const Eigen::MatrixXd& result) const { Eigen::MatrixXd diff = input * beta - result; double loss = diff.array().pow(2).sum() / (2 * input.rows()); loss += _regularization * (beta.array().pow(2)).sum(); Eigen::MatrixXd d_beta = (input.transpose() * diff) / input.rows(); d_beta += _regularization * 2 * beta; return std::make_tuple(loss, d_beta); } double _regularization; }; } } } #endif<|endoftext|>
<commit_before>#include <compress.hpp> #include <vector> #include <iostream> using iter::compress; template <typename DataType, typename SelectorType> void testcase(std::vector<DataType> data_vec, std::vector<SelectorType> sel_vec) { for (auto e : compress(data_vec, sel_vec)) { std::cout << e << '\n'; } } int main(void) { std::vector<int> ivec{1, 2, 3, 4, 5, 6}; std::vector<bool> bvec{true, false, true, false, true, false}; std::cout << "Should print 1 3 5\n"; testcase(ivec, bvec); std::vector<bool> bvec2{false, true, false, false, false, true}; std::cout << "Should print 2 6\n"; testcase(ivec, bvec2); std::vector<bool> bvec3{false, true}; std::cout << "Should print 2\n"; testcase(ivec, bvec3); return 0; } <commit_msg>Adds test with temporary<commit_after>#include <compress.hpp> #include <range.hpp> #include <vector> #include <iostream> using iter::compress; using iter::range; template <typename DataType, typename SelectorType> void testcase(std::vector<DataType> data_vec, std::vector<SelectorType> sel_vec) { for (auto e : compress(data_vec, sel_vec)) { std::cout << e << '\n'; } } int main(void) { std::vector<int> ivec{1, 2, 3, 4, 5, 6}; std::vector<bool> bvec{true, false, true, false, true, false}; std::cout << "Should print 1 3 5\n"; testcase(ivec, bvec); std::vector<bool> bvec2{false, true, false, false, false, true}; std::cout << "Should print 2 6\n"; testcase(ivec, bvec2); std::vector<bool> bvec3{false, true}; std::cout << "Should print 2\n"; testcase(ivec, bvec3); for (auto i : compress(range(10), bvec)) { std::cout << i << '\n'; } return 0; } <|endoftext|>
<commit_before>/* // $ g++ -O3 -o cluster createClusters.cpp // $ ./cluster network.pairs network.jaccs network.clusters threshold // // -- network.pairs is an integer edgelist (one edge, two nodes // per line) // // -- network.jaccs contains network.jaccs the jaccard // coefficient for each pair of edges compared, of the form: // i_0 i_1 j_0 j_1 jaccard<newline> // ... // for edges (i_0,i_1) and (j_0,j_1), etc. // // -- network.clusters will contain one cluster of edges per line // (edge nodes are comma-separated and edges are space-separated) // // --threshold is the [0,1] threshold for the clustering */ #include <ctime> #include <cstdlib> #include <fstream> #include <iostream> #include <set> #include <map> #include <utility> // for pairs #include <algorithm> // for swap using namespace std; int main (int argc, char const *argv[]){ //************* make sure args are present: if (argc != 6){ cout << "ERROR: something wrong with the inputs" << endl; cout << "usage:\n " << argv[0] << " network.pairs network.jaccs network.clusters network.cluster_stats threshold" << endl; exit(1); } float threshold = atof( argv[5] ); if (threshold < 0.0 || threshold > 1.0){ cout << "ERROR: specified threshold not in [0,1]" << endl; exit(1); } //************* got the args clock_t begin = clock(); //************* start load edgelist ifstream inFile; inFile.open( argv[1] ); if (!inFile) { cout << "ERROR: unable to open input file" << endl; exit(1); // terminate with error } // index should be iterator not integer???? map< int, set<int> > index2cluster; // O(log n) access too slow? map< int, map<int, set<int> >::iterator > edge2iter; int ni, nj, edgeId, index = 0; while (inFile >> ni >> nj >> edgeId){ // scan edgelist to populate //while (inFile >> ni >> nj >> wij){ // scan edgelist to populate WEIGHTED //if (ni >= nj) swap(ni,nj); // undirected! index2cluster[ index ].insert( edgeId ); // build cluster index to set of edge-pairs map edge2iter[ edgeId ] = index2cluster.find(index); // build edge pair to cluster iter map ******???? index++; } inFile.close(); inFile.clear(); //************* end load edgelist //************* loop over jaccards file and do the clustering ifstream jaccFile; jaccFile.open( argv[2] ); if (!jaccFile) { cout << "ERROR: unable to open jaccards file" << endl; exit(1); // terminate with error } int edgeId1,edgeId2; double jacc; int idx_i, idx_j; map< int, set<int > >::iterator iter_i,iter_j; set<int>::iterator iterS; while ( jaccFile >> edgeId1 >> edgeId2 >> jacc ) { if ( jacc >= threshold ) { iter_i = edge2iter[ edgeId1 ]; iter_j = edge2iter[ edgeId2 ]; if ( iter_i != iter_j ) { // always merge smaller cluster into bigger: if ( (*iter_j).second.size() > (*iter_i).second.size() ){ // !!!!!! swap(iter_i, iter_j); } // merge cluster j into i and update index for all elements in j: for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){ iter_i->second.insert( *iterS ); edge2iter[ *iterS ] = iter_i; } // delete cluster j: index2cluster.erase(iter_j); } } // done merging clusters i and j } //************* done looping over jaccards file //************* write the clusters to file: jaccFile.close(); cout << "There were " << index2cluster.size() << " clusters at threshold " << threshold << "." << endl; // all done clustering, write to file (and calculated partition density): FILE * clustersFile = fopen( argv[3], "w" ); FILE * clusterStatsFile = fopen( argv[4], "w" ); set<int> clusterNodes; int mc, nc; int M = 0, Mns = 0; double wSum = 0.0; set< int >::iterator S; map< int,set< int > >::iterator it; for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) { clusterNodes.clear(); for (S = it->second.begin(); S != it->second.end(); S++ ){ fprintf( clustersFile, "%i ", *S ); // this leaves a trailing space...! clusterNodes.insert(*S); } mc = it->second.size(); nc = clusterNodes.size(); M += mc; if (nc != 2) { Mns += mc; wSum += mc * (mc - (nc-1.0)) / ((nc-2.0)*(nc-1.0)); } fprintf( clustersFile, "\n" ); fprintf( clusterStatsFile, "%i %i\n", mc, nc ); } fclose(clustersFile); fclose(clusterStatsFile); //************* cout << "The partition density is:" << endl; cout << " D = " << 2.0 * wSum / M << endl; cout << "not counting one-edge clusters:" << endl; cout << " D = " << 2.0 * wSum / Mns << endl; cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl; return 0; } <commit_msg>Update createClusters.cpp<commit_after>/* // $ g++ -O3 -o cluster createClusters.cpp // $ ./cluster network.pairs network.jaccs network.clusters threshold // // -- network.pairs is an integer edgelist (one edge, two nodes // per line) // // -- network.jaccs contains network.jaccs the jaccard // coefficient for each pair of edges compared, of the form: // i_0 i_1 j_0 j_1 jaccard<newline> // ... // for edges (i_0,i_1) and (j_0,j_1), etc. // // -- network.clusters will contain one cluster of edges per line // (edge nodes are comma-separated and edges are space-separated) // // --threshold is the [0,1] threshold for the clustering */ #include <ctime> #include <cstdlib> #include <fstream> #include <iostream> #include <set> #include <map> #include <utility> // for pairs #include <algorithm> // for swap using namespace std; int main (int argc, char const *argv[]){ //************* make sure args are present: if (argc != 6){ cout << "ERROR: something wrong with the inputs" << endl; cout << "usage:\n " << argv[0] << " network.pairs network.jaccs network.clusters network.cluster_stats threshold" << endl; exit(1); } float threshold = atof( argv[5] ); if (threshold < 0.0 || threshold > 1.0){ cout << "ERROR: specified threshold not in [0,1]" << endl; exit(1); } //************* got the args clock_t begin = clock(); //************* start load edgelist ifstream inFile; inFile.open( argv[1] ); if (!inFile) { cout << "ERROR: unable to open input file" << endl; exit(1); // terminate with error } // index should be iterator not integer???? map< int, set<int> > index2cluster; // O(log n) access too slow? map< int, map<int, set<int> >::iterator > edge2iter; int ni, nj, edgeId, index = 0; while (inFile >> ni >> nj >> edgeId){ // scan edgelist to populate //while (inFile >> ni >> nj >> wij){ // scan edgelist to populate WEIGHTED //if (ni >= nj) swap(ni,nj); // undirected! index2cluster[ index ].insert( edgeId ); // build cluster index to set of edge-pairs map edge2iter[ edgeId ] = index2cluster.find(index); // build edge pair to cluster iter map ******???? index++; } inFile.close(); inFile.clear(); //************* end load edgelist //************* loop over jaccards file and do the clustering ifstream jaccFile; jaccFile.open( argv[2] ); if (!jaccFile) { cout << "ERROR: unable to open jaccards file" << endl; exit(1); // terminate with error } int edgeId1,edgeId2; double jacc; int idx_i, idx_j; map< int, set<int > >::iterator iter_i,iter_j; set<int>::iterator iterS; while ( jaccFile >> edgeId1 >> edgeId2 >> jacc ) { if ( jacc >= threshold ) { iter_i = edge2iter[ edgeId1 ]; iter_j = edge2iter[ edgeId2 ]; if ( iter_i != iter_j ) { // always merge smaller cluster into bigger: if ( (*iter_j).second.size() > (*iter_i).second.size() ){ // !!!!!! swap(iter_i, iter_j); } // merge cluster j into i and update index for all elements in j: for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){ iter_i->second.insert( *iterS ); edge2iter[ *iterS ] = iter_i; } // delete cluster j: index2cluster.erase(iter_j); } } // done merging clusters i and j } //************* done looping over jaccards file //************* write the clusters to file: jaccFile.close(); cout << "There were " << index2cluster.size() << " clusters at threshold " << threshold << "." << endl; // all done clustering, write to file (and calculated partition density): FILE * clustersFile = fopen( argv[3], "w" ); FILE * clusterStatsFile = fopen( argv[4], "w" ); set<int> clusterNodes; int mc, nc; int M = 0, Mns = 0; double wSum = 0.0; set< int >::iterator S; map< int,set< int > >::iterator it; for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) { clusterNodes.clear(); for (S = it->second.begin(); S != it->second.end(); S++ ){ fprintf( clustersFile, "%i ", *S ); // this leaves a trailing space...! clusterNodes.insert(*S); } mc = it->second.size(); nc = clusterNodes.size(); M += mc; if (nc > 2) { Mns += mc; wSum += mc * (mc - (nc-1.0)) / ((nc-2.0)*(nc-1.0)); } fprintf( clustersFile, "\n" ); fprintf( clusterStatsFile, "%i %i\n", mc, nc ); } fclose(clustersFile); fclose(clusterStatsFile); //************* cout << "The partition density is:" << endl; cout << " D = " << 2.0 * wSum / M << endl; cout << "not counting one-edge clusters:" << endl; cout << " D = " << 2.0 * wSum / Mns << endl; cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl; return 0; } <|endoftext|>
<commit_before>// Copyright 2016 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "helpers.hpp" #include <chrono> #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/document/view.hpp> #include <bsoncxx/private/suppress_deprecation_warnings.hh> #include <bsoncxx/test_util/catch.hh> #include <mongocxx/exception/logic_error.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/options/private/rewriter.hh> namespace { using namespace bsoncxx::builder::basic; using namespace mongocxx; TEST_CASE("options::rewriter::rewrite_find_modifiers() with $comment", "[find][option]") { instance::current(); SECTION("$comment with k_utf8 type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$comment", "test")))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.comment()); REQUIRE(*find_opts.comment() == stdx::string_view("test")); } SECTION("$comment with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$comment", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $explain", "[find][option]") { instance::current(); SECTION("$explain isn't supported") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$explain", true)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $hint", "[find][option]") { instance::current(); options::find find_opts; SECTION("$hint with k_utf8 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$hint", "index")))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.hint()); REQUIRE(*find_opts.hint() == "index"); } SECTION("$hint with k_document is translated") { find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$hint", make_document(kvp("a", 1)))))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.hint()); REQUIRE(*find_opts.hint() == make_document(kvp("a", 1))); } SECTION("$hint with other types is rejected") { REQUIRE_THROWS_AS(options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$hint", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $max", "[find][option]") { instance::current(); SECTION("$max with k_document type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$max", make_document(kvp("a", 1)))))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max()); REQUIRE(*find_opts.max() == make_document(kvp("a", 1))); } SECTION("$max with other types is rejected") { REQUIRE_THROWS_AS(options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$max", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $maxScan", "[find][option]") { instance::current(); options::find find_opts; SECTION("$maxScan with k_int32 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxScan", 1)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_scan()); REQUIRE(*find_opts.max_scan() == 1); } SECTION("$maxScan with k_int64 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxScan", std::int64_t{1})))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_scan()); REQUIRE(*find_opts.max_scan() == 1); } SECTION("$maxScan with k_double type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxScan", 1.0)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_scan()); REQUIRE(*find_opts.max_scan() == 1); } SECTION("$maxScan with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxScan", "foo")))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $maxTimeMS", "[find][option]") { instance::current(); options::find find_opts; SECTION("$maxTimeMS with k_int32 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxTimeMS", 1)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_time()); REQUIRE(find_opts.max_time()->count() == 1); } SECTION("$maxTimeMS with k_int64 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$maxTimeMS", std::int64_t{1})))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_time()); REQUIRE(find_opts.max_time()->count() == 1); } SECTION("$maxTimeMS with k_double type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxTimeMS", 1.0)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_time()); REQUIRE(find_opts.max_time()->count() == 1); } SECTION("$maxTimeMS with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxTimeMS", "foo")))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $min", "[find][option]") { instance::current(); SECTION("$min with k_document type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$min", make_document(kvp("a", 1)))))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.min()); REQUIRE(*find_opts.min() == make_document(kvp("a", 1))); } SECTION("$min with other types is rejected") { REQUIRE_THROWS_AS(options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$min", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $orderby", "[find][option]") { instance::current(); SECTION("$orderby with k_document type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$orderby", make_document(kvp("a", 1)))))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.sort()); REQUIRE(*find_opts.sort() == make_document(kvp("a", 1))); } SECTION("$orderby with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$orderby", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $query", "[find][option]") { instance::current(); SECTION("$query isn't supported") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$query", make_document(kvp("a", 1)))))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $returnKey", "[find][option]") { instance::current(); SECTION("$returnKey with k_bool type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$returnKey", true)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.return_key()); REQUIRE(*find_opts.return_key() == true); } SECTION("$returnKey with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$returnKey", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $showDiskLoc", "[find][option]") { instance::current(); SECTION("$showDiskLoc with k_bool type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$showDiskLoc", true)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.show_record_id()); REQUIRE(*find_opts.show_record_id() == true); } SECTION("$showDiskLoc with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$showDiskLoc", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $snapshot", "[find][option]") { instance::current(); SECTION("$snapshot with k_bool type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$snapshot", true)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.snapshot()); REQUIRE(*find_opts.snapshot() == true); } SECTION("$snapshot with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$snapshot", 1)))), logic_error); } } BSONCXX_SUPPRESS_DEPRECATION_WARNINGS_END } // namespace <commit_msg>Remove stray test macro<commit_after>// Copyright 2016 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "helpers.hpp" #include <chrono> #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/document/view.hpp> #include <bsoncxx/private/suppress_deprecation_warnings.hh> #include <bsoncxx/test_util/catch.hh> #include <mongocxx/exception/logic_error.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/options/private/rewriter.hh> namespace { using namespace bsoncxx::builder::basic; using namespace mongocxx; TEST_CASE("options::rewriter::rewrite_find_modifiers() with $comment", "[find][option]") { instance::current(); SECTION("$comment with k_utf8 type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$comment", "test")))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.comment()); REQUIRE(*find_opts.comment() == stdx::string_view("test")); } SECTION("$comment with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$comment", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $explain", "[find][option]") { instance::current(); SECTION("$explain isn't supported") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$explain", true)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $hint", "[find][option]") { instance::current(); options::find find_opts; SECTION("$hint with k_utf8 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$hint", "index")))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.hint()); REQUIRE(*find_opts.hint() == "index"); } SECTION("$hint with k_document is translated") { find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$hint", make_document(kvp("a", 1)))))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.hint()); REQUIRE(*find_opts.hint() == make_document(kvp("a", 1))); } SECTION("$hint with other types is rejected") { REQUIRE_THROWS_AS(options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$hint", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $max", "[find][option]") { instance::current(); SECTION("$max with k_document type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$max", make_document(kvp("a", 1)))))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max()); REQUIRE(*find_opts.max() == make_document(kvp("a", 1))); } SECTION("$max with other types is rejected") { REQUIRE_THROWS_AS(options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$max", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $maxScan", "[find][option]") { instance::current(); options::find find_opts; SECTION("$maxScan with k_int32 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxScan", 1)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_scan()); REQUIRE(*find_opts.max_scan() == 1); } SECTION("$maxScan with k_int64 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxScan", std::int64_t{1})))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_scan()); REQUIRE(*find_opts.max_scan() == 1); } SECTION("$maxScan with k_double type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxScan", 1.0)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_scan()); REQUIRE(*find_opts.max_scan() == 1); } SECTION("$maxScan with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxScan", "foo")))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $maxTimeMS", "[find][option]") { instance::current(); options::find find_opts; SECTION("$maxTimeMS with k_int32 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxTimeMS", 1)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_time()); REQUIRE(find_opts.max_time()->count() == 1); } SECTION("$maxTimeMS with k_int64 type is translated") { find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$maxTimeMS", std::int64_t{1})))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_time()); REQUIRE(find_opts.max_time()->count() == 1); } SECTION("$maxTimeMS with k_double type is translated") { find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxTimeMS", 1.0)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.max_time()); REQUIRE(find_opts.max_time()->count() == 1); } SECTION("$maxTimeMS with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$maxTimeMS", "foo")))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $min", "[find][option]") { instance::current(); SECTION("$min with k_document type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$min", make_document(kvp("a", 1)))))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.min()); REQUIRE(*find_opts.min() == make_document(kvp("a", 1))); } SECTION("$min with other types is rejected") { REQUIRE_THROWS_AS(options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$min", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $orderby", "[find][option]") { instance::current(); SECTION("$orderby with k_document type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$orderby", make_document(kvp("a", 1)))))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.sort()); REQUIRE(*find_opts.sort() == make_document(kvp("a", 1))); } SECTION("$orderby with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$orderby", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $query", "[find][option]") { instance::current(); SECTION("$query isn't supported") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers(options::find{}.modifiers_deprecated( make_document(kvp("$query", make_document(kvp("a", 1)))))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $returnKey", "[find][option]") { instance::current(); SECTION("$returnKey with k_bool type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$returnKey", true)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.return_key()); REQUIRE(*find_opts.return_key() == true); } SECTION("$returnKey with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$returnKey", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $showDiskLoc", "[find][option]") { instance::current(); SECTION("$showDiskLoc with k_bool type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$showDiskLoc", true)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.show_record_id()); REQUIRE(*find_opts.show_record_id() == true); } SECTION("$showDiskLoc with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$showDiskLoc", 1)))), logic_error); } } TEST_CASE("options::rewriter::rewrite_find_modifiers() with $snapshot", "[find][option]") { instance::current(); SECTION("$snapshot with k_bool type is translated") { auto find_opts = options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$snapshot", true)))); REQUIRE(!find_opts.modifiers_deprecated()); REQUIRE(find_opts.snapshot()); REQUIRE(*find_opts.snapshot() == true); } SECTION("$snapshot with other types is rejected") { REQUIRE_THROWS_AS( options::rewriter::rewrite_find_modifiers( options::find{}.modifiers_deprecated(make_document(kvp("$snapshot", 1)))), logic_error); } } } // namespace <|endoftext|>
<commit_before>#include <IOKit/IOLib.h> #include "EventOutputQueue.hpp" #include "FlagStatus.hpp" #include "UserClient_kext.hpp" #include "VK_CONFIG.hpp" namespace org_pqrs_Karabiner { VirtualKey::VK_CONFIG::Vector_Item VirtualKey::VK_CONFIG::items_; void VirtualKey::VK_CONFIG::initialize(void) {} void VirtualKey::VK_CONFIG::terminate(void) { items_.clear(); } void VirtualKey::VK_CONFIG::add_item(RemapClass* remapclass, unsigned int keycode_toggle, unsigned int keycode_force_on, unsigned int keycode_force_off, unsigned int keycode_sync_keydownup) { items_.push_back(Item(remapclass, keycode_toggle, keycode_force_on, keycode_force_off, keycode_sync_keydownup)); } void VirtualKey::VK_CONFIG::clear_items(void) { items_.clear(); } bool VirtualKey::VK_CONFIG::handle(const Params_KeyboardEventCallBack& params, AutogenId autogenId) { RemapClass* remapclass = nullptr; bool value_old = false; for (size_t i = 0; i < items_.size(); ++i) { remapclass = items_[i].remapclass; KeyCode keycode_toggle(items_[i].keycode_toggle); KeyCode keycode_force_on(items_[i].keycode_force_on); KeyCode keycode_force_off(items_[i].keycode_force_off); KeyCode keycode_sync_keydownup(items_[i].keycode_sync_keydownup); if (!remapclass) return false; value_old = remapclass->enabled(); if (params.key == keycode_toggle) { if (params.repeat) goto finish; if (params.ex_iskeydown) { remapclass->toggleEnabled(); goto refresh; } goto finish; } else if (params.key == keycode_force_on) { if (params.repeat) goto finish; if (params.ex_iskeydown) { remapclass->setEnabled(true); goto refresh; } goto finish; } else if (params.key == keycode_force_off) { if (params.repeat) goto finish; if (params.ex_iskeydown) { remapclass->setEnabled(false); goto refresh; } goto finish; } else if (params.key == keycode_sync_keydownup) { if (params.repeat) goto finish; if (params.ex_iskeydown) { remapclass->setEnabled(true); } else { remapclass->setEnabled(false); } goto refresh; } } return false; refresh: if (remapclass) { bool value_new = remapclass->enabled(); // * send_notification_to_userspace takes a time. // * VK_CONFIG_FORCE_OFF_* might not change remapclass state. // Therefore, we call send_notification_to_userspace only if needed. if (value_old != value_new) { RemapClassManager::refresh(); // Tell remapclass status is changed to userspace. org_pqrs_driver_Karabiner_UserClient_kext::send_notification_to_userspace(BRIDGE_USERCLIENT_NOTIFICATION_TYPE_CONFIG_ENABLED_UPDATED, remapclass->get_configindex()); } } finish: EventOutputQueue::FireModifiers::fire(autogenId); return true; } bool VirtualKey::VK_CONFIG::is_VK_CONFIG_SYNC_KEYDOWNUP(KeyCode keycode) { for (size_t i = 0; i < items_.size(); ++i) { KeyCode keycode_sync_keydownup(items_[i].keycode_sync_keydownup); if (keycode == keycode_sync_keydownup) return true; } return false; } } <commit_msg>remove EventOutputQueue::FireModifiers::fire from VK_CONFIG<commit_after>#include <IOKit/IOLib.h> #include "EventOutputQueue.hpp" #include "FlagStatus.hpp" #include "UserClient_kext.hpp" #include "VK_CONFIG.hpp" namespace org_pqrs_Karabiner { VirtualKey::VK_CONFIG::Vector_Item VirtualKey::VK_CONFIG::items_; void VirtualKey::VK_CONFIG::initialize(void) {} void VirtualKey::VK_CONFIG::terminate(void) { items_.clear(); } void VirtualKey::VK_CONFIG::add_item(RemapClass* remapclass, unsigned int keycode_toggle, unsigned int keycode_force_on, unsigned int keycode_force_off, unsigned int keycode_sync_keydownup) { items_.push_back(Item(remapclass, keycode_toggle, keycode_force_on, keycode_force_off, keycode_sync_keydownup)); } void VirtualKey::VK_CONFIG::clear_items(void) { items_.clear(); } bool VirtualKey::VK_CONFIG::handle(const Params_KeyboardEventCallBack& params, AutogenId autogenId) { RemapClass* remapclass = nullptr; bool value_old = false; for (size_t i = 0; i < items_.size(); ++i) { remapclass = items_[i].remapclass; KeyCode keycode_toggle(items_[i].keycode_toggle); KeyCode keycode_force_on(items_[i].keycode_force_on); KeyCode keycode_force_off(items_[i].keycode_force_off); KeyCode keycode_sync_keydownup(items_[i].keycode_sync_keydownup); if (!remapclass) return false; value_old = remapclass->enabled(); if (params.key == keycode_toggle) { if (params.repeat) goto finish; if (params.ex_iskeydown) { remapclass->toggleEnabled(); goto refresh; } goto finish; } else if (params.key == keycode_force_on) { if (params.repeat) goto finish; if (params.ex_iskeydown) { remapclass->setEnabled(true); goto refresh; } goto finish; } else if (params.key == keycode_force_off) { if (params.repeat) goto finish; if (params.ex_iskeydown) { remapclass->setEnabled(false); goto refresh; } goto finish; } else if (params.key == keycode_sync_keydownup) { if (params.repeat) goto finish; if (params.ex_iskeydown) { remapclass->setEnabled(true); } else { remapclass->setEnabled(false); } goto refresh; } } return false; refresh: if (remapclass) { bool value_new = remapclass->enabled(); // * send_notification_to_userspace takes a time. // * VK_CONFIG_FORCE_OFF_* might not change remapclass state. // Therefore, we call send_notification_to_userspace only if needed. if (value_old != value_new) { RemapClassManager::refresh(); // Tell remapclass status is changed to userspace. org_pqrs_driver_Karabiner_UserClient_kext::send_notification_to_userspace(BRIDGE_USERCLIENT_NOTIFICATION_TYPE_CONFIG_ENABLED_UPDATED, remapclass->get_configindex()); } } finish: return true; } bool VirtualKey::VK_CONFIG::is_VK_CONFIG_SYNC_KEYDOWNUP(KeyCode keycode) { for (size_t i = 0; i < items_.size(); ++i) { KeyCode keycode_sync_keydownup(items_[i].keycode_sync_keydownup); if (keycode == keycode_sync_keydownup) return true; } return false; } } <|endoftext|>
<commit_before>#include "CallBackWrapper.hpp" #include "CommonData.hpp" #include "Config.hpp" #include "FlagStatus.hpp" #include "FromKeyChecker.hpp" #include "KeyCode.hpp" #include "ListHookedConsumer.hpp" #include "ListHookedKeyboard.hpp" #include "ListHookedPointing.hpp" #include "RemapClass.hpp" namespace org_pqrs_KeyRemap4MacBook { void Params_KeyboardEventCallBack::log(bool isCaught, EventType eventType, Flags flags, KeyCode key, KeyboardType keyboardType, bool repeat) { IOLOG_DEBUG("KeyboardEventCallback [%7s]: eventType %2d, flags 0x%08x, key %4d, kbdType %3d, repeat = %d\n", isCaught ? "caught" : "sending", eventType.get(), flags.get(), key.get(), keyboardType.get(), repeat); } void Params_UpdateEventFlagsCallback::log(bool isCaught, Flags flags) { IOLOG_DEBUG("UpdateEventFlagsCallback [%7s]: flags 0x%08x\n", isCaught ? "caught" : "sending", flags.get()); } void Params_KeyboardSpecialEventCallback::log(bool isCaught, EventType eventType, Flags flags, ConsumerKeyCode key, unsigned int flavor, UInt64 guid, bool repeat) { IOLOG_DEBUG("KeyboardSpecialEventCallBack [%7s]: eventType %2d, flags 0x%08x, key %4d, flavor %4d, guid %lld, repeat = %d\n", isCaught ? "caught" : "sending", eventType.get(), flags.get(), key.get(), flavor, guid, repeat); } void Params_RelativePointerEventCallback::log(bool isCaught, Buttons buttons, int dx, int dy) { IOLOG_DEBUG_POINTING("RelativePointerEventCallBack [%7s]: buttons: 0x%08x, dx: %3d, dy: %3d\n", isCaught ? "caught" : "sending", buttons.get(), dx, dy); } void Params_ScrollWheelEventCallback::log(bool isCaught, short deltaAxis1, short deltaAxis2, short deltaAxis3, IOFixed fixedDelta1, IOFixed fixedDelta2, IOFixed fixedDelta3, SInt32 pointDelta1, SInt32 pointDelta2, SInt32 pointDelta3, SInt32 options) { #if __x86_64__ IOLOG_DEBUG_POINTING("ScrollWheelEventCallback [%7s]: deltaAxis(%d,%d,%d), fixedDelta(%d,%d,%d), pointDelta(%d,%d,%d), options: %d\n", isCaught ? "caught" : "sending", deltaAxis1, deltaAxis2, deltaAxis3, fixedDelta1, fixedDelta2, fixedDelta3, pointDelta1, pointDelta2, pointDelta3, options); #else IOLOG_DEBUG_POINTING("ScrollWheelEventCallback [%7s]: deltaAxis(%d,%d,%d), fixedDelta(%ld,%ld,%ld), pointDelta(%ld,%ld,%ld), options: %ld\n", isCaught ? "caught" : "sending", deltaAxis1, deltaAxis2, deltaAxis3, fixedDelta1, fixedDelta2, fixedDelta3, pointDelta1, pointDelta2, pointDelta3, options); #endif } } <commit_msg>change key code in debug log to hex<commit_after>#include "CallBackWrapper.hpp" #include "CommonData.hpp" #include "Config.hpp" #include "FlagStatus.hpp" #include "FromKeyChecker.hpp" #include "KeyCode.hpp" #include "ListHookedConsumer.hpp" #include "ListHookedKeyboard.hpp" #include "ListHookedPointing.hpp" #include "RemapClass.hpp" namespace org_pqrs_KeyRemap4MacBook { void Params_KeyboardEventCallBack::log(bool isCaught, EventType eventType, Flags flags, KeyCode key, KeyboardType keyboardType, bool repeat) { IOLOG_DEBUG("KeyboardEventCallback [%7s]: eventType %2d, flags 0x%08x, key 0x%04x, kbdType %3d, repeat = %d\n", isCaught ? "caught" : "sending", eventType.get(), flags.get(), key.get(), keyboardType.get(), repeat); } void Params_UpdateEventFlagsCallback::log(bool isCaught, Flags flags) { IOLOG_DEBUG("UpdateEventFlagsCallback [%7s]: flags 0x%08x\n", isCaught ? "caught" : "sending", flags.get()); } void Params_KeyboardSpecialEventCallback::log(bool isCaught, EventType eventType, Flags flags, ConsumerKeyCode key, unsigned int flavor, UInt64 guid, bool repeat) { IOLOG_DEBUG("KeyboardSpecialEventCallBack [%7s]: eventType %2d, flags 0x%08x, key 0x%04x, flavor %4d, guid %lld, repeat = %d\n", isCaught ? "caught" : "sending", eventType.get(), flags.get(), key.get(), flavor, guid, repeat); } void Params_RelativePointerEventCallback::log(bool isCaught, Buttons buttons, int dx, int dy) { IOLOG_DEBUG_POINTING("RelativePointerEventCallBack [%7s]: buttons: 0x%08x, dx: %3d, dy: %3d\n", isCaught ? "caught" : "sending", buttons.get(), dx, dy); } void Params_ScrollWheelEventCallback::log(bool isCaught, short deltaAxis1, short deltaAxis2, short deltaAxis3, IOFixed fixedDelta1, IOFixed fixedDelta2, IOFixed fixedDelta3, SInt32 pointDelta1, SInt32 pointDelta2, SInt32 pointDelta3, SInt32 options) { #if __x86_64__ IOLOG_DEBUG_POINTING("ScrollWheelEventCallback [%7s]: deltaAxis(%d,%d,%d), fixedDelta(%d,%d,%d), pointDelta(%d,%d,%d), options: %d\n", isCaught ? "caught" : "sending", deltaAxis1, deltaAxis2, deltaAxis3, fixedDelta1, fixedDelta2, fixedDelta3, pointDelta1, pointDelta2, pointDelta3, options); #else IOLOG_DEBUG_POINTING("ScrollWheelEventCallback [%7s]: deltaAxis(%d,%d,%d), fixedDelta(%ld,%ld,%ld), pointDelta(%ld,%ld,%ld), options: %ld\n", isCaught ? "caught" : "sending", deltaAxis1, deltaAxis2, deltaAxis3, fixedDelta1, fixedDelta2, fixedDelta3, pointDelta1, pointDelta2, pointDelta3, options); #endif } } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin developers // Copyright (c) 2017 Empinel/The Ion Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include "amount.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" /** * Main network */ //! Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, const uint64_t nTime, const uint32_t nNonce, const uint32_t nBits, const int32_t nVersion, const CAmount& genesisReward) { std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << nTime << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].nValue = genesisReward; vout[0].scriptPubKey = genesisOutputScript; CTransaction txNew(1, nTime, vin, vout, 0); CBlock genesis; genesis.nTime = nTime; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.vtx.push_back(txNew); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = genesis.BuildMerkleTree(); return genesis; } static CBlock CreateGenesisBlock(uint64_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { const char* pszTimestamp = "The Guardian: [2nd Feb 2017] Finsbury Park mosque wins apology and damages from Thomson Reuters"; const CScript genesisOutputScript = CScript() << ParseHex("045622582bdfad9366cdff9652d35a562af17ea4e3462d32cd988b32919ba2ff4bc806485be5228185ad3f75445039b6e744819c4a63304277ca8d20c99a6acec8") << OP_CHECKSIG; return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward); } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xc4; pchMessageStart[1] = 0xe1; pchMessageStart[2] = 0xd8; pchMessageStart[3] = 0xec; vAlertPubKey = ParseHex(""); nDefaultPort = 12700; nRPCPort = 12705; nProofOfWorkLimit = uint256S("000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); nProofOfStakeLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); genesis = CreateGenesisBlock(1486045800, 28884498, 0x1e00ffff, 1, (1 * COIN)); hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000004cf5ffbf2e31a9aa07c86298efb01a30b8911b80af7473d1114715084b")); assert(genesis.hashMerkleRoot == uint256("0x7af2e961c5262cb0411edcb7414ab7178133fc06257ceb47d349e4e5e35e2d40")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,103); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,88); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); vSeeds.push_back(CDNSSeedData("seeder.baseserv.com", "main.seeder.baseserv.com")); vSeeds.push_back(CDNSSeedData("seeder.uksafedns.net", "main.seeder.uksafedns.net")); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nPoolMaxTransactions = 3; strDarksendPoolDummyAddress = "iqbMeTpdFfxiNcWHn255T2TneJTrUECCBE"; nLastPOWBlock = 1000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x2f; pchMessageStart[1] = 0xca; pchMessageStart[2] = 0x4d; pchMessageStart[3] = 0x3e; nProofOfWorkLimit = uint256S("000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); nProofOfStakeLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); vAlertPubKey = ParseHex(""); nDefaultPort = 27170; nRPCPort = 27171; strDataDir = "testnet"; genesis = CreateGenesisBlock(1485852000, 5579, 0x1f0fffff, 1, (1 * COIN)); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,97); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>[Alert System] Insert our public key<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin developers // Copyright (c) 2017 Empinel/The Ion Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include "amount.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" /** * Main network */ //! Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, const uint64_t nTime, const uint32_t nNonce, const uint32_t nBits, const int32_t nVersion, const CAmount& genesisReward) { std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << nTime << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].nValue = genesisReward; vout[0].scriptPubKey = genesisOutputScript; CTransaction txNew(1, nTime, vin, vout, 0); CBlock genesis; genesis.nTime = nTime; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.vtx.push_back(txNew); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = genesis.BuildMerkleTree(); return genesis; } static CBlock CreateGenesisBlock(uint64_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { const char* pszTimestamp = "The Guardian: [2nd Feb 2017] Finsbury Park mosque wins apology and damages from Thomson Reuters"; const CScript genesisOutputScript = CScript() << ParseHex("045622582bdfad9366cdff9652d35a562af17ea4e3462d32cd988b32919ba2ff4bc806485be5228185ad3f75445039b6e744819c4a63304277ca8d20c99a6acec8") << OP_CHECKSIG; return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward); } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xc4; pchMessageStart[1] = 0xe1; pchMessageStart[2] = 0xd8; pchMessageStart[3] = 0xec; vAlertPubKey = ParseHex("040fd972dba056779d9f998cba8d5866e47fb875fd8cb9c4d36baf88db738a6ffbc581e0fad7f2f129c7f814d81baeda567a3735aaf0bfbc339f40359d4a52b4bf"); nDefaultPort = 12700; nRPCPort = 12705; nProofOfWorkLimit = uint256S("000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); nProofOfStakeLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); genesis = CreateGenesisBlock(1486045800, 28884498, 0x1e00ffff, 1, (1 * COIN)); hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000004cf5ffbf2e31a9aa07c86298efb01a30b8911b80af7473d1114715084b")); assert(genesis.hashMerkleRoot == uint256("0x7af2e961c5262cb0411edcb7414ab7178133fc06257ceb47d349e4e5e35e2d40")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,103); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,88); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); vSeeds.push_back(CDNSSeedData("seeder.baseserv.com", "main.seeder.baseserv.com")); vSeeds.push_back(CDNSSeedData("seeder.uksafedns.net", "main.seeder.uksafedns.net")); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nPoolMaxTransactions = 3; strDarksendPoolDummyAddress = "iqbMeTpdFfxiNcWHn255T2TneJTrUECCBE"; nLastPOWBlock = 1000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x2f; pchMessageStart[1] = 0xca; pchMessageStart[2] = 0x4d; pchMessageStart[3] = 0x3e; nProofOfWorkLimit = uint256S("000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); nProofOfStakeLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); vAlertPubKey = ParseHex(""); nDefaultPort = 27170; nRPCPort = 27171; strDataDir = "testnet"; genesis = CreateGenesisBlock(1485852000, 5579, 0x1f0fffff, 1, (1 * COIN)); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,97); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>/** * @brief 所有channel文件的模式均为 c + channel<br /> * 使用c的模式是为了简单、结构清晰并且避免异常<br /> * 附带c++的部分是为了避免命名空间污染并且c++的跨平台适配更加简单 */ #include "lock/atomic_int_type.h" #include <assert.h> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <map> #include <stdint.h> #include "detail/libatbus_channel_export.h" #include "detail/libatbus_error.h" // spin_lock and lock_holder will include Windows.h, which should be included after Winsock2.h #include "common/string_oprs.h" #include "lock/lock_holder.h" #include "lock/spin_lock.h" #ifdef WIN32 #include <Windows.h> #ifdef _MSC_VER #include <atlconv.h> #endif #ifdef UNICODE #define ATBUS_VC_TEXT(x) A2W(x) #else #define ATBUS_VC_TEXT(x) x #endif #else #include <unistd.h> #endif #ifdef ATBUS_CHANNEL_SHM namespace atbus { namespace channel { struct shm_channel {}; struct shm_conf {}; typedef union { shm_channel *shm; mem_channel *mem; } shm_channel_switcher; typedef union { const shm_conf *shm; const mem_conf *mem; } shm_conf_cswitcher; #ifdef WIN32 typedef struct { HANDLE handle; LPCTSTR buffer; size_t size; size_t reference_count; } shm_mapped_record_type; #else typedef struct { int shm_id; void *buffer; size_t size; size_t reference_count; } shm_mapped_record_type; #endif static std::map<key_t, shm_mapped_record_type> shm_mapped_records; static ::util::lock::spin_lock shm_mapped_records_lock; static int shm_close_buffer(key_t shm_key) { ::util::lock::lock_holder< ::util::lock::spin_lock> lock_guard(shm_mapped_records_lock); std::map<key_t, shm_mapped_record_type>::iterator iter = shm_mapped_records.find(shm_key); if (shm_mapped_records.end() == iter) return EN_ATBUS_ERR_SHM_NOT_FOUND; assert(iter->second.reference_count > 0); if (iter->second.reference_count > 1) { --iter->second.reference_count; return EN_ATBUS_ERR_SUCCESS; } else { iter->second.reference_count = 0; } shm_mapped_record_type record = iter->second; shm_mapped_records.erase(iter); #ifdef WIN32 UnmapViewOfFile(record.buffer); CloseHandle(record.handle); #else int res = shmdt(record.buffer); if (-1 == res) return EN_ATBUS_ERR_SHM_GET_FAILED; #endif return EN_ATBUS_ERR_SUCCESS; } static int shm_open_buffer(key_t shm_key, size_t len, void **data, size_t *real_size, bool create) { ::util::lock::lock_holder< ::util::lock::spin_lock> lock_guard(shm_mapped_records_lock); shm_mapped_record_type shm_record; // 已经映射则直接返回 { std::map<key_t, shm_mapped_record_type>::iterator iter = shm_mapped_records.find(shm_key); if (shm_mapped_records.end() != iter) { if (data) *data = (void *)iter->second.buffer; if (real_size) *real_size = iter->second.size; ++iter->second.reference_count; return EN_ATBUS_ERR_SUCCESS; } } #ifdef _WIN32 #ifdef _MSC_VER USES_CONVERSION; #endif memset(&shm_record, 0, sizeof(shm_record)); SYSTEM_INFO si; ::GetSystemInfo(&si); // size_t page_size = static_cast<std::size_t>(si.dwPageSize); char shm_file_name[64] = {0}; // Use Global\\ prefix requires the SeCreateGlobalPrivilege privilege, so we do not use it UTIL_STRFUNC_SNPRINTF(shm_file_name, sizeof(shm_file_name), "Global\\libatbus_win_shm_%ld.bus", shm_key); // 首先尝试直接打开 shm_record.handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, // read/write access FALSE, // do not inherit the name ATBUS_VC_TEXT(shm_file_name) // name of mapping object ); if (NULL != shm_record.handle) { shm_record.buffer = (LPTSTR)MapViewOfFile(shm_record.handle, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, len); if (NULL == shm_record.buffer) { CloseHandle(shm_record.handle); return EN_ATBUS_ERR_SHM_GET_FAILED; } if (data) *data = (void *)shm_record.buffer; if (real_size) *real_size = len; shm_record.size = len; shm_record.reference_count = 1; shm_mapped_records[shm_key] = shm_record; return EN_ATBUS_ERR_SUCCESS; } // 如果允许创建则创建 if (!create) return EN_ATBUS_ERR_SHM_GET_FAILED; shm_record.handle = CreateFileMapping(INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) static_cast<DWORD>(len), // maximum object size (low-order DWORD) ATBUS_VC_TEXT(shm_file_name) // name of mapping object ); if (NULL == shm_record.handle) return EN_ATBUS_ERR_SHM_GET_FAILED; shm_record.buffer = (LPTSTR)MapViewOfFile(shm_record.handle, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, len); if (NULL == shm_record.buffer) return EN_ATBUS_ERR_SHM_GET_FAILED; shm_record.size = len; shm_record.reference_count = 1; shm_mapped_records[shm_key] = shm_record; if (data) *data = (void *)shm_record.buffer; if (real_size) *real_size = len; #else // len 长度对齐到分页大小 size_t page_size = ::sysconf(_SC_PAGESIZE); len = (len + page_size - 1) & (~(page_size - 1)); int shmflag = 0666; if (create) shmflag |= IPC_CREAT; #ifdef __linux__ // linux下阻止从交换分区分配物理页 shmflag |= SHM_NORESERVE; // 临时关闭大页表功能,等后续增加了以下判定之后再看情况加回来 // 使用大页表要先判定 /proc/meminfo 内的一些字段内容,再配置大页表 // -- Hugepagesize: 大页表的分页大小,如果ATBUS_MACRO_HUGETLB_SIZE小于这个值,要对齐到这个值 // -- HugePages_Total: 大页表总大小 // -- HugePages_Free: 大页表可用大小,如果可用值小于需要分配的空间,也不能用大页表 //#ifdef ATBUS_MACRO_HUGETLB_SIZE // // 如果大于4倍的大页表,则对齐到大页表并使用大页表 // if (len > (4 * ATBUS_MACRO_HUGETLB_SIZE)) { // len = (len + (ATBUS_MACRO_HUGETLB_SIZE)-1) & (~((ATBUS_MACRO_HUGETLB_SIZE)-1)); // shmflag |= SHM_HUGETLB; // } //#endif #endif shm_record.shm_id = shmget(shm_key, len, shmflag); if (-1 == shm_record.shm_id) return EN_ATBUS_ERR_SHM_GET_FAILED; // 获取实际长度 { struct shmid_ds shm_info; if (shmctl(shm_record.shm_id, IPC_STAT, &shm_info)) return EN_ATBUS_ERR_SHM_GET_FAILED; shm_record.size = shm_info.shm_segsz; } // 获取地址 shm_record.buffer = shmat(shm_record.shm_id, NULL, 0); shm_record.reference_count = 1; shm_mapped_records[shm_key] = shm_record; if (data) *data = shm_record.buffer; if (real_size) { *real_size = shm_record.size; } #endif return EN_ATBUS_ERR_SUCCESS; } int shm_configure_set_write_timeout(shm_channel *channel, uint64_t ms) { shm_channel_switcher switcher; switcher.shm = channel; return mem_configure_set_write_timeout(switcher.mem, ms); } uint64_t shm_configure_get_write_timeout(shm_channel *channel) { shm_channel_switcher switcher; switcher.shm = channel; return mem_configure_get_write_timeout(switcher.mem); } int shm_configure_set_write_retry_times(shm_channel *channel, size_t times) { shm_channel_switcher switcher; switcher.shm = channel; return mem_configure_set_write_retry_times(switcher.mem, times); } size_t shm_configure_get_write_retry_times(shm_channel *channel) { shm_channel_switcher switcher; switcher.shm = channel; return mem_configure_get_write_retry_times(switcher.mem); } int shm_attach(key_t shm_key, size_t len, shm_channel **channel, const shm_conf *conf) { shm_channel_switcher channel_s; shm_conf_cswitcher conf_s; conf_s.shm = conf; size_t real_size; void *buffer; int ret = shm_open_buffer(shm_key, len, &buffer, &real_size, false); if (ret < 0) return ret; ret = mem_attach(buffer, real_size, &channel_s.mem, conf_s.mem); if (ret < 0) { shm_close_buffer(shm_key); return ret; } if (channel) *channel = channel_s.shm; return ret; } int shm_init(key_t shm_key, size_t len, shm_channel **channel, const shm_conf *conf) { shm_channel_switcher channel_s; shm_conf_cswitcher conf_s; conf_s.shm = conf; size_t real_size; void *buffer; int ret = shm_open_buffer(shm_key, len, &buffer, &real_size, true); if (ret < 0) return ret; ret = mem_init(buffer, real_size, &channel_s.mem, conf_s.mem); if (ret < 0) { shm_close_buffer(shm_key); return ret; } if (channel) *channel = channel_s.shm; return ret; } int shm_close(key_t shm_key) { return shm_close_buffer(shm_key); } int shm_send(shm_channel *channel, const void *buf, size_t len) { shm_channel_switcher switcher; switcher.shm = channel; return mem_send(switcher.mem, buf, len); } int shm_recv(shm_channel *channel, void *buf, size_t len, size_t *recv_size) { shm_channel_switcher switcher; switcher.shm = channel; return mem_recv(switcher.mem, buf, len, recv_size); } std::pair<size_t, size_t> shm_last_action() { return mem_last_action(); } void shm_show_channel(shm_channel *channel, std::ostream &out, bool need_node_status, size_t need_node_data) { shm_channel_switcher switcher; switcher.shm = channel; mem_show_channel(switcher.mem, out, need_node_status, need_node_data); } void shm_stats_get_error(shm_channel *channel, shm_stats_block_error &out) { shm_channel_switcher switcher; switcher.shm = channel; mem_stats_get_error(switcher.mem, out); } } // namespace channel } // namespace atbus #endif <commit_msg>fix include order in shm<commit_after>/** * @brief 所有channel文件的模式均为 c + channel<br /> * 使用c的模式是为了简单、结构清晰并且避免异常<br /> * 附带c++的部分是为了避免命名空间污染并且c++的跨平台适配更加简单 */ #include <assert.h> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <map> #include <stdint.h> #include "detail/libatbus_adapter_libuv.h" #include "lock/atomic_int_type.h" #include "lock/spin_lock.h" #include "detail/libatbus_channel_export.h" #include "detail/libatbus_error.h" // spin_lock and lock_holder will include Windows.h, which should be included after Winsock2.h #include "common/string_oprs.h" #include "lock/lock_holder.h" #include "lock/spin_lock.h" #ifdef WIN32 #include <Windows.h> #ifdef _MSC_VER #include <atlconv.h> #endif #ifdef UNICODE #define ATBUS_VC_TEXT(x) A2W(x) #else #define ATBUS_VC_TEXT(x) x #endif #else #include <unistd.h> #endif #ifdef ATBUS_CHANNEL_SHM namespace atbus { namespace channel { struct shm_channel {}; struct shm_conf {}; typedef union { shm_channel *shm; mem_channel *mem; } shm_channel_switcher; typedef union { const shm_conf *shm; const mem_conf *mem; } shm_conf_cswitcher; #ifdef WIN32 typedef struct { HANDLE handle; LPCTSTR buffer; size_t size; size_t reference_count; } shm_mapped_record_type; #else typedef struct { int shm_id; void *buffer; size_t size; size_t reference_count; } shm_mapped_record_type; #endif static std::map<key_t, shm_mapped_record_type> shm_mapped_records; static ::util::lock::spin_lock shm_mapped_records_lock; static int shm_close_buffer(key_t shm_key) { ::util::lock::lock_holder< ::util::lock::spin_lock> lock_guard(shm_mapped_records_lock); std::map<key_t, shm_mapped_record_type>::iterator iter = shm_mapped_records.find(shm_key); if (shm_mapped_records.end() == iter) return EN_ATBUS_ERR_SHM_NOT_FOUND; assert(iter->second.reference_count > 0); if (iter->second.reference_count > 1) { --iter->second.reference_count; return EN_ATBUS_ERR_SUCCESS; } else { iter->second.reference_count = 0; } shm_mapped_record_type record = iter->second; shm_mapped_records.erase(iter); #ifdef WIN32 UnmapViewOfFile(record.buffer); CloseHandle(record.handle); #else int res = shmdt(record.buffer); if (-1 == res) return EN_ATBUS_ERR_SHM_GET_FAILED; #endif return EN_ATBUS_ERR_SUCCESS; } static int shm_open_buffer(key_t shm_key, size_t len, void **data, size_t *real_size, bool create) { ::util::lock::lock_holder< ::util::lock::spin_lock> lock_guard(shm_mapped_records_lock); shm_mapped_record_type shm_record; // 已经映射则直接返回 { std::map<key_t, shm_mapped_record_type>::iterator iter = shm_mapped_records.find(shm_key); if (shm_mapped_records.end() != iter) { if (data) *data = (void *)iter->second.buffer; if (real_size) *real_size = iter->second.size; ++iter->second.reference_count; return EN_ATBUS_ERR_SUCCESS; } } #ifdef _WIN32 #ifdef _MSC_VER USES_CONVERSION; #endif memset(&shm_record, 0, sizeof(shm_record)); SYSTEM_INFO si; ::GetSystemInfo(&si); // size_t page_size = static_cast<std::size_t>(si.dwPageSize); char shm_file_name[64] = {0}; // Use Global\\ prefix requires the SeCreateGlobalPrivilege privilege, so we do not use it UTIL_STRFUNC_SNPRINTF(shm_file_name, sizeof(shm_file_name), "Global\\libatbus_win_shm_%ld.bus", shm_key); // 首先尝试直接打开 shm_record.handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, // read/write access FALSE, // do not inherit the name ATBUS_VC_TEXT(shm_file_name) // name of mapping object ); if (NULL != shm_record.handle) { shm_record.buffer = (LPTSTR)MapViewOfFile(shm_record.handle, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, len); if (NULL == shm_record.buffer) { CloseHandle(shm_record.handle); return EN_ATBUS_ERR_SHM_GET_FAILED; } if (data) *data = (void *)shm_record.buffer; if (real_size) *real_size = len; shm_record.size = len; shm_record.reference_count = 1; shm_mapped_records[shm_key] = shm_record; return EN_ATBUS_ERR_SUCCESS; } // 如果允许创建则创建 if (!create) return EN_ATBUS_ERR_SHM_GET_FAILED; shm_record.handle = CreateFileMapping(INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) static_cast<DWORD>(len), // maximum object size (low-order DWORD) ATBUS_VC_TEXT(shm_file_name) // name of mapping object ); if (NULL == shm_record.handle) return EN_ATBUS_ERR_SHM_GET_FAILED; shm_record.buffer = (LPTSTR)MapViewOfFile(shm_record.handle, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, len); if (NULL == shm_record.buffer) return EN_ATBUS_ERR_SHM_GET_FAILED; shm_record.size = len; shm_record.reference_count = 1; shm_mapped_records[shm_key] = shm_record; if (data) *data = (void *)shm_record.buffer; if (real_size) *real_size = len; #else // len 长度对齐到分页大小 size_t page_size = ::sysconf(_SC_PAGESIZE); len = (len + page_size - 1) & (~(page_size - 1)); int shmflag = 0666; if (create) shmflag |= IPC_CREAT; #ifdef __linux__ // linux下阻止从交换分区分配物理页 shmflag |= SHM_NORESERVE; // 临时关闭大页表功能,等后续增加了以下判定之后再看情况加回来 // 使用大页表要先判定 /proc/meminfo 内的一些字段内容,再配置大页表 // -- Hugepagesize: 大页表的分页大小,如果ATBUS_MACRO_HUGETLB_SIZE小于这个值,要对齐到这个值 // -- HugePages_Total: 大页表总大小 // -- HugePages_Free: 大页表可用大小,如果可用值小于需要分配的空间,也不能用大页表 //#ifdef ATBUS_MACRO_HUGETLB_SIZE // // 如果大于4倍的大页表,则对齐到大页表并使用大页表 // if (len > (4 * ATBUS_MACRO_HUGETLB_SIZE)) { // len = (len + (ATBUS_MACRO_HUGETLB_SIZE)-1) & (~((ATBUS_MACRO_HUGETLB_SIZE)-1)); // shmflag |= SHM_HUGETLB; // } //#endif #endif shm_record.shm_id = shmget(shm_key, len, shmflag); if (-1 == shm_record.shm_id) return EN_ATBUS_ERR_SHM_GET_FAILED; // 获取实际长度 { struct shmid_ds shm_info; if (shmctl(shm_record.shm_id, IPC_STAT, &shm_info)) return EN_ATBUS_ERR_SHM_GET_FAILED; shm_record.size = shm_info.shm_segsz; } // 获取地址 shm_record.buffer = shmat(shm_record.shm_id, NULL, 0); shm_record.reference_count = 1; shm_mapped_records[shm_key] = shm_record; if (data) *data = shm_record.buffer; if (real_size) { *real_size = shm_record.size; } #endif return EN_ATBUS_ERR_SUCCESS; } int shm_configure_set_write_timeout(shm_channel *channel, uint64_t ms) { shm_channel_switcher switcher; switcher.shm = channel; return mem_configure_set_write_timeout(switcher.mem, ms); } uint64_t shm_configure_get_write_timeout(shm_channel *channel) { shm_channel_switcher switcher; switcher.shm = channel; return mem_configure_get_write_timeout(switcher.mem); } int shm_configure_set_write_retry_times(shm_channel *channel, size_t times) { shm_channel_switcher switcher; switcher.shm = channel; return mem_configure_set_write_retry_times(switcher.mem, times); } size_t shm_configure_get_write_retry_times(shm_channel *channel) { shm_channel_switcher switcher; switcher.shm = channel; return mem_configure_get_write_retry_times(switcher.mem); } int shm_attach(key_t shm_key, size_t len, shm_channel **channel, const shm_conf *conf) { shm_channel_switcher channel_s; shm_conf_cswitcher conf_s; conf_s.shm = conf; size_t real_size; void *buffer; int ret = shm_open_buffer(shm_key, len, &buffer, &real_size, false); if (ret < 0) return ret; ret = mem_attach(buffer, real_size, &channel_s.mem, conf_s.mem); if (ret < 0) { shm_close_buffer(shm_key); return ret; } if (channel) *channel = channel_s.shm; return ret; } int shm_init(key_t shm_key, size_t len, shm_channel **channel, const shm_conf *conf) { shm_channel_switcher channel_s; shm_conf_cswitcher conf_s; conf_s.shm = conf; size_t real_size; void *buffer; int ret = shm_open_buffer(shm_key, len, &buffer, &real_size, true); if (ret < 0) return ret; ret = mem_init(buffer, real_size, &channel_s.mem, conf_s.mem); if (ret < 0) { shm_close_buffer(shm_key); return ret; } if (channel) *channel = channel_s.shm; return ret; } int shm_close(key_t shm_key) { return shm_close_buffer(shm_key); } int shm_send(shm_channel *channel, const void *buf, size_t len) { shm_channel_switcher switcher; switcher.shm = channel; return mem_send(switcher.mem, buf, len); } int shm_recv(shm_channel *channel, void *buf, size_t len, size_t *recv_size) { shm_channel_switcher switcher; switcher.shm = channel; return mem_recv(switcher.mem, buf, len, recv_size); } std::pair<size_t, size_t> shm_last_action() { return mem_last_action(); } void shm_show_channel(shm_channel *channel, std::ostream &out, bool need_node_status, size_t need_node_data) { shm_channel_switcher switcher; switcher.shm = channel; mem_show_channel(switcher.mem, out, need_node_status, need_node_data); } void shm_stats_get_error(shm_channel *channel, shm_stats_block_error &out) { shm_channel_switcher switcher; switcher.shm = channel; mem_stats_get_error(switcher.mem, out); } } // namespace channel } // namespace atbus #endif <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 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 <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "txdb.h" #include "main.h" #include "uint256.h" static const int nCheckpointSpan = 500; namespace Checkpoints { // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x0000046309984501e5e724498cddb4aff41a126927355f64b44f1b8bba4f447e") ) // Params().HashGenesisBlock()) ( 6900, uint256("0x00000000007ab23f193e14dce62f4e7713b15e9fc7555ee82188d126abbe2c2f") ) ( 69000, uint256("0x2145ba590371077d372550850c81a4db38e8bc026e500cfe0a20e8859485dcc3") ) ( 88888, uint256("0xbe44edfa112d8cc3fcabd873a2fb4f606310f57ce1c7f7630db790ed0dbd325e") ) ( 111111, uint256("0xf3ada8d6d5aea41dad9d8a6146c2f5066b796e33d465c58e0bc1cdfd81d656a3") ) ( 200000, uint256("0x40ffcce0ac611aab08c7acd41c66201e1584ba36d017657e224a77901282bb7d") ) ( 240000, uint256("0x1db5755d5947747cbfb5f6edd98a8ff0bf5f4c8d42a5958c96f1682763f3827f") ) ( 280000, uint256("0xf8f9b5bb15d44af850e566e112679f13673d2d32ba65ef78549161bcadfc388b") ) ( 300000, uint256("0xbd1178c903fbf5a2ed6c7e7207f82a828f392d8d80499d9daa2ad2311817d075") ) ( 360000, uint256("0xfad01c88115aeacf5871459cc76325b6766214334c98d9b53da48dc6605b725c") ) ( 400000, uint256("0xc0bf944bac3cb24974578c5c17479cb05ac41d12305b51b324eadcb2855b1a14") ) ( 471000, uint256("0x8ea2035f9a8bd9edaa9f39897f9e6e7492736a2815ec1507ddcb40a963c93293") ) ( 500000, uint256("0x2d2139f39759be2e70b1ea42211ccf07c2a20787f81485b2cc4544166dd57bef") ) ( 560000, uint256("0x9bab9b7588d4a2929ec36a27b5c7fccf1ae9063b408d91f92fc288a1c1dea751") ) ( 720000, uint256("0xd379d5bba81966d4fe3d7d1065a2e8be2380582d12a92101e4d648d14b32055f") ) ( 798000, uint256("0xb84acefdd7acd8b63e78fab121ed57aa5428e5f634c6f9c09d7cfe79a4ff19fc") ) ( 900000, uint256("0x1ee5e72f281b50f95ac5452f9f2b1fca34595b99b8815a85a7ab97e964919860") ) ( 972000, uint256("0xd302a7015edd96078ba02a5d4b51e7377428386e3e911a76eb0dd5bddaf0697a") ) ( 1117300, uint256("0x190e3b4224643d868b451f2b8e13a2a48ac605dc776e661920fc1ab48e27a460") ) ( 1230333, uint256("0xeba330f3efa967bef8f9e6530577a3e030b2e442cc817dce5460eb1beb5e1b20") ) ( 1330333, uint256("0xf81d9e7013b95ea3be7d41674029dd6fe2c8f4abf6ecefb98c4a80ad01eeb5bc") ) ( 1904444, uint256("0x1dbe1b873c8fddf05aa5055274b5b15e22161fdc3bd8b7dc7819f94ca58bc5ae") ) ( 2017171, uint256("0x8c46a987d8b7956d8d30ee0e9f21700923187053074c677c1f75bd99abda90fa") ) ( 2308300, uint256("0x7125680b2ed17924a3a77915334e44b119d0c32c215c6f3be8700a3fc08e2deb") ) ( 2370700, uint256("0x7f2bccc681e40ca2aa44a9f83fa8301676cc66a690e7a346b486353dcdf6176a") ) ( 2494200, uint256("0x1dd3dca52ec2f3aa80492e48926eec03edb73897269b69c6eaabee3452ddce97") ) ( 2530000, uint256("0x13fdac99dee847cab93c16e56cb3ce432c50b0b89988b89e160d7bb7d6666da2") ) ( 2672672, uint256("0xe8523e5c85baa3266f4b48e142870f134eaf1002bdbf303df62e6293fbb4756b") ) ; // TestNet has no checkpoints MapCheckpoints mapCheckpointsTestnet; bool CheckHardened(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); if (checkpoints.empty()) return 0; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } CBlockThinIndex* GetLastCheckpoint(const std::map<uint256, CBlockThinIndex*>& mapBlockThinIndex) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockThinIndex*>::const_iterator t = mapBlockThinIndex.find(hash); if (t != mapBlockThinIndex.end()) return t->second; } return NULL; } // Automatically select a suitable sync-checkpoint const CBlockIndex* AutoSelectSyncCheckpoint() { const CBlockIndex *pindex = pindexBest; // Search backward for a block within max span and maturity window while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight) pindex = pindex->pprev; return pindex; } // Automatically select a suitable sync-checkpoint - Thin mode const CBlockThinIndex* AutoSelectSyncThinCheckpoint() { const CBlockThinIndex *pindex = pindexBestHeader; // Search backward for a block within max span and maturity window while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight) pindex = pindex->pprev; return pindex; } // Check against synchronized checkpoint bool CheckSync(int nHeight) { if(nNodeMode == NT_FULL) { const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint(); if (nHeight <= pindexSync->nHeight) return false; } else { const CBlockThinIndex *pindexSync = AutoSelectSyncThinCheckpoint(); if (nHeight <= pindexSync->nHeight) return false; } return true; } } <commit_msg>+ ccheckpointdata + verifprog<commit_after>// Copyright (c) 2009-2012 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 <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "txdb.h" #include "main.h" #include "uint256.h" static const int nCheckpointSpan = 500; namespace Checkpoints { // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // typedef std::map<int, uint256> MapCheckpoints; // // How many times we expect transactions after the last checkpoint to // be slower. This number is conservative. On multi-core CPUs with // parallel signature checking enabled, this number is way too high. // We prefer a progressbar that's faster at the end than the other // way around, though. static const double fSigcheckVerificationFactor = 15.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64_t nTimeLastCheckpoint; int64_t nTransactionsLastCheckpoint; double fTransactionsPerDay; }; MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x0000046309984501e5e724498cddb4aff41a126927355f64b44f1b8bba4f447e") ) // Params().HashGenesisBlock()) ( 6900, uint256("0x00000000007ab23f193e14dce62f4e7713b15e9fc7555ee82188d126abbe2c2f") ) ( 69000, uint256("0x2145ba590371077d372550850c81a4db38e8bc026e500cfe0a20e8859485dcc3") ) ( 88888, uint256("0xbe44edfa112d8cc3fcabd873a2fb4f606310f57ce1c7f7630db790ed0dbd325e") ) ( 111111, uint256("0xf3ada8d6d5aea41dad9d8a6146c2f5066b796e33d465c58e0bc1cdfd81d656a3") ) ( 200000, uint256("0x40ffcce0ac611aab08c7acd41c66201e1584ba36d017657e224a77901282bb7d") ) ( 240000, uint256("0x1db5755d5947747cbfb5f6edd98a8ff0bf5f4c8d42a5958c96f1682763f3827f") ) ( 280000, uint256("0xf8f9b5bb15d44af850e566e112679f13673d2d32ba65ef78549161bcadfc388b") ) ( 300000, uint256("0xbd1178c903fbf5a2ed6c7e7207f82a828f392d8d80499d9daa2ad2311817d075") ) ( 360000, uint256("0xfad01c88115aeacf5871459cc76325b6766214334c98d9b53da48dc6605b725c") ) ( 400000, uint256("0xc0bf944bac3cb24974578c5c17479cb05ac41d12305b51b324eadcb2855b1a14") ) ( 471000, uint256("0x8ea2035f9a8bd9edaa9f39897f9e6e7492736a2815ec1507ddcb40a963c93293") ) ( 500000, uint256("0x2d2139f39759be2e70b1ea42211ccf07c2a20787f81485b2cc4544166dd57bef") ) ( 560000, uint256("0x9bab9b7588d4a2929ec36a27b5c7fccf1ae9063b408d91f92fc288a1c1dea751") ) ( 720000, uint256("0xd379d5bba81966d4fe3d7d1065a2e8be2380582d12a92101e4d648d14b32055f") ) ( 798000, uint256("0xb84acefdd7acd8b63e78fab121ed57aa5428e5f634c6f9c09d7cfe79a4ff19fc") ) ( 900000, uint256("0x1ee5e72f281b50f95ac5452f9f2b1fca34595b99b8815a85a7ab97e964919860") ) ( 972000, uint256("0xd302a7015edd96078ba02a5d4b51e7377428386e3e911a76eb0dd5bddaf0697a") ) ( 1117300, uint256("0x190e3b4224643d868b451f2b8e13a2a48ac605dc776e661920fc1ab48e27a460") ) ( 1230333, uint256("0xeba330f3efa967bef8f9e6530577a3e030b2e442cc817dce5460eb1beb5e1b20") ) ( 1330333, uint256("0xf81d9e7013b95ea3be7d41674029dd6fe2c8f4abf6ecefb98c4a80ad01eeb5bc") ) ( 1904444, uint256("0x1dbe1b873c8fddf05aa5055274b5b15e22161fdc3bd8b7dc7819f94ca58bc5ae") ) ( 2017171, uint256("0x8c46a987d8b7956d8d30ee0e9f21700923187053074c677c1f75bd99abda90fa") ) ( 2308300, uint256("0x7125680b2ed17924a3a77915334e44b119d0c32c215c6f3be8700a3fc08e2deb") ) ( 2370700, uint256("0x7f2bccc681e40ca2aa44a9f83fa8301676cc66a690e7a346b486353dcdf6176a") ) ( 2494200, uint256("0x1dd3dca52ec2f3aa80492e48926eec03edb73897269b69c6eaabee3452ddce97") ) ( 2530000, uint256("0x13fdac99dee847cab93c16e56cb3ce432c50b0b89988b89e160d7bb7d6666da2") ) ( 2672672, uint256("0xe8523e5c85baa3266f4b48e142870f134eaf1002bdbf303df62e6293fbb4756b") ) ; static const CCheckpointData data = { &mapCheckpoints, 1604199328, // * UNIX timestamp of last checkpoint block 11011160, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 5000.0 // * estimated number of transactions per day after checkpoint }; // TestNet has no checkpoints MapCheckpoints mapCheckpointsTestnet; bool CheckHardened(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); if (checkpoints.empty()) return 0; return checkpoints.rbegin()->first; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { //int64_t nNow = time(NULL); //int nEstimBlocks = GetNumBlocksOfPeers(); //double nRemainingBlocks = nEstimBlocks - pindex->nHeight; if (pindex->nHeight < 0) { return 0.0; } else if (pindex->nHeight > GetNumBlocksOfPeers()) { return 0.99996298; } else { return pindex->nHeight / (GetNumBlocksOfPeers() * 1.0); } } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } CBlockThinIndex* GetLastCheckpoint(const std::map<uint256, CBlockThinIndex*>& mapBlockThinIndex) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockThinIndex*>::const_iterator t = mapBlockThinIndex.find(hash); if (t != mapBlockThinIndex.end()) return t->second; } return NULL; } // Automatically select a suitable sync-checkpoint const CBlockIndex* AutoSelectSyncCheckpoint() { const CBlockIndex *pindex = pindexBest; // Search backward for a block within max span and maturity window while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight) pindex = pindex->pprev; return pindex; } // Automatically select a suitable sync-checkpoint - Thin mode const CBlockThinIndex* AutoSelectSyncThinCheckpoint() { const CBlockThinIndex *pindex = pindexBestHeader; // Search backward for a block within max span and maturity window while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight) pindex = pindex->pprev; return pindex; } // Check against synchronized checkpoint bool CheckSync(int nHeight) { if(nNodeMode == NT_FULL) { const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint(); if (nHeight <= pindexSync->nHeight) return false; } else { const CBlockThinIndex *pindexSync = AutoSelectSyncThinCheckpoint(); if (nHeight <= pindexSync->nHeight) return false; } return true; } } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: AliTRDCalDCS.cxx 18952 2007-06-08 11:36:12Z cblume $ */ /////////////////////////////////////////////////////////////////////////////// // // // TRD calibration class for TRD DCS parameters // // // /////////////////////////////////////////////////////////////////////////////// #include "AliTRDCalDCS.h" #include "AliTRDCalDCSFEE.h" #include "AliTRDCalDCSGTU.h" ClassImp(AliTRDCalDCS) //_____________________________________________________________________________ AliTRDCalDCS::AliTRDCalDCS() :TNamed() ,fGNumberOfTimeBins(-1) ,fGConfigTag(-1) ,fGSingleHitThres(-1) ,fGThreePadClustThres(-1) ,fGSelNoZS(-1) ,fGTCFilterWeight(-1) ,fGTCFilterShortDecPar(-1) ,fGTCFilterLongDecPar(-1) ,fGFastStatNoise(-1) ,fGConfigVersion(0) ,fGConfigName(0) ,fGFilterType(0) ,fGReadoutParam(0) ,fGTestPattern(0) ,fGTrackletMode(0) ,fGTrackletDef(0) ,fGTriggerSetup(0) ,fGAddOptions(0) ,fFEEArr(new TObjArray(540)) ,fPTRArr(new TObjArray(6)) ,fGTUObj(new AliTRDCalDCSGTU()) ,fRunType("") ,fStartTime(0) ,fEndTime(0) { // // AliTRDCalDCS default constructor // } //_____________________________________________________________________________ AliTRDCalDCS::AliTRDCalDCS(const Text_t *name, const Text_t *title) :TNamed(name,title) ,fGNumberOfTimeBins(-1) ,fGConfigTag(-1) ,fGSingleHitThres(-1) ,fGThreePadClustThres(-1) ,fGSelNoZS(-1) ,fGTCFilterWeight(-1) ,fGTCFilterShortDecPar(-1) ,fGTCFilterLongDecPar(-1) ,fGFastStatNoise(-1) ,fGConfigVersion(0) ,fGConfigName(0) ,fGFilterType(0) ,fGReadoutParam(0) ,fGTestPattern(0) ,fGTrackletMode(0) ,fGTrackletDef(0) ,fGTriggerSetup(0) ,fGAddOptions(0) ,fFEEArr(new TObjArray(540)) ,fPTRArr(new TObjArray(6)) ,fGTUObj(new AliTRDCalDCSGTU()) ,fRunType("") ,fStartTime(0) ,fEndTime(0) { // // AliTRDCalDCS constructor // } //_____________________________________________________________________________ AliTRDCalDCS::AliTRDCalDCS(const AliTRDCalDCS &cd) :TNamed(cd) ,fGNumberOfTimeBins(-1) ,fGConfigTag(-1) ,fGSingleHitThres(-1) ,fGThreePadClustThres(-1) ,fGSelNoZS(-1) ,fGTCFilterWeight(-1) ,fGTCFilterShortDecPar(-1) ,fGTCFilterLongDecPar(-1) ,fGFastStatNoise(-1) ,fGConfigVersion(0) ,fGConfigName(0) ,fGFilterType(0) ,fGReadoutParam(0) ,fGTestPattern(0) ,fGTrackletMode(0) ,fGTrackletDef(0) ,fGTriggerSetup(0) ,fGAddOptions(0) ,fFEEArr(new TObjArray(540)) ,fPTRArr(new TObjArray(6)) ,fGTUObj(new AliTRDCalDCSGTU()) ,fRunType("") ,fStartTime(0) ,fEndTime(0) { // // AliTRDCalDCS copy constructor // } //_____________________________________________________________________________ AliTRDCalDCS &AliTRDCalDCS::operator=(const AliTRDCalDCS &cd) { // // Assignment operator // if (&cd == this) return *this; new (this) AliTRDCalDCS(cd); return *this; } //_____________________________________________________________________________ void AliTRDCalDCS::EvaluateGlobalParameters() { // // Do an evaluation of all global parameters // for(Int_t i=0; i<540; i++) { AliTRDCalDCSFEE *iDCSFEEObj; iDCSFEEObj = GetCalDCSFEEObj(i); if(iDCSFEEObj != NULL) { if(iDCSFEEObj->GetStatusBit() == 0) { // first, set the parameters of the first good ROC as global fGNumberOfTimeBins = iDCSFEEObj->GetNumberOfTimeBins(); fGConfigTag = iDCSFEEObj->GetConfigTag(); fGSingleHitThres = iDCSFEEObj->GetSingleHitThres(); fGThreePadClustThres = iDCSFEEObj->GetThreePadClustThres(); fGSelNoZS = iDCSFEEObj->GetSelectiveNoZS(); fGTCFilterWeight = iDCSFEEObj->GetTCFilterWeight(); fGTCFilterShortDecPar = iDCSFEEObj->GetTCFilterShortDecPar(); fGTCFilterLongDecPar = iDCSFEEObj->GetTCFilterLongDecPar(); fGFastStatNoise = iDCSFEEObj->GetFastStatNoise(); fGConfigVersion = iDCSFEEObj->GetConfigVersion(); fGConfigName = iDCSFEEObj->GetConfigName(); fGFilterType = iDCSFEEObj->GetFilterType(); fGReadoutParam = iDCSFEEObj->GetReadoutParam(); fGTestPattern = iDCSFEEObj->GetTestPattern(); fGTrackletMode = iDCSFEEObj->GetTrackletMode(); fGTrackletDef = iDCSFEEObj->GetTrackletDef(); fGTriggerSetup = iDCSFEEObj->GetTriggerSetup(); fGAddOptions = iDCSFEEObj->GetAddOptions(); break; } } } for(Int_t i=0; i<540; i++) { AliTRDCalDCSFEE *iDCSFEEObj; iDCSFEEObj = GetCalDCSFEEObj(i); if(iDCSFEEObj != NULL) { if(iDCSFEEObj->GetStatusBit() == 0) { // second, if any of the other good chambers differ, set the global value to -1/"" if(fGNumberOfTimeBins != iDCSFEEObj->GetNumberOfTimeBins()) fGNumberOfTimeBins = -2; if(fGConfigTag != iDCSFEEObj->GetConfigTag()) fGConfigTag = -2; if(fGSingleHitThres != iDCSFEEObj->GetSingleHitThres()) fGSingleHitThres = -2; if(fGThreePadClustThres != iDCSFEEObj->GetThreePadClustThres()) fGThreePadClustThres = -2; if(fGSelNoZS != iDCSFEEObj->GetSelectiveNoZS()) fGSelNoZS = -2; if(fGTCFilterWeight != iDCSFEEObj->GetTCFilterWeight()) fGTCFilterWeight = -2; if(fGTCFilterShortDecPar != iDCSFEEObj->GetTCFilterShortDecPar()) fGTCFilterShortDecPar = -2; if(fGTCFilterLongDecPar != iDCSFEEObj->GetTCFilterLongDecPar()) fGTCFilterLongDecPar = -2; if(fGFastStatNoise != iDCSFEEObj->GetFastStatNoise()) fGFastStatNoise = -2; if(fGConfigVersion != iDCSFEEObj->GetConfigVersion()) fGConfigVersion = "mixed"; if(fGConfigName != iDCSFEEObj->GetConfigName()) fGConfigName = "mixed"; if(fGFilterType != iDCSFEEObj->GetFilterType()) fGFilterType = "mixed"; if(fGReadoutParam != iDCSFEEObj->GetReadoutParam()) fGReadoutParam = "mixed"; if(fGTestPattern != iDCSFEEObj->GetTestPattern()) fGTestPattern = "mixed"; if(fGTrackletMode != iDCSFEEObj->GetTrackletMode()) fGTrackletMode = "mixed"; if(fGTrackletDef != iDCSFEEObj->GetTrackletDef()) fGTrackletDef = "mixed"; if(fGTriggerSetup != iDCSFEEObj->GetTriggerSetup()) fGTriggerSetup = "mixed"; if(fGAddOptions != iDCSFEEObj->GetAddOptions()) fGAddOptions = "mixed"; } } } } <commit_msg>Fix compiler warning<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: AliTRDCalDCS.cxx 18952 2007-06-08 11:36:12Z cblume $ */ /////////////////////////////////////////////////////////////////////////////// // // // TRD calibration class for TRD DCS parameters // // // /////////////////////////////////////////////////////////////////////////////// #include "AliTRDCalDCS.h" #include "AliTRDCalDCSFEE.h" #include "AliTRDCalDCSGTU.h" ClassImp(AliTRDCalDCS) //_____________________________________________________________________________ AliTRDCalDCS::AliTRDCalDCS() :TNamed() ,fGNumberOfTimeBins(-1) ,fGConfigTag(-1) ,fGSingleHitThres(-1) ,fGThreePadClustThres(-1) ,fGSelNoZS(-1) ,fGTCFilterWeight(-1) ,fGTCFilterShortDecPar(-1) ,fGTCFilterLongDecPar(-1) ,fGFastStatNoise(-1) ,fGConfigVersion(0) ,fGConfigName(0) ,fGFilterType(0) ,fGReadoutParam(0) ,fGTestPattern(0) ,fGTrackletMode(0) ,fGTrackletDef(0) ,fGTriggerSetup(0) ,fGAddOptions(0) ,fRunType("") ,fStartTime(0) ,fEndTime(0) ,fFEEArr(new TObjArray(540)) ,fPTRArr(new TObjArray(6)) ,fGTUObj(new AliTRDCalDCSGTU()) { // // AliTRDCalDCS default constructor // } //_____________________________________________________________________________ AliTRDCalDCS::AliTRDCalDCS(const Text_t *name, const Text_t *title) :TNamed(name,title) ,fGNumberOfTimeBins(-1) ,fGConfigTag(-1) ,fGSingleHitThres(-1) ,fGThreePadClustThres(-1) ,fGSelNoZS(-1) ,fGTCFilterWeight(-1) ,fGTCFilterShortDecPar(-1) ,fGTCFilterLongDecPar(-1) ,fGFastStatNoise(-1) ,fGConfigVersion(0) ,fGConfigName(0) ,fGFilterType(0) ,fGReadoutParam(0) ,fGTestPattern(0) ,fGTrackletMode(0) ,fGTrackletDef(0) ,fGTriggerSetup(0) ,fGAddOptions(0) ,fRunType("") ,fStartTime(0) ,fEndTime(0) ,fFEEArr(new TObjArray(540)) ,fPTRArr(new TObjArray(6)) ,fGTUObj(new AliTRDCalDCSGTU()) { // // AliTRDCalDCS constructor // } //_____________________________________________________________________________ AliTRDCalDCS::AliTRDCalDCS(const AliTRDCalDCS &cd) :TNamed(cd) ,fGNumberOfTimeBins(-1) ,fGConfigTag(-1) ,fGSingleHitThres(-1) ,fGThreePadClustThres(-1) ,fGSelNoZS(-1) ,fGTCFilterWeight(-1) ,fGTCFilterShortDecPar(-1) ,fGTCFilterLongDecPar(-1) ,fGFastStatNoise(-1) ,fGConfigVersion(0) ,fGConfigName(0) ,fGFilterType(0) ,fGReadoutParam(0) ,fGTestPattern(0) ,fGTrackletMode(0) ,fGTrackletDef(0) ,fGTriggerSetup(0) ,fGAddOptions(0) ,fRunType("") ,fStartTime(0) ,fEndTime(0) ,fFEEArr(new TObjArray(540)) ,fPTRArr(new TObjArray(6)) ,fGTUObj(new AliTRDCalDCSGTU()) { // // AliTRDCalDCS copy constructor // } //_____________________________________________________________________________ AliTRDCalDCS &AliTRDCalDCS::operator=(const AliTRDCalDCS &cd) { // // Assignment operator // if (&cd == this) return *this; new (this) AliTRDCalDCS(cd); return *this; } //_____________________________________________________________________________ void AliTRDCalDCS::EvaluateGlobalParameters() { // // Do an evaluation of all global parameters // for(Int_t i=0; i<540; i++) { AliTRDCalDCSFEE *iDCSFEEObj; iDCSFEEObj = GetCalDCSFEEObj(i); if(iDCSFEEObj != NULL) { if(iDCSFEEObj->GetStatusBit() == 0) { // first, set the parameters of the first good ROC as global fGNumberOfTimeBins = iDCSFEEObj->GetNumberOfTimeBins(); fGConfigTag = iDCSFEEObj->GetConfigTag(); fGSingleHitThres = iDCSFEEObj->GetSingleHitThres(); fGThreePadClustThres = iDCSFEEObj->GetThreePadClustThres(); fGSelNoZS = iDCSFEEObj->GetSelectiveNoZS(); fGTCFilterWeight = iDCSFEEObj->GetTCFilterWeight(); fGTCFilterShortDecPar = iDCSFEEObj->GetTCFilterShortDecPar(); fGTCFilterLongDecPar = iDCSFEEObj->GetTCFilterLongDecPar(); fGFastStatNoise = iDCSFEEObj->GetFastStatNoise(); fGConfigVersion = iDCSFEEObj->GetConfigVersion(); fGConfigName = iDCSFEEObj->GetConfigName(); fGFilterType = iDCSFEEObj->GetFilterType(); fGReadoutParam = iDCSFEEObj->GetReadoutParam(); fGTestPattern = iDCSFEEObj->GetTestPattern(); fGTrackletMode = iDCSFEEObj->GetTrackletMode(); fGTrackletDef = iDCSFEEObj->GetTrackletDef(); fGTriggerSetup = iDCSFEEObj->GetTriggerSetup(); fGAddOptions = iDCSFEEObj->GetAddOptions(); break; } } } for(Int_t i=0; i<540; i++) { AliTRDCalDCSFEE *iDCSFEEObj; iDCSFEEObj = GetCalDCSFEEObj(i); if(iDCSFEEObj != NULL) { if(iDCSFEEObj->GetStatusBit() == 0) { // second, if any of the other good chambers differ, set the global value to -1/"" if(fGNumberOfTimeBins != iDCSFEEObj->GetNumberOfTimeBins()) fGNumberOfTimeBins = -2; if(fGConfigTag != iDCSFEEObj->GetConfigTag()) fGConfigTag = -2; if(fGSingleHitThres != iDCSFEEObj->GetSingleHitThres()) fGSingleHitThres = -2; if(fGThreePadClustThres != iDCSFEEObj->GetThreePadClustThres()) fGThreePadClustThres = -2; if(fGSelNoZS != iDCSFEEObj->GetSelectiveNoZS()) fGSelNoZS = -2; if(fGTCFilterWeight != iDCSFEEObj->GetTCFilterWeight()) fGTCFilterWeight = -2; if(fGTCFilterShortDecPar != iDCSFEEObj->GetTCFilterShortDecPar()) fGTCFilterShortDecPar = -2; if(fGTCFilterLongDecPar != iDCSFEEObj->GetTCFilterLongDecPar()) fGTCFilterLongDecPar = -2; if(fGFastStatNoise != iDCSFEEObj->GetFastStatNoise()) fGFastStatNoise = -2; if(fGConfigVersion != iDCSFEEObj->GetConfigVersion()) fGConfigVersion = "mixed"; if(fGConfigName != iDCSFEEObj->GetConfigName()) fGConfigName = "mixed"; if(fGFilterType != iDCSFEEObj->GetFilterType()) fGFilterType = "mixed"; if(fGReadoutParam != iDCSFEEObj->GetReadoutParam()) fGReadoutParam = "mixed"; if(fGTestPattern != iDCSFEEObj->GetTestPattern()) fGTestPattern = "mixed"; if(fGTrackletMode != iDCSFEEObj->GetTrackletMode()) fGTrackletMode = "mixed"; if(fGTrackletDef != iDCSFEEObj->GetTrackletDef()) fGTrackletDef = "mixed"; if(fGTriggerSetup != iDCSFEEObj->GetTriggerSetup()) fGTriggerSetup = "mixed"; if(fGAddOptions != iDCSFEEObj->GetAddOptions()) fGAddOptions = "mixed"; } } } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 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 <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xecba185817b726ef62e53afb14241a8095bd9613d2d3df679911029b83c98e5b")) ( 18, uint256("0x632aa100b8055344be4e765defd1a07a1e3d053eb67332c9a95045eb87b7f3ab")) ( 70, uint256("0x9f0d4db126647e607a14da83f89b103f0fb5f29c6447c1574a011f7204b6a02f")) ( 105, uint256("0xbf7bc864ecfb4803df34d1e05024654d9a65159c875f60fe07eeda2203ac734c")) ( 200, uint256("0x3ba4bd313ce1a76e519ebc60c3e82154561c65c4b11ea82de1b3b0cc93f6eebb")) (299893, uint256("0xca07e64a675616af303ec911343b2473904334b043f8e972eb9dc03720995f01")) (599787, uint256("0x464cef0fed8c75ce46b48d19b97d70eb919edcca51523c793b830db1a710167e")) (1199646, uint256("0xce0e285eb16b6940dd7dd7b0fea58f3d93ffdfc7544ff1274ca5ff9496773903")) (2399216, uint256("0x4720496d86f9fea0a100c678d76192f753ba8da8f9c3d41eb739e479fa8e5bda")) ; static const CCheckpointData data = { &mapCheckpoints, 1402291952, // * UNIX timestamp of last checkpoint block 3113946, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 16000.0 // * estimated number of transactions per day after checkpoint }; const CCheckpointData &Checkpoints() { return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Update checkpoints.cpp<commit_after>// Copyright (c) 2009-2012 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 <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xecba185817b726ef62e53afb14241a8095bd9613d2d3df679911029b83c98e5b")) ( 18, uint256("0x632aa100b8055344be4e765defd1a07a1e3d053eb67332c9a95045eb87b7f3ab")) ( 70, uint256("0x9f0d4db126647e607a14da83f89b103f0fb5f29c6447c1574a011f7204b6a02f")) ( 105, uint256("0xbf7bc864ecfb4803df34d1e05024654d9a65159c875f60fe07eeda2203ac734c")) ( 200, uint256("0x3ba4bd313ce1a76e519ebc60c3e82154561c65c4b11ea82de1b3b0cc93f6eebb")) (299893, uint256("0xca07e64a675616af303ec911343b2473904334b043f8e972eb9dc03720995f01")) (599787, uint256("0x464cef0fed8c75ce46b48d19b97d70eb919edcca51523c793b830db1a710167e")) (1199646, uint256("0xce0e285eb16b6940dd7dd7b0fea58f3d93ffdfc7544ff1274ca5ff9496773903")) (2399216, uint256("0x4720496d86f9fea0a100c678d76192f753ba8da8f9c3d41eb739e479fa8e5bda")) (2899214, uint256("0x8652192d0905663bceed4c10d5759c2691a767768f1f80b30a9447cfa0978ba9")) (3380762, uint256("0x85207e898babf569cf7d59f06d3bbfa80f4041e2747d4b401367380d0f3cc985")) (3621535, uint256("0x0e69ac77ca6336a1d7faf5a37bbb68fe3305a601f1976cca35e9325bec9cd612")) ; static const CCheckpointData data = { &mapCheckpoints, 1416303108, // * UNIX timestamp of last checkpoint block 4483343, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 16000.0 // * estimated number of transactions per day after checkpoint }; const CCheckpointData &Checkpoints() { return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #define BOOST_TEST_IGNORE_NON_ZERO_CHILD_CODE #include <boost/version.hpp> #include <boost/test/unit_test.hpp> #include <boost/algorithm/string.hpp> #include <iostream> #include <string> #include <vector> #include "storage/Exception.h" #include "storage/Utils/Mockup.h" #include "storage/Utils/SystemCmd.h" using namespace std; using namespace storage; string join(const vector<string>& input) { return boost::join(input, "\n") + "\n"; } BOOST_AUTO_TEST_CASE(hello_stdout) { vector<string> stdout = { "stdout #1: hello", "stdout #2: stdout" }; SystemCmd cmd( "helpers/echoargs hello stdout" ); BOOST_CHECK_EQUAL(join(cmd.stdout()), join(stdout)); BOOST_CHECK(cmd.stderr().empty()); BOOST_CHECK(cmd.retcode() == 0); } BOOST_AUTO_TEST_CASE(hello_stderr) { vector<string> stderr = { "stderr #1: hello", "stderr #2: stderr" }; SystemCmd cmd("helpers/echoargs_stderr hello stderr"); BOOST_CHECK_EQUAL(join(cmd.stderr()),join(stderr)); BOOST_CHECK(cmd.stdout().empty()); } BOOST_AUTO_TEST_CASE(hello_mixed) { vector<string> stdout = { "line #1: stdout #1: mixed", "line #3: stdout #2: stdout", "line #5: stdout #3: stderr" }; vector<string> stderr = { "line #2: stderr #1: to", "line #4: stderr #2: and" }; SystemCmd cmd( "helpers/echoargs_mixed mixed to stdout and stderr" ); BOOST_CHECK_EQUAL(join(cmd.stdout()), join(stdout)); BOOST_CHECK_EQUAL(join(cmd.stderr()), join(stderr)); } BOOST_AUTO_TEST_CASE(retcode_42) { #if BOOST_VERSION >= 1058000 setenv("BOOST_TEST_CATCH_SYSTEM_ERRORS", "no", 1); SystemCmd cmd("helpers/retcode 42"); BOOST_CHECK(cmd.retcode() == 42); #endif } <commit_msg>add test cases for exceptions<commit_after> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #define BOOST_TEST_IGNORE_NON_ZERO_CHILD_CODE #include <boost/version.hpp> #include <boost/test/unit_test.hpp> #include <boost/algorithm/string.hpp> #include <iostream> #include <string> #include <vector> #include "storage/Exception.h" #include "storage/Utils/Mockup.h" #include "storage/Utils/SystemCmd.h" using namespace std; using namespace storage; string join(const vector<string>& input) { return boost::join(input, "\n") + "\n"; } BOOST_AUTO_TEST_CASE(hello_stdout) { vector<string> stdout = { "stdout #1: hello", "stdout #2: stdout" }; SystemCmd cmd( "helpers/echoargs hello stdout" ); BOOST_CHECK_EQUAL(join(cmd.stdout()), join(stdout)); BOOST_CHECK(cmd.stderr().empty()); BOOST_CHECK(cmd.retcode() == 0); } BOOST_AUTO_TEST_CASE(hello_stderr) { vector<string> stderr = { "stderr #1: hello", "stderr #2: stderr" }; SystemCmd cmd("helpers/echoargs_stderr hello stderr"); BOOST_CHECK_EQUAL(join(cmd.stderr()),join(stderr)); BOOST_CHECK(cmd.stdout().empty()); } BOOST_AUTO_TEST_CASE(hello_mixed) { vector<string> stdout = { "line #1: stdout #1: mixed", "line #3: stdout #2: stdout", "line #5: stdout #3: stderr" }; vector<string> stderr = { "line #2: stderr #1: to", "line #4: stderr #2: and" }; SystemCmd cmd( "helpers/echoargs_mixed mixed to stdout and stderr" ); BOOST_CHECK_EQUAL(join(cmd.stdout()), join(stdout)); BOOST_CHECK_EQUAL(join(cmd.stderr()), join(stderr)); } BOOST_AUTO_TEST_CASE(retcode_42) { #if BOOST_VERSION >= 1058000 setenv("BOOST_TEST_CATCH_SYSTEM_ERRORS", "no", 1); SystemCmd cmd("helpers/retcode 42"); BOOST_CHECK(cmd.retcode() == 42); #endif } BOOST_AUTO_TEST_CASE(non_existent_no_throw) { BOOST_CHECK_NO_THROW({SystemCmd cmd("/bin/wrglbrmpf", SystemCmd::ThrowBehaviour::NoThrow);}); } BOOST_AUTO_TEST_CASE(non_existent_throw) { BOOST_CHECK_THROW({SystemCmd cmd("/bin/wrglbrmpf", SystemCmd::ThrowBehaviour::DoThrow);}, CommandNotFoundException); } BOOST_AUTO_TEST_CASE(segfault_no_throw) { BOOST_CHECK_NO_THROW({SystemCmd cmd( "helpers/segfaulter", SystemCmd::ThrowBehaviour::NoThrow);}); } BOOST_AUTO_TEST_CASE(segfault_throw) { BOOST_CHECK_THROW({SystemCmd cmd( "helpers/segfaulter", SystemCmd::ThrowBehaviour::DoThrow);}, SystemCmdException); } BOOST_AUTO_TEST_CASE(non_exec_no_throw) { BOOST_CHECK_NO_THROW({SystemCmd cmd( "/etc/fstab", SystemCmd::ThrowBehaviour::NoThrow);}); } BOOST_AUTO_TEST_CASE(non_exec_throw) { BOOST_CHECK_THROW({SystemCmd cmd( "/etc/fstab", SystemCmd::ThrowBehaviour::DoThrow);}, SystemCmdException); } <|endoftext|>
<commit_before>/// HEADER #include "model_to_marker.h" /// PROJECT #include <csapex/model/connector_out.h> #include <csapex/model/connector_in.h> #include <csapex_core_plugins/ros_message_conversion.h> //#include <csapex/model/message.h> #include <utils_param/parameter_factory.h> /// SYSTEM #include <csapex/utility/register_apex_plugin.h> #include <visualization_msgs/Marker.h> CSAPEX_REGISTER_CLASS(csapex::ModelToMarker, csapex::Node) using namespace csapex; using namespace csapex::connection_types; ModelToMarker::ModelToMarker() { //addTag(Tag::get("PointCloud")); } void ModelToMarker::process() { boost::shared_ptr<GenericMessage<ModelMessage> > message = input_->getMessage<GenericMessage<ModelMessage> >(); if(param<bool>("publish marker")) { publishMarkers(*(message->value)); } } void ModelToMarker::setup() { setSynchronizedInputs(true); input_ = addInput<GenericMessage<ModelMessage> >("ModelMessage"); output_ = addOutput<visualization_msgs::Marker>("Marker"); addParameter(param::ParameterFactory::declareBool("publish marker", true)); } void ModelToMarker::publishMarkers(const ModelMessage model_message) { //visualization_msgs::MarkerArray::Ptr marker_array(new visualization_msgs::MarkerArray); //visualization_msgs::Marker marker; visualization_msgs::Marker::Ptr marker(new visualization_msgs::Marker); marker->header.frame_id = model_message.frame_id; marker->header.stamp = ros::Time::now(); marker->ns = "model"; marker->id = 1; marker->action = visualization_msgs::Marker::ADD; // marker->pose.position.x = 1; // marker->pose.position.y = 1; // see below // marker->pose.position.z = 1; // marker->pose.orientation.x = 0.0; // marker->pose.orientation.y = 0.0; // marker->pose.orientation.z = 0.0; // marker->pose.orientation.w = 1.0; // marker->scale.x = 1.0; // marker->scale.y = 1.0; // marker->scale.z = 1.0; marker->color.a = 1.0; marker->color.r = 0.0; marker->color.g = 1.0; marker->color.b = 0.0; if (model_message.model_type == pcl::SACMODEL_SPHERE ) { marker->type = visualization_msgs::Marker::SPHERE; marker->pose.position.x = model_message.coefficients->values.at(0); marker->pose.position.y = model_message.coefficients->values.at(1); marker->pose.position.z = model_message.coefficients->values.at(2); marker->pose.orientation.x = 0.0; marker->pose.orientation.y = 0.0; marker->pose.orientation.z = 0.0; marker->pose.orientation.w = 1.0; double min_scale = 0.001; double scale = model_message.coefficients->values.at(3) > min_scale ? model_message.coefficients->values.at(3) : min_scale; marker->scale.x = scale; marker->scale.y = scale; marker->scale.z = scale; } else { printf("unknown Model!!"); } output_->publish<visualization_msgs::Marker>(marker); } <commit_msg>added display of a cone, but has to be improved<commit_after>/// HEADER #include "model_to_marker.h" /// PROJECT #include <csapex/model/connector_out.h> #include <csapex/model/connector_in.h> #include <csapex_core_plugins/ros_message_conversion.h> //#include <csapex/model/message.h> #include <utils_param/parameter_factory.h> /// SYSTEM #include <csapex/utility/register_apex_plugin.h> #include <visualization_msgs/Marker.h> #include <geometry_msgs/Point.h> CSAPEX_REGISTER_CLASS(csapex::ModelToMarker, csapex::Node) using namespace csapex; using namespace csapex::connection_types; ModelToMarker::ModelToMarker() { //addTag(Tag::get("PointCloud")); } void ModelToMarker::process() { boost::shared_ptr<GenericMessage<ModelMessage> > message = input_->getMessage<GenericMessage<ModelMessage> >(); if(param<bool>("publish marker")) { publishMarkers(*(message->value)); } } void ModelToMarker::setup() { setSynchronizedInputs(true); input_ = addInput<GenericMessage<ModelMessage> >("ModelMessage"); output_ = addOutput<visualization_msgs::Marker>("Marker"); addParameter(param::ParameterFactory::declareBool("publish marker", true)); } void ModelToMarker::publishMarkers(const ModelMessage model_message) { //visualization_msgs::MarkerArray::Ptr marker_array(new visualization_msgs::MarkerArray); //visualization_msgs::Marker marker; visualization_msgs::Marker::Ptr marker(new visualization_msgs::Marker); marker->header.frame_id = model_message.frame_id; marker->header.stamp = ros::Time::now(); marker->ns = "model"; marker->id = 1; marker->action = visualization_msgs::Marker::ADD; if (model_message.model_type == pcl::SACMODEL_SPHERE ) { marker->type = visualization_msgs::Marker::SPHERE; marker->pose.position.x = model_message.coefficients->values.at(0); marker->pose.position.y = model_message.coefficients->values.at(1); marker->pose.position.z = model_message.coefficients->values.at(2); marker->pose.orientation.x = 0.0; marker->pose.orientation.y = 0.0; marker->pose.orientation.z = 0.0; marker->pose.orientation.w = 1.0; double min_scale = 0.001; double scale = model_message.coefficients->values.at(3) > min_scale ? model_message.coefficients->values.at(3) : min_scale; marker->scale.x = scale; marker->scale.y = scale; marker->scale.z = scale; marker->color.a = 0.8; marker->color.r = 0.0; marker->color.g = 1.0; marker->color.b = 0.0; } else if (model_message.model_type == pcl::SACMODEL_CONE ) { marker->type = visualization_msgs::Marker::ARROW; geometry_msgs::Point apex; apex.x = model_message.coefficients->values.at(0); apex.y = model_message.coefficients->values.at(1); apex.z = model_message.coefficients->values.at(2); geometry_msgs::Point base; base.x = apex.x - model_message.coefficients->values.at(3); base.y = apex.y - model_message.coefficients->values.at(4); base.z = apex.z - model_message.coefficients->values.at(5); marker->points.push_back(base); marker->points.push_back(apex); // marker->pose.orientation.x = 0.0; // marker->pose.orientation.y = 0.0; // marker->pose.orientation.z = 0.0; // marker->pose.orientation.w = 1.0; double scale = 1.0; marker->scale.x = scale; marker->scale.y = scale; marker->scale.z = scale; marker->color.a = 0.8; marker->color.r = 1.0; marker->color.g = 1.0; marker->color.b = 0.0; } else { printf("unknown Model!!"); } // Todo: // Add plane and cylinder // Add circle // Change to marker array so that a nicer cone can be displayed by a vector and a circle output_->publish<visualization_msgs::Marker>(marker); } <|endoftext|>
<commit_before>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file opt_structure_splitting.cpp * * If a structure is only ever referenced by its components, then * split those components out to individual variables so they can be * handled normally by other optimization passes. * * This skips structures like uniforms, which need to be accessible as * structures for their access by the GL. */ #include "ir.h" #include "ir_visitor.h" #include "ir_rvalue_visitor.h" #include "compiler/glsl_types.h" namespace { static bool debug = false; class variable_entry : public exec_node { public: variable_entry(ir_variable *var) { this->var = var; this->whole_structure_access = 0; this->declaration = false; this->components = NULL; this->mem_ctx = NULL; } ir_variable *var; /* The key: the variable's pointer. */ /** Number of times the variable is referenced, including assignments. */ unsigned whole_structure_access; /* If the variable had a decl we can work with in the instruction * stream. We can't do splitting on function arguments, which * don't get this variable set. */ bool declaration; ir_variable **components; /** ralloc_parent(this->var) -- the shader's ralloc context. */ void *mem_ctx; }; class ir_structure_reference_visitor : public ir_hierarchical_visitor { public: ir_structure_reference_visitor(void) { this->mem_ctx = ralloc_context(NULL); this->variable_list.make_empty(); } ~ir_structure_reference_visitor(void) { ralloc_free(mem_ctx); } virtual ir_visitor_status visit(ir_variable *); virtual ir_visitor_status visit(ir_dereference_variable *); virtual ir_visitor_status visit_enter(ir_dereference_record *); virtual ir_visitor_status visit_enter(ir_assignment *); virtual ir_visitor_status visit_enter(ir_function_signature *); variable_entry *get_variable_entry(ir_variable *var); /* List of variable_entry */ exec_list variable_list; void *mem_ctx; }; variable_entry * ir_structure_reference_visitor::get_variable_entry(ir_variable *var) { assert(var); if (!var->type->is_record() || var->data.mode == ir_var_uniform || var->data.mode == ir_var_shader_storage || var->data.mode == ir_var_shader_in || var->data.mode == ir_var_shader_out) return NULL; foreach_in_list(variable_entry, entry, &this->variable_list) { if (entry->var == var) return entry; } variable_entry *entry = new(mem_ctx) variable_entry(var); this->variable_list.push_tail(entry); return entry; } ir_visitor_status ir_structure_reference_visitor::visit(ir_variable *ir) { variable_entry *entry = this->get_variable_entry(ir); if (entry) entry->declaration = true; return visit_continue; } ir_visitor_status ir_structure_reference_visitor::visit(ir_dereference_variable *ir) { ir_variable *const var = ir->variable_referenced(); variable_entry *entry = this->get_variable_entry(var); if (entry) entry->whole_structure_access++; return visit_continue; } ir_visitor_status ir_structure_reference_visitor::visit_enter(ir_dereference_record *ir) { (void) ir; /* Don't descend into the ir_dereference_variable below. */ return visit_continue_with_parent; } ir_visitor_status ir_structure_reference_visitor::visit_enter(ir_assignment *ir) { /* If there are no structure references yet, no need to bother with * processing the expression tree. */ if (this->variable_list.is_empty()) return visit_continue_with_parent; if (ir->lhs->as_dereference_variable() && ir->rhs->as_dereference_variable() && !ir->condition) { /* We'll split copies of a structure to copies of components, so don't * descend to the ir_dereference_variables. */ return visit_continue_with_parent; } return visit_continue; } ir_visitor_status ir_structure_reference_visitor::visit_enter(ir_function_signature *ir) { /* We don't have logic for structure-splitting function arguments, * so just look at the body instructions and not the parameter * declarations. */ visit_list_elements(this, &ir->body); return visit_continue_with_parent; } class ir_structure_splitting_visitor : public ir_rvalue_visitor { public: ir_structure_splitting_visitor(exec_list *vars) { this->variable_list = vars; } virtual ~ir_structure_splitting_visitor() { } virtual ir_visitor_status visit_leave(ir_assignment *); void split_deref(ir_dereference **deref); void handle_rvalue(ir_rvalue **rvalue); variable_entry *get_splitting_entry(ir_variable *var); exec_list *variable_list; }; variable_entry * ir_structure_splitting_visitor::get_splitting_entry(ir_variable *var) { assert(var); if (!var->type->is_record()) return NULL; foreach_in_list(variable_entry, entry, this->variable_list) { if (entry->var == var) { return entry; } } return NULL; } void ir_structure_splitting_visitor::split_deref(ir_dereference **deref) { if ((*deref)->ir_type != ir_type_dereference_record) return; ir_dereference_record *deref_record = (ir_dereference_record *)*deref; ir_dereference_variable *deref_var = deref_record->record->as_dereference_variable(); if (!deref_var) return; variable_entry *entry = get_splitting_entry(deref_var->var); if (!entry) return; unsigned int i; for (i = 0; i < entry->var->type->length; i++) { if (strcmp(deref_record->field, entry->var->type->fields.structure[i].name) == 0) break; } assert(i != entry->var->type->length); *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[i]); } void ir_structure_splitting_visitor::handle_rvalue(ir_rvalue **rvalue) { if (!*rvalue) return; ir_dereference *deref = (*rvalue)->as_dereference(); if (!deref) return; split_deref(&deref); *rvalue = deref; } ir_visitor_status ir_structure_splitting_visitor::visit_leave(ir_assignment *ir) { ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable(); ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable(); variable_entry *lhs_entry = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL; variable_entry *rhs_entry = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL; const glsl_type *type = ir->rhs->type; if ((lhs_entry || rhs_entry) && !ir->condition) { for (unsigned int i = 0; i < type->length; i++) { ir_dereference *new_lhs, *new_rhs; void *mem_ctx = lhs_entry ? lhs_entry->mem_ctx : rhs_entry->mem_ctx; if (lhs_entry) { new_lhs = new(mem_ctx) ir_dereference_variable(lhs_entry->components[i]); } else { new_lhs = new(mem_ctx) ir_dereference_record(ir->lhs->clone(mem_ctx, NULL), type->fields.structure[i].name); } if (rhs_entry) { new_rhs = new(mem_ctx) ir_dereference_variable(rhs_entry->components[i]); } else { new_rhs = new(mem_ctx) ir_dereference_record(ir->rhs->clone(mem_ctx, NULL), type->fields.structure[i].name); } ir->insert_before(new(mem_ctx) ir_assignment(new_lhs, new_rhs, NULL)); } ir->remove(); } else { handle_rvalue(&ir->rhs); split_deref(&ir->lhs); } handle_rvalue(&ir->condition); return visit_continue; } } /* unnamed namespace */ bool do_structure_splitting(exec_list *instructions) { ir_structure_reference_visitor refs; visit_list_elements(&refs, instructions); /* Trim out variables we can't split. */ foreach_in_list_safe(variable_entry, entry, &refs.variable_list) { if (debug) { printf("structure %s@%p: decl %d, whole_access %d\n", entry->var->name, (void *) entry->var, entry->declaration, entry->whole_structure_access); } if (!entry->declaration || entry->whole_structure_access) { entry->remove(); } } if (refs.variable_list.is_empty()) return false; void *mem_ctx = ralloc_context(NULL); /* Replace the decls of the structures to be split with their split * components. */ foreach_in_list_safe(variable_entry, entry, &refs.variable_list) { const struct glsl_type *type = entry->var->type; entry->mem_ctx = ralloc_parent(entry->var); entry->components = ralloc_array(mem_ctx, ir_variable *, type->length); for (unsigned int i = 0; i < entry->var->type->length; i++) { const char *name = ralloc_asprintf(mem_ctx, "%s_%s", entry->var->name, type->fields.structure[i].name); entry->components[i] = new(entry->mem_ctx) ir_variable(type->fields.structure[i].type, name, ir_var_temporary); entry->var->insert_before(entry->components[i]); } entry->var->remove(); } ir_structure_splitting_visitor split(&refs.variable_list); visit_list_elements(&split, instructions); ralloc_free(mem_ctx); return true; } <commit_msg>glsl: Use correct mode for split components.<commit_after>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file opt_structure_splitting.cpp * * If a structure is only ever referenced by its components, then * split those components out to individual variables so they can be * handled normally by other optimization passes. * * This skips structures like uniforms, which need to be accessible as * structures for their access by the GL. */ #include "ir.h" #include "ir_visitor.h" #include "ir_rvalue_visitor.h" #include "compiler/glsl_types.h" namespace { static bool debug = false; class variable_entry : public exec_node { public: variable_entry(ir_variable *var) { this->var = var; this->whole_structure_access = 0; this->declaration = false; this->components = NULL; this->mem_ctx = NULL; } ir_variable *var; /* The key: the variable's pointer. */ /** Number of times the variable is referenced, including assignments. */ unsigned whole_structure_access; /* If the variable had a decl we can work with in the instruction * stream. We can't do splitting on function arguments, which * don't get this variable set. */ bool declaration; ir_variable **components; /** ralloc_parent(this->var) -- the shader's ralloc context. */ void *mem_ctx; }; class ir_structure_reference_visitor : public ir_hierarchical_visitor { public: ir_structure_reference_visitor(void) { this->mem_ctx = ralloc_context(NULL); this->variable_list.make_empty(); } ~ir_structure_reference_visitor(void) { ralloc_free(mem_ctx); } virtual ir_visitor_status visit(ir_variable *); virtual ir_visitor_status visit(ir_dereference_variable *); virtual ir_visitor_status visit_enter(ir_dereference_record *); virtual ir_visitor_status visit_enter(ir_assignment *); virtual ir_visitor_status visit_enter(ir_function_signature *); variable_entry *get_variable_entry(ir_variable *var); /* List of variable_entry */ exec_list variable_list; void *mem_ctx; }; variable_entry * ir_structure_reference_visitor::get_variable_entry(ir_variable *var) { assert(var); if (!var->type->is_record() || var->data.mode == ir_var_uniform || var->data.mode == ir_var_shader_storage || var->data.mode == ir_var_shader_in || var->data.mode == ir_var_shader_out) return NULL; foreach_in_list(variable_entry, entry, &this->variable_list) { if (entry->var == var) return entry; } variable_entry *entry = new(mem_ctx) variable_entry(var); this->variable_list.push_tail(entry); return entry; } ir_visitor_status ir_structure_reference_visitor::visit(ir_variable *ir) { variable_entry *entry = this->get_variable_entry(ir); if (entry) entry->declaration = true; return visit_continue; } ir_visitor_status ir_structure_reference_visitor::visit(ir_dereference_variable *ir) { ir_variable *const var = ir->variable_referenced(); variable_entry *entry = this->get_variable_entry(var); if (entry) entry->whole_structure_access++; return visit_continue; } ir_visitor_status ir_structure_reference_visitor::visit_enter(ir_dereference_record *ir) { (void) ir; /* Don't descend into the ir_dereference_variable below. */ return visit_continue_with_parent; } ir_visitor_status ir_structure_reference_visitor::visit_enter(ir_assignment *ir) { /* If there are no structure references yet, no need to bother with * processing the expression tree. */ if (this->variable_list.is_empty()) return visit_continue_with_parent; if (ir->lhs->as_dereference_variable() && ir->rhs->as_dereference_variable() && !ir->condition) { /* We'll split copies of a structure to copies of components, so don't * descend to the ir_dereference_variables. */ return visit_continue_with_parent; } return visit_continue; } ir_visitor_status ir_structure_reference_visitor::visit_enter(ir_function_signature *ir) { /* We don't have logic for structure-splitting function arguments, * so just look at the body instructions and not the parameter * declarations. */ visit_list_elements(this, &ir->body); return visit_continue_with_parent; } class ir_structure_splitting_visitor : public ir_rvalue_visitor { public: ir_structure_splitting_visitor(exec_list *vars) { this->variable_list = vars; } virtual ~ir_structure_splitting_visitor() { } virtual ir_visitor_status visit_leave(ir_assignment *); void split_deref(ir_dereference **deref); void handle_rvalue(ir_rvalue **rvalue); variable_entry *get_splitting_entry(ir_variable *var); exec_list *variable_list; }; variable_entry * ir_structure_splitting_visitor::get_splitting_entry(ir_variable *var) { assert(var); if (!var->type->is_record()) return NULL; foreach_in_list(variable_entry, entry, this->variable_list) { if (entry->var == var) { return entry; } } return NULL; } void ir_structure_splitting_visitor::split_deref(ir_dereference **deref) { if ((*deref)->ir_type != ir_type_dereference_record) return; ir_dereference_record *deref_record = (ir_dereference_record *)*deref; ir_dereference_variable *deref_var = deref_record->record->as_dereference_variable(); if (!deref_var) return; variable_entry *entry = get_splitting_entry(deref_var->var); if (!entry) return; unsigned int i; for (i = 0; i < entry->var->type->length; i++) { if (strcmp(deref_record->field, entry->var->type->fields.structure[i].name) == 0) break; } assert(i != entry->var->type->length); *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[i]); } void ir_structure_splitting_visitor::handle_rvalue(ir_rvalue **rvalue) { if (!*rvalue) return; ir_dereference *deref = (*rvalue)->as_dereference(); if (!deref) return; split_deref(&deref); *rvalue = deref; } ir_visitor_status ir_structure_splitting_visitor::visit_leave(ir_assignment *ir) { ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable(); ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable(); variable_entry *lhs_entry = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL; variable_entry *rhs_entry = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL; const glsl_type *type = ir->rhs->type; if ((lhs_entry || rhs_entry) && !ir->condition) { for (unsigned int i = 0; i < type->length; i++) { ir_dereference *new_lhs, *new_rhs; void *mem_ctx = lhs_entry ? lhs_entry->mem_ctx : rhs_entry->mem_ctx; if (lhs_entry) { new_lhs = new(mem_ctx) ir_dereference_variable(lhs_entry->components[i]); } else { new_lhs = new(mem_ctx) ir_dereference_record(ir->lhs->clone(mem_ctx, NULL), type->fields.structure[i].name); } if (rhs_entry) { new_rhs = new(mem_ctx) ir_dereference_variable(rhs_entry->components[i]); } else { new_rhs = new(mem_ctx) ir_dereference_record(ir->rhs->clone(mem_ctx, NULL), type->fields.structure[i].name); } ir->insert_before(new(mem_ctx) ir_assignment(new_lhs, new_rhs, NULL)); } ir->remove(); } else { handle_rvalue(&ir->rhs); split_deref(&ir->lhs); } handle_rvalue(&ir->condition); return visit_continue; } } /* unnamed namespace */ bool do_structure_splitting(exec_list *instructions) { ir_structure_reference_visitor refs; visit_list_elements(&refs, instructions); /* Trim out variables we can't split. */ foreach_in_list_safe(variable_entry, entry, &refs.variable_list) { if (debug) { printf("structure %s@%p: decl %d, whole_access %d\n", entry->var->name, (void *) entry->var, entry->declaration, entry->whole_structure_access); } if (!entry->declaration || entry->whole_structure_access) { entry->remove(); } } if (refs.variable_list.is_empty()) return false; void *mem_ctx = ralloc_context(NULL); /* Replace the decls of the structures to be split with their split * components. */ foreach_in_list_safe(variable_entry, entry, &refs.variable_list) { const struct glsl_type *type = entry->var->type; entry->mem_ctx = ralloc_parent(entry->var); entry->components = ralloc_array(mem_ctx, ir_variable *, type->length); for (unsigned int i = 0; i < entry->var->type->length; i++) { const char *name = ralloc_asprintf(mem_ctx, "%s_%s", entry->var->name, type->fields.structure[i].name); entry->components[i] = new(entry->mem_ctx) ir_variable(type->fields.structure[i].type, name, (ir_variable_mode) entry->var->data.mode); entry->var->insert_before(entry->components[i]); } entry->var->remove(); } ir_structure_splitting_visitor split(&refs.variable_list); visit_list_elements(&split, instructions); ralloc_free(mem_ctx); return true; } <|endoftext|>
<commit_before>// Original Code: Copyright (c) 2009-2014 The Bitcoin Core Developers // Modified Code: Copyright (c) 2014 Project Bitmark // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "main.h" #include "uint256.h" #include <stdint.h> #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double SIGCHECK_VERIFICATION_FACTOR = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64_t nTimeLastCheckpoint; int64_t nTransactionsLastCheckpoint; double fTransactionsPerDay; }; bool fEnabled = true; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("c1fb746e87e89ae75bdec2ef0639a1f6786744639ce3d0ece1dcf979b79137cb")) ( 4918, uint256("79aa44255b446aedb3cd9d765c4c7fc51b9c4a82e7d8639bf97ba42a73e61aec")) ( 11571, uint256("ec7fa58c5659476f5bafc1ff70d41188a73cdaa6deffb0fc42b7054815225f21")) ( 17500, uint256("812f6ba1879ef23d3210c831b2572b411ee272f16317a541461fddfda5d2ebbf")) ( 20675, uint256("8fb648c380b3bdb52d700a377ab6fc84cac742a2ab0c27dda2118e4820366189")) ( 27050, uint256("2ef099e35b775661d748296da1a43cdd62b7bf34f1f347cb7e14855841064560")) ( 28400, uint256("70541d1ae78f7788fddfe4ace548db50e3b101d0d59335feb69ee801ee6fdc6a")) ( 30688, uint256("767543f214b4c6590a583c114195b004cfe32657360a2dc3407a096a2ba973a5")) ( 33298, uint256("ce5bc23644c83868038f6b08a9e6db3120613404036d2da371524ad168ad2413")) ( 34830, uint256("bac0d1820dad632b2874c77a9edc6ab0d15e5049aabac1802358ce3679097e9d")) ; static const CCheckpointData data = { &mapCheckpoints, 1410225222, // * UNIX timestamp of last checkpoint block 50191, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 2500.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("1d6329aeff3ff6786635afd5d6715b24667329cfda199bd7a1d6626d81a4573c")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1405274408, 0, 300 }; static MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")) ; static const CCheckpointData dataRegtest = { &mapCheckpointsRegtest, 0, 0, 0 }; const CCheckpointData &Checkpoints() { if (Params().NetworkID() == CChainParams::TESTNET) return dataTestnet; else if (Params().NetworkID() == CChainParams::MAIN) return data; else return dataRegtest; } bool CheckBlock(int nHeight, const uint256& hash) { if (!fEnabled) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) { if (pindex==NULL) return 0.0; int64_t nNow = time(NULL); double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0; double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkpoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!fEnabled) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!fEnabled) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>checkpoints at 38290<commit_after>// Original Code: Copyright (c) 2009-2014 The Bitcoin Core Developers // Modified Code: Copyright (c) 2014 Project Bitmark // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "main.h" #include "uint256.h" #include <stdint.h> #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double SIGCHECK_VERIFICATION_FACTOR = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64_t nTimeLastCheckpoint; int64_t nTransactionsLastCheckpoint; double fTransactionsPerDay; }; bool fEnabled = true; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("c1fb746e87e89ae75bdec2ef0639a1f6786744639ce3d0ece1dcf979b79137cb")) ( 4918, uint256("79aa44255b446aedb3cd9d765c4c7fc51b9c4a82e7d8639bf97ba42a73e61aec")) ( 11571, uint256("ec7fa58c5659476f5bafc1ff70d41188a73cdaa6deffb0fc42b7054815225f21")) ( 17500, uint256("812f6ba1879ef23d3210c831b2572b411ee272f16317a541461fddfda5d2ebbf")) ( 20675, uint256("8fb648c380b3bdb52d700a377ab6fc84cac742a2ab0c27dda2118e4820366189")) ( 27050, uint256("2ef099e35b775661d748296da1a43cdd62b7bf34f1f347cb7e14855841064560")) ( 28400, uint256("70541d1ae78f7788fddfe4ace548db50e3b101d0d59335feb69ee801ee6fdc6a")) ( 30688, uint256("767543f214b4c6590a583c114195b004cfe32657360a2dc3407a096a2ba973a5")) ( 33298, uint256("ce5bc23644c83868038f6b08a9e6db3120613404036d2da371524ad168ad2413")) ( 34830, uint256("bac0d1820dad632b2874c77a9edc6ab0d15e5049aabac1802358ce3679097e9d")) ( 38290, uint256("984b6bd2c102bbeda7cef322f4b76109f6b42b64b2ae4beadc12d70614ffeeda")) ; static const CCheckpointData data = { &mapCheckpoints, 1410726662, // * UNIX timestamp of last checkpoint block 55651, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 2500.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("1d6329aeff3ff6786635afd5d6715b24667329cfda199bd7a1d6626d81a4573c")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1405274408, 0, 300 }; static MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")) ; static const CCheckpointData dataRegtest = { &mapCheckpointsRegtest, 0, 0, 0 }; const CCheckpointData &Checkpoints() { if (Params().NetworkID() == CChainParams::TESTNET) return dataTestnet; else if (Params().NetworkID() == CChainParams::MAIN) return data; else return dataRegtest; } bool CheckBlock(int nHeight, const uint256& hash) { if (!fEnabled) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) { if (pindex==NULL) return 0.0; int64_t nNow = time(NULL); double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0; double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkpoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!fEnabled) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!fEnabled) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 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 <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")) (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763")) (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317")) (210000, uint256("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e")) (216116, uint256("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e")) (225430, uint256("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932")) (250000, uint256("0x000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214")) ; static const CCheckpointData data = { &mapCheckpoints, 1375533383, // * UNIX timestamp of last checkpoint block 21491097, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 60000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1338180505, 16341, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { return 0; if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { return NULL; if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Add checkpoint data for BOB blockchain<commit_after>// Copyright (c) 2009-2012 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 <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 1, uint256("0xe613b5a195556386f422875d8df68e3e154f37b4981dec641fe041211672870f")) ( 2016, uint256("0x94a9ab39b9e1e7dafdda1a5823c11556750157aa16e93ae2a59de426e185de58")) ( 4032, uint256("0xa29010ca0ec82b0d2d937f5d82d2e30918467b1f4b3bb51026d13782b7aac73a")) ( 8064, uint256("0x76ef2061b587842f424aae28fcab25fb8434612b58125258292799aaaed0f833")) ( 12096, uint256("0x5abe39584788a018296d97a6f00ca80c81603ebbe8ad84af5778e7d6fcdbed70")) ; static const CCheckpointData data = { &mapCheckpoints, 1389963410, // * UNIX timestamp of last checkpoint block 12243, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 600.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x0d44ae9be7f13a64253c9b61dbbddc37304e1c359fd593565caf356e4fd597c7")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1393990003, 0, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { return 0; if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { return NULL; if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>#include "ksp_plugin/vessel_subsets.hpp" #include <list> #include "ksp_plugin/pile_up.hpp" namespace principia { using ksp_plugin::Vessel; using ksp_plugin::PileUp; namespace base { Subset<Vessel>::Properties::SubsetOfExistingPileUp::SubsetOfExistingPileUp( ContainerIterator<PileUps> pile_up) : pile_up_(pile_up) { missing_ = pile_up_.iterator->vessels().size() - 1; } Subset<Vessel>::Properties::Properties(not_null<ksp_plugin::Vessel*> vessel) { if (vessel->piled_up()) { subset_of_existing_pile_up_.emplace( SubsetOfExistingPileUp(*vessel->containing_pile_up())); } vessels_.emplace_back(vessel); } void Subset<ksp_plugin::Vessel>::Properties::Collect( not_null<PileUps*> pile_ups) { if (!collected_ && !(EqualsExistingPileUp())) { collected_ = true; pile_ups->emplace_front(std::move(vessels_)); auto const it = pile_ups->begin(); for (not_null<Vessel*> const vessel : it->vessels()) { vessel->set_containing_pile_up(ContainerIterator<PileUps>(pile_ups, it)); } } } bool Subset<ksp_plugin::Vessel>::Properties::SubsetsOfSamePileUp( Properties const& left, Properties const& right) { return left.subset_of_existing_pile_up_ && right.subset_of_existing_pile_up_ && left.subset_of_existing_pile_up_->pile_up_.iterator == right.subset_of_existing_pile_up_->pile_up_.iterator; } bool Subset<ksp_plugin::Vessel>::Properties::EqualsExistingPileUp() const { return subset_of_existing_pile_up_ && subset_of_existing_pile_up_->missing_ == 0; } bool Subset<ksp_plugin::Vessel>::Properties::StrictSubsetOfExistingPileUp() const { return subset_of_existing_pile_up_ && subset_of_existing_pile_up_->missing_ > 0; } void Subset<Vessel>::Properties::MergeWith(Properties& other) { if (SubsetsOfSamePileUp(*this, other)) { // The subsets |*this| and |other| are disjoint. CHECK_EQ(subset_of_existing_pile_up_->missing_ - other.vessels_.size(), other.subset_of_existing_pile_up_->missing_ - vessels_.size()); subset_of_existing_pile_up_->missing_ -= other.vessels_.size(); CHECK_GE(subset_of_existing_pile_up_->missing_, 0); } else { if (subset_of_existing_pile_up_) { subset_of_existing_pile_up_->pile_up_.Erase(); } if (other.subset_of_existing_pile_up_) { other.subset_of_existing_pile_up_->pile_up_.Erase(); } subset_of_existing_pile_up_ = std::experimental::nullopt; } vessels_.splice(vessels_.end(), other.vessels_); } template<> not_null<Subset<ksp_plugin::Vessel>::Node*> Subset<ksp_plugin::Vessel>::Node::Get(ksp_plugin::Vessel& element) { return element.subset_node_.get(); } } // namespace base } // namespace principia <commit_msg>const<commit_after>#include "ksp_plugin/vessel_subsets.hpp" #include <list> #include "ksp_plugin/pile_up.hpp" namespace principia { using ksp_plugin::Vessel; using ksp_plugin::PileUp; namespace base { Subset<Vessel>::Properties::SubsetOfExistingPileUp::SubsetOfExistingPileUp( ContainerIterator<PileUps> const pile_up) : pile_up_(pile_up) { missing_ = pile_up_.iterator->vessels().size() - 1; } Subset<Vessel>::Properties::Properties(not_null<ksp_plugin::Vessel*> vessel) { if (vessel->piled_up()) { subset_of_existing_pile_up_.emplace( SubsetOfExistingPileUp(*vessel->containing_pile_up())); } vessels_.emplace_back(vessel); } void Subset<ksp_plugin::Vessel>::Properties::Collect( not_null<PileUps*> const pile_ups) { if (!collected_ && !(EqualsExistingPileUp())) { collected_ = true; pile_ups->emplace_front(std::move(vessels_)); auto const it = pile_ups->begin(); for (not_null<Vessel*> const vessel : it->vessels()) { vessel->set_containing_pile_up(ContainerIterator<PileUps>(pile_ups, it)); } } } bool Subset<ksp_plugin::Vessel>::Properties::SubsetsOfSamePileUp( Properties const& left, Properties const& right) { return left.subset_of_existing_pile_up_ && right.subset_of_existing_pile_up_ && left.subset_of_existing_pile_up_->pile_up_.iterator == right.subset_of_existing_pile_up_->pile_up_.iterator; } bool Subset<ksp_plugin::Vessel>::Properties::EqualsExistingPileUp() const { return subset_of_existing_pile_up_ && subset_of_existing_pile_up_->missing_ == 0; } bool Subset<ksp_plugin::Vessel>::Properties::StrictSubsetOfExistingPileUp() const { return subset_of_existing_pile_up_ && subset_of_existing_pile_up_->missing_ > 0; } void Subset<Vessel>::Properties::MergeWith(Properties& other) { if (SubsetsOfSamePileUp(*this, other)) { // The subsets |*this| and |other| are disjoint. CHECK_EQ(subset_of_existing_pile_up_->missing_ - other.vessels_.size(), other.subset_of_existing_pile_up_->missing_ - vessels_.size()); subset_of_existing_pile_up_->missing_ -= other.vessels_.size(); CHECK_GE(subset_of_existing_pile_up_->missing_, 0); } else { if (subset_of_existing_pile_up_) { subset_of_existing_pile_up_->pile_up_.Erase(); } if (other.subset_of_existing_pile_up_) { other.subset_of_existing_pile_up_->pile_up_.Erase(); } subset_of_existing_pile_up_ = std::experimental::nullopt; } vessels_.splice(vessels_.end(), other.vessels_); } template<> not_null<Subset<ksp_plugin::Vessel>::Node*> Subset<ksp_plugin::Vessel>::Node::Get(ksp_plugin::Vessel& element) { return element.subset_node_.get(); } } // namespace base } // namespace principia <|endoftext|>
<commit_before>// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include "os/OsDefs.h" #include "mp/MpMisc.h" #include "mp/MpBuf.h" #include "mp/MprMixer.h" #ifndef ABS #define ABS(x) (max((x), -(x))) #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MprMixer::MprMixer(const UtlString& rName, int numWeights, int samplesPerFrame, int samplesPerSec) : MpAudioResource(rName, 1, numWeights, 1, 1, samplesPerFrame, samplesPerSec), mScale(0) { int i; mNumWeights = max(0, min(numWeights, MAX_MIXER_INPUTS)); for (i=0; i<numWeights; i++) mWeights[i] = 0; } // Destructor MprMixer::~MprMixer() { // no work to do } /* ============================ MANIPULATORS ============================== */ // Sets the weighting factors for the first "numWeights" inputs. // For now, this method always returns TRUE. UtlBoolean MprMixer::setWeights(int *newWeights, int numWeights) { int i; MpFlowGraphMsg msg(SET_WEIGHTS, this, NULL, NULL, numWeights); OsStatus res; int* weights; weights = new int[numWeights]; // allocate storage for the weights here. for (i=0; i < numWeights; i++) // the storage will be freed by weights[i] = newWeights[i]; // handleMessage() msg.setPtr1(weights); res = postMessage(msg); return res; } // Sets the weighting factor for the "weightIndex" input. // For now, this method always returns TRUE. UtlBoolean MprMixer::setWeight(int newWeight, int weightIndex) { MpFlowGraphMsg msg(SET_WEIGHT, this, NULL, NULL, newWeight, weightIndex); OsStatus res; res = postMessage(msg); return res; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean MprMixer::doProcessFrame(MpBufPtr inBufs[], MpBufPtr outBufs[], int inBufsSize, int outBufsSize, UtlBoolean isEnabled, int samplesPerFrame, int samplesPerSecond) { MpAudioBufPtr out; MpAudioSample* outstart; if (outBufsSize != 1) return FALSE; // Don't waste the time if output is not connected if (!isOutputConnected(0)) return TRUE; if (!isEnabled || (inBufsSize == 0)) { // Disabled, return first input outBufs[0] = inBufs[0]; inBufs[0].release(); return TRUE; } if (mScale == 0) { // scale factors are all zero, mute output return TRUE; } if (mScale == 1) { // must be only one weight != 0, and it is == 1 for (int i=0; i < inBufsSize; i++) { if (mWeights[i] != 0) { outBufs[0] = inBufs[i]; inBufs[i].release(); return TRUE; } } return TRUE; // even if we did not find it (mNWeights > inBufsSize) } // Get new buffer for our output out = MpMisc.RawAudioPool->getBuffer(); if (!out.isValid()) return FALSE; out->setSamplesNumber(samplesPerFrame); // Fill buffer with silence outstart = out->getSamples(); memset((char *) outstart, 0, samplesPerFrame * sizeof(MpAudioSample)); for (int i=0; i < inBufsSize; i++) { int wgt = mWeights[i]; if ((inBufs[i].isValid()) && (wgt != 0)) { MpAudioBufPtr in = inBufs[i]; MpAudioSample* output = outstart; MpAudioSample* input = in->getSamples(); int n = min(in->getSamplesNumber(), samplesPerFrame); if (wgt == 1) { for (i=0; i<n; i++) *output++ += (*input++) / mScale; } else { for (i=0; i<n; i++) *output++ += (*input++ * wgt) / mScale; } } } // push it downstream outBufs[0] = out; return TRUE; } // Handle messages for this resource. UtlBoolean MprMixer::handleMessage(MpFlowGraphMsg& rMsg) { UtlBoolean boolRes; int msgType; int* weights; msgType = rMsg.getMsg(); switch (msgType) { case SET_WEIGHT: return handleSetWeight(rMsg.getInt1(), rMsg.getInt2()); break; case SET_WEIGHTS: weights = (int*) rMsg.getPtr1(); boolRes = handleSetWeights(weights, rMsg.getInt1()); delete[] weights; // delete storage allocated in the setWeights() method return boolRes; break; default: return MpAudioResource::handleMessage(rMsg); break; } } // Handle the SET_WEIGHT message. UtlBoolean MprMixer::handleSetWeight(int newWeight, int weightIndex) { if (weightIndex < mNumWeights) { mScale -= ABS(mWeights[weightIndex]); mScale += ABS(newWeight); mWeights[weightIndex] = newWeight; } return TRUE; } // Handle the SET_WEIGHTS message. UtlBoolean MprMixer::handleSetWeights(int *newWeights, int numWeights) { int i; int wgt; mNumWeights = max(0, min(numWeights, MAX_MIXER_INPUTS)); mScale = 0; for (i=0; i < numWeights; i++) { mWeights[i] = wgt = newWeights[i]; mScale += ABS(wgt); } return TRUE; } /* ============================ FUNCTIONS ================================= */ <commit_msg>* MprMixer: set type of audio block after mix to UNKNOWN. There chould be VAD after mixer to detect real type. * Minor optimization: use MpBufPtr::swap() to exchange buffers.<commit_after>// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include "os/OsDefs.h" #include "mp/MpMisc.h" #include "mp/MpBuf.h" #include "mp/MprMixer.h" #ifndef ABS #define ABS(x) (max((x), -(x))) #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MprMixer::MprMixer(const UtlString& rName, int numWeights, int samplesPerFrame, int samplesPerSec) : MpAudioResource(rName, 1, numWeights, 1, 1, samplesPerFrame, samplesPerSec), mScale(0) { int i; mNumWeights = max(0, min(numWeights, MAX_MIXER_INPUTS)); for (i=0; i<numWeights; i++) mWeights[i] = 0; } // Destructor MprMixer::~MprMixer() { // no work to do } /* ============================ MANIPULATORS ============================== */ // Sets the weighting factors for the first "numWeights" inputs. // For now, this method always returns TRUE. UtlBoolean MprMixer::setWeights(int *newWeights, int numWeights) { int i; MpFlowGraphMsg msg(SET_WEIGHTS, this, NULL, NULL, numWeights); OsStatus res; int* weights; weights = new int[numWeights]; // allocate storage for the weights here. for (i=0; i < numWeights; i++) // the storage will be freed by weights[i] = newWeights[i]; // handleMessage() msg.setPtr1(weights); res = postMessage(msg); return res; } // Sets the weighting factor for the "weightIndex" input. // For now, this method always returns TRUE. UtlBoolean MprMixer::setWeight(int newWeight, int weightIndex) { MpFlowGraphMsg msg(SET_WEIGHT, this, NULL, NULL, newWeight, weightIndex); OsStatus res; res = postMessage(msg); return res; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean MprMixer::doProcessFrame(MpBufPtr inBufs[], MpBufPtr outBufs[], int inBufsSize, int outBufsSize, UtlBoolean isEnabled, int samplesPerFrame, int samplesPerSecond) { MpAudioBufPtr out; MpAudioSample* outstart; if (outBufsSize != 1) return FALSE; // Don't waste the time if output is not connected if (!isOutputConnected(0)) return TRUE; if (!isEnabled || (inBufsSize == 0)) { // Disabled, return first input outBufs[0].swap(inBufs[0]); return TRUE; } if (mScale == 0) { // scale factors are all zero, mute output return TRUE; } if (mScale == 1) { // must be only one weight != 0, and it is == 1 for (int i=0; i < inBufsSize; i++) { if (mWeights[i] != 0) { outBufs[0].swap(inBufs[i]); return TRUE; } } return TRUE; // even if we did not find it (mNWeights > inBufsSize) } // Get new buffer for our output out = MpMisc.RawAudioPool->getBuffer(); if (!out.isValid()) return FALSE; out->setSamplesNumber(samplesPerFrame); out->setSpeechType(MpAudioBuf::MP_SPEECH_UNKNOWN); // Fill buffer with silence outstart = out->getSamples(); memset((char *) outstart, 0, samplesPerFrame * sizeof(MpAudioSample)); for (int i=0; i < inBufsSize; i++) { int wgt = mWeights[i]; if ((inBufs[i].isValid()) && (wgt != 0)) { MpAudioBufPtr in = inBufs[i]; MpAudioSample* output = outstart; MpAudioSample* input = in->getSamples(); int n = min(in->getSamplesNumber(), samplesPerFrame); if (wgt == 1) { for (i=0; i<n; i++) *output++ += (*input++) / mScale; } else { for (i=0; i<n; i++) *output++ += (*input++ * wgt) / mScale; } } } // push it downstream outBufs[0].swap(out); return TRUE; } // Handle messages for this resource. UtlBoolean MprMixer::handleMessage(MpFlowGraphMsg& rMsg) { UtlBoolean boolRes; int msgType; int* weights; msgType = rMsg.getMsg(); switch (msgType) { case SET_WEIGHT: return handleSetWeight(rMsg.getInt1(), rMsg.getInt2()); break; case SET_WEIGHTS: weights = (int*) rMsg.getPtr1(); boolRes = handleSetWeights(weights, rMsg.getInt1()); delete[] weights; // delete storage allocated in the setWeights() method return boolRes; break; default: return MpAudioResource::handleMessage(rMsg); break; } } // Handle the SET_WEIGHT message. UtlBoolean MprMixer::handleSetWeight(int newWeight, int weightIndex) { if (weightIndex < mNumWeights) { mScale -= ABS(mWeights[weightIndex]); mScale += ABS(newWeight); mWeights[weightIndex] = newWeight; } return TRUE; } // Handle the SET_WEIGHTS message. UtlBoolean MprMixer::handleSetWeights(int *newWeights, int numWeights) { int i; int wgt; mNumWeights = max(0, min(numWeights, MAX_MIXER_INPUTS)); mScale = 0; for (i=0; i < numWeights; i++) { mWeights[i] = wgt = newWeights[i]; mScale += ABS(wgt); } return TRUE; } /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2013-2014 The Dogecoin developers // Copyright (c) 2014 The Inutoshi developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "main.h" #include "uint256.h" #include <stdint.h> #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64_t nTimeLastCheckpoint; int64_t nTransactionsLastCheckpoint; double fTransactionsPerDay; }; bool fEnabled = true; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x00000ebcecd9c5bec0311d97f997d09c887b6952123f1a492d417ed1e3e6282f")) ; static const CCheckpointData data = { &mapCheckpoints, 1411016405, // * UNIX timestamp of last checkpoint block 1, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 60*60*24*2+100 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x000003030c996912d1d5d0b47f41ab2316da31cea8e15b5c44226aaf76ab351f")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1411022846, 0, 300 }; static MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of ( 0, uint256("3d2160a3b5dc4a9d62e7e66a295f70313ac808440ef7400d6c0772171ce973a5")) ; static const CCheckpointData dataRegtest = { &mapCheckpointsRegtest, 0, 0, 0 }; const CCheckpointData &Checkpoints() { if (Params().NetworkID() == CChainParams::TESTNET) return dataTestnet; else if (Params().NetworkID() == CChainParams::MAIN) return data; else return dataRegtest; } bool CheckBlock(int nHeight, const uint256& hash) { if (!fEnabled) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64_t nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkpoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!fEnabled) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!fEnabled) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>add protective checkpoint at 4<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2013-2014 The Dogecoin developers // Copyright (c) 2014 The Inutoshi developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "main.h" #include "uint256.h" #include <stdint.h> #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64_t nTimeLastCheckpoint; int64_t nTransactionsLastCheckpoint; double fTransactionsPerDay; }; bool fEnabled = true; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x00000ebcecd9c5bec0311d97f997d09c887b6952123f1a492d417ed1e3e6282f")) ( 4, uint256("0x0000092cefcb9688e94cf4ca5f1ecbb1be83eb6d7f8f0c38a312adbfe21216ef")) ; static const CCheckpointData data = { &mapCheckpoints, 1411102688, // * UNIX timestamp of last checkpoint block 4, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 60*60*24*2+100 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x000003030c996912d1d5d0b47f41ab2316da31cea8e15b5c44226aaf76ab351f")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1411022846, 0, 300 }; static MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of ( 0, uint256("3d2160a3b5dc4a9d62e7e66a295f70313ac808440ef7400d6c0772171ce973a5")) ; static const CCheckpointData dataRegtest = { &mapCheckpointsRegtest, 0, 0, 0 }; const CCheckpointData &Checkpoints() { if (Params().NetworkID() == CChainParams::TESTNET) return dataTestnet; else if (Params().NetworkID() == CChainParams::MAIN) return data; else return dataRegtest; } bool CheckBlock(int nHeight, const uint256& hash) { if (!fEnabled) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64_t nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkpoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!fEnabled) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!fEnabled) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before><commit_msg>11001 - Necklace<commit_after><|endoftext|>
<commit_before>#include "Polynomial.h" Polynomial Polynomial::makeDerivative(size_t order) const { if (degree() <= order) return Polynomial(); auto cbegin = data().cbegin() + order; Polynomial d(data().cbegin()+order, data().cend()); for (size_t i = 0; i < d.degree()+1; i++) for(size_t j = 1; j <= order; j++) d[i] *= i + j; return d; } Polynomial::Solutions Polynomial::makeSolutions() const { Polynomial p(*this); p.normalize(); const auto& d = p.data(); if (p.degree() == 0) return Solutions(); if (p.degree() == 1) return Solutions({-d[0]/d[1]}); else if (p.degree() == 2) { Real det = d[1] * d[1] - 4. * d[2] * d[0]; if (det < 0.) return Solutions(); else if (det == 0.) { return Solutions({ -d[1] / (2.*d[2]) }); } else { Real det_root = sqrt(det); Real divisor = 2.*d[2]; return Solutions({ (-d[1] - det_root) / divisor, (-d[1] + det_root) / divisor }); } } else if (p.degree() == 3) { throw (std::domain_error("TODO: implement cubic solutions")); } else { throw(std::domain_error("Solutions to quartic and higher polynomials are not implemented")); } } PolynomialAugmented::PolynomialAugmented(const Polynomial & p): mPolynomial(p), mDerivative(p.makeDerivative()), mExtrema(makeExtrema()) { } const Polynomial & PolynomialAugmented::polynomial() const { return mPolynomial; } const Polynomial & PolynomialAugmented::derivative() const { return mDerivative; } const PolynomialAugmented::Extrema & PolynomialAugmented::extrema() const { return mExtrema; } Interval PolynomialAugmented::makeRange(const Interval & domain) const { return makeRange(domain, mExtrema); } Interval PolynomialAugmented::makeRange(const Interval & domain, const Extrema & restricted_extrema) const { Real min = mPolynomial.evaluate(domain.a); Real max = min; min = std::min(min, mPolynomial.evaluate(domain.b)); max = std::max(max, mPolynomial.evaluate(domain.b)); for (auto it : restricted_extrema) { if (domain.contains(it.first)) { min = std::min(min, it.second); max = std::max(max, it.second); } } return Interval(min, max); } PolynomialAugmented::Extrema PolynomialAugmented::makeExtrema() const { Extrema e; for (auto sol : mDerivative.makeSolutions()) { e.push_back({ sol, mPolynomial.evaluate(sol) }); } return e; } <commit_msg>Just use clipping for both purposes<commit_after>#include "Polynomial.h" Polynomial Polynomial::makeDerivative(size_t order) const { if (degree() <= order) return Polynomial(); auto cbegin = data().cbegin() + order; Polynomial d(data().cbegin()+order, data().cend()); for (size_t i = 0; i < d.degree()+1; i++) for(size_t j = 1; j <= order; j++) d[i] *= i + j; return d; } Polynomial::Solutions Polynomial::makeSolutions() const { Polynomial p(*this); p.normalize(); const auto& d = p.data(); if (p.degree() == 0) return Solutions(); if (p.degree() == 1) return Solutions({-d[0]/d[1]}); else if (p.degree() == 2) { Real det = d[1] * d[1] - 4. * d[2] * d[0]; if (det < 0.) return Solutions(); else if (det == 0.) { return Solutions({ -d[1] / (2.*d[2]) }); } else { Real det_root = sqrt(det); Real divisor = 2.*d[2]; return Solutions({ (-d[1] - det_root) / divisor, (-d[1] + det_root) / divisor }); } } else { throw(std::domain_error("Solutions to cubic and higher polynomials are not implemented")); } } PolynomialAugmented::PolynomialAugmented(const Polynomial & p): mPolynomial(p), mDerivative(p.makeDerivative()), mExtrema(makeExtrema()) { } const Polynomial & PolynomialAugmented::polynomial() const { return mPolynomial; } const Polynomial & PolynomialAugmented::derivative() const { return mDerivative; } const PolynomialAugmented::Extrema & PolynomialAugmented::extrema() const { return mExtrema; } Interval PolynomialAugmented::makeRange(const Interval & domain) const { return makeRange(domain, mExtrema); } Interval PolynomialAugmented::makeRange(const Interval & domain, const Extrema & restricted_extrema) const { Real min = mPolynomial.evaluate(domain.a); Real max = min; min = std::min(min, mPolynomial.evaluate(domain.b)); max = std::max(max, mPolynomial.evaluate(domain.b)); for (auto it : restricted_extrema) { if (domain.contains(it.first)) { min = std::min(min, it.second); max = std::max(max, it.second); } } return Interval(min, max); } PolynomialAugmented::Extrema PolynomialAugmented::makeExtrema() const { Extrema e; for (auto sol : mDerivative.makeSolutions()) { e.push_back({ sol, mPolynomial.evaluate(sol) }); } return e; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // *** Modern C++ Wrappers Around Windows Registry C API *** // // Copyright (C) by Giovanni Dicanio // // =========================================================================== // FILE: WinReg.cpp // DESC: Non-inline method implementations for the WinReg wrapper. // =========================================================================== // // The MIT License(MIT) // // Copyright(c) 2020 by Giovanni Dicanio // // 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 "WinReg.hpp" // Public header #include <memory> // std::unique_ptr //------------------------------------------------------------------------------ // Module-Private Helper Functions //------------------------------------------------------------------------------ namespace { // Helper function to build a multi-string from a vector<wstring> static std::vector<wchar_t> BuildMultiString(const std::vector<std::wstring>& data) { // Special case of the empty multi-string if (data.empty()) { // Build a vector containing just two NULs return std::vector<wchar_t>(2, L'\0'); } // Get the total length in wchar_ts of the multi-string size_t totalLen = 0; for (const auto& s : data) { // Add one to current string's length for the terminating NUL totalLen += (s.length() + 1); } // Add one for the last NUL terminator (making the whole structure double-NUL terminated) totalLen++; // Allocate a buffer to store the multi-string std::vector<wchar_t> multiString; multiString.reserve(totalLen); // Copy the single strings into the multi-string for (const auto& s : data) { multiString.insert(multiString.end(), s.begin(), s.end()); // Don't forget to NUL-terminate the current string multiString.push_back(L'\0'); } // Add the last NUL-terminator multiString.push_back(L'\0'); return multiString; } } // namespace //------------------------------------------------------------------------------ // RegKey Non-Inline Method Implementations //------------------------------------------------------------------------------ namespace winreg { void RegKey::Create( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess, const DWORD options, SECURITY_ATTRIBUTES* const securityAttributes, DWORD* const disposition ) { HKEY hKey = nullptr; LONG retCode = ::RegCreateKeyExW( hKeyParent, subKey.c_str(), 0, // reserved REG_NONE, // user-defined class type parameter not supported options, desiredAccess, securityAttributes, &hKey, disposition ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "RegCreateKeyEx failed." ); } // Safely close any previously opened key Close(); // Take ownership of the newly created key m_hKey = hKey; } RegResult RegKey::TryCreate( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess, const DWORD options, SECURITY_ATTRIBUTES* const securityAttributes, DWORD* const disposition ) noexcept { HKEY hKey = nullptr; RegResult retCode = ::RegCreateKeyExW( hKeyParent, subKey.c_str(), 0, // reserved REG_NONE, // user-defined class type parameter not supported options, desiredAccess, securityAttributes, &hKey, disposition ); if (retCode.Failed()) { return retCode; } // Safely close any previously opened key Close(); // Take ownership of the newly created key m_hKey = hKey; _ASSERTE(retCode.IsOk()); return retCode; } void RegKey::Open( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess ) { HKEY hKey = nullptr; LONG retCode = ::RegOpenKeyExW( hKeyParent, subKey.c_str(), REG_NONE, // default options desiredAccess, &hKey ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "RegOpenKeyEx failed."); } // Safely close any previously opened key Close(); // Take ownership of the newly created key m_hKey = hKey; } RegResult RegKey::TryOpen( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess ) noexcept { HKEY hKey = nullptr; RegResult retCode = ::RegOpenKeyExW( hKeyParent, subKey.c_str(), REG_NONE, // default options desiredAccess, &hKey ); if (retCode.Failed()) { return retCode; } // Safely close any previously opened key Close(); // Take ownership of the newly created key m_hKey = hKey; _ASSERTE(retCode.IsOk()); return retCode; } void RegKey::SetMultiStringValue( const std::wstring& valueName, const std::vector<std::wstring>& data ) { _ASSERTE(IsValid()); // First, we have to build a double-NUL-terminated multi-string from the input data const std::vector<wchar_t> multiString = BuildMultiString(data); // Total size, in bytes, of the whole multi-string structure const DWORD dataSize = static_cast<DWORD>(multiString.size() * sizeof(wchar_t)); LONG retCode = ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_MULTI_SZ, reinterpret_cast<const BYTE*>(&multiString[0]), dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot write multi-string value: RegSetValueEx failed."); } } RegResult RegKey::TrySetMultiStringValue( const std::wstring& valueName, const std::vector<std::wstring>& data ) // Can't be noexcept! { // // NOTE: // This method can't be marked noexcept, because it calls details::BuildMultiString(), // which allocates dynamic memory for the resulting std::vector<wchar_t>. // _ASSERTE(IsValid()); // First, we have to build a double-NUL-terminated multi-string from the input data const std::vector<wchar_t> multiString = BuildMultiString(data); // Total size, in bytes, of the whole multi-string structure const DWORD dataSize = static_cast<DWORD>(multiString.size() * sizeof(wchar_t)); return ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_MULTI_SZ, reinterpret_cast<const BYTE*>(&multiString[0]), dataSize ); } std::wstring RegKey::GetStringValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); // Get the size of the result string DWORD dataSize = 0; // size of data, in bytes const DWORD flags = RRF_RT_REG_SZ; LONG retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot get size of string value: RegGetValue failed."); } // Allocate a string of proper size. // Note that dataSize is in bytes and includes the terminating NUL; // we have to convert the size from bytes to wchar_ts for wstring::resize. std::wstring result; result.resize(dataSize / sizeof(wchar_t)); // Call RegGetValue for the second time to read the string's content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &result[0], // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot get string value: RegGetValue failed."); } // Remove the NUL terminator scribbled by RegGetValue from the wstring result.resize((dataSize / sizeof(wchar_t)) - 1); return result; } std::wstring RegKey::GetExpandStringValue( const std::wstring& valueName, const ExpandStringOption expandOption ) const { _ASSERTE(IsValid()); DWORD flags = RRF_RT_REG_EXPAND_SZ; // Adjust the flag for RegGetValue considering the expand string option specified by the caller if (expandOption == ExpandStringOption::DontExpand) { flags |= RRF_NOEXPAND; } // Get the size of the result string DWORD dataSize = 0; // size of data, in bytes LONG retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot get size of expand string value: RegGetValue failed."); } // Allocate a string of proper size. // Note that dataSize is in bytes and includes the terminating NUL. // We must convert from bytes to wchar_ts for wstring::resize. std::wstring result; result.resize(dataSize / sizeof(wchar_t)); // Call RegGetValue for the second time to read the string's content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &result[0], // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot get expand string value: RegGetValue failed."); } // Remove the NUL terminator scribbled by RegGetValue from the wstring result.resize((dataSize / sizeof(wchar_t)) - 1); return result; } std::vector<std::wstring> RegKey::GetMultiStringValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); // Request the size of the multi-string, in bytes DWORD dataSize = 0; const DWORD flags = RRF_RT_REG_MULTI_SZ; LONG retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot get size of multi-string value: RegGetValue failed."); } // Allocate room for the result multi-string. // Note that dataSize is in bytes, but our vector<wchar_t>::resize method requires size // to be expressed in wchar_ts. std::vector<wchar_t> data; data.resize(dataSize / sizeof(wchar_t)); // Read the multi-string from the registry into the vector object retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // no type required &data[0], // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot get multi-string value: RegGetValue failed."); } // Resize vector to the actual size returned by GetRegValue. // Note that the vector is a vector of wchar_ts, instead the size returned by GetRegValue // is in bytes, so we have to scale from bytes to wchar_t count. data.resize(dataSize / sizeof(wchar_t)); // Parse the double-NUL-terminated string into a vector<wstring>, // which will be returned to the caller std::vector<std::wstring> result; const wchar_t* currStringPtr = &data[0]; while (*currStringPtr != L'\0') { // Current string is NUL-terminated, so get its length calling wcslen const size_t currStringLength = wcslen(currStringPtr); // Add current string to the result vector result.push_back(std::wstring(currStringPtr, currStringLength)); // Move to the next string currStringPtr += currStringLength + 1; } return result; } std::vector<BYTE> RegKey::GetBinaryValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); // Get the size of the binary data DWORD dataSize = 0; // size of data, in bytes const DWORD flags = RRF_RT_REG_BINARY; LONG retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot get size of binary data: RegGetValue failed."); } // Allocate a buffer of proper size to store the binary data std::vector<BYTE> data(dataSize); // Call RegGetValue for the second time to read the data content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &data[0], // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot get binary data: RegGetValue failed."); } return data; } RegResult RegKey::TryGetStringValue(const std::wstring& valueName, std::wstring& result) const { _ASSERTE(IsValid()); result.clear(); // Get the size of the result string DWORD dataSize = 0; // size of data, in bytes const DWORD flags = RRF_RT_REG_SZ; RegResult retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode.Failed()) { _ASSERTE(result.empty()); return retCode; } // Allocate a string of proper size. // Note that dataSize is in bytes and includes the terminating NUL; // we have to convert the size from bytes to wchar_ts for wstring::resize. result.resize(dataSize / sizeof(wchar_t)); // Call RegGetValue for the second time to read the string's content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &result[0], // output buffer &dataSize ); if (retCode.Failed()) { result.clear(); return retCode; } // Remove the NUL terminator scribbled by RegGetValue from the wstring result.resize((dataSize / sizeof(wchar_t)) - 1); _ASSERTE(retCode.IsOk()); return retCode; } RegResult RegKey::TryGetExpandStringValue( const std::wstring& valueName, std::wstring& result, const ExpandStringOption expandOption ) const { _ASSERTE(IsValid()); result.clear(); DWORD flags = RRF_RT_REG_EXPAND_SZ; // Adjust the flag for RegGetValue considering the expand string option specified by the caller if (expandOption == ExpandStringOption::DontExpand) { flags |= RRF_NOEXPAND; } // Get the size of the result string DWORD dataSize = 0; // size of data, in bytes RegResult retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode.Failed()) { _ASSERTE(result.empty()); return retCode; } // Allocate a string of proper size. // Note that dataSize is in bytes and includes the terminating NUL. // We must convert from bytes to wchar_ts for wstring::resize. result.resize(dataSize / sizeof(wchar_t)); // Call RegGetValue for the second time to read the string's content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &result[0], // output buffer &dataSize ); if (retCode.Failed()) { result.clear(); return retCode; } // Remove the NUL terminator scribbled by RegGetValue from the wstring result.resize((dataSize / sizeof(wchar_t)) - 1); _ASSERTE(retCode.IsOk()); return retCode; } RegResult RegKey::TryGetMultiStringValue(const std::wstring& valueName, std::vector<std::wstring>& result) const { _ASSERTE(IsValid()); result.clear(); // Request the size of the multi-string, in bytes DWORD dataSize = 0; const DWORD flags = RRF_RT_REG_MULTI_SZ; RegResult retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode.Failed()) { _ASSERTE(result.empty()); return retCode; } // Allocate room for the result multi-string. // Note that dataSize is in bytes, but our vector<wchar_t>::resize method requires size // to be expressed in wchar_ts. std::vector<wchar_t> data; data.resize(dataSize / sizeof(wchar_t)); // Read the multi-string from the registry into the vector object retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // no type required &data[0], // output buffer &dataSize ); if (retCode.Failed()) { _ASSERTE(result.empty()); return retCode; } // Resize vector to the actual size returned by GetRegValue. // Note that the vector is a vector of wchar_ts, instead the size returned by GetRegValue // is in bytes, so we have to scale from bytes to wchar_t count. data.resize(dataSize / sizeof(wchar_t)); // Parse the double-NUL-terminated string into a vector<wstring>, // which will be returned to the caller _ASSERTE(result.empty()); const wchar_t* currStringPtr = &data[0]; while (*currStringPtr != L'\0') { // Current string is NUL-terminated, so get its length calling wcslen const size_t currStringLength = wcslen(currStringPtr); // Add current string to the result vector result.push_back(std::wstring(currStringPtr, currStringLength)); // Move to the next string currStringPtr += currStringLength + 1; } _ASSERTE(retCode.IsOk()); return retCode; } RegResult RegKey::TryGetBinaryValue(const std::wstring& valueName, std::vector<BYTE>& result) const { _ASSERTE(IsValid()); result.clear(); // Get the size of the binary data DWORD dataSize = 0; // size of data, in bytes const DWORD flags = RRF_RT_REG_BINARY; RegResult retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode.Failed()) { _ASSERTE(result.empty()); return retCode; } // Allocate a buffer of proper size to store the binary data result.resize(dataSize); // Call RegGetValue for the second time to read the data content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &result[0], // output buffer &dataSize ); if (retCode.Failed()) { result.clear(); return retCode; } _ASSERTE(retCode.IsOk()); return retCode; } std::vector<std::wstring> RegKey::EnumSubKeys() const { _ASSERTE(IsValid()); // Get some useful enumeration info, like the total number of subkeys // and the maximum length of the subkey names DWORD subKeyCount{}; DWORD maxSubKeyNameLen{}; LONG retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, // no user-defined class nullptr, // no user-defined class size nullptr, // reserved &subKeyCount, &maxSubKeyNameLen, nullptr, // no subkey class length nullptr, // no value count nullptr, // no value name max length nullptr, // no max value length nullptr, // no security descriptor nullptr // no last write time ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "RegQueryInfoKey failed while preparing for subkey enumeration." ); } // NOTE: According to the MSDN documentation, the size returned for subkey name max length // does *not* include the terminating NUL, so let's add +1 to take it into account // when I allocate the buffer for reading subkey names. maxSubKeyNameLen++; // Preallocate a buffer for the subkey names auto nameBuffer = std::make_unique<wchar_t[]>(maxSubKeyNameLen); // The result subkey names will be stored here std::vector<std::wstring> subkeyNames; // Enumerate all the subkeys for (DWORD index = 0; index < subKeyCount; index++) { // Get the name of the current subkey DWORD subKeyNameLen = maxSubKeyNameLen; retCode = ::RegEnumKeyExW( m_hKey, index, nameBuffer.get(), &subKeyNameLen, nullptr, // reserved nullptr, // no class nullptr, // no class nullptr // no last write time ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot enumerate subkeys: RegEnumKeyEx failed."); } // On success, the ::RegEnumKeyEx API writes the length of the // subkey name in the subKeyNameLen output parameter // (not including the terminating NUL). // So I can build a wstring based on that length. subkeyNames.push_back(std::wstring(nameBuffer.get(), subKeyNameLen)); } return subkeyNames; } std::vector<std::pair<std::wstring, DWORD>> RegKey::EnumValues() const { _ASSERTE(IsValid()); // Get useful enumeration info, like the total number of values // and the maximum length of the value names DWORD valueCount{}; DWORD maxValueNameLen{}; LONG retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, // no user-defined class nullptr, // no user-defined class size nullptr, // reserved nullptr, // no subkey count nullptr, // no subkey max length nullptr, // no subkey class length &valueCount, &maxValueNameLen, nullptr, // no max value length nullptr, // no security descriptor nullptr // no last write time ); if (retCode != ERROR_SUCCESS) { throw RegException( retCode, "RegQueryInfoKey failed while preparing for value enumeration." ); } // NOTE: According to the MSDN documentation, the size returned for value name max length // does *not* include the terminating NUL, so let's add +1 to take it into account // when I allocate the buffer for reading value names. maxValueNameLen++; // Preallocate a buffer for the value names auto nameBuffer = std::make_unique<wchar_t[]>(maxValueNameLen); // The value names and types will be stored here std::vector<std::pair<std::wstring, DWORD>> valueInfo; // Enumerate all the values for (DWORD index = 0; index < valueCount; index++) { // Get the name and the type of the current value DWORD valueNameLen = maxValueNameLen; DWORD valueType{}; retCode = ::RegEnumValueW( m_hKey, index, nameBuffer.get(), &valueNameLen, nullptr, // reserved &valueType, nullptr, // no data nullptr // no data size ); if (retCode != ERROR_SUCCESS) { throw RegException(retCode, "Cannot enumerate values: RegEnumValue failed."); } // On success, the RegEnumValue API writes the length of the // value name in the valueNameLen output parameter // (not including the terminating NUL). // So we can build a wstring based on that. valueInfo.push_back( std::make_pair(std::wstring(nameBuffer.get(), valueNameLen), valueType) ); } return valueInfo; } RegResult RegKey::TryEnumSubKeys(std::vector<std::wstring>& subKeys) const { subKeys.clear(); _ASSERTE(IsValid()); // Get some useful enumeration info, like the total number of subkeys // and the maximum length of the subkey names DWORD subKeyCount{}; DWORD maxSubKeyNameLen{}; RegResult retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, // no user-defined class nullptr, // no user-defined class size nullptr, // reserved &subKeyCount, &maxSubKeyNameLen, nullptr, // no subkey class length nullptr, // no value count nullptr, // no value name max length nullptr, // no max value length nullptr, // no security descriptor nullptr // no last write time ); if (retCode.Failed()) { return retCode; } // NOTE: According to the MSDN documentation, the size returned for subkey name max length // does *not* include the terminating NUL, so let's add +1 to take it into account // when I allocate the buffer for reading subkey names. maxSubKeyNameLen++; // Preallocate a buffer for the subkey names auto nameBuffer = std::make_unique<wchar_t[]>(maxSubKeyNameLen); // Should have been cleared at the beginning of the method _ASSERTE(subKeys.empty()); // Enumerate all the subkeys for (DWORD index = 0; index < subKeyCount; index++) { // Get the name of the current subkey DWORD subKeyNameLen = maxSubKeyNameLen; retCode = ::RegEnumKeyExW( m_hKey, index, nameBuffer.get(), &subKeyNameLen, nullptr, // reserved nullptr, // no class nullptr, // no class nullptr // no last write time ); if (retCode.Failed()) { subKeys.clear(); return retCode; } // On success, the ::RegEnumKeyEx API writes the length of the // subkey name in the subKeyNameLen output parameter // (not including the terminating NUL). // So I can build a wstring based on that length. subKeys.push_back(std::wstring(nameBuffer.get(), subKeyNameLen)); } return ERROR_SUCCESS; } RegResult RegKey::TryEnumValues(std::vector<std::pair<std::wstring, DWORD>>& values) const { values.clear(); _ASSERTE(IsValid()); // Get useful enumeration info, like the total number of values // and the maximum length of the value names DWORD valueCount{}; DWORD maxValueNameLen{}; RegResult retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, // no user-defined class nullptr, // no user-defined class size nullptr, // reserved nullptr, // no subkey count nullptr, // no subkey max length nullptr, // no subkey class length &valueCount, &maxValueNameLen, nullptr, // no max value length nullptr, // no security descriptor nullptr // no last write time ); if (retCode.Failed()) { return retCode; } // NOTE: According to the MSDN documentation, the size returned for value name max length // does *not* include the terminating NUL, so let's add +1 to take it into account // when I allocate the buffer for reading value names. maxValueNameLen++; // Preallocate a buffer for the value names auto nameBuffer = std::make_unique<wchar_t[]>(maxValueNameLen); // Should have been cleared at the beginning of the method _ASSERTE(values.empty()); // Enumerate all the values for (DWORD index = 0; index < valueCount; index++) { // Get the name and the type of the current value DWORD valueNameLen = maxValueNameLen; DWORD valueType{}; retCode = ::RegEnumValueW( m_hKey, index, nameBuffer.get(), &valueNameLen, nullptr, // reserved &valueType, nullptr, // no data nullptr // no data size ); if (retCode.Failed()) { values.clear(); return retCode; } // On success, the RegEnumValue API writes the length of the // value name in the valueNameLen output parameter // (not including the terminating NUL). // So we can build a wstring based on that. values.push_back( std::make_pair(std::wstring(nameBuffer.get(), valueNameLen), valueType) ); } return ERROR_SUCCESS; } RegResult RegKey::TryConnectRegistry(const std::wstring& machineName, HKEY hKeyPredefined) noexcept { // Safely close any previously opened key Close(); HKEY hKeyResult = nullptr; RegResult retCode = ::RegConnectRegistryW(machineName.c_str(), hKeyPredefined, &hKeyResult); if (retCode.Failed()) { return retCode; } // Take ownership of the result key m_hKey = hKeyResult; _ASSERTE(retCode.IsOk()); return retCode; } } // namespace winreg <commit_msg>Delete WinReg.cpp<commit_after><|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2003 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _WIN32 #define strcasecmp _stricmp #endif #include <math.h> #include "common.h" #include "Team.h" #include "Flag.h" #include "Pack.h" std::map<std::string, FlagDesc*> FlagDesc::flagMap; int FlagDesc::flagCount = 0; FlagSet FlagDesc::flagSets[NumQualities]; // Initialize flag description singletons in our Flags namespace namespace Flags { FlagDesc *Null = new FlagDesc( "", "", FlagNormal, NormalShot, FlagGood, NoTeam, NULL ); FlagDesc *RedTeam = new FlagDesc( "Red Team", "R*", FlagNormal, NormalShot, FlagGood, ::RedTeam, "Team flag: If it's yours, prevent other teams from taking it. If it's not take it to your base to capture it!" ); FlagDesc *GreenTeam = new FlagDesc( "Green Team", "G*", FlagNormal, NormalShot, FlagGood, ::GreenTeam, "Team flag: If it's yours, prevent other teams from taking it. If it's not take it to your base to capture it!" ); FlagDesc *BlueTeam = new FlagDesc( "Blue Team", "B*", FlagNormal, NormalShot, FlagGood, ::BlueTeam, "Team flag: If it's yours, prevent other teams from taking it. If it's not take it to your base to capture it!" ); FlagDesc *PurpleTeam = new FlagDesc( "Purple Team", "P*", FlagNormal, NormalShot, FlagGood, ::PurpleTeam, "Team flag: If it's yours, prevent other teams from taking it. If it's not take it to your base to capture it!" ); FlagDesc *HighSpeed = new FlagDesc( "High Speed", "V", FlagUnstable, NormalShot, FlagGood, NoTeam, "Velocity (+V): Tank moves faster. Outrun bad guys." ); FlagDesc *QuickTurn = new FlagDesc( "Quick Turn", "A", FlagUnstable, NormalShot, FlagGood, NoTeam, "Angular velocity (+A): Tank turns faster. Dodge quicker." ); FlagDesc *OscillationOverthruster = new FlagDesc( "Oscillation Overthruster", "OO", FlagUnstable, NormalShot, FlagGood, NoTeam, "Oscillation Overthruster (+OO): Can drive through buildings. Can't backup or shoot while inside." ); FlagDesc *RapidFire = new FlagDesc( "Rapid Fire", "F", FlagUnstable, SpecialShot, FlagGood, NoTeam, "rapid Fire (+F): Shoots more often. Shells go faster but not as far." ); FlagDesc *MachineGun = new FlagDesc( "Machine Gun", "MG", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Machine Gun (+MG): Very fast reload and very short range." ); FlagDesc *GuidedMissle = new FlagDesc( "Guided Missile", "GM", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Guided Missile (+GM): Shots track a target. Lock on with right button. Can lock on or retarget after firing." ); FlagDesc *Laser = new FlagDesc( "Laser", "L", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Laser (+L): Shoots a laser. Infinite speed and range but long reload time."); FlagDesc *Ricochet = new FlagDesc( "Ricochet", "R", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Ricochet (+R): Shots bounce off walls. Don't shoot yourself!" ); FlagDesc *SuperBullet = new FlagDesc( "Super Bullet", "SB", FlagUnstable, SpecialShot, FlagGood, NoTeam, "SuperBullet (+SB): Shoots through buildings. Can kill Phantom Zone." ); FlagDesc *InvisibleBullet = new FlagDesc( "Invisible Bullet", "IB", FlagUnstable, NormalShot, FlagGood, NoTeam, "Invisible Bullet (+IB): Your shots don't appear on other radars. Can still see them out window."); FlagDesc *Stealth = new FlagDesc( "Stealth", "ST", FlagUnstable, NormalShot, FlagGood, NoTeam, "STealth (+ST): Tank is invisible on radar. Shots are still visible. Sneak up behind enemies!"); FlagDesc *Tiny = new FlagDesc( "Tiny", "T", FlagUnstable, NormalShot, FlagGood, NoTeam, "Tiny (+T): Tank is small and can get through small openings. Very hard to hit." ); FlagDesc *Narrow = new FlagDesc( "Narrow", "N", FlagUnstable, NormalShot, FlagGood, NoTeam, "Narrow (+N): Tank is super thin. Very hard to hit from front but is normal size from side. Can get through small openings."); FlagDesc *Shield = new FlagDesc( "Shield", "SH", FlagUnstable, NormalShot, FlagGood, NoTeam, "SHield (+SH): Getting hit only drops flag. Flag flies an extra-long time."); FlagDesc *Steamroller = new FlagDesc( "Steamroller", "SR", FlagUnstable, NormalShot, FlagGood, NoTeam, "SteamRoller (+SR): Destroys tanks you touch but you have to get really close."); FlagDesc *ShockWave = new FlagDesc( "Shock Wave", "SW", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Shock Wave (+SW): Firing destroys all tanks nearby. Don't kill teammates! Can kill tanks on/in buildings."); FlagDesc *PhantomZone = new FlagDesc( "Phantom Zone", "PZ", FlagUnstable, NormalShot, FlagGood, NoTeam, "Phantom Zone (+PZ): Teleporting toggles Zoned effect. Zoned tank can drive through buildings. Zoned tank can't shoot or be shot (except by superbullet and shock wave)."); FlagDesc *Genocide = new FlagDesc( "Genocide", "G", FlagUnstable, NormalShot, FlagGood, NoTeam, "Genocide (+G): Killing one tank kills that tank's whole team."); FlagDesc *Jumping = new FlagDesc( "Jumping", "JP", FlagUnstable, NormalShot, FlagGood, NoTeam, "JumPing (+JP): Tank can jump. Use Tab key. Can't steer in the air."); FlagDesc *Identify = new FlagDesc( "Identify", "ID", FlagUnstable, NormalShot, FlagGood, NoTeam, "IDentify (+ID): Identifies type of nearest flag."); FlagDesc *Cloaking = new FlagDesc( "Cloaking", "CL", FlagUnstable, NormalShot, FlagGood, NoTeam, "CLoaking (+CL): Makes your tank invisible out-the-window. Still visible on radar."); FlagDesc *Useless = new FlagDesc( "Useless", "US", FlagUnstable, NormalShot, FlagGood, NoTeam, "USeless (+US): You have found the useless flag. Use it wisely."); FlagDesc *Masquerade = new FlagDesc( "Masquerade", "MQ", FlagUnstable, NormalShot, FlagGood, NoTeam, "MasQuerade (+MQ): In opponent's hud, you appear as a teammate."); FlagDesc *Seer = new FlagDesc( "Seer", "SE", FlagUnstable, NormalShot, FlagGood, NoTeam, "SEer (+SE): See stealthed, cloaked and masquerading tanks as normal."); FlagDesc *Colorblindness = new FlagDesc( "Colorblindness", "CB", FlagSticky, NormalShot, FlagBad, NoTeam, "ColorBlindness (-CB): Can't tell team colors. Don't shoot teammates!"); FlagDesc *Obesity = new FlagDesc( "Obesity", "O", FlagSticky, NormalShot, FlagBad, NoTeam, "Obesity (-O): Tank becomes very large. Can't fit through teleporters."); FlagDesc *LeftTurnOnly = new FlagDesc( "Left Turn Only", "<-", FlagSticky, NormalShot, FlagBad, NoTeam, "left turn only (- <-): Can't turn right."); FlagDesc *RightTurnOnly = new FlagDesc( "Right Turn Only", "->", FlagSticky, NormalShot, FlagBad, NoTeam, "right turn only (- ->): Can't turn left."); FlagDesc *Momentum = new FlagDesc( "Momentum", "M", FlagSticky, NormalShot, FlagBad, NoTeam, "Momentum (-M): Tank has inertia. Acceleration is limited."); FlagDesc *Blindness = new FlagDesc( "Blindness", "B", FlagSticky, NormalShot, FlagBad, NoTeam, "Blindness (-B): Can't see out window. Radar still works."); FlagDesc *Jamming = new FlagDesc( "Jamming", "JM", FlagSticky, NormalShot, FlagBad, NoTeam, "JaMming (-JM): Radar doesn't work. Can still see."); FlagDesc *WideAngle = new FlagDesc( "Wide Angle", "WA", FlagSticky, NormalShot, FlagBad, NoTeam, "Wide Angle (-WA): Fish-eye lens distorts view."); } void* FlagDesc::pack(void* buf) const { buf = nboPackUByte(buf, flagAbbv[0]); buf = nboPackUByte(buf, flagAbbv[1]); return buf; } void* FlagDesc::unpack(void* buf, FlagDesc* &desc) { unsigned char abbv[3] = {0,0,0}; buf = nboUnpackUByte(buf, abbv[0]); buf = nboUnpackUByte(buf, abbv[1]); desc = Flag::getDescFromAbbreviation((const char *)abbv); return buf; } void* Flag::pack(void* buf) const { buf = desc->pack(buf); buf = nboPackUShort(buf, uint16_t(status)); buf = nboPackUShort(buf, uint16_t(type)); buf = nboPackUByte(buf, owner); buf = nboPackVector(buf, position); buf = nboPackVector(buf, launchPosition); buf = nboPackVector(buf, landingPosition); buf = nboPackFloat(buf, flightTime); buf = nboPackFloat(buf, flightEnd); buf = nboPackFloat(buf, initialVelocity); return buf; } void* Flag::unpack(void* buf) { uint16_t data; buf = FlagDesc::unpack(buf, desc); buf = nboUnpackUShort(buf, data); status = FlagStatus(data); buf = nboUnpackUShort(buf, data); type = FlagType(data); buf = nboUnpackUByte(buf, owner); buf = nboUnpackVector(buf, position); buf = nboUnpackVector(buf, launchPosition); buf = nboUnpackVector(buf, landingPosition); buf = nboUnpackFloat(buf, flightTime); buf = nboUnpackFloat(buf, flightEnd); buf = nboUnpackFloat(buf, initialVelocity); return buf; } FlagDesc* Flag::getDescFromAbbreviation(const char* abbreviation) { std::map<std::string, FlagDesc*>::iterator i; i = FlagDesc::flagMap.find(abbreviation); if (i == FlagDesc::flagMap.end()) return Flags::Null; else return i->second; } FlagSet& Flag::getGoodFlags() { return FlagDesc::flagSets[FlagGood]; } FlagSet& Flag::getBadFlags() { return FlagDesc::flagSets[FlagBad]; } const float* FlagDesc::getColor() { static const float superColor[3] = { 1.0, 1.0, 1.0 }; if (flagTeam == NoTeam) return superColor; else return Team::getTankColor(flagTeam); } // ex: shiftwidth=2 tabstop=8 <commit_msg>Realphanumericalize left and right turn only abbreviations<commit_after>/* bzflag * Copyright (c) 1993 - 2003 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _WIN32 #define strcasecmp _stricmp #endif #include <math.h> #include "common.h" #include "Team.h" #include "Flag.h" #include "Pack.h" std::map<std::string, FlagDesc*> FlagDesc::flagMap; int FlagDesc::flagCount = 0; FlagSet FlagDesc::flagSets[NumQualities]; // Initialize flag description singletons in our Flags namespace namespace Flags { FlagDesc *Null = new FlagDesc( "", "", FlagNormal, NormalShot, FlagGood, NoTeam, NULL ); FlagDesc *RedTeam = new FlagDesc( "Red Team", "R*", FlagNormal, NormalShot, FlagGood, ::RedTeam, "Team flag: If it's yours, prevent other teams from taking it. If it's not take it to your base to capture it!" ); FlagDesc *GreenTeam = new FlagDesc( "Green Team", "G*", FlagNormal, NormalShot, FlagGood, ::GreenTeam, "Team flag: If it's yours, prevent other teams from taking it. If it's not take it to your base to capture it!" ); FlagDesc *BlueTeam = new FlagDesc( "Blue Team", "B*", FlagNormal, NormalShot, FlagGood, ::BlueTeam, "Team flag: If it's yours, prevent other teams from taking it. If it's not take it to your base to capture it!" ); FlagDesc *PurpleTeam = new FlagDesc( "Purple Team", "P*", FlagNormal, NormalShot, FlagGood, ::PurpleTeam, "Team flag: If it's yours, prevent other teams from taking it. If it's not take it to your base to capture it!" ); FlagDesc *HighSpeed = new FlagDesc( "High Speed", "V", FlagUnstable, NormalShot, FlagGood, NoTeam, "Velocity (+V): Tank moves faster. Outrun bad guys." ); FlagDesc *QuickTurn = new FlagDesc( "Quick Turn", "A", FlagUnstable, NormalShot, FlagGood, NoTeam, "Angular velocity (+A): Tank turns faster. Dodge quicker." ); FlagDesc *OscillationOverthruster = new FlagDesc( "Oscillation Overthruster", "OO", FlagUnstable, NormalShot, FlagGood, NoTeam, "Oscillation Overthruster (+OO): Can drive through buildings. Can't backup or shoot while inside." ); FlagDesc *RapidFire = new FlagDesc( "Rapid Fire", "F", FlagUnstable, SpecialShot, FlagGood, NoTeam, "rapid Fire (+F): Shoots more often. Shells go faster but not as far." ); FlagDesc *MachineGun = new FlagDesc( "Machine Gun", "MG", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Machine Gun (+MG): Very fast reload and very short range." ); FlagDesc *GuidedMissile = new FlagDesc( "Guided Missile", "GM", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Guided Missile (+GM): Shots track a target. Lock on with right button. Can lock on or retarget after firing." ); FlagDesc *Laser = new FlagDesc( "Laser", "L", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Laser (+L): Shoots a laser. Infinite speed and range but long reload time."); FlagDesc *Ricochet = new FlagDesc( "Ricochet", "R", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Ricochet (+R): Shots bounce off walls. Don't shoot yourself!" ); FlagDesc *SuperBullet = new FlagDesc( "Super Bullet", "SB", FlagUnstable, SpecialShot, FlagGood, NoTeam, "SuperBullet (+SB): Shoots through buildings. Can kill Phantom Zone." ); FlagDesc *InvisibleBullet = new FlagDesc( "Invisible Bullet", "IB", FlagUnstable, NormalShot, FlagGood, NoTeam, "Invisible Bullet (+IB): Your shots don't appear on other radars. Can still see them out window."); FlagDesc *Stealth = new FlagDesc( "Stealth", "ST", FlagUnstable, NormalShot, FlagGood, NoTeam, "STealth (+ST): Tank is invisible on radar. Shots are still visible. Sneak up behind enemies!"); FlagDesc *Tiny = new FlagDesc( "Tiny", "T", FlagUnstable, NormalShot, FlagGood, NoTeam, "Tiny (+T): Tank is small and can get through small openings. Very hard to hit." ); FlagDesc *Narrow = new FlagDesc( "Narrow", "N", FlagUnstable, NormalShot, FlagGood, NoTeam, "Narrow (+N): Tank is super thin. Very hard to hit from front but is normal size from side. Can get through small openings."); FlagDesc *Shield = new FlagDesc( "Shield", "SH", FlagUnstable, NormalShot, FlagGood, NoTeam, "SHield (+SH): Getting hit only drops flag. Flag flies an extra-long time."); FlagDesc *Steamroller = new FlagDesc( "Steamroller", "SR", FlagUnstable, NormalShot, FlagGood, NoTeam, "SteamRoller (+SR): Destroys tanks you touch but you have to get really close."); FlagDesc *ShockWave = new FlagDesc( "Shock Wave", "SW", FlagUnstable, SpecialShot, FlagGood, NoTeam, "Shock Wave (+SW): Firing destroys all tanks nearby. Don't kill teammates! Can kill tanks on/in buildings."); FlagDesc *PhantomZone = new FlagDesc( "Phantom Zone", "PZ", FlagUnstable, NormalShot, FlagGood, NoTeam, "Phantom Zone (+PZ): Teleporting toggles Zoned effect. Zoned tank can drive through buildings. Zoned tank can't shoot or be shot (except by superbullet and shock wave)."); FlagDesc *Genocide = new FlagDesc( "Genocide", "G", FlagUnstable, NormalShot, FlagGood, NoTeam, "Genocide (+G): Killing one tank kills that tank's whole team."); FlagDesc *Jumping = new FlagDesc( "Jumping", "JP", FlagUnstable, NormalShot, FlagGood, NoTeam, "JumPing (+JP): Tank can jump. Use Tab key. Can't steer in the air."); FlagDesc *Identify = new FlagDesc( "Identify", "ID", FlagUnstable, NormalShot, FlagGood, NoTeam, "IDentify (+ID): Identifies type of nearest flag."); FlagDesc *Cloaking = new FlagDesc( "Cloaking", "CL", FlagUnstable, NormalShot, FlagGood, NoTeam, "CLoaking (+CL): Makes your tank invisible out-the-window. Still visible on radar."); FlagDesc *Useless = new FlagDesc( "Useless", "US", FlagUnstable, NormalShot, FlagGood, NoTeam, "USeless (+US): You have found the useless flag. Use it wisely."); FlagDesc *Masquerade = new FlagDesc( "Masquerade", "MQ", FlagUnstable, NormalShot, FlagGood, NoTeam, "MasQuerade (+MQ): In opponent's hud, you appear as a teammate."); FlagDesc *Seer = new FlagDesc( "Seer", "SE", FlagUnstable, NormalShot, FlagGood, NoTeam, "SEer (+SE): See stealthed, cloaked and masquerading tanks as normal."); FlagDesc *Colorblindness = new FlagDesc( "Colorblindness", "CB", FlagSticky, NormalShot, FlagBad, NoTeam, "ColorBlindness (-CB): Can't tell team colors. Don't shoot teammates!"); FlagDesc *Obesity = new FlagDesc( "Obesity", "O", FlagSticky, NormalShot, FlagBad, NoTeam, "Obesity (-O): Tank becomes very large. Can't fit through teleporters."); FlagDesc *LeftTurnOnly = new FlagDesc( "Left Turn Only", "LT", FlagSticky, NormalShot, FlagBad, NoTeam, "Left Turn only (-LT): Can't turn right."); FlagDesc *RightTurnOnly = new FlagDesc( "Right Turn Only", "RT", FlagSticky, NormalShot, FlagBad, NoTeam, "Right Turn only (-RT): Can't turn left."); FlagDesc *Momentum = new FlagDesc( "Momentum", "M", FlagSticky, NormalShot, FlagBad, NoTeam, "Momentum (-M): Tank has inertia. Acceleration is limited."); FlagDesc *Blindness = new FlagDesc( "Blindness", "B", FlagSticky, NormalShot, FlagBad, NoTeam, "Blindness (-B): Can't see out window. Radar still works."); FlagDesc *Jamming = new FlagDesc( "Jamming", "JM", FlagSticky, NormalShot, FlagBad, NoTeam, "JaMming (-JM): Radar doesn't work. Can still see."); FlagDesc *WideAngle = new FlagDesc( "Wide Angle", "WA", FlagSticky, NormalShot, FlagBad, NoTeam, "Wide Angle (-WA): Fish-eye lens distorts view."); } void* FlagDesc::pack(void* buf) const { buf = nboPackUByte(buf, flagAbbv[0]); buf = nboPackUByte(buf, flagAbbv[1]); return buf; } void* FlagDesc::unpack(void* buf, FlagDesc* &desc) { unsigned char abbv[3] = {0,0,0}; buf = nboUnpackUByte(buf, abbv[0]); buf = nboUnpackUByte(buf, abbv[1]); desc = Flag::getDescFromAbbreviation((const char *)abbv); return buf; } void* Flag::pack(void* buf) const { buf = desc->pack(buf); buf = nboPackUShort(buf, uint16_t(status)); buf = nboPackUShort(buf, uint16_t(type)); buf = nboPackUByte(buf, owner); buf = nboPackVector(buf, position); buf = nboPackVector(buf, launchPosition); buf = nboPackVector(buf, landingPosition); buf = nboPackFloat(buf, flightTime); buf = nboPackFloat(buf, flightEnd); buf = nboPackFloat(buf, initialVelocity); return buf; } void* Flag::unpack(void* buf) { uint16_t data; buf = FlagDesc::unpack(buf, desc); buf = nboUnpackUShort(buf, data); status = FlagStatus(data); buf = nboUnpackUShort(buf, data); type = FlagType(data); buf = nboUnpackUByte(buf, owner); buf = nboUnpackVector(buf, position); buf = nboUnpackVector(buf, launchPosition); buf = nboUnpackVector(buf, landingPosition); buf = nboUnpackFloat(buf, flightTime); buf = nboUnpackFloat(buf, flightEnd); buf = nboUnpackFloat(buf, initialVelocity); return buf; } FlagDesc* Flag::getDescFromAbbreviation(const char* abbreviation) { std::map<std::string, FlagDesc*>::iterator i; i = FlagDesc::flagMap.find(abbreviation); if (i == FlagDesc::flagMap.end()) return Flags::Null; else return i->second; } FlagSet& Flag::getGoodFlags() { return FlagDesc::flagSets[FlagGood]; } FlagSet& Flag::getBadFlags() { return FlagDesc::flagSets[FlagBad]; } const float* FlagDesc::getColor() { static const float superColor[3] = { 1.0, 1.0, 1.0 }; if (flagTeam == NoTeam) return superColor; else return Team::getTankColor(flagTeam); } // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* * Physically Based Rendering * Copyright (c) 2017-2018 Michał Siejak */ #if !(defined(ENABLE_OPENGL) || defined(ENABLE_VULKAN) || defined(ENABLE_D3D11) || defined(ENABLE_D3D12)) #error "At least one renderer implementation must be enabled via an appropriate ENABLE_* preprocessor macro" #endif #include <cstdio> #include <string> #include <memory> #include <vector> #include "application.hpp" #include "../opengl.hpp" #include "../vulkan.hpp" #include "../d3d11.hpp" #include "../d3d12.hpp" static void printUsage(const char* argv0) { const std::vector<const char*> flags = { #if defined(ENABLE_OPENGL) "-opengl", #endif #if defined(ENABLE_VULKAN) "-vulkan", #endif #if defined(ENABLE_D3D11) "-d3d11", #endif #if defined(ENABLE_D3D12) "-d3d12", #endif }; std::fprintf(stderr, "Usage: %s [", argv0); for(size_t i=0; i<flags.size(); ++i) { std::fprintf(stderr, "%s%s", flags[i], i < (flags.size()-1) ? "|":""); } std::fprintf(stderr, "]\n"); } static RendererInterface* createDefaultRenderer() { #if defined(ENABLE_D3D11) return new D3D11::Renderer; #elif defined(ENABLE_D3D12) return new D3D12::Renderer; #elif defined(ENABLE_OPENGL) return new OpenGL::Renderer; #elif defined(ENABLE_VULKAN) return new Vulkan::Renderer; #endif } int main(int argc, char* argv[]) { RendererInterface* renderer = nullptr; if(argc < 2) { renderer = createDefaultRenderer(); } else { const std::string flag = argv[1]; #if defined(ENABLE_OPENGL) if(flag == "-opengl") { renderer = new OpenGL::Renderer; } #endif #if defined(ENABLE_VULKAN) if(flag == "-vulkan") { renderer = new Vulkan::Renderer; } #endif #if defined(ENABLE_D3D11) if(flag == "-d3d11") { renderer = new D3D11::Renderer; } #endif #if defined(ENABLE_D3D12) if(flag == "-d3d12") { renderer = new D3D12::Renderer; } #endif if(!renderer) { printUsage(argv[0]); return 1; } } try { Application().run(std::unique_ptr<RendererInterface>{ renderer }); } catch(const std::exception& e) { std::fprintf(stderr, "Error: %s\n", e.what()); return 1; } } <commit_msg>Refactored renderer creation based on command line flag<commit_after>/* * Physically Based Rendering * Copyright (c) 2017-2018 Michał Siejak */ #if !(defined(ENABLE_OPENGL) || defined(ENABLE_VULKAN) || defined(ENABLE_D3D11) || defined(ENABLE_D3D12)) #error "At least one renderer implementation must be enabled via an appropriate ENABLE_* preprocessor macro" #endif #include <cstdio> #include <string> #include <memory> #include <vector> #include "application.hpp" #include "../opengl.hpp" #include "../vulkan.hpp" #include "../d3d11.hpp" #include "../d3d12.hpp" static void printUsage(const char* argv0) { const std::vector<const char*> flags = { #if defined(ENABLE_OPENGL) "-opengl", #endif #if defined(ENABLE_VULKAN) "-vulkan", #endif #if defined(ENABLE_D3D11) "-d3d11", #endif #if defined(ENABLE_D3D12) "-d3d12", #endif }; std::fprintf(stderr, "Usage: %s [", argv0); for(size_t i=0; i<flags.size(); ++i) { std::fprintf(stderr, "%s%s", flags[i], i < (flags.size()-1) ? "|":""); } std::fprintf(stderr, "]\n"); } static RendererInterface* createDefaultRenderer() { #if defined(ENABLE_D3D11) return new D3D11::Renderer; #elif defined(ENABLE_D3D12) return new D3D12::Renderer; #elif defined(ENABLE_OPENGL) return new OpenGL::Renderer; #elif defined(ENABLE_VULKAN) return new Vulkan::Renderer; #endif } static RendererInterface* createNamedRenderer(const std::string& flag) { #if defined(ENABLE_OPENGL) if(flag == "-opengl") { return new OpenGL::Renderer; } #endif #if defined(ENABLE_VULKAN) if(flag == "-vulkan") { return new Vulkan::Renderer; } #endif #if defined(ENABLE_D3D11) if(flag == "-d3d11") { return new D3D11::Renderer; } #endif #if defined(ENABLE_D3D12) if(flag == "-d3d12") { return new D3D12::Renderer; } #endif return nullptr; } int main(int argc, char* argv[]) { RendererInterface* renderer = nullptr; if(argc < 2) { renderer = createDefaultRenderer(); } else { renderer = createNamedRenderer(argv[1]); if(!renderer) { printUsage(argv[0]); return 1; } } try { Application().run(std::unique_ptr<RendererInterface>{ renderer }); } catch(const std::exception& e) { std::fprintf(stderr, "Error: %s\n", e.what()); return 1; } } <|endoftext|>
<commit_before>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided 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. #include <assert.h> #include <algorithm> #include "../basic/TLogging.h" #include "TIgnoreSigPipe.h" #include "TSocketSupport.h" #include "TChannel.h" #include "TPoller.h" #include "TTimerQueue.h" #include "TKernWrapper.h" #include "TEventLoop.h" namespace tyr { namespace net { #if defined(TYR_WINDOWS) __declspec(thread) EventLoop* t_loop_this_thread = nullptr; #else __thread EventLoop* t_loop_this_thread = nullptr; #endif const int kPollMicroSecond = 10000; IgnoreSigPipe g_ignore_sigpipe; void EventLoop::abort_not_in_loopthread(void) { TYRLOG_SYSFATAL << "EventLoop::abort_not_in_loopthread - EventLoop " << this << " was created in thread: " << tid_ << ", current thread id: " << basic::CurrentThread::tid(); } void EventLoop::handle_read(void) { // for waked up uint64_t one = 1; int n = Kern::read_eventfd(wakeup_fd_, &one, sizeof(one)); if (n != sizeof(one)) TYRLOG_ERROR << "EventLoop::handle_read - reads " << n << " bytes instead of 8"; } void EventLoop::do_pending_functors(void) { std::vector<FunctorCallback> functors; calling_pending_functors_ = true; { basic::MutexGuard guard(mtx_); functors.swap(pending_functors_); } for (auto& fn : functors) fn(); calling_pending_functors_ = false; } void EventLoop::debug_active_channels(void) const { for (auto ch : active_channels_) TYRLOG_TRACE << "EventLoop""debug_active_channels - {" << ch->revents_to_string() << "}"; } // ================== PUBLIC ================== EventLoop::EventLoop(void) : tid_(basic::CurrentThread::tid()) , poller_(Poller::new_default_poller(this)) , timer_queue_(new TimerQueue(this)) , wakeup_fd_(Kern::create_eventfd()) , wakeup_channel_(new Channel(this, wakeup_fd_)) { TYRLOG_DEBUG << "EventLoop::EventLoop - created " << this << " in thread " << tid_; if (nullptr != t_loop_this_thread) { TYRLOG_SYSFATAL << "EventLoop::EventLoop - another EventLoop " << t_loop_this_thread << " exists in this thread " << tid_; } else { t_loop_this_thread = this; } wakeup_channel_->set_read_callback(std::bind(&EventLoop::handle_read, this)); wakeup_channel_->enabled_reading(); } EventLoop::~EventLoop(void) { TYRLOG_DEBUG << "EventLoop::~EventLoop - " << this << " of thread " << tid_ << " destructs in thread " << basic::CurrentThread::tid(); wakeup_channel_->disabled_all(); wakeup_channel_->remove(); Kern::close_eventfd(wakeup_fd_); t_loop_this_thread = nullptr; } void EventLoop::loop(void) { assert(!looping_); assert_in_loopthread(); looping_ = true; quit_ = false; TYRLOG_TRACE << "EventLoop::loop - " << this << " start looping"; while (!quit_) { active_channels_.clear(); poll_return_time_ = poller_->poll(kPollMicroSecond, &active_channels_); ++iteration_; if (basic::Logger::log_level() <= basic::LoggingLevel::LOGGINGLEVEL_TRACE) debug_active_channels(); event_handling_ = true; for (auto channel : active_channels_) { current_active_channel_ = channel; current_active_channel_->handle_event(poll_return_time_); } current_active_channel_ = nullptr; event_handling_ = false; do_pending_functors(); } TYRLOG_TRACE << "EventLoop::loop - " << this << " stop looping"; looping_ = false; } void EventLoop::quit(void) { quit_ = true; if (!in_loopthread()) wakeup(); } void EventLoop::update_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); poller_->update_channel(channel); } void EventLoop::remove_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); if (event_handling_) { assert(current_active_channel_ == channel || std::find(active_channels_.begin(), active_channels_.end(), channel) == active_channels_.end()); } poller_->remove_channel(channel); } bool EventLoop::has_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); return poller_->has_channel(channel); } size_t EventLoop::get_functor_count(void) const { basic::MutexGuard guard(mtx_); return pending_functors_.size(); } TimerID EventLoop::run_at(basic::Timestamp time, const TimerCallback& fn) { return timer_queue_->add_timer(fn, time, 0.0); } TimerID EventLoop::run_at(basic::Timestamp time, TimerCallback&& fn) { return timer_queue_->add_timer(std::move(fn), time, 0.0); } TimerID EventLoop::run_after(double delay, const TimerCallback& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), delay)); return run_at(time, fn); } TimerID EventLoop::run_after(double delay, TimerCallback&& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), delay)); return run_at(time, std::move(fn)); } TimerID EventLoop::run_every(double interval, const TimerCallback& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), interval)); return timer_queue_->add_timer(fn, time, interval); } TimerID EventLoop::run_every(double interval, TimerCallback&& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), interval)); return timer_queue_->add_timer(std::move(fn), time, interval); } void EventLoop::wakeup(void) { uint64_t one = 1; int n = Kern::write_eventfd(wakeup_fd_, &one, sizeof(one)); if (n != sizeof(one)) TYRLOG_ERROR << "EventLoop::wakeup - writes " << n << " bytes instead of 8"; } void EventLoop::cancel(TimerID timerid) { timer_queue_->cancel(timerid); } void EventLoop::run_in_loop(const FunctorCallback& fn) { if (in_loopthread()) fn(); else put_in_loop(fn); } void EventLoop::run_in_loop(FunctorCallback&& fn) { if (in_loopthread()) fn(); else put_in_loop(std::move(fn)); } void EventLoop::put_in_loop(const FunctorCallback& fn) { { basic::MutexGuard guard(mtx_); pending_functors_.push_back(fn); } if (!in_loopthread() || calling_pending_functors_) wakeup(); } void EventLoop::put_in_loop(FunctorCallback&& fn) { { basic::MutexGuard guard(mtx_); pending_functors_.push_back(std::move(fn)); } if (!in_loopthread() || calling_pending_functors_) wakeup(); } EventLoop* EventLoop::get_loop_of_current_thread(void) { return t_loop_this_thread; } }} <commit_msg>:construction: chore(eventloop): updated the implementation of event loop<commit_after>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided 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. #include <assert.h> #include <algorithm> #include "../basic/TLogging.h" #include "TIgnoreSigPipe.h" #include "TSocketSupport.h" #include "TChannel.h" #include "TPoller.h" #include "TTimerQueue.h" #include "TKernWrapper.h" #include "TEventLoop.h" namespace tyr { namespace net { #if defined(TYR_WINDOWS) __declspec(thread) EventLoop* t_loop_this_thread = nullptr; #else __thread EventLoop* t_loop_this_thread = nullptr; #endif const int kPollMicroSecond = 10000; IgnoreSigPipe g_ignore_sigpipe; EventLoop::EventLoop(void) : tid_(basic::CurrentThread::tid()) , poller_(Poller::new_default_poller(this)) , timer_queue_(new TimerQueue(this)) , wakeup_fd_(Kern::create_eventfd()) , wakeup_channel_(new Channel(this, wakeup_fd_)) { TYRLOG_DEBUG << "EventLoop::EventLoop - created " << this << " in thread " << tid_; if (nullptr != t_loop_this_thread) { TYRLOG_SYSFATAL << "EventLoop::EventLoop - another EventLoop " << t_loop_this_thread << " exists in this thread " << tid_; } else { t_loop_this_thread = this; } wakeup_channel_->set_read_callback(std::bind(&EventLoop::handle_read, this)); wakeup_channel_->enabled_reading(); } EventLoop::~EventLoop(void) { TYRLOG_DEBUG << "EventLoop::~EventLoop - " << this << " of thread " << tid_ << " destructs in thread " << basic::CurrentThread::tid(); wakeup_channel_->disabled_all(); wakeup_channel_->remove(); Kern::close_eventfd(wakeup_fd_); t_loop_this_thread = nullptr; } void EventLoop::loop(void) { assert(!looping_); assert_in_loopthread(); looping_ = true; quit_ = false; TYRLOG_TRACE << "EventLoop::loop - " << this << " start looping"; while (!quit_) { active_channels_.clear(); poll_return_time_ = poller_->poll(kPollMicroSecond, &active_channels_); ++iteration_; if (basic::Logger::log_level() <= basic::LoggingLevel::LOGGINGLEVEL_TRACE) debug_active_channels(); event_handling_ = true; for (auto channel : active_channels_) { current_active_channel_ = channel; current_active_channel_->handle_event(poll_return_time_); } current_active_channel_ = nullptr; event_handling_ = false; do_pending_functors(); } TYRLOG_TRACE << "EventLoop::loop - " << this << " stop looping"; looping_ = false; } void EventLoop::quit(void) { quit_ = true; if (!in_loopthread()) wakeup(); } void EventLoop::update_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); poller_->update_channel(channel); } void EventLoop::remove_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); if (event_handling_) { assert(current_active_channel_ == channel || std::find(active_channels_.begin(), active_channels_.end(), channel) == active_channels_.end()); } poller_->remove_channel(channel); } bool EventLoop::has_channel(Channel* channel) { assert(channel->get_owner_loop() == this); assert_in_loopthread(); return poller_->has_channel(channel); } size_t EventLoop::get_functor_count(void) const { basic::MutexGuard guard(mtx_); return pending_functors_.size(); } TimerID EventLoop::run_at(basic::Timestamp time, const TimerCallback& fn) { return timer_queue_->add_timer(fn, time, 0.0); } TimerID EventLoop::run_at(basic::Timestamp time, TimerCallback&& fn) { return timer_queue_->add_timer(std::move(fn), time, 0.0); } TimerID EventLoop::run_after(double delay, const TimerCallback& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), delay)); return run_at(time, fn); } TimerID EventLoop::run_after(double delay, TimerCallback&& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), delay)); return run_at(time, std::move(fn)); } TimerID EventLoop::run_every(double interval, const TimerCallback& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), interval)); return timer_queue_->add_timer(fn, time, interval); } TimerID EventLoop::run_every(double interval, TimerCallback&& fn) { basic::Timestamp time(basic::add_time(basic::Timestamp::now(), interval)); return timer_queue_->add_timer(std::move(fn), time, interval); } void EventLoop::wakeup(void) { uint64_t one = 1; int n = Kern::write_eventfd(wakeup_fd_, &one, sizeof(one)); if (n != sizeof(one)) TYRLOG_ERROR << "EventLoop::wakeup - writes " << n << " bytes instead of 8"; } void EventLoop::cancel(TimerID timerid) { timer_queue_->cancel(timerid); } void EventLoop::run_in_loop(const FunctorCallback& fn) { if (in_loopthread()) fn(); else put_in_loop(fn); } void EventLoop::run_in_loop(FunctorCallback&& fn) { if (in_loopthread()) fn(); else put_in_loop(std::move(fn)); } void EventLoop::put_in_loop(const FunctorCallback& fn) { { basic::MutexGuard guard(mtx_); pending_functors_.push_back(fn); } if (!in_loopthread() || calling_pending_functors_) wakeup(); } void EventLoop::put_in_loop(FunctorCallback&& fn) { { basic::MutexGuard guard(mtx_); pending_functors_.push_back(std::move(fn)); } if (!in_loopthread() || calling_pending_functors_) wakeup(); } EventLoop* EventLoop::get_loop_of_current_thread(void) { return t_loop_this_thread; } void EventLoop::abort_not_in_loopthread(void) { TYRLOG_SYSFATAL << "EventLoop::abort_not_in_loopthread - EventLoop " << this << " was created in thread: " << tid_ << ", current thread id: " << basic::CurrentThread::tid(); } void EventLoop::handle_read(void) { // for waked up uint64_t one = 1; int n = Kern::read_eventfd(wakeup_fd_, &one, sizeof(one)); if (n != sizeof(one)) TYRLOG_ERROR << "EventLoop::handle_read - reads " << n << " bytes instead of 8"; } void EventLoop::do_pending_functors(void) { std::vector<FunctorCallback> functors; calling_pending_functors_ = true; { basic::MutexGuard guard(mtx_); functors.swap(pending_functors_); } for (auto& fn : functors) fn(); calling_pending_functors_ = false; } void EventLoop::debug_active_channels(void) const { for (auto ch : active_channels_) TYRLOG_TRACE << "EventLoop""debug_active_channels - {" << ch->revents_to_string() << "}"; } }} <|endoftext|>
<commit_before>/* dtkComposerNodeControlIf.cpp --- * * Author: Nicolas Niclausse * Copyright (C) 2012 - Nicolas Niclausse, Inria. * Created: mar. mai 15 17:05:32 2012 (+0200) * Version: $Id$ * Last-Updated: mer. mai 16 16:59:07 2012 (+0200) * By: Nicolas Niclausse * Update #: 229 */ /* Commentary: * */ /* Change log: * */ #include "dtkComposerNodeControlCase.h" #include "dtkComposerNodeComposite.h" #include "dtkComposerNodeProxy.h" #include "dtkComposerTransmitter.h" #include "dtkComposerTransmitterVariant.h" #include <dtkCore/dtkGlobal.h> #include <dtkLog/dtkLog.h> // ///////////////////////////////////////////////////////////////// // dtkComposerNodeControlCasePrivate definition // ///////////////////////////////////////////////////////////////// class dtkComposerNodeControlCasePrivate { public: dtkComposerNodeProxy header; dtkComposerNodeProxy footer; QList<dtkComposerNodeComposite *> blocks; QList<dtkComposerTransmitterVariant *> blocks_input; public: dtkComposerTransmitterVariant cond; }; // ///////////////////////////////////////////////////////////////// // dtkComposerNodeControlCase implementation // ///////////////////////////////////////////////////////////////// dtkComposerNodeControlCase::dtkComposerNodeControlCase(void) : dtkComposerNodeControl(), d(new dtkComposerNodeControlCasePrivate) { d->header.removeEmitter(0); d->header.setInputLabelHint("switch", 0); d->header.setAsHeader(true); d->cond.appendPrevious(d->header.receivers().first()); d->header.receivers().first()->appendNext(&(d->cond)); d->footer.removeReceiver(0); d->footer.setOutputLabelHint("switch", 0); d->footer.setAsFooter(true); d->cond.appendNext(d->footer.emitters().first()); d->footer.emitters().first()->appendPrevious(&(d->cond)); dtkComposerNodeComposite *def = new dtkComposerNodeComposite; def->setTitleHint("Case#default"); d->blocks << def; } dtkComposerNodeControlCase::~dtkComposerNodeControlCase(void) { //FIXME: delete blocks delete d; d = NULL; } int dtkComposerNodeControlCase::blockCount(void) { return d->blocks.count(); } dtkComposerNodeLeaf *dtkComposerNodeControlCase::header(void) { return &(d->header); } dtkComposerNodeLeaf *dtkComposerNodeControlCase::footer(void) { return &(d->footer); } dtkComposerNodeComposite *dtkComposerNodeControlCase::block(int id) { if(id < d->blocks.count() && id >= 0) return d->blocks[id]; return NULL; } void dtkComposerNodeControlCase::addBlock(void) { dtkComposerNodeComposite *c = new dtkComposerNodeComposite; QString id = QString::number(d->blocks.count()); c->setTitleHint("Case#"+id); d->blocks << c; dtkComposerTransmitterVariant *v = new dtkComposerTransmitterVariant; d->blocks_input << v; c->appendReceiver(v); c->setInputLabelHint("case",0); } void dtkComposerNodeControlCase::removeBlock(int id) { if (id = 0) // can't remove default block return; for (int i=0; i< d->blocks.count(); i++) if (id == i) { dtkComposerNodeComposite *b = d->blocks.takeAt(id); dtkComposerTransmitterVariant *t = d->blocks_input.takeAt(id-1); delete t; delete b; } for (int i=0; i< d->blocks.count(); i++) d->blocks.at(i)->setTitleHint("Case#"+QString::number(i)); } void dtkComposerNodeControlCase::setInputs(void) { } void dtkComposerNodeControlCase::setConditions(void) { } void dtkComposerNodeControlCase::setOutputs(void) { } void dtkComposerNodeControlCase::setVariables(void) { } int dtkComposerNodeControlCase::selectBranch(void) { int value = 0; for (int i = 1; i < d->blocks.count(); i++) foreach(dtkComposerTransmitter *t, d->blocks[i]->emitters()) { dtkComposerTransmitterVariant *v = dynamic_cast<dtkComposerTransmitterVariant *>(d->blocks_input[i-1]); if (d->cond.data() == v->data() ) { t->setActive(true); value = i; } else t->setActive(false); } foreach(dtkComposerTransmitter *t, d->blocks[0]->emitters()) if (value == 0) t->setActive(true); else t->setActive(false); return value; } void dtkComposerNodeControlCase::begin(void) { } void dtkComposerNodeControlCase::end(void) { } QString dtkComposerNodeControlCase::type(void) { return "case"; } QString dtkComposerNodeControlCase::titleHint(void) { return "Case"; } <commit_msg>small optimization<commit_after>/* dtkComposerNodeControlIf.cpp --- * * Author: Nicolas Niclausse * Copyright (C) 2012 - Nicolas Niclausse, Inria. * Created: mar. mai 15 17:05:32 2012 (+0200) * Version: $Id$ * Last-Updated: mer. mai 16 18:07:02 2012 (+0200) * By: Nicolas Niclausse * Update #: 256 */ /* Commentary: * */ /* Change log: * */ #include "dtkComposerNodeControlCase.h" #include "dtkComposerNodeComposite.h" #include "dtkComposerNodeProxy.h" #include "dtkComposerTransmitter.h" #include "dtkComposerTransmitterVariant.h" #include <dtkCore/dtkGlobal.h> #include <dtkLog/dtkLog.h> // ///////////////////////////////////////////////////////////////// // dtkComposerNodeControlCasePrivate definition // ///////////////////////////////////////////////////////////////// class dtkComposerNodeControlCasePrivate { public: dtkComposerNodeProxy header; dtkComposerNodeProxy footer; QList<dtkComposerNodeComposite *> blocks; QList<dtkComposerTransmitterVariant *> blocks_input; public: dtkComposerTransmitterVariant cond; }; // ///////////////////////////////////////////////////////////////// // dtkComposerNodeControlCase implementation // ///////////////////////////////////////////////////////////////// dtkComposerNodeControlCase::dtkComposerNodeControlCase(void) : dtkComposerNodeControl(), d(new dtkComposerNodeControlCasePrivate) { d->header.removeEmitter(0); d->header.setInputLabelHint("switch", 0); d->header.setAsHeader(true); d->cond.appendPrevious(d->header.receivers().first()); d->header.receivers().first()->appendNext(&(d->cond)); d->footer.removeReceiver(0); d->footer.setOutputLabelHint("switch", 0); d->footer.setAsFooter(true); d->cond.appendNext(d->footer.emitters().first()); d->footer.emitters().first()->appendPrevious(&(d->cond)); dtkComposerNodeComposite *def = new dtkComposerNodeComposite; def->setTitleHint("Case#default"); d->blocks << def; } dtkComposerNodeControlCase::~dtkComposerNodeControlCase(void) { //FIXME: delete blocks delete d; d = NULL; } int dtkComposerNodeControlCase::blockCount(void) { return d->blocks.count(); } dtkComposerNodeLeaf *dtkComposerNodeControlCase::header(void) { return &(d->header); } dtkComposerNodeLeaf *dtkComposerNodeControlCase::footer(void) { return &(d->footer); } dtkComposerNodeComposite *dtkComposerNodeControlCase::block(int id) { if(id < d->blocks.count() && id >= 0) return d->blocks[id]; return NULL; } void dtkComposerNodeControlCase::addBlock(void) { dtkComposerNodeComposite *c = new dtkComposerNodeComposite; QString id = QString::number(d->blocks.count()); c->setTitleHint("Case#"+id); d->blocks << c; dtkComposerTransmitterVariant *v = new dtkComposerTransmitterVariant; d->blocks_input << v; c->appendReceiver(v); c->setInputLabelHint("case",0); } void dtkComposerNodeControlCase::removeBlock(int id) { if (id = 0) // can't remove default block return; for (int i=0; i< d->blocks.count(); i++) if (id == i) { dtkComposerNodeComposite *b = d->blocks.takeAt(id); dtkComposerTransmitterVariant *t = d->blocks_input.takeAt(id-1); delete t; delete b; } for (int i=0; i< d->blocks.count(); i++) d->blocks.at(i)->setTitleHint("Case#"+QString::number(i)); } void dtkComposerNodeControlCase::setInputs(void) { } void dtkComposerNodeControlCase::setConditions(void) { } void dtkComposerNodeControlCase::setOutputs(void) { } void dtkComposerNodeControlCase::setVariables(void) { } int dtkComposerNodeControlCase::selectBranch(void) { int value = 0; bool is_case = false; for (int i = 1; i < d->blocks.count(); i++) { dtkComposerTransmitterVariant *v = dynamic_cast < dtkComposerTransmitterVariant * > ( d->blocks_input[i-1]) ; if (value > 0) //already found the good block, no need to check again. is_case = false; else is_case = d->cond.data() == v->data(); foreach(dtkComposerTransmitter *t, d->blocks[i]->emitters()) { if (is_case) { t->setActive(true); value = i; } else t->setActive(false); } } foreach(dtkComposerTransmitter *t, d->blocks[0]->emitters()) if (value == 0) t->setActive(true); else t->setActive(false); return value; } void dtkComposerNodeControlCase::begin(void) { } void dtkComposerNodeControlCase::end(void) { } QString dtkComposerNodeControlCase::type(void) { return "case"; } QString dtkComposerNodeControlCase::titleHint(void) { return "Case"; } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2009-2011 VMware, Inc. * All Rights Reserved. * * 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, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <stddef.h> #include <llvm-c/Core.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetInstrInfo.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/MemoryObject.h> #if HAVE_LLVM >= 0x0300 #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/TargetSelect.h> #else /* HAVE_LLVM < 0x0300 */ #include <llvm/Target/TargetRegistry.h> #include <llvm/Target/TargetSelect.h> #endif /* HAVE_LLVM < 0x0300 */ #if HAVE_LLVM >= 0x0209 #include <llvm/Support/Host.h> #else /* HAVE_LLVM < 0x0209 */ #include <llvm/System/Host.h> #endif /* HAVE_LLVM < 0x0209 */ #if HAVE_LLVM >= 0x0207 #include <llvm/MC/MCDisassembler.h> #include <llvm/MC/MCAsmInfo.h> #include <llvm/MC/MCInst.h> #include <llvm/MC/MCInstPrinter.h> #endif /* HAVE_LLVM >= 0x0207 */ #include "util/u_math.h" #include "util/u_debug.h" #include "lp_bld_debug.h" /** * Check alignment. * * It is important that this check is not implemented as a macro or inlined * function, as the compiler assumptions in respect to alignment of global * and stack variables would often make the check a no op, defeating the * whole purpose of the exercise. */ extern "C" boolean lp_check_alignment(const void *ptr, unsigned alignment) { assert(util_is_power_of_two(alignment)); return ((uintptr_t)ptr & (alignment - 1)) == 0; } class raw_debug_ostream : public llvm::raw_ostream { uint64_t pos; void write_impl(const char *Ptr, size_t Size); uint64_t current_pos() { return pos; } uint64_t current_pos() const { return pos; } #if HAVE_LLVM >= 0x207 uint64_t preferred_buffer_size() { return 512; } #else size_t preferred_buffer_size() { return 512; } #endif }; void raw_debug_ostream::write_impl(const char *Ptr, size_t Size) { if (Size > 0) { char *lastPtr = (char *)&Ptr[Size]; char last = *lastPtr; *lastPtr = 0; _debug_printf("%*s", Size, Ptr); *lastPtr = last; pos += Size; } } /** * Same as LLVMDumpValue, but through our debugging channels. */ extern "C" void lp_debug_dump_value(LLVMValueRef value) { #if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED) raw_debug_ostream os; llvm::unwrap(value)->print(os); os.flush(); #else LLVMDumpValue(value); #endif } #if HAVE_LLVM >= 0x0207 /* * MemoryObject wrapper around a buffer of memory, to be used by MC * disassembler. */ class BufferMemoryObject: public llvm::MemoryObject { private: const uint8_t *Bytes; uint64_t Length; public: BufferMemoryObject(const uint8_t *bytes, uint64_t length) : Bytes(bytes), Length(length) { } uint64_t getBase() const { return 0; } #if HAVE_LLVM >= 0x0301 uint64_t getExtent() #else uint64_t getExtent() const #endif { return Length; } #if HAVE_LLVM >= 0x0301 int readByte(uint64_t addr, uint8_t *byte) #else int readByte(uint64_t addr, uint8_t *byte) const #endif { if (addr > getExtent()) return -1; *byte = Bytes[addr]; return 0; } }; #endif /* HAVE_LLVM >= 0x0207 */ /* * Disassemble a function, using the LLVM MC disassembler. * * See also: * - http://blog.llvm.org/2010/01/x86-disassembler.html * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html */ extern "C" void lp_disassemble(const void* func) { #if HAVE_LLVM >= 0x0207 using namespace llvm; const uint8_t *bytes = (const uint8_t *)func; /* * Limit disassembly to this extent */ const uint64_t extent = 0x10000; uint64_t max_pc = 0; /* * Initialize all used objects. */ #if HAVE_LLVM >= 0x0301 std::string Triple = sys::getDefaultTargetTriple(); #else std::string Triple = sys::getHostTriple(); #endif std::string Error; const Target *T = TargetRegistry::lookupTarget(Triple, Error); #if HAVE_LLVM >= 0x0208 InitializeNativeTargetAsmPrinter(); #elif LLVM_NATIVE_ARCH == X86Target LLVMInitializeX86AsmPrinter(); #elif LLVM_NATIVE_ARCH == ARMTarget LLVMInitializeARMAsmPrinter(); #endif #if (LLVM_NATIVE_ARCH == X86 || LLVM_NATIVE_ARCH == X86Target) LLVMInitializeX86Disassembler(); #elif (LLVM_NATIVE_ARCH == ARM || LLVM_NATIVE_ARCH == ARMTarget) LLVMInitializeARMDisassembler(); #endif #if HAVE_LLVM >= 0x0300 OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple)); #else OwningPtr<const MCAsmInfo> AsmInfo(T->createAsmInfo(Triple)); #endif if (!AsmInfo) { debug_printf("error: no assembly info for target %s\n", Triple.c_str()); return; } #if HAVE_LLVM >= 0x0300 const MCSubtargetInfo *STI = T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""); OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI)); #else OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler()); #endif if (!DisAsm) { debug_printf("error: no disassembler for target %s\n", Triple.c_str()); return; } raw_debug_ostream Out; #if HAVE_LLVM >= 0x0300 unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); #else int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); #endif #if HAVE_LLVM >= 0x0300 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *STI)); #elif HAVE_LLVM >= 0x0208 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo)); #else OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out)); #endif if (!Printer) { debug_printf("error: no instruction printer for target %s\n", Triple.c_str()); return; } #if HAVE_LLVM >= 0x0301 TargetOptions options; #if defined(DEBUG) options.JITEmitDebugInfo = true; #endif #if defined(PIPE_ARCH_X86) options.StackAlignmentOverride = 4; #endif #if defined(DEBUG) || defined(PROFILE) options.NoFramePointerElim = true; #endif TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "", options); #elif HAVE_LLVM == 0x0300 TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), ""); #else TargetMachine *TM = T->createTargetMachine(Triple, ""); #endif const TargetInstrInfo *TII = TM->getInstrInfo(); /* * Wrap the data in a MemoryObject */ BufferMemoryObject memoryObject((const uint8_t *)bytes, extent); uint64_t pc; pc = 0; while (true) { MCInst Inst; uint64_t Size; /* * Print address. We use addresses relative to the start of the function, * so that between runs. */ debug_printf("%6lu:\t", (unsigned long)pc); if (!DisAsm->getInstruction(Inst, Size, memoryObject, pc, #if HAVE_LLVM >= 0x0300 nulls(), nulls())) { #else nulls())) { #endif debug_printf("invalid\n"); pc += 1; } /* * Output the bytes in hexidecimal format. */ if (0) { unsigned i; for (i = 0; i < Size; ++i) { debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]); } for (; i < 16; ++i) { debug_printf(" "); } } /* * Print the instruction. */ #if HAVE_LLVM >= 0x0300 Printer->printInst(&Inst, Out, ""); #elif HAVE_LLVM >= 0x208 Printer->printInst(&Inst, Out); #else Printer->printInst(&Inst); #endif Out.flush(); /* * Advance. */ pc += Size; #if HAVE_LLVM >= 0x0300 const MCInstrDesc &TID = TII->get(Inst.getOpcode()); #else const TargetInstrDesc &TID = TII->get(Inst.getOpcode()); #endif /* * Keep track of forward jumps to a nearby address. */ if (TID.isBranch()) { for (unsigned i = 0; i < Inst.getNumOperands(); ++i) { const MCOperand &operand = Inst.getOperand(i); if (operand.isImm()) { uint64_t jump; /* * FIXME: Handle both relative and absolute addresses correctly. * EDInstInfo actually has this info, but operandTypes and * operandFlags enums are not exposed in the public interface. */ if (1) { /* * PC relative addr. */ jump = pc + operand.getImm(); } else { /* * Absolute addr. */ jump = (uint64_t)operand.getImm(); } /* * Output the address relative to the function start, given * that MC will print the addresses relative the current pc. */ debug_printf("\t\t; %lu", (unsigned long)jump); /* * Ignore far jumps given it could be actually a tail return to * a random address. */ if (jump > max_pc && jump < extent) { max_pc = jump; } } } } debug_printf("\n"); /* * Stop disassembling on return statements, if there is no record of a * jump to a successive address. */ if (TID.isReturn()) { if (pc > max_pc) { break; } } } /* * Print GDB command, useful to verify output. */ if (0) { debug_printf("disassemble %p %p\n", bytes, bytes + pc); } debug_printf("\n"); #else /* HAVE_LLVM < 0x0207 */ (void)func; #endif /* HAVE_LLVM < 0x0207 */ } <commit_msg>gallivm: Replace architecture test with PIPE_ARCH_*<commit_after>/************************************************************************** * * Copyright 2009-2011 VMware, Inc. * All Rights Reserved. * * 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, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <stddef.h> #include <llvm-c/Core.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetInstrInfo.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/MemoryObject.h> #if HAVE_LLVM >= 0x0300 #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/TargetSelect.h> #else /* HAVE_LLVM < 0x0300 */ #include <llvm/Target/TargetRegistry.h> #include <llvm/Target/TargetSelect.h> #endif /* HAVE_LLVM < 0x0300 */ #if HAVE_LLVM >= 0x0209 #include <llvm/Support/Host.h> #else /* HAVE_LLVM < 0x0209 */ #include <llvm/System/Host.h> #endif /* HAVE_LLVM < 0x0209 */ #if HAVE_LLVM >= 0x0207 #include <llvm/MC/MCDisassembler.h> #include <llvm/MC/MCAsmInfo.h> #include <llvm/MC/MCInst.h> #include <llvm/MC/MCInstPrinter.h> #endif /* HAVE_LLVM >= 0x0207 */ #include "util/u_math.h" #include "util/u_debug.h" #include "lp_bld_debug.h" /** * Check alignment. * * It is important that this check is not implemented as a macro or inlined * function, as the compiler assumptions in respect to alignment of global * and stack variables would often make the check a no op, defeating the * whole purpose of the exercise. */ extern "C" boolean lp_check_alignment(const void *ptr, unsigned alignment) { assert(util_is_power_of_two(alignment)); return ((uintptr_t)ptr & (alignment - 1)) == 0; } class raw_debug_ostream : public llvm::raw_ostream { uint64_t pos; void write_impl(const char *Ptr, size_t Size); uint64_t current_pos() { return pos; } uint64_t current_pos() const { return pos; } #if HAVE_LLVM >= 0x207 uint64_t preferred_buffer_size() { return 512; } #else size_t preferred_buffer_size() { return 512; } #endif }; void raw_debug_ostream::write_impl(const char *Ptr, size_t Size) { if (Size > 0) { char *lastPtr = (char *)&Ptr[Size]; char last = *lastPtr; *lastPtr = 0; _debug_printf("%*s", Size, Ptr); *lastPtr = last; pos += Size; } } /** * Same as LLVMDumpValue, but through our debugging channels. */ extern "C" void lp_debug_dump_value(LLVMValueRef value) { #if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED) raw_debug_ostream os; llvm::unwrap(value)->print(os); os.flush(); #else LLVMDumpValue(value); #endif } #if HAVE_LLVM >= 0x0207 /* * MemoryObject wrapper around a buffer of memory, to be used by MC * disassembler. */ class BufferMemoryObject: public llvm::MemoryObject { private: const uint8_t *Bytes; uint64_t Length; public: BufferMemoryObject(const uint8_t *bytes, uint64_t length) : Bytes(bytes), Length(length) { } uint64_t getBase() const { return 0; } #if HAVE_LLVM >= 0x0301 uint64_t getExtent() #else uint64_t getExtent() const #endif { return Length; } #if HAVE_LLVM >= 0x0301 int readByte(uint64_t addr, uint8_t *byte) #else int readByte(uint64_t addr, uint8_t *byte) const #endif { if (addr > getExtent()) return -1; *byte = Bytes[addr]; return 0; } }; #endif /* HAVE_LLVM >= 0x0207 */ /* * Disassemble a function, using the LLVM MC disassembler. * * See also: * - http://blog.llvm.org/2010/01/x86-disassembler.html * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html */ extern "C" void lp_disassemble(const void* func) { #if HAVE_LLVM >= 0x0207 using namespace llvm; const uint8_t *bytes = (const uint8_t *)func; /* * Limit disassembly to this extent */ const uint64_t extent = 0x10000; uint64_t max_pc = 0; /* * Initialize all used objects. */ #if HAVE_LLVM >= 0x0301 std::string Triple = sys::getDefaultTargetTriple(); #else std::string Triple = sys::getHostTriple(); #endif std::string Error; const Target *T = TargetRegistry::lookupTarget(Triple, Error); #if HAVE_LLVM >= 0x0208 InitializeNativeTargetAsmPrinter(); #elif defined(PIPE_ARCH_X86) LLVMInitializeX86AsmPrinter(); #elif defined(PIPE_ARCH_ARM) LLVMInitializeARMAsmPrinter(); #elif defined(PIPE_ARCH_PPC) LLVMInitializePowerPCAsmPrinter(); #endif #if defined(PIPE_ARCH_X86) LLVMInitializeX86Disassembler(); #elif defined(PIPE_ARCH_ARM) LLVMInitializeARMDisassembler(); #endif #if HAVE_LLVM >= 0x0300 OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple)); #else OwningPtr<const MCAsmInfo> AsmInfo(T->createAsmInfo(Triple)); #endif if (!AsmInfo) { debug_printf("error: no assembly info for target %s\n", Triple.c_str()); return; } #if HAVE_LLVM >= 0x0300 const MCSubtargetInfo *STI = T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""); OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI)); #else OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler()); #endif if (!DisAsm) { debug_printf("error: no disassembler for target %s\n", Triple.c_str()); return; } raw_debug_ostream Out; #if HAVE_LLVM >= 0x0300 unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); #else int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); #endif #if HAVE_LLVM >= 0x0300 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *STI)); #elif HAVE_LLVM >= 0x0208 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo)); #else OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out)); #endif if (!Printer) { debug_printf("error: no instruction printer for target %s\n", Triple.c_str()); return; } #if HAVE_LLVM >= 0x0301 TargetOptions options; #if defined(DEBUG) options.JITEmitDebugInfo = true; #endif #if defined(PIPE_ARCH_X86) options.StackAlignmentOverride = 4; #endif #if defined(DEBUG) || defined(PROFILE) options.NoFramePointerElim = true; #endif TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "", options); #elif HAVE_LLVM == 0x0300 TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), ""); #else TargetMachine *TM = T->createTargetMachine(Triple, ""); #endif const TargetInstrInfo *TII = TM->getInstrInfo(); /* * Wrap the data in a MemoryObject */ BufferMemoryObject memoryObject((const uint8_t *)bytes, extent); uint64_t pc; pc = 0; while (true) { MCInst Inst; uint64_t Size; /* * Print address. We use addresses relative to the start of the function, * so that between runs. */ debug_printf("%6lu:\t", (unsigned long)pc); if (!DisAsm->getInstruction(Inst, Size, memoryObject, pc, #if HAVE_LLVM >= 0x0300 nulls(), nulls())) { #else nulls())) { #endif debug_printf("invalid\n"); pc += 1; } /* * Output the bytes in hexidecimal format. */ if (0) { unsigned i; for (i = 0; i < Size; ++i) { debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]); } for (; i < 16; ++i) { debug_printf(" "); } } /* * Print the instruction. */ #if HAVE_LLVM >= 0x0300 Printer->printInst(&Inst, Out, ""); #elif HAVE_LLVM >= 0x208 Printer->printInst(&Inst, Out); #else Printer->printInst(&Inst); #endif Out.flush(); /* * Advance. */ pc += Size; #if HAVE_LLVM >= 0x0300 const MCInstrDesc &TID = TII->get(Inst.getOpcode()); #else const TargetInstrDesc &TID = TII->get(Inst.getOpcode()); #endif /* * Keep track of forward jumps to a nearby address. */ if (TID.isBranch()) { for (unsigned i = 0; i < Inst.getNumOperands(); ++i) { const MCOperand &operand = Inst.getOperand(i); if (operand.isImm()) { uint64_t jump; /* * FIXME: Handle both relative and absolute addresses correctly. * EDInstInfo actually has this info, but operandTypes and * operandFlags enums are not exposed in the public interface. */ if (1) { /* * PC relative addr. */ jump = pc + operand.getImm(); } else { /* * Absolute addr. */ jump = (uint64_t)operand.getImm(); } /* * Output the address relative to the function start, given * that MC will print the addresses relative the current pc. */ debug_printf("\t\t; %lu", (unsigned long)jump); /* * Ignore far jumps given it could be actually a tail return to * a random address. */ if (jump > max_pc && jump < extent) { max_pc = jump; } } } } debug_printf("\n"); /* * Stop disassembling on return statements, if there is no record of a * jump to a successive address. */ if (TID.isReturn()) { if (pc > max_pc) { break; } } } /* * Print GDB command, useful to verify output. */ if (0) { debug_printf("disassemble %p %p\n", bytes, bytes + pc); } debug_printf("\n"); #else /* HAVE_LLVM < 0x0207 */ (void)func; #endif /* HAVE_LLVM < 0x0207 */ } <|endoftext|>
<commit_before>// // asset_reader_android.cc // GameEngine // // Created by Jon Sharkey on 2013-04-19. // Copyright 2013 Sharkable. All rights reserved. // #include "gameengine/android/asset_reader_android.h" // TODO This is currently in the airhockey source. Rethink JNI... and the GameEngine in general. #include "libzip/zip.h" // TODO UGH this is kinda gross. This is needed for the GLOBAL variable APKArchive. #include "app.h" AssetReaderAndroid::AssetReaderAndroid(std::string filename) : filename_(filename), file_size_(-1) { file_ptr_ = zip_fopen(APKArchive, filename.c_str(), 0); } AssetReaderAndroid::~AssetReaderAndroid() { s_log("deconstruct"); if (file_ptr_) { zip_fclose(file_ptr_); } } size_t AssetReaderAndroid::size() { if (file_size_ == -1) { struct zip_stat stat; zip_stat(APKArchive, filename_.c_str(), 0, &stat); file_size_ = stat.size; } return file_size_; } size_t AssetReaderAndroid::read(void *ptr, size_t size, size_t count) { if (file_ptr_) { return zip_fread(file_ptr_, ptr, size * count); } return 0; } bool AssetReaderAndroid::close() { if (file_ptr_) { bool result = zip_fclose(file_ptr_); file_ptr_ = NULL; return result; } return false; } <commit_msg>[Android] Removed log statment.<commit_after>// // asset_reader_android.cc // GameEngine // // Created by Jon Sharkey on 2013-04-19. // Copyright 2013 Sharkable. All rights reserved. // #include "gameengine/android/asset_reader_android.h" // TODO This is currently in the airhockey source. Rethink JNI... and the GameEngine in general. #include "libzip/zip.h" // TODO UGH this is kinda gross. This is needed for the GLOBAL variable APKArchive. #include "app.h" AssetReaderAndroid::AssetReaderAndroid(std::string filename) : filename_(filename), file_size_(-1) { file_ptr_ = zip_fopen(APKArchive, filename.c_str(), 0); } AssetReaderAndroid::~AssetReaderAndroid() { if (file_ptr_) { zip_fclose(file_ptr_); } } size_t AssetReaderAndroid::size() { if (file_size_ == -1) { struct zip_stat stat; zip_stat(APKArchive, filename_.c_str(), 0, &stat); file_size_ = stat.size; } return file_size_; } size_t AssetReaderAndroid::read(void *ptr, size_t size, size_t count) { if (file_ptr_) { return zip_fread(file_ptr_, ptr, size * count); } return 0; } bool AssetReaderAndroid::close() { if (file_ptr_) { bool result = zip_fclose(file_ptr_); file_ptr_ = NULL; return result; } return false; } <|endoftext|>
<commit_before>//============================================================================= // ■ ruby_connection.cpp //----------------------------------------------------------------------------- // 包装每一个导出到Ruby中的函数,也负责一些Ruby扩展所需的杂务。 //============================================================================= #include "global.hpp" namespace RubyWrapper { VALUE load_pic(VALUE self, VALUE path) { Check_Type(path, T_STRING); char* a = RSTRING_PTR(path); return Qnil;//RSTRING(load_img(a)); } VALUE init_engine(VALUE self, VALUE w, VALUE h) { Check_Type(w, T_FIXNUM); Check_Type(h, T_FIXNUM); ::init_engine(FIX2INT(w), FIX2INT(h)); return Qtrue; } VALUE main_draw_loop() { ::main_draw_loop(); return Qnil; } VALUE main_get_frame_count() { return LONG2FIX(VMDE->frame_count); } VALUE main_get_fps() { return INT2FIX(VMDE->fps); } } void init_ruby_modules() { Global_module = rb_define_module("VMDE"); rb_define_module_function(Global_module, "init", (type_ruby_function) RubyWrapper::init_engine, 2); rb_define_module_function(Global_module, "update", (type_ruby_function) RubyWrapper::main_draw_loop, 0); rb_define_module_function(Global_module, "frame_count", (type_ruby_function) RubyWrapper::main_get_frame_count, 0); rb_define_module_function(Global_module, "fps", (type_ruby_function) RubyWrapper::main_get_fps, 0); } void init_ruby_classes() { GResPic = rb_define_class_under(Global_module, "GRes_Picture", rb_cObject); rb_define_method(GResPic, "load_pic", (type_ruby_function) RubyWrapper::load_pic, 1); } extern "C" DLLEXPORT void Init_VMDE() { log("initializing the module"); init_ruby_modules(); init_ruby_classes(); } <commit_msg>“Look Mum, I've learned macros!”<commit_after>//============================================================================= // ■ ruby_connection.cpp //----------------------------------------------------------------------------- // 包装每一个导出到Ruby中的函数,也负责一些Ruby扩展所需的杂务。 //============================================================================= #include "global.hpp" namespace RubyWrapper { VALUE load_pic(VALUE self, VALUE path) { Check_Type(path, T_STRING); char* a = RSTRING_PTR(path); return Qnil;//RSTRING(load_img(a)); } VALUE init_engine(VALUE self, VALUE w, VALUE h) { Check_Type(w, T_FIXNUM); Check_Type(h, T_FIXNUM); ::init_engine(FIX2INT(w), FIX2INT(h)); return Qtrue; } VALUE main_draw_loop() { ::main_draw_loop(); return Qnil; } VALUE main_get_frame_count() { return LONG2FIX(VMDE->frame_count); } VALUE main_get_fps() { return INT2FIX(VMDE->fps); } } void init_ruby_modules() { Global_module = rb_define_module("VMDE"); #define RUBY_MODULE_API(ruby_name, wrapper_name, parameter_count) \ rb_define_module_function(Global_module, #ruby_name, \ (type_ruby_function) RubyWrapper::wrapper_name, parameter_count) RUBY_MODULE_API(init, init_engine, 2); RUBY_MODULE_API(update, main_draw_loop, 0); RUBY_MODULE_API(frame_count, main_get_frame_count, 0); RUBY_MODULE_API(fps, main_get_fps, 0); #undef RUBY_MODULE_API } void init_ruby_classes() { GResPic = rb_define_class_under(Global_module, "GRes_Picture", rb_cObject); rb_define_method(GResPic, "load_pic", (type_ruby_function) RubyWrapper::load_pic, 1); } extern "C" DLLEXPORT void Init_VMDE() { log("initializing the module"); init_ruby_modules(); init_ruby_classes(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), 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 Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <essentia/algorithmfactory.h> #include <essentia/essentiamath.h> #include <essentia/scheduler/network.h> #include <essentia/streaming/algorithms/poolstorage.h> #include "credit_libav.h" using namespace std; using namespace essentia; using namespace essentia::standard; int essentia_main(string audioFilename, string outputFilename) { // Returns: 1 on essentia error try { essentia::init(); cout.precision(10); // TODO ???? // instanciate factory and create algorithms: AlgorithmFactory& factory = AlgorithmFactory::instance(); Real sr = 44100.f; int framesize = 512; int hopsize = 256; Pool pool; // Algorithm instantiations Algorithm* audioStereo = factory.create("AudioLoader", "filename", audioFilename); Algorithm* monoMixer = factory.create("MonoMixer"); Algorithm* frameCutter = factory.create("FrameCutter", "frameSize", framesize, "hopSize", hopsize, "startFromZero", true); Algorithm* discontinuityDetector = factory.create("DiscontinuityDetector", "detectionThreshold", 15, "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -25); Algorithm* gapsDetector = factory.create("GapsDetector", "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -70); // in the first itteration of the assessment it was found // that low level noise was sometimes considered noise Algorithm* startStopCut = factory.create("StartStopCut", "maximumStartTime", 1, // Found song with only this margin (to double-check) "maximumStopTime", 1); Algorithm* saturationDetector = factory.create("SaturationDetector", "frameSize", framesize, "hopSize", hopsize, "differentialThreshold", 0.0001, "minimumDuration", 2.0f); // An experiment on rock songs showed that distortion is evident when // the median duration of the saturated regions is around 2ms Algorithm* truePeakDetector = factory.create("TruePeakDetector", "threshold", 0.0f); // The algorithm should skip beginings. Algorithm* clickDetector = factory.create("ClickDetector", "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -25, // This is too high. Just a work around to the problem on initial and final non-silent parts "detectionThreshold", 38); // Experiments showed that a higher threshold is not eenough to detect audible clicks. Algorithm* loudnessEBUR128 = factory.create("LoudnessEBUR128"); Algorithm* humDetector = factory.create("HumDetector", "sampleRate", sr, "minimumDuration", 20.f, // [seconds] We are only interested in humming tones if they are present over very long segments "frameSize", .4, // For this algorithm, `frameSize` `hopSoze` are expresed in seconds. "hopSize", .2); Algorithm* snr = factory.create("SNR", "frameSize", framesize, "sampleRate", sr); Algorithm* startStopSilence = factory.create("StartStopSilence"); Algorithm* windowing = factory.create("Windowing", "size", framesize, "zeroPadding", 0, "type", "hann", "normalized", false); Algorithm* noiseBurstDetector = factory.create("NoiseBurstDetector", "threshold", 200); Algorithm* falseStereoDetector = factory.create("FalseStereoDetector"); cout << "-------- connecting algos ---------" << endl; Real fs; int ch, br; std::string md5, cod; vector<StereoSample> audioBuffer; audioStereo->output("audio").set(audioBuffer); audioStereo->output("sampleRate").set(fs); audioStereo->output("numberChannels").set(ch); audioStereo->output("md5").set(md5); audioStereo->output("bit_rate").set(br); audioStereo->output("codec").set(cod); vector<Real> momentaryLoudness, shortTermLoudness; Real integratedLoudness, loudnessRange; loudnessEBUR128->input("signal").set(audioBuffer); loudnessEBUR128->output("momentaryLoudness").set(momentaryLoudness); loudnessEBUR128->output("shortTermLoudness").set(shortTermLoudness); loudnessEBUR128->output("integratedLoudness").set(integratedLoudness); loudnessEBUR128->output("loudnessRange").set(loudnessRange); Real correlation; int isFalseStereo; falseStereoDetector->input("frame").set(audioBuffer); falseStereoDetector->output("isFalseStereo").set(isFalseStereo); falseStereoDetector->output("correlation").set(correlation); vector<Real> audio; monoMixer->input("audio").set(audioBuffer); monoMixer->input("numberChannels").set(2); monoMixer->output("audio").set(audio); int startStopCutStart, startStopCutEnd; startStopCut->input("audio").set(audio); startStopCut->output("startCut").set(startStopCutStart); startStopCut->output("stopCut").set(startStopCutEnd); TNT::Array2D<Real> r; vector<Real> humFrequencies, humSaliences, humStarts, humEnds; humDetector->input("signal").set(audio); humDetector->output("r").set(r); humDetector->output("frequencies").set(humFrequencies); humDetector->output("saliences").set(humSaliences); humDetector->output("starts").set(humStarts); humDetector->output("ends").set(humEnds); std::vector<Real> peakLocations, truePeakDetectorOutput; truePeakDetector->input("signal").set(audio); truePeakDetector->output("peakLocations").set(peakLocations); truePeakDetector->output("output") .set(truePeakDetectorOutput); std::vector<Real> frame; frameCutter->input("signal").set(audio); frameCutter->output("frame").set(frame); // Time domain algorithms do not require Windowing. std::vector<Real> discontinuityLocations, discontinuityAmplitudes; discontinuityDetector->input("frame").set(frame); discontinuityDetector->output("discontinuityLocations").set(discontinuityLocations); discontinuityDetector->output("discontinuityAmplitudes").set(discontinuityAmplitudes); std::vector<Real> gapsDetectorStarts, gapsDetectorEnds; gapsDetector->input("frame").set(frame); gapsDetector->output("starts").set(gapsDetectorStarts); gapsDetector->output("ends").set(gapsDetectorEnds); std::vector<Real> saturationDetectorStarts, saturationDetectorEnds; saturationDetector->input("frame").set(frame); saturationDetector->output("starts").set(saturationDetectorStarts); saturationDetector->output("ends").set(saturationDetectorEnds); std::vector<Real> clickDetectorStarts, clickDetectorEnds; clickDetector->input("frame").set(frame); clickDetector->output("starts").set(clickDetectorStarts); clickDetector->output("ends").set(clickDetectorEnds); int startFrame, stopFrame; startStopSilence->input("frame").set(frame); startStopSilence->output("startFrame").set(startFrame); startStopSilence->output("stopFrame").set(stopFrame); vector<Real> noiseBurstIndexes; noiseBurstDetector->input("frame").set(frame); noiseBurstDetector->output("indexes").set(noiseBurstIndexes); std::vector<Real> windowedFrame; windowing->input("frame").set(frame); windowing->output("frame").set(windowedFrame); Real averagedSNR, instantSNR; std::vector<Real> spectralSNR; snr->input("frame").set(windowedFrame); snr->output("instantSNR").set(instantSNR); snr->output("averagedSNR").set(averagedSNR); snr->output("spectralSNR").set(spectralSNR); cout << "-------- running algos ---------" << endl; audioStereo->compute(); pool.set("filename", audioFilename); pool.set("duration", audio.size() / sr); pool.set("filename", audioFilename); loudnessEBUR128->compute(); pool.set("EBUR128.integratedLoudness", integratedLoudness); pool.set("EBUR128.range", loudnessRange); falseStereoDetector->compute(); pool.set("channelsCorrelation", correlation); monoMixer->compute(); startStopCut->compute(); pool.set("startStopCut.start", startStopCutStart); pool.set("startStopCut.end", startStopCutEnd); humDetector->compute(); if (humFrequencies.size() > 0) { pool.set("humDetector.present", true); pool.set("humDetector.frequencies", humFrequencies); pool.set("humDetector.saliences", humSaliences); pool.set("humDetector.starts", humStarts); pool.set("humDetector.ends", humEnds); } else { pool.set("humDetector.present", false); } truePeakDetector->compute(); for (uint i = 0; i < peakLocations.size(); i++) peakLocations[i] /= sr; if (peakLocations.size() > 0) { pool.set("truePeakDetector.present", true); pool.set("truePeakDetector.locations", peakLocations); } else { pool.set("truePeakDetector.present", false); } vector<Real> noiseBursts; size_t idx = 0; while (true) { // compute a frame frameCutter->compute(); // if it was the last one (ie: it was empty), then we're done. if (!frame.size()) { break; } // skippint silent frames should be internally done by each algorithm // if (isSilent(frame)) continue; discontinuityDetector->compute(); gapsDetector->compute(); saturationDetector->compute(); clickDetector->compute(); noiseBurstDetector->compute(); windowing->compute(); snr->compute(); startStopSilence->compute(); if (noiseBurstIndexes.size() > 3) { noiseBursts.push_back(idx * hopsize / (Real)fs); } noiseBurstIndexes.clear(); idx++; } if (noiseBursts.size() > 0) { pool.set("noiseBursts.present", true); pool.set("noiseBursts.locations", noiseBursts); } else { pool.set("noiseBursts.present", false); } if (discontinuityLocations.size() > 0) { pool.set("discontinuities.present", true); for (uint i = 0; i < discontinuityLocations.size(); i++) discontinuityLocations[i] /= sr; pool.set("discontinuities.locations", discontinuityLocations); pool.set("discontinuities.amplitudes", discontinuityAmplitudes); } else { pool.set("discontinuities.present", false); } if (gapsDetectorStarts.size() > 0) { pool.set("gaps.present", true); pool.set("gaps.starts", gapsDetectorStarts); pool.set("gaps.ends", gapsDetectorEnds); } else { pool.set("gaps.present", false); } if (saturationDetectorStarts.size() > 0) { pool.set("saturationDetector.present", true); pool.set("saturationDetector.starts", saturationDetectorStarts); pool.set("saturationDetector.ends", saturationDetectorEnds); } else { pool.set("saturationDetector.present", false); } if (clickDetectorStarts.size() > 0) { pool.set("clickDetector.present", true); pool.set("clickDetector.starts", clickDetectorStarts); pool.set("clickDetector.ends", clickDetectorEnds); } else { pool.set("clickDetector.present", false); } // Spectral SNR is not very relevant. // pool.set("snr.spectralSNR", spectralSNR); pool.set("snr.averagedSNR", averagedSNR); pool.set("startStopSilence.start", startFrame * hopsize / fs); pool.set("startStopSilence.end", stopFrame * hopsize / fs); cout << "-------- writting Yaml ---------" << endl; // Write to yaml file. Algorithm* output = standard::AlgorithmFactory::create("YamlOutput", "filename", outputFilename); output->input("pool").set(pool); output->compute(); delete output; delete frameCutter; delete discontinuityDetector; delete gapsDetector; delete startStopCut; delete saturationDetector; delete truePeakDetector; delete clickDetector; delete windowing; delete humDetector; delete snr; delete loudnessEBUR128; delete startStopSilence; essentia::shutdown(); cout << "-------- Done! ---------" << endl; } catch (EssentiaException& e) { cerr << e.what() << endl; return 1; } return 0; } int main(int argc, char* argv[]) { string audioFilename, outputFilename; switch (argc) { case 3: audioFilename = argv[1]; outputFilename = argv[2]; break; default: return -1; } return essentia_main(audioFilename, outputFilename); } <commit_msg>la-cupula extractor. minor changes<commit_after>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), 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 Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <essentia/algorithmfactory.h> #include <essentia/essentiamath.h> #include <essentia/scheduler/network.h> #include <essentia/streaming/algorithms/poolstorage.h> #include "credit_libav.h" using namespace std; using namespace essentia; using namespace essentia::standard; int essentia_main(string audioFilename, string outputFilename) { // Returns: 1 on essentia error try { essentia::init(); cout.precision(10); // TODO ???? // instanciate factory and create algorithms: AlgorithmFactory& factory = AlgorithmFactory::instance(); Real sr = 44100.f; int framesize = 512; int hopsize = 256; Real silenceThreshold = -25; Pool pool; // Algorithm instantiations Algorithm* audioStereo = factory.create("AudioLoader", "filename", audioFilename); Algorithm* monoMixer = factory.create("MonoMixer"); Algorithm* frameCutter = factory.create("FrameCutter", "frameSize", framesize, "hopSize", hopsize, "startFromZero", true); Algorithm* discontinuityDetector = factory.create("DiscontinuityDetector", "detectionThreshold", 15, "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", silenceThreshold); Algorithm* gapsDetector = factory.create("GapsDetector", "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -70); // in the first itteration of the assessment it was found // that low level noise was sometimes considered noise Algorithm* startStopCut = factory.create("StartStopCut", "maximumStartTime", 1, // Found song with only this margin (to double-check) "maximumStopTime", 1); Algorithm* saturationDetector = factory.create("SaturationDetector", "frameSize", framesize, "hopSize", hopsize, "differentialThreshold", 0.0001, "minimumDuration", 2.0f); // An experiment on rock songs showed that distortion is evident when // the median duration of the saturated regions is around 2ms Algorithm* truePeakDetector = factory.create("TruePeakDetector", "threshold", 0.0f, "quality", 2); // Reducing the quality of the conversion doubles the conversion speed. // The algorithm should skip beginings. Algorithm* clickDetector = factory.create("ClickDetector", "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", silenceThreshold, // This is too high. Just a work around to the problem on initial and final non-silent parts "detectionThreshold", 38); // Experiments showed that a higher threshold is not eenough to detect audible clicks. Algorithm* loudnessEBUR128 = factory.create("LoudnessEBUR128"); Algorithm* humDetector = factory.create("HumDetector", "sampleRate", sr, "minimumDuration", 20.f, // [seconds] We are only interested in humming tones if they are present over very long segments "frameSize", .4, // For this algorithm, `frameSize` `hopSoze` are expresed in seconds. "hopSize", .2); Algorithm* snr = factory.create("SNR", "frameSize", framesize, "sampleRate", sr); Algorithm* startStopSilence = factory.create("StartStopSilence"); Algorithm* windowing = factory.create("Windowing", "size", framesize, "zeroPadding", 0, "type", "hann", "normalized", false); Algorithm* noiseBurstDetector = factory.create("NoiseBurstDetector", "threshold", 200, "silenceThreshold", silenceThreshold); Algorithm* falseStereoDetector = factory.create("FalseStereoDetector"); cout << "-------- connecting algos ---------" << endl; Real fs; int ch, br; std::string md5, cod; vector<StereoSample> audioBuffer; audioStereo->output("audio").set(audioBuffer); audioStereo->output("sampleRate").set(fs); audioStereo->output("numberChannels").set(ch); audioStereo->output("md5").set(md5); audioStereo->output("bit_rate").set(br); audioStereo->output("codec").set(cod); vector<Real> momentaryLoudness, shortTermLoudness; Real integratedLoudness, loudnessRange; loudnessEBUR128->input("signal").set(audioBuffer); loudnessEBUR128->output("momentaryLoudness").set(momentaryLoudness); loudnessEBUR128->output("shortTermLoudness").set(shortTermLoudness); loudnessEBUR128->output("integratedLoudness").set(integratedLoudness); loudnessEBUR128->output("loudnessRange").set(loudnessRange); Real correlation; int isFalseStereo; falseStereoDetector->input("frame").set(audioBuffer); falseStereoDetector->output("isFalseStereo").set(isFalseStereo); falseStereoDetector->output("correlation").set(correlation); vector<Real> audio; monoMixer->input("audio").set(audioBuffer); monoMixer->input("numberChannels").set(2); monoMixer->output("audio").set(audio); int startStopCutStart, startStopCutEnd; startStopCut->input("audio").set(audio); startStopCut->output("startCut").set(startStopCutStart); startStopCut->output("stopCut").set(startStopCutEnd); TNT::Array2D<Real> r; vector<Real> humFrequencies, humSaliences, humStarts, humEnds; humDetector->input("signal").set(audio); humDetector->output("r").set(r); humDetector->output("frequencies").set(humFrequencies); humDetector->output("saliences").set(humSaliences); humDetector->output("starts").set(humStarts); humDetector->output("ends").set(humEnds); std::vector<Real> peakLocations, truePeakDetectorOutput; truePeakDetector->input("signal").set(audio); truePeakDetector->output("peakLocations").set(peakLocations); truePeakDetector->output("output") .set(truePeakDetectorOutput); std::vector<Real> frame; frameCutter->input("signal").set(audio); frameCutter->output("frame").set(frame); // Time domain algorithms do not require Windowing. std::vector<Real> discontinuityLocations, discontinuityAmplitudes; discontinuityDetector->input("frame").set(frame); discontinuityDetector->output("discontinuityLocations").set(discontinuityLocations); discontinuityDetector->output("discontinuityAmplitudes").set(discontinuityAmplitudes); std::vector<Real> gapsDetectorStarts, gapsDetectorEnds; gapsDetector->input("frame").set(frame); gapsDetector->output("starts").set(gapsDetectorStarts); gapsDetector->output("ends").set(gapsDetectorEnds); std::vector<Real> saturationDetectorStarts, saturationDetectorEnds; saturationDetector->input("frame").set(frame); saturationDetector->output("starts").set(saturationDetectorStarts); saturationDetector->output("ends").set(saturationDetectorEnds); std::vector<Real> clickDetectorStarts, clickDetectorEnds; clickDetector->input("frame").set(frame); clickDetector->output("starts").set(clickDetectorStarts); clickDetector->output("ends").set(clickDetectorEnds); int startFrame, stopFrame; startStopSilence->input("frame").set(frame); startStopSilence->output("startFrame").set(startFrame); startStopSilence->output("stopFrame").set(stopFrame); vector<Real> noiseBurstIndexes; noiseBurstDetector->input("frame").set(frame); noiseBurstDetector->output("indexes").set(noiseBurstIndexes); std::vector<Real> windowedFrame; windowing->input("frame").set(frame); windowing->output("frame").set(windowedFrame); Real averagedSNR, instantSNR; std::vector<Real> spectralSNR; snr->input("frame").set(windowedFrame); snr->output("instantSNR").set(instantSNR); snr->output("averagedSNR").set(averagedSNR); snr->output("spectralSNR").set(spectralSNR); cout << "-------- running algos ---------" << endl; audioStereo->compute(); pool.set("filename", audioFilename); pool.set("duration", audio.size() / sr); pool.set("filename", audioFilename); loudnessEBUR128->compute(); pool.set("EBUR128.integratedLoudness", integratedLoudness); pool.set("EBUR128.range", loudnessRange); falseStereoDetector->compute(); pool.set("channelsCorrelation", correlation); monoMixer->compute(); startStopCut->compute(); pool.set("startStopCut.start", startStopCutStart); pool.set("startStopCut.end", startStopCutEnd); humDetector->compute(); if (humFrequencies.size() > 0) { pool.set("humDetector.present", true); pool.set("humDetector.frequencies", humFrequencies); pool.set("humDetector.saliences", humSaliences); pool.set("humDetector.starts", humStarts); pool.set("humDetector.ends", humEnds); } else { pool.set("humDetector.present", false); } truePeakDetector->compute(); for (uint i = 0; i < peakLocations.size(); i++) peakLocations[i] /= sr; if (peakLocations.size() > 0) { pool.set("truePeakDetector.present", true); pool.set("truePeakDetector.locations", peakLocations); } else { pool.set("truePeakDetector.present", false); } vector<Real> noiseBursts; size_t idx = 0; while (true) { // compute a frame frameCutter->compute(); // if it was the last one (ie: it was empty), then we're done. if (!frame.size()) { break; } // skippint silent frames should be internally done by each algorithm // if (isSilent(frame)) continue; discontinuityDetector->compute(); gapsDetector->compute(); saturationDetector->compute(); clickDetector->compute(); noiseBurstDetector->compute(); windowing->compute(); snr->compute(); startStopSilence->compute(); if (noiseBurstIndexes.size() > 3) { noiseBursts.push_back(idx * hopsize / (Real)fs); } noiseBurstIndexes.clear(); idx++; } if (noiseBursts.size() > 0) { pool.set("noiseBursts.present", true); pool.set("noiseBursts.locations", noiseBursts); } else { pool.set("noiseBursts.present", false); } if (discontinuityLocations.size() > 0) { pool.set("discontinuities.present", true); for (uint i = 0; i < discontinuityLocations.size(); i++) discontinuityLocations[i] /= sr; pool.set("discontinuities.locations", discontinuityLocations); pool.set("discontinuities.amplitudes", discontinuityAmplitudes); } else { pool.set("discontinuities.present", false); } if (gapsDetectorStarts.size() > 0) { pool.set("gaps.present", true); pool.set("gaps.starts", gapsDetectorStarts); pool.set("gaps.ends", gapsDetectorEnds); } else { pool.set("gaps.present", false); } if (saturationDetectorStarts.size() > 0) { pool.set("saturationDetector.present", true); pool.set("saturationDetector.starts", saturationDetectorStarts); pool.set("saturationDetector.ends", saturationDetectorEnds); } else { pool.set("saturationDetector.present", false); } if (clickDetectorStarts.size() > 0) { pool.set("clickDetector.present", true); pool.set("clickDetector.starts", clickDetectorStarts); pool.set("clickDetector.ends", clickDetectorEnds); } else { pool.set("clickDetector.present", false); } // Spectral SNR is not very relevant. // pool.set("snr.spectralSNR", spectralSNR); pool.set("snr.averagedSNR", averagedSNR); pool.set("startStopSilence.start", startFrame * hopsize / fs); pool.set("startStopSilence.end", stopFrame * hopsize / fs); cout << "-------- writting Yaml ---------" << endl; // Write to yaml file. Algorithm* output = standard::AlgorithmFactory::create("YamlOutput", "filename", outputFilename); output->input("pool").set(pool); output->compute(); delete output; delete frameCutter; delete discontinuityDetector; delete gapsDetector; delete startStopCut; delete saturationDetector; delete truePeakDetector; delete clickDetector; delete windowing; delete humDetector; delete snr; delete loudnessEBUR128; delete startStopSilence; essentia::shutdown(); cout << "-------- Done! ---------" << endl; } catch (EssentiaException& e) { cerr << e.what() << endl; return 1; } return 0; } int main(int argc, char* argv[]) { string audioFilename, outputFilename; switch (argc) { case 3: audioFilename = argv[1]; outputFilename = argv[2]; break; default: return -1; } return essentia_main(audioFilename, outputFilename); } <|endoftext|>
<commit_before> // [TODO] This belongs into the cmake platform files!! #if defined(WIN32) && !defined(_DEBUG) #pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup") #endif #include <memory> #include <gloperate/ext-includes-begin.h> #include <widgetzeug/dark_fusion_style.hpp> #include <gloperate/ext-includes-end.h> #include <gloperate-qt/viewer/Viewer.h> #include "Application.h" int main(int argc, char * argv[]) { Application app(argc, argv); widgetzeug::enableDarkFusionStyle(); gloperate_qt::Viewer viewer; viewer.show(); viewer.loadPainter("Logo"); return app.exec(); } <commit_msg>Allow user to specify the initial painter on the commandline for gloperate-viewer<commit_after> // [TODO] This belongs into the cmake platform files!! #if defined(WIN32) && !defined(_DEBUG) #pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup") #endif #include <memory> #include <gloperate/ext-includes-begin.h> #include <widgetzeug/dark_fusion_style.hpp> #include <gloperate/ext-includes-end.h> #include <gloperate-qt/viewer/Viewer.h> #include "Application.h" int main(int argc, char * argv[]) { Application app(argc, argv); widgetzeug::enableDarkFusionStyle(); gloperate_qt::Viewer viewer; viewer.show(); std::string painterName = (argc > 1) ? argv[1] : "Logo"; viewer.loadPainter(painterName); return app.exec(); } <|endoftext|>
<commit_before>#include "stm32f4xx.h" // All of these belong to port D. const uint16_t orangeLedPin = 13; const uint16_t greenLedPin = 12; const uint16_t redLedPin = 14; const uint16_t blueLedPin = 15; void enableGPIOD(); void enableOutputPin(GPIO_TypeDef* gpio, uint16_t pin); void setPin(GPIO_TypeDef* gpio, uint16_t pin, bool value); void enableTIM2(); void enableTimerUpdateInterrupt(TIM_TypeDef* tim); void setPrescaler(TIM_TypeDef* tim, uint16_t prescaler); uint32_t millisecondsToMicroseconds(uint32_t ms); void setPeriod(TIM_TypeDef* tim, uint32_t value); void enableAutoReload(TIM_TypeDef* tim); void enableCounter(TIM_TypeDef* tim); void resetTimer(TIM_TypeDef* tim); void enableIRQ(IRQn_Type irq); void resetTimerInterrupt(TIM_TypeDef* tim); int main() { SystemInit(); enableGPIOD(); enableOutputPin(GPIOD, orangeLedPin); enableOutputPin(GPIOD, greenLedPin); enableOutputPin(GPIOD, redLedPin); enableOutputPin(GPIOD, blueLedPin); setPin(GPIOD, blueLedPin, true); enableTIM2(); enableIRQ(TIM2_IRQn); enableTimerUpdateInterrupt(TIM2); setPrescaler(TIM2, 16 - 1); // Set scale to microseconds, based on a 16 MHz clock setPeriod(TIM2, millisecondsToMicroseconds(1000) - 1); enableAutoReload(TIM2); enableCounter(TIM2); resetTimer(TIM2); } void enableGPIOD() { RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN; } void enableOutputPin(GPIO_TypeDef* gpio, uint16_t pin) { gpio->MODER |= 0b01 << (pin * 2); } void setPin(GPIO_TypeDef* gpio, uint16_t pin, bool value) { if (value) { gpio->BSRRL = 1 << pin; } else { gpio->BSRRH = 1 << pin; } } void enableTIM2() { RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; } void enableTimerUpdateInterrupt(TIM_TypeDef* tim) { tim->DIER |= TIM_DIER_UIE; } // Note: according to section 18.4.11 of the reference manual, there's a +1 on the value in the prescaler. // So, for example, setting the prescaler to 10 has the effect of dividing the clock by 11. void setPrescaler(TIM_TypeDef* tim, uint16_t prescaler) { tim->PSC = prescaler; } uint32_t millisecondsToMicroseconds(uint32_t ms) { return ms * 1000; } void setPeriod(TIM_TypeDef* tim, uint32_t value) { tim->ARR = value; } void enableAutoReload(TIM_TypeDef* tim) { tim->CR1 |= TIM_CR1_ARPE; } void enableCounter(TIM_TypeDef* tim) { tim->CR1 |= TIM_CR1_CEN; } void resetTimer(TIM_TypeDef* tim) { tim->EGR |= TIM_EGR_UG; } void enableIRQ(IRQn_Type irq) { NVIC_EnableIRQ(irq); } void resetTimerInterrupt(TIM_TypeDef* tim) { tim->SR = 0; } extern "C" { void TIM2_IRQHandler() { if (TIM2->SR & TIM_SR_UIF) { GPIOD->ODR ^= 1 << orangeLedPin; } resetTimerInterrupt(TIM2); } }<commit_msg>Fix signature of main().<commit_after>#include "stm32f4xx.h" // All of these belong to port D. const uint16_t orangeLedPin = 13; const uint16_t greenLedPin = 12; const uint16_t redLedPin = 14; const uint16_t blueLedPin = 15; void enableGPIOD(); void enableOutputPin(GPIO_TypeDef* gpio, uint16_t pin); void setPin(GPIO_TypeDef* gpio, uint16_t pin, bool value); void enableTIM2(); void enableTimerUpdateInterrupt(TIM_TypeDef* tim); void setPrescaler(TIM_TypeDef* tim, uint16_t prescaler); uint32_t millisecondsToMicroseconds(uint32_t ms); void setPeriod(TIM_TypeDef* tim, uint32_t value); void enableAutoReload(TIM_TypeDef* tim); void enableCounter(TIM_TypeDef* tim); void resetTimer(TIM_TypeDef* tim); void enableIRQ(IRQn_Type irq); void resetTimerInterrupt(TIM_TypeDef* tim); void main() { SystemInit(); enableGPIOD(); enableOutputPin(GPIOD, orangeLedPin); enableOutputPin(GPIOD, greenLedPin); enableOutputPin(GPIOD, redLedPin); enableOutputPin(GPIOD, blueLedPin); setPin(GPIOD, blueLedPin, true); enableTIM2(); enableIRQ(TIM2_IRQn); enableTimerUpdateInterrupt(TIM2); setPrescaler(TIM2, 16 - 1); // Set scale to microseconds, based on a 16 MHz clock setPeriod(TIM2, millisecondsToMicroseconds(1000) - 1); enableAutoReload(TIM2); enableCounter(TIM2); resetTimer(TIM2); } void enableGPIOD() { RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN; } void enableOutputPin(GPIO_TypeDef* gpio, uint16_t pin) { gpio->MODER |= 0b01 << (pin * 2); } void setPin(GPIO_TypeDef* gpio, uint16_t pin, bool value) { if (value) { gpio->BSRRL = 1 << pin; } else { gpio->BSRRH = 1 << pin; } } void enableTIM2() { RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; } void enableTimerUpdateInterrupt(TIM_TypeDef* tim) { tim->DIER |= TIM_DIER_UIE; } // Note: according to section 18.4.11 of the reference manual, there's a +1 on the value in the prescaler. // So, for example, setting the prescaler to 10 has the effect of dividing the clock by 11. void setPrescaler(TIM_TypeDef* tim, uint16_t prescaler) { tim->PSC = prescaler; } uint32_t millisecondsToMicroseconds(uint32_t ms) { return ms * 1000; } void setPeriod(TIM_TypeDef* tim, uint32_t value) { tim->ARR = value; } void enableAutoReload(TIM_TypeDef* tim) { tim->CR1 |= TIM_CR1_ARPE; } void enableCounter(TIM_TypeDef* tim) { tim->CR1 |= TIM_CR1_CEN; } void resetTimer(TIM_TypeDef* tim) { tim->EGR |= TIM_EGR_UG; } void enableIRQ(IRQn_Type irq) { NVIC_EnableIRQ(irq); } void resetTimerInterrupt(TIM_TypeDef* tim) { tim->SR = 0; } extern "C" { void TIM2_IRQHandler() { if (TIM2->SR & TIM_SR_UIF) { GPIOD->ODR ^= 1 << orangeLedPin; } resetTimerInterrupt(TIM2); } }<|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include <unistd.h> #include <fstream> #define HEIGHT 80 #define WIDTH 180 #define UPDATELENGTH 150000 #define ALIVE '*' #define DEAD ' ' int board[HEIGHT][WIDTH]; int weightedarray[10] = {0,0,0,0,0,0,1,1,1}; void genBoard(int (board)[HEIGHT][WIDTH]) { std::ifstream ifs ("/dev/urandom", std::ifstream::in); for (int x = 0; x < HEIGHT; ++x) { for (int y = 0; y < WIDTH; ++y) { board[x][y] = weightedarray[(int) ifs.get() % 10]; } } ifs.close(); } void copyBoard(int (newB)[HEIGHT][WIDTH], int (oldB)[HEIGHT][WIDTH]) { for (int x = 0; x < HEIGHT; ++x) { for (int y = 0; y < WIDTH; ++y) { newB[x][y] = oldB[x][y]; } } } void updateBoard(int (board)[HEIGHT][WIDTH]) { int next_board[HEIGHT][WIDTH]; copyBoard(next_board, board); for (int x = 0; x < HEIGHT; ++x) { for (int y = 0; y < WIDTH; ++y) { if ((x == 0 || x == HEIGHT) || (y == 0 || y == WIDTH)) { continue; } int aliveN = 0; int deadN = 0; if (!board[x-1][y+1]) { deadN++; } else { aliveN++; } if (!board[x][y+1]) { deadN++; } else { aliveN++; } if (!board[x+1][y+1]) { deadN++; } else { aliveN++; } if (!board[x+1][y]) { deadN++; } else { aliveN++; } if (!board[x+1][y-1]) { deadN++; } else { aliveN++; } if (!board[x][y-1]) { deadN++; } else { aliveN++; } if (!board[x-1][y-1]) { deadN++; } else { aliveN++; } if (!board[x-1][y]) { deadN++; } else { aliveN++; } /* Rules ===== 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by overcrowding. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. */ if ((board[x][y] && aliveN < 2)) { next_board[x][y] = 0; continue; } if ((board[x][y]) && ((aliveN == 2) || (aliveN == 3))) continue; if ((board[x][y]) && (aliveN > 3)) { next_board[x][y] = 0; continue; } if ((!board[x][y]) && (aliveN == 3)) { next_board[x][y] = 1; continue; } } } copyBoard(board, next_board); } void drawBoard(int (board)[HEIGHT][WIDTH]) { std::cout << "\033[2J\033[1;1H"; for (int x = 0; x < HEIGHT; ++x) { for (int y = 0; y < WIDTH; ++y) { if (board[x][y] == 0) { std::cout << DEAD; } else { std::cout << ALIVE; } } std::cout << std::endl; } } int main() { genBoard(board); while (1) { updateBoard(board); drawBoard(board); usleep(UPDATELENGTH); } return 0; } <commit_msg>We don't use the number of dead neighbours so remove it<commit_after>#include <iostream> #include <stdlib.h> #include <unistd.h> #include <fstream> #define HEIGHT 80 #define WIDTH 180 #define UPDATELENGTH 150000 #define ALIVE '*' #define DEAD ' ' int board[HEIGHT][WIDTH]; int weightedarray[10] = {0,0,0,0,0,0,1,1,1}; void genBoard(int (board)[HEIGHT][WIDTH]) { std::ifstream ifs ("/dev/urandom", std::ifstream::in); for (int x = 0; x < HEIGHT; ++x) { for (int y = 0; y < WIDTH; ++y) { board[x][y] = weightedarray[(int) ifs.get() % 10]; } } ifs.close(); } void copyBoard(int (newB)[HEIGHT][WIDTH], int (oldB)[HEIGHT][WIDTH]) { for (int x = 0; x < HEIGHT; ++x) { for (int y = 0; y < WIDTH; ++y) { newB[x][y] = oldB[x][y]; } } } void updateBoard(int (board)[HEIGHT][WIDTH]) { int next_board[HEIGHT][WIDTH]; copyBoard(next_board, board); for (int x = 0; x < HEIGHT; ++x) { for (int y = 0; y < WIDTH; ++y) { if ((x == 0 || x == HEIGHT) || (y == 0 || y == WIDTH)) { continue; } int aliveN = 0; if (board[x-1][y+1]) aliveN++; if (board[x][y+1]) aliveN++; if (board[x+1][y+1]) aliveN++; if (board[x+1][y]) aliveN++; if (board[x+1][y-1]) aliveN++; if (board[x][y-1]) aliveN++; if (board[x-1][y-1]) aliveN++; if (board[x-1][y]) aliveN++; /* Rules ===== 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by overcrowding. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. */ if ((board[x][y] && aliveN < 2)) { next_board[x][y] = 0; continue; } if ((board[x][y]) && ((aliveN == 2) || (aliveN == 3))) continue; if ((board[x][y]) && (aliveN > 3)) { next_board[x][y] = 0; continue; } if ((!board[x][y]) && (aliveN == 3)) { next_board[x][y] = 1; continue; } } } copyBoard(board, next_board); } void drawBoard(int (board)[HEIGHT][WIDTH]) { std::cout << "\033[2J\033[1;1H"; for (int x = 0; x < HEIGHT; ++x) { for (int y = 0; y < WIDTH; ++y) { if (board[x][y] == 0) { std::cout << DEAD; } else { std::cout << ALIVE; } } std::cout << std::endl; } } int main() { genBoard(board); while (1) { updateBoard(board); drawBoard(board); usleep(UPDATELENGTH); } return 0; } <|endoftext|>
<commit_before>/********************************************************************* * * * ConfigFemtoAnalysis.C - configuration macro for the femtoscopic * * analysis, meant as a QA process for two-particle effects * * * * Author: Adam Kisiel (Adam.Kisiel@cern.ch) * * * *********************************************************************/ #if !defined(__CINT__) || defined(__MAKECINT_) #include "AliFemtoManager.h" #include "AliFemtoEventReaderESDChain.h" #include "AliFemtoEventReaderESDChainKine.h" #include "AliFemtoEventReaderAODChain.h" #include "AliFemtoSimpleAnalysis.h" #include "AliFemtoBasicEventCut.h" #include "AliFemtoESDTrackCut.h" #include "AliFemtoCorrFctn.h" #include "AliFemtoCutMonitorParticleYPt.h" #include "AliFemtoCutMonitorParticleVertPos.h" #include "AliFemtoCutMonitorParticleMomRes.h" #include "AliFemtoCutMonitorParticlePID.h" #include "AliFemtoCutMonitorEventMult.h" #include "AliFemtoCutMonitorEventVertex.h" #include "AliFemtoShareQualityTPCEntranceSepPairCut.h" #include "AliFemtoPairCutAntiGamma.h" #include "AliFemtoPairCutRadialDistance.h" #include "AliFemtoQinvCorrFctn.h" #include "AliFemtoShareQualityCorrFctn.h" #include "AliFemtoTPCInnerCorrFctn.h" #include "AliFemtoVertexMultAnalysis.h" #include "AliFemtoCorrFctn3DSpherical.h" #include "AliFemtoChi2CorrFctn.h" #include "AliFemtoCorrFctnTPCNcls.h" #include "AliFemtoBPLCMS3DCorrFctn.h" #include "AliFemtoCorrFctn3DLCMSSym.h" #include "AliFemtoModelBPLCMSCorrFctn.h" #include "AliFemtoModelCorrFctn3DSpherical.h" #include "AliFemtoModelGausLCMSFreezeOutGenerator.h" #include "AliFemtoModelGausRinvFreezeOutGenerator.h" #include "AliFemtoModelManager.h" #include "AliFemtoModelWeightGeneratorBasic.h" #include "AliFemtoModelWeightGeneratorLednicky.h" #include "AliFemtoCorrFctnDirectYlm.h" #include "AliFemtoModelCorrFctnDirectYlm.h" #include "AliFemtoModelCorrFctnSource.h" #include "AliFemtoCutMonitorParticlePtPDG.h" #include "AliFemtoKTPairCut.h" #include "AliFemtoCutMonitorCollections.h" #include "AliFemtoCorrFctnNonIdDR.h" #include "AliFemtoCorrFctnDPhiStarDEta.h" #include "AliFemtoPairCutRadialDistanceAsymmetric.h" #include "AliFemtoKKTrackCut.h" #include "AliFemtoKKTrackCutFull.h" #include "AliFemtoPairCutMergedFraction.h" #include "AliFemtoCorrFctnDPhiStarKStarMergedFraction.h" #include "AliFemtoCorrFctnDPhiStarKStarAverageMergedPointsFraction.h" #include "AliFemtoBetaTPairCut.h" #include "AliFemtoCutMonitorPairBetaT.h" #endif //_ AliFemtoManager* ConfigFemtoAnalysis(int runcentrality0, int runcentrality1, int runcentrality2, int runcentrality3, int runcentrality4,int runcentrality5, int runcentrality6, int runSHCorrFctn, int runNonIdCorrFctn, int paircutantigammaon, int paircutmergedfractionon, double distance, double fraction1, int runDPhiStarKStarMergedFraction, int runDPhiStarKStarAverageMergedPointsFraction, int runDPhiStarDEta, int turnOnMonitors, int turnOnBetaTMonitor, int runbetatdep, int runbetatylm, int runbetatnonid) { double PionMass = 0.13957018;//0.13956995; double KaonMass = 0.493677; double ProtonMass = 0.938272013; const int numOfMultBins = 7; const int numOfChTypes = 4; const int numOfkTbins = 2; int runmults[numOfMultBins] = {runcentrality0, runcentrality1, runcentrality2, runcentrality3, runcentrality4, runcentrality5, runcentrality6}; int multbins[numOfMultBins + 1] = {0.001, 50, 100, 200, 300, 400, 500, 900}; int runch[numOfChTypes] = {1, 1, 1, 1}; const char *chrgs[numOfChTypes] = { "PIpKp", "PImKm", "PIpKm","PImKp"}; //int runktdep = 1; double ktrng[numOfkTbins + 1] = {0.5, 0.85, 1.0}; int runshlcms = 0;// 0:PRF(PAP), 1:LCMS(PP,APAP) int runtype = 2; // Types 0 - global, 1 - ITS only, 2 - TPC Inner int gammacut = 1; double shqmax = 0.5; //if (runshlcms) shqmax = 2.0; //else shqmax = 0.9; int nbinssh = 100; //AliFemtoEventReaderAODChain *Reader = new AliFemtoEventReaderAODChain(); AliFemtoEventReaderAODMultSelection *Reader = new AliFemtoEventReaderAODMultSelection(); Reader->SetFilterBit(7); //Reader->SetCentralityPreSelection(0.001, 950); AliFemtoManager* Manager=new AliFemtoManager(); Manager->SetEventReader(Reader); const int size = numOfMultBins * numOfChTypes; AliFemtoVertexMultAnalysis *anetaphitpc[size]; AliFemtoBasicEventCut *mecetaphitpc[size]; AliFemtoCutMonitorEventMult *cutPassEvMetaphitpc[size]; AliFemtoCutMonitorEventMult *cutFailEvMetaphitpc[size]; AliFemtoCutMonitorEventVertex *cutPassEvVetaphitpc[size]; AliFemtoCutMonitorEventVertex *cutFailEvVetaphitpc[size]; AliFemtoCutMonitorCollections *cutPassColletaphitpc[size]; AliFemtoCutMonitorCollections *cutFailColletaphitpc[size]; AliFemtoESDTrackCut *dtc1etaphitpc[size]; //AliFemtoESDTrackCut *dtc2etaphitpc[size]; AliFemtoKKTrackCutFull *dtc2etaphitpc[size]; AliFemtoCutMonitorParticleYPt *cutPass1YPtetaphitpc[size]; AliFemtoCutMonitorParticleYPt *cutFail1YPtetaphitpc[size]; AliFemtoCutMonitorParticlePID *cutPass1PIDetaphitpc[size]; AliFemtoCutMonitorParticlePID *cutFail1PIDetaphitpc[size]; AliFemtoCutMonitorParticleYPt *cutPass2YPtetaphitpc[size]; AliFemtoCutMonitorParticleYPt *cutFail2YPtetaphitpc[size]; AliFemtoCutMonitorParticlePID *cutPass2PIDetaphitpc[size]; AliFemtoCutMonitorParticlePID *cutFail2PIDetaphitpc[size]; AliFemtoPairCutAntiGamma *sqpcetaphitpc[size]; //AliFemtoShareQualityTPCEntranceSepPairCut *sqpcetaphitpc[20]; //AliFemtoPairCutRadialDistance *sqpcetaphitpc[size]; //AliFemtoPairCutRadialDistanceAsymmetric *sqpcetaphitpc[size]; //AliFemtoPairCutMergedFraction *sqpcetaphitpcmf[size]; //AliFemtoPairCutRadialDistanceLM *sqpcetaphitpcRD[size]; AliFemtoCorrFctnDirectYlm *cylmetaphitpc[size]; //AliFemtoCorrFctnDEtaDPhi *cdedpetaphi[size]; //AliFemtoChi2CorrFctn *cchiqinvetaphitpc[size]; AliFemtoCorrFctnDPhiStarKStarMergedFraction *dphistarkstarmftpc[size]; AliFemtoCorrFctnDPhiStarKStarAverageMergedPointsFraction *dphistarkstarampftpc[size]; //AliFemtoKTPairCut *ktpcuts[size*numOfkTbins]; AliFemtoBetaTPairCut *ktpcuts[size*numOfkTbins]; AliFemtoCutMonitorPairBetaT *cutpassbetatcutmonitor[size*numOfkTbins]; AliFemtoCutMonitorPairBetaT *cutfailbetatcutmonitor[size*numOfkTbins]; //AliFemtoPairCutMergedFraction *ktpcuts[size*numOfkTbins]; AliFemtoCorrFctnDirectYlm *cylmkttpc[size*numOfkTbins]; //AliFemtoQinvCorrFctn *cqinvkttpc[size*numOfkTbins]; AliFemtoCorrFctn3DLCMSSym *cq3dlcmskttpc[size*numOfkTbins]; //AliFemtoCorrFctn3DSpherical *cq3dspherical[size*numOfkTbins]; //AliFemtoCorrFctnTPCNcls *cqinvnclstpc[size]; //AliFemtoChi2CorrFctn *cqinvchi2tpc[size]; //AliFemtoModelGausLCMSFreezeOutGenerator *gausLCMSFreezeOutGenerator[size]; //AliFemtoModelWeightGeneratorBasic *weightGeneratorLednicky[size]; //AliFemtoModelManager *tModelManager[size]; AliFemtoCorrFctnNonIdDR *cnonidtpc[size]; AliFemtoCorrFctnDPhiStarDEta *cdphistardeta08[size]; AliFemtoCorrFctnDPhiStarDEta *cdphistardeta12[size]; AliFemtoCorrFctnDPhiStarDEta *cdphistardeta16[size]; AliFemtoCorrFctnDPhiStarDEta *cdphistardeta20[size]; AliFemtoCorrFctnNonIdDR *cnonidkttpc[size*numOfkTbins]; // *** Begin pion-kaon analysis *** int aniter = 0; for (int imult = 0; imult < numOfMultBins; imult++) { if (runmults[imult]) { for (int ichg = 0; ichg < numOfChTypes; ichg++) { if (runch[ichg]) { //Iterator: aniter = ichg * numOfMultBins + imult; //Mix events with respect to the z position of the primary vertex and event total multipliticy: anetaphitpc[aniter] = new AliFemtoVertexMultAnalysis(7, -7.0, 7.0, 2, multbins[imult], multbins[imult+1]); //VertZPos changed from (-10,10) to (-7,7), VertZbins changed from 10 to 7, mult bins changed from 4 to 2 anetaphitpc[aniter]->SetNumEventsToMix(3); //change the Num from 5 to 3 anetaphitpc[aniter]->SetMinSizePartCollection(1); anetaphitpc[aniter]->SetVerboseMode(kFALSE); //Select basic cuts: mecetaphitpc[aniter] = new AliFemtoBasicEventCut(); mecetaphitpc[aniter]->SetEventMult(0.001,100000); mecetaphitpc[aniter]->SetVertZPos(-7,7); //VertZPos changed from (-10,10) to (-7,7) //Study the multiplicity distribution: if(turnOnMonitors == 1) { cutPassEvMetaphitpc[aniter] = new AliFemtoCutMonitorEventMult(Form("cutPass%stpcM%i", chrgs[ichg], imult),500); cutFailEvMetaphitpc[aniter] = new AliFemtoCutMonitorEventMult(Form("cutFail%stpcM%i", chrgs[ichg], imult),500); mecetaphitpc[aniter]->AddCutMonitor(cutPassEvMetaphitpc[aniter], cutFailEvMetaphitpc[aniter]); } //Study the distribution and error of the primary vertex: if(turnOnMonitors == 1) { cutPassEvVetaphitpc[aniter] = new AliFemtoCutMonitorEventVertex(Form("cutPass%stpcM%i", chrgs[ichg], imult)); cutFailEvVetaphitpc[aniter] = new AliFemtoCutMonitorEventVertex(Form("cutFail%stpcM%i", chrgs[ichg], imult)); mecetaphitpc[aniter]->AddCutMonitor(cutPassEvVetaphitpc[aniter], cutFailEvVetaphitpc[aniter]); } //Study the multiplicity distribution: if(turnOnMonitors == 1) { cutPassColletaphitpc[aniter] = new AliFemtoCutMonitorCollections(Form("cutPass%stpcM%i", chrgs[ichg], imult)); cutFailColletaphitpc[aniter] = new AliFemtoCutMonitorCollections(Form("cutFail%stpcM%i", chrgs[ichg], imult)); mecetaphitpc[aniter]->AddCutMonitor(cutPassColletaphitpc[aniter], cutFailColletaphitpc[aniter]); } //Basic track cut for pions: dtc1etaphitpc[aniter] = new AliFemtoESDTrackCut(); dtc1etaphitpc[aniter]->SetNsigmaTPCTOF(true); dtc1etaphitpc[aniter]->SetNsigma(3.0); //Basic track cut for kaons: dtc2etaphitpc[aniter] = new AliFemtoKKTrackCutFull(); dtc2etaphitpc[aniter]->SetNsigmaTPCle250(2.0); dtc2etaphitpc[aniter]->SetNsigmaTPC250_400(2.0); dtc2etaphitpc[aniter]->SetNsigmaTPC400_450(1.0); dtc2etaphitpc[aniter]->SetNsigmaTPC450_500(3.0); dtc2etaphitpc[aniter]->SetNsigmaTOF450_500(2.0); dtc2etaphitpc[aniter]->UseNsigmaTOF450_500(true); dtc2etaphitpc[aniter]->SetNsigmaTPCge500(3.0); dtc2etaphitpc[aniter]->SetNsigmaTOF500_800(2.0); dtc2etaphitpc[aniter]->SetNsigmaTOF800_1000(1.5); dtc2etaphitpc[aniter]->SetNsigmaTOFge1000(1.0); //Set charge of particles: if (ichg == 0) { dtc1etaphitpc[aniter]->SetCharge(1.0); dtc2etaphitpc[aniter]->SetCharge(1.0); } else if (ichg == 1) { dtc1etaphitpc[aniter]->SetCharge(-1.0); dtc2etaphitpc[aniter]->SetCharge(-1.0); } else if (ichg == 2) { dtc1etaphitpc[aniter]->SetCharge(1.0); dtc2etaphitpc[aniter]->SetCharge(-1.0); } else if (ichg == 3) { dtc1etaphitpc[aniter]->SetCharge(-1.0); dtc2etaphitpc[aniter]->SetCharge(1.0); } //Set particle 1: dtc1etaphitpc[aniter]->SetPt(0.19,1.5); dtc1etaphitpc[aniter]->SetEta(-0.8,0.8); dtc1etaphitpc[aniter]->SetMass(PionMass); dtc1etaphitpc[aniter]->SetMostProbablePion(); //Set particle 2: dtc2etaphitpc[aniter]->SetPt(0.19,1.5); dtc2etaphitpc[aniter]->SetEta(-0.8,0.8); dtc2etaphitpc[aniter]->SetMass(KaonMass); dtc2etaphitpc[aniter]->SetMostProbableKaon(); //============PION============ //The cut monitor for particles to study the difference between reconstructed and true momentum: if(turnOnMonitors == 1) { cutPass1YPtetaphitpc[aniter] = new AliFemtoCutMonitorParticleYPt(Form("cutPass1%stpcM%i", chrgs[ichg], imult),PionMass); cutFail1YPtetaphitpc[aniter] = new AliFemtoCutMonitorParticleYPt(Form("cutFail1%stpcM%i", chrgs[ichg], imult),PionMass); dtc1etaphitpc[aniter]->AddCutMonitor(cutPass1YPtetaphitpc[aniter], cutFail1YPtetaphitpc[aniter]); } //The cut monitor for particles to study various aspects of the PID determination: if(turnOnMonitors == 1) { cutPass1PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutPass1%stpcM%i", chrgs[ichg], imult),0);//0-pion,1-kaon,2-proton cutFail1PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutFail1%stpcM%i", chrgs[ichg], imult),0); dtc1etaphitpc[aniter]->AddCutMonitor(cutPass1PIDetaphitpc[aniter], cutFail1PIDetaphitpc[aniter]); } //============KAON============ if(turnOnMonitors == 1) { cutPass2YPtetaphitpc[aniter] = new AliFemtoCutMonitorParticleYPt(Form("cutPass2%stpcM%i", chrgs[ichg], imult),KaonMass); cutFail2YPtetaphitpc[aniter] = new AliFemtoCutMonitorParticleYPt(Form("cutFail2%stpcM%i", chrgs[ichg], imult),KaonMass); dtc2etaphitpc[aniter]->AddCutMonitor(cutPass2YPtetaphitpc[aniter], cutFail2YPtetaphitpc[aniter]); } if(turnOnMonitors == 1) { cutPass2PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutPass2%stpcM%i", chrgs[ichg], imult),1);//0-pion,1-kaon,2-proton cutFail2PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutFail2%stpcM%i", chrgs[ichg], imult),1); dtc2etaphitpc[aniter]->AddCutMonitor(cutPass2PIDetaphitpc[aniter], cutFail2PIDetaphitpc[aniter]); } //A pair cut which checks for some pair qualities that attempt to identify slit/doubly reconstructed tracks and also selects pairs based on their separation at the entrance to the TPC //sqpcetaphitpc[aniter] = new AliFemtoPairCutRadialDistance(); //sqpcetaphitpcRD[aniter] = new AliFemtoPairCutRadialDistanceLM(); if (paircutmergedfractionon == 1) sqpcetaphitpc[aniter] = new AliFemtoPairCutMergedFraction(distance, fraction1, 0.01, 0.8, 2.5); else sqpcetaphitpc[aniter] = new AliFemtoPairCutAntiGamma(); if(paircutantigammaon == 1) sqpcetaphitpc[aniter]->SetDataType(AliFemtoPairCut::kAOD); else sqpcetaphitpc[aniter]->SetDataType(AliFemtoPairCut::kKine); if(gammacut == 1) { sqpcetaphitpc[aniter]->SetMaxEEMinv(0.002); sqpcetaphitpc[aniter]->SetMaxThetaDiff(0.008); } if( runtype==0){ sqpcetaphitpc[aniter]->SetMaxEEMinv(0.0); sqpcetaphitpc[aniter]->SetMaxThetaDiff(0.0); sqpcetaphitpc[aniter]->SetTPCEntranceSepMinimum(1.5); } else if (runtype==1){ //sqpcetaphitpc[aniter]->SetTPCEntranceSepMinimum(5.0); //sqpcetaphitpc[aniter]->SetPhiStarDistanceMinimum(0.03); //sqpcetaphitpc[aniter]->SetRadialDistanceMinimum(1.2, 0.03); //sqpcetaphitpc[aniter]->SetEtaDifferenceMinimum(0.02); } else if ( runtype==2 ){ sqpcetaphitpc[aniter]->SetShareQualityMax(1.0); sqpcetaphitpc[aniter]->SetShareFractionMax(0.05); sqpcetaphitpc[aniter]->SetRemoveSameLabel(kFALSE); sqpcetaphitpc[aniter]->SetTPCEntranceSepMinimum(0.0); } // Study the betaT distribution: if(turnOnBetaTMonitor == 1) { cutpassbetatcutmonitor[aniter] = new AliFemtoCutMonitorPairBetaT(Form("cutPass%stpcM%i", chrgs[ichg], imult), 100, 0.0, 1.0, PionMass, KaonMass); cutfailbetatcutmonitor[aniter] = new AliFemtoCutMonitorPairBetaT(Form("cutFail%stpcM%i", chrgs[ichg], imult), 100, 0.0, 1.0, PionMass, KaonMass); sqpcetaphitpc[aniter]->AddCutMonitor(cutpassbetatcutmonitor[aniter], cutfailbetatcutmonitor[aniter]); } anetaphitpc[aniter]->SetEnablePairMonitors(true); anetaphitpc[aniter]->SetEventCut(mecetaphitpc[aniter]); anetaphitpc[aniter]->SetFirstParticleCut(dtc1etaphitpc[aniter]); anetaphitpc[aniter]->SetSecondParticleCut(dtc2etaphitpc[aniter]); anetaphitpc[aniter]->SetPairCut(sqpcetaphitpc[aniter]); //Correlation functions //Spherical harmonics (without kT bins) if(runSHCorrFctn == 1) { cylmetaphitpc[aniter] = new AliFemtoCorrFctnDirectYlm(Form("cylm%stpcM%i", chrgs[ichg], imult),1,nbinssh,0.0,shqmax,runshlcms); anetaphitpc[aniter]->AddCorrFctn(cylmetaphitpc[aniter]); } // NonId (without kT bins) // Correlation function for non-identical particles uses k* as a function variable. Stores the correlation // function separately for positive and negative signs of k* projections into out, side and long directions, // enabling the calculations of double ratios if(runNonIdCorrFctn == 1) { cnonidtpc[aniter] = new AliFemtoCorrFctnNonIdDR(Form("cnonid%stpcM%i", chrgs[ichg], imult), nbinssh, 0.0, shqmax); anetaphitpc[aniter]->AddCorrFctn(cnonidtpc[aniter]); } if(runDPhiStarKStarMergedFraction == 1) { dphistarkstarmftpc[aniter] = new AliFemtoCorrFctnDPhiStarKStarMergedFraction(Form("cdphistarkstarmergedfraction%stpcM%iD%lfF%lf", chrgs[ichg], imult, distance, fraction1), 0.8, 2.5, distance, fraction1, 0.01, 51, 0.0, 0.5, 127, -1.0, 1.0); anetaphitpc[aniter]->AddCorrFctn(dphistarkstarmftpc[aniter]); } if(runDPhiStarKStarAverageMergedPointsFraction == 1) { dphistarkstarampftpc[aniter] = new AliFemtoCorrFctnDPhiStarKStarAverageMergedPointsFraction(Form("cdphistarkstaraveragemergedpointsfraction%stpcM%iD%lf", chrgs[ichg], imult, distance), 0.8, 2.5, distance, 0.01, 51, 0.0, 0.5, 127, -0.5, 0.5); anetaphitpc[aniter]->AddCorrFctn(dphistarkstarampftpc[aniter]); } // DPhiStarDEta (without bins) // Correlation function for two particle correlations which uses dPhi* and dEta as a function variables. if(runDPhiStarDEta == 1) { cdphistardeta08[aniter] = new AliFemtoCorrFctnDPhiStarDEta(Form("cdphistardeta08%stpcM%i", chrgs[ichg], imult), 0.8, 51, -0.05, 0.05, 127, -1.0, 1.0); anetaphitpc[aniter]->AddCorrFctn(cdphistardeta08[aniter]); cdphistardeta12[aniter] = new AliFemtoCorrFctnDPhiStarDEta(Form("cdphistardeta12%stpcM%i", chrgs[ichg], imult), 1.2, 51, -0.05, 0.05, 127, -1.0, 1.0); anetaphitpc[aniter]->AddCorrFctn(cdphistardeta12[aniter]); cdphistardeta16[aniter] = new AliFemtoCorrFctnDPhiStarDEta(Form("cdphistardeta16%stpcM%i", chrgs[ichg], imult), 1.6, 51, -0.05, 0.05, 127, -1.0, 1.0); anetaphitpc[aniter]->AddCorrFctn(cdphistardeta16[aniter]); cdphistardeta20[aniter] = new AliFemtoCorrFctnDPhiStarDEta(Form("cdphistardeta20%stpcM%i", chrgs[ichg], imult), 2.0, 51, -0.05, 0.05, 127, -1.0, 1.0); anetaphitpc[aniter]->AddCorrFctn(cdphistardeta20[aniter]); } if (runbetatdep) { int ktm; for (int ikt=0; ikt<numOfkTbins; ikt++) { ktm = aniter*numOfkTbins + ikt; //ktpcuts[ktm] = new AliFemtoKTPairCut(ktrng[ikt], ktrng[ikt+1]); ktpcuts[ktm] = new AliFemtoBetaTPairCut(ktrng[ikt], ktrng[ikt + 1], PionMass, KaonMass); if (runbetatylm) { cylmkttpc[ktm] = new AliFemtoCorrFctnDirectYlm(Form("cylm%stpcM%iD%lfF%lfbetat%d", chrgs[ichg], imult, distance, fraction1, ikt),3,nbinssh, 0.0,shqmax, runshlcms); cylmkttpc[ktm]->SetPairSelectionCut(ktpcuts[ktm]); anetaphitpc[aniter]->AddCorrFctn(cylmkttpc[ktm]); } if (runbetatnonid) { cnonidkttpc[ktm] = new AliFemtoCorrFctnNonIdDR(Form("cnonid%stpcM%ibetaT%i", chrgs[ichg], imult,ikt), nbinssh, 0.0, shqmax); cnonidkttpc[ktm]->SetPairSelectionCut(ktpcuts[ktm]); anetaphitpc[aniter]->AddCorrFctn(cnonidkttpc[ktm]); } } } Manager->AddAnalysis(anetaphitpc[aniter]); } } } } // *** End pion-kaon analysis return Manager; } <commit_msg>Delete ConfigFemtoAnalysis.C<commit_after><|endoftext|>
<commit_before><commit_msg>Fix crash in device_sensors.<commit_after><|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright 2016 Davide Faconti * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #include <ros_type_introspection/deserializer.hpp> #include <functional> namespace RosIntrospection{ inline void SkipBytesInBuffer( uint8_t** buffer, int vector_size, const BuiltinType& type ) { if( type == STRING) { for (int i=0; i<vector_size; i++){ int32_t string_size = ReadFromBuffer<int32_t>( buffer ); *buffer += string_size; } } else{ *buffer += vector_size * BuiltinTypeSize[ static_cast<int>(type) ]; } } void buildRosFlatTypeImpl(const ROSTypeList& type_list, const ROSType &type, StringTreeLeaf tree_node, // easier to use copy instead of reference or pointer uint8_t** buffer_ptr, ROSTypeFlat* flat_container, uint16_t max_array_size ) { int array_size = type.arraySize(); if( array_size == -1) { array_size = ReadFromBuffer<int32_t>( buffer_ptr ); } // std::cout << type.msgName() << " type: " << type.typeID() << " size: " << array_size << std::endl; std::function<void(StringTreeLeaf)> deserializeAndStore; if( type.typeID() == STRING ) { deserializeAndStore = [&](StringTreeLeaf tree_node) { size_t string_size = (size_t) ReadFromBuffer<int32_t>( buffer_ptr ); SString id( (const char*)(*buffer_ptr), string_size ); (*buffer_ptr) += string_size; flat_container->name.push_back( std::make_pair( std::move(tree_node), id ) ); }; } else if( type.isBuiltin()) { deserializeAndStore = [&](StringTreeLeaf tree_node){ flat_container->value.push_back( std::make_pair( std::move(tree_node), type.deserializeFromBuffer(buffer_ptr) ) ); }; } else if( type.typeID() == OTHER) { deserializeAndStore = [&](StringTreeLeaf tree_node) { bool done = false; for(const ROSMessage& msg: type_list) // find in the list { if( msg.type().msgName() == type.msgName() && msg.type().pkgName() == type.pkgName() ) { auto& children_nodes = tree_node.node_ptr->children(); bool to_add = false; if( children_nodes.empty() ) { children_nodes.reserve( msg.fields().size() ); to_add = true; } size_t index = 0; for (const ROSField& field : msg.fields() ) { if(field.isConstant() == false) { if( to_add){ SString node_name( field.name() ) ; tree_node.node_ptr->addChild( node_name ); } auto new_tree_node = tree_node; new_tree_node.node_ptr = &children_nodes[index++]; // note: this is not invalidated only because we reserved space in the vector // tree_node.element_ptr = &children_nodes[index++]; buildRosFlatTypeImpl(type_list, field.type(), (new_tree_node), buffer_ptr, flat_container, max_array_size); } } done = true; break; } } if( !done ){ std::string output( "can't deserialize this stuff: "); output += type.baseName().toStdString() + "\n\n"; output += "Available types are: \n\n"; for(const ROSMessage& msg: type_list) // find in the list { output += " " +msg.type().baseName().toStdString() + "\n"; } throw std::runtime_error( output ); } }; } else { throw std::runtime_error( "can't deserialize this stuff"); } if( array_size < max_array_size ) { StringTreeNode* node = tree_node.node_ptr; if( type.isArray() ) { node->children().reserve(1); node->addChild( "#" ); tree_node.node_ptr = &node->children().back(); tree_node.array_size++; for (int v=0; v<array_size; v++) { tree_node.index_array[ tree_node.array_size-1 ] = v; deserializeAndStore( (tree_node) ); } } else{ deserializeAndStore( (tree_node) ); } } else{ SkipBytesInBuffer( buffer_ptr, array_size, type.typeID() ); } } void buildRosFlatType(const ROSTypeList& type_map, ROSType type, SString prefix, uint8_t *buffer_ptr, ROSTypeFlat* flat_container_output, uint16_t max_array_size) { uint8_t** buffer = &buffer_ptr; flat_container_output->tree.root()->children().clear(); flat_container_output->tree.root()->value() = prefix; flat_container_output->name.clear(); flat_container_output->value.clear(); flat_container_output->renamed_value.clear(); StringTreeLeaf rootnode; rootnode.node_ptr = flat_container_output->tree.root(); buildRosFlatTypeImpl( type_map, type, rootnode, buffer, flat_container_output, max_array_size ); } StringTreeLeaf::StringTreeLeaf(): node_ptr(nullptr), array_size(0) { for (int i=0; i<7; i++) index_array[i] = 0;} SString StringTreeLeaf::toStr() const{ const StringTreeNode* node = this->node_ptr; if( !node ) return SString(); const StringTreeNode* array[64]; int index = 0; int char_count = 0; while(node) { char_count += node->value().size(); array[index] = node; index++; node = node->parent(); }; array[index] = nullptr; index--; int array_count = 0; char buffer[200]; int off = 0; while ( index >=0) { const SString& value = array[index]->value(); if( value.size()== 1 && value.at(0) == '#' ) { buffer[off-1] = '.'; off += sprintf( &buffer[off],"%d", this->index_array[ array_count++ ] ); } else{ off += sprintf( &buffer[off],"%s", array[index]->value().data() ); } if( index > 0 ) off += sprintf( &buffer[off],"/"); index--; } return SString(buffer); } } // end namespace <commit_msg>considerable speed improvement<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright 2016 Davide Faconti * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #include <ros_type_introspection/deserializer.hpp> #include <functional> namespace RosIntrospection{ inline void SkipBytesInBuffer( uint8_t** buffer, int vector_size, const BuiltinType& type ) { if( type == STRING) { for (int i=0; i<vector_size; i++){ int32_t string_size = ReadFromBuffer<int32_t>( buffer ); *buffer += string_size; } } else{ *buffer += vector_size * BuiltinTypeSize[ static_cast<int>(type) ]; } } void buildRosFlatTypeImpl(const ROSTypeList& type_list, const ROSType &type, StringTreeLeaf tree_node, // easier to use copy instead of reference or pointer uint8_t** buffer_ptr, ROSTypeFlat* flat_container, uint16_t max_array_size ) { int array_size = type.arraySize(); if( array_size == -1) { array_size = ReadFromBuffer<int32_t>( buffer_ptr ); } // std::cout << type.msgName() << " type: " << type.typeID() << " size: " << array_size << std::endl; std::function<void(StringTreeLeaf)> deserializeAndStore; if( type.typeID() == STRING ) { deserializeAndStore = [&](StringTreeLeaf tree_node) { size_t string_size = (size_t) ReadFromBuffer<int32_t>( buffer_ptr ); SString id( (const char*)(*buffer_ptr), string_size ); (*buffer_ptr) += string_size; flat_container->name.push_back( std::make_pair( std::move(tree_node), id ) ); }; } else if( type.isBuiltin()) { deserializeAndStore = [&](StringTreeLeaf tree_node){ flat_container->value.push_back( std::make_pair( std::move(tree_node), type.deserializeFromBuffer(buffer_ptr) ) ); }; } else if( type.typeID() == OTHER) { deserializeAndStore = [&](StringTreeLeaf tree_node) { bool done = false; for(const ROSMessage& msg: type_list) // find in the list { if( msg.type().msgName() == type.msgName() && msg.type().pkgName() == type.pkgName() ) { auto& children_nodes = tree_node.node_ptr->children(); bool to_add = false; if( children_nodes.empty() ) { children_nodes.reserve( msg.fields().size() ); to_add = true; } size_t index = 0; for (const ROSField& field : msg.fields() ) { if(field.isConstant() == false) { if( to_add){ SString node_name( field.name() ) ; tree_node.node_ptr->addChild( node_name ); } auto new_tree_node = tree_node; new_tree_node.node_ptr = &children_nodes[index++]; // note: this is not invalidated only because we reserved space in the vector // tree_node.element_ptr = &children_nodes[index++]; buildRosFlatTypeImpl(type_list, field.type(), (new_tree_node), buffer_ptr, flat_container, max_array_size); } } done = true; break; } } if( !done ){ std::string output( "can't deserialize this stuff: "); output += type.baseName().toStdString() + "\n\n"; output += "Available types are: \n\n"; for(const ROSMessage& msg: type_list) // find in the list { output += " " +msg.type().baseName().toStdString() + "\n"; } throw std::runtime_error( output ); } }; } else { throw std::runtime_error( "can't deserialize this stuff"); } if( array_size < max_array_size ) { StringTreeNode* node = tree_node.node_ptr; if( type.isArray() ) { node->children().reserve(1); node->addChild( "#" ); tree_node.node_ptr = &node->children().back(); tree_node.array_size++; for (int v=0; v<array_size; v++) { tree_node.index_array[ tree_node.array_size-1 ] = v; deserializeAndStore( (tree_node) ); } } else{ deserializeAndStore( (tree_node) ); } } else{ SkipBytesInBuffer( buffer_ptr, array_size, type.typeID() ); } } void buildRosFlatType(const ROSTypeList& type_map, ROSType type, SString prefix, uint8_t *buffer_ptr, ROSTypeFlat* flat_container_output, uint16_t max_array_size) { uint8_t** buffer = &buffer_ptr; flat_container_output->tree.root()->children().clear(); flat_container_output->tree.root()->value() = prefix; flat_container_output->name.clear(); flat_container_output->value.clear(); flat_container_output->renamed_value.clear(); StringTreeLeaf rootnode; rootnode.node_ptr = flat_container_output->tree.root(); buildRosFlatTypeImpl( type_map, type, rootnode, buffer, flat_container_output, max_array_size ); } StringTreeLeaf::StringTreeLeaf(): node_ptr(nullptr), array_size(0) { for (int i=0; i<7; i++) index_array[i] = 0;} // The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". // much faster for numbers below 100 inline int print_number(char* buffer, uint16_t value) { const char DIGITS[] = "00010203040506070809" "10111213141516171819" "20212223242526272829" "30313233343536373839" "40414243444546474849" "50515253545556575859" "60616263646566676869" "70717273747576777879" "80818283848586878889" "90919293949596979899"; if (value < 10) { buffer[0] = static_cast<char>('0' + value); return 1; } else if (value < 100) { value *= 2; buffer[0] = DIGITS[ value+1 ]; buffer[1] = DIGITS[ value ]; return 2; } else{ return sprintf( buffer,"%d", value ); } } SString StringTreeLeaf::toStr() const { const StringTreeNode* node = this->node_ptr; if( !node ) return SString(); const StringTreeNode* array[64]; int index = 0; int char_count = 0; while(node) { char_count += node->value().size(); array[index] = node; index++; node = node->parent(); }; array[index] = nullptr; index--; int array_count = 0; char buffer[200]; int off = 0; while ( index >=0) { const SString& value = array[index]->value(); if( value.size()== 1 && value.at(0) == '#' ) { buffer[off-1] = '.'; off += print_number(&buffer[off], this->index_array[ array_count++ ] ); } else{ memcpy( &buffer[off], array[index]->value().data(), array[index]->value().size() ); off += array[index]->value().size(); } if( index > 0 ){ buffer[off] = '/'; off += 1; } index--; } buffer[off] = '\0'; return SString(buffer); } } // end namespace <|endoftext|>
<commit_before>#include "RenderItemMatcher.hpp" double RenderItemMatcher::computeMatching(const RenderItemList & lhs, const RenderItemList & rhs) const { for (int i = 0; i < lhs.size();i++) { int j; for (j = 0; j < rhs.size();j++) _weights[i][j] = _distanceFunction(lhs[i], rhs[j]); for (; j < lhs.size();j++) _weights[i][j] = RenderItemDistanceMetric::NOT_COMPARABLE_VALUE; } const double error = _hungarianMethod(_weights, lhs.size()); std::cout << "[computeMatching] total error is " << error << std::endl; return error; } void RenderItemMatcher::setMatches(RenderItemMatchList & dest, const RenderItemList & lhs_src, const RenderItemList & rhs_src) const { for (int i = 0; i < lhs_src.size();i++) { const int j = _hungarianMethod.matching(i); if (_weights[i][j] == RenderItemDistanceMetric::NOT_COMPARABLE_VALUE) { // dest.push_back(std::make_pair(lhs_src[i], lhs_src[i])); dest.push_back(std::make_pair(rhs_src[j], rhs_src[j])); } else { dest.push_back(std::make_pair(lhs_src[i], rhs_src[j])); } } }<commit_msg>accidentally commented out a push_back operation<commit_after>#include "RenderItemMatcher.hpp" double RenderItemMatcher::computeMatching(const RenderItemList & lhs, const RenderItemList & rhs) const { for (int i = 0; i < lhs.size();i++) { int j; for (j = 0; j < rhs.size();j++) _weights[i][j] = _distanceFunction(lhs[i], rhs[j]); for (; j < lhs.size();j++) _weights[i][j] = RenderItemDistanceMetric::NOT_COMPARABLE_VALUE; } const double error = _hungarianMethod(_weights, lhs.size()); std::cout << "[computeMatching] total error is " << error << std::endl; return error; } void RenderItemMatcher::setMatches(RenderItemMatchList & dest, const RenderItemList & lhs_src, const RenderItemList & rhs_src) const { for (int i = 0; i < lhs_src.size();i++) { const int j = _hungarianMethod.matching(i); if (_weights[i][j] == RenderItemDistanceMetric::NOT_COMPARABLE_VALUE) { dest.push_back(std::make_pair(lhs_src[i], lhs_src[i])); dest.push_back(std::make_pair(rhs_src[j], rhs_src[j])); } else { dest.push_back(std::make_pair(lhs_src[i], rhs_src[j])); } } }<|endoftext|>
<commit_before>// Memory.cpp (Oclgrind) // Copyright (c) 2013-2015, James Price and Simon McIntosh-Smith, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "common.h" #include <cassert> #include <cmath> #include <cstring> #include "Context.h" #include "Memory.h" #include "WorkGroup.h" #include "WorkItem.h" using namespace oclgrind; using namespace std; Memory::Memory(unsigned int addrSpace, const Context *context) { m_context = context; m_addressSpace = addrSpace; clear(); } Memory::~Memory() { clear(); } size_t Memory::allocateBuffer(size_t size, cl_mem_flags flags) { // Check requested size doesn't exceed maximum if (size > MAX_BUFFER_SIZE) { return 0; } // Find first unallocated buffer slot unsigned b = getNextBuffer(); if (b >= MAX_NUM_BUFFERS) { return 0; } // Create buffer Buffer *buffer = new Buffer; buffer->size = size; buffer->flags = flags; buffer->data = new unsigned char[size]; // Initialize contents to 0 memset(buffer->data, 0, size); if (b >= m_memory.size()) { m_memory.push_back(buffer); } else { m_memory[b] = buffer; } m_totalAllocated += size; size_t address = ((size_t)b) << NUM_ADDRESS_BITS; m_context->notifyMemoryAllocated(this, address, size, flags); return address; } uint32_t Memory::atomic(AtomicOp op, size_t address, uint32_t value) { m_context->notifyMemoryAtomicLoad(this, op, address, 4); m_context->notifyMemoryAtomicStore(this, op, address, 4); // Bounds check if (!isAddressValid(address, 4)) { return 0; } // Get buffer size_t offset = EXTRACT_OFFSET(address); Buffer *buffer = m_memory[EXTRACT_BUFFER(address)]; uint32_t *ptr = (uint32_t*)(buffer->data + offset); uint32_t old = *ptr; switch(op) { case AtomicAdd: *ptr = old + value; break; case AtomicAnd: *ptr = old & value; break; case AtomicCmpXchg: FATAL_ERROR("AtomicCmpXchg in generic atomic handler"); break; case AtomicDec: *ptr = old - 1; break; case AtomicInc: *ptr = old + 1; break; case AtomicMax: *ptr = old > value ? old : value; break; case AtomicMin: *ptr = old < value ? old : value; break; case AtomicOr: *ptr = old | value; break; case AtomicSub: *ptr = old - value; break; case AtomicXchg: *ptr = value; break; case AtomicXor: *ptr = old ^ value; break; } return old; } uint32_t Memory::atomicCmpxchg(size_t address, uint32_t cmp, uint32_t value) { m_context->notifyMemoryAtomicLoad(this, AtomicCmpXchg, address, 4); // Bounds check if (!isAddressValid(address, 4)) { return 0; } // Get buffer size_t offset = EXTRACT_OFFSET(address); Buffer *buffer = m_memory[EXTRACT_BUFFER(address)]; // Perform cmpxchg uint32_t *ptr = (uint32_t*)(buffer->data + offset); uint32_t old = *ptr; if (old == cmp) { *ptr = value; m_context->notifyMemoryAtomicStore(this, AtomicCmpXchg, address, 4); } return old; } void Memory::clear() { vector<Buffer*>::iterator itr; for (itr = m_memory.begin(); itr != m_memory.end(); itr++) { if (*itr) { if (!((*itr)->flags & CL_MEM_USE_HOST_PTR)) { delete[] (*itr)->data; } delete *itr; size_t address = (itr-m_memory.begin())<<NUM_ADDRESS_BITS; m_context->notifyMemoryDeallocated(this, address); } } m_memory.resize(1); m_memory[0] = NULL; m_freeBuffers = queue<unsigned>(); m_totalAllocated = 0; } Memory* Memory::clone() const { Memory *mem = new Memory(m_addressSpace, m_context); // Clone buffers mem->m_memory.resize(m_memory.size()); mem->m_memory[0] = NULL; for (unsigned i = 1; i < m_memory.size(); i++) { Buffer *src = m_memory[i]; Buffer *dst = new Buffer; dst->size = src->size; dst->flags = src->flags, dst->data = (src->flags&CL_MEM_USE_HOST_PTR) ? src->data : new unsigned char[src->size], memcpy(dst->data, src->data, src->size); mem->m_memory[i] = dst; m_context->notifyMemoryAllocated(mem, ((size_t)i<<NUM_ADDRESS_BITS), src->size, src->flags); } // Clone state mem->m_freeBuffers = m_freeBuffers; mem->m_totalAllocated = m_totalAllocated; return mem; } size_t Memory::createHostBuffer(size_t size, void *ptr, cl_mem_flags flags) { // Check requested size doesn't exceed maximum if (size > MAX_BUFFER_SIZE) { return 0; } // Find first unallocated buffer slot unsigned b = getNextBuffer(); if (b >= MAX_NUM_BUFFERS) { return 0; } // Create buffer Buffer *buffer = new Buffer; buffer->size = size; buffer->flags = flags; buffer->data = (unsigned char*)ptr; if (b >= m_memory.size()) { m_memory.push_back(buffer); } else { m_memory[b] = buffer; } m_totalAllocated += size; size_t address = ((size_t)b) << NUM_ADDRESS_BITS; m_context->notifyMemoryAllocated(this, address, size, flags); return address; } bool Memory::copy(size_t dst, size_t src, size_t size) { m_context->notifyMemoryLoad(this, src, size); // Check source address if (!isAddressValid(src, size)) { return false; } size_t src_offset = EXTRACT_OFFSET(src); Buffer *src_buffer = m_memory.at(EXTRACT_BUFFER(src)); m_context->notifyMemoryStore(this, dst, size, src_buffer->data + src_offset); // Check destination address if (!isAddressValid(dst, size)) { return false; } size_t dst_offset = EXTRACT_OFFSET(dst); Buffer *dst_buffer = m_memory.at(EXTRACT_BUFFER(dst)); // Copy data memcpy(dst_buffer->data + dst_offset, src_buffer->data + src_offset, size); return true; } void Memory::deallocateBuffer(size_t address) { unsigned buffer = EXTRACT_BUFFER(address); assert(buffer < m_memory.size() && m_memory[buffer]); if (!(m_memory[buffer]->flags & CL_MEM_USE_HOST_PTR)) { delete[] m_memory[buffer]->data; } m_totalAllocated -= m_memory[buffer]->size; m_freeBuffers.push(buffer); delete m_memory[buffer]; m_memory[buffer] = NULL; m_context->notifyMemoryDeallocated(this, address); } void Memory::dump() const { for (unsigned b = 0; b < m_memory.size(); b++) { if (!m_memory[b]->data) { continue; } for (unsigned i = 0; i < m_memory[b]->size; i++) { if (i%4 == 0) { cout << endl << hex << uppercase << setw(16) << setfill(' ') << right << ((((size_t)b)<<NUM_ADDRESS_BITS) | i) << ":"; } cout << " " << hex << uppercase << setw(2) << setfill('0') << (int)m_memory[b]->data[i]; } } cout << endl; } unsigned int Memory::getAddressSpace() const { return m_addressSpace; } const Memory::Buffer* Memory::getBuffer(size_t address) const { size_t buf = EXTRACT_BUFFER(address); if (buf == 0 || buf >= m_memory.size() || !m_memory[buf]->data) { return NULL; } return m_memory[buf]; } size_t Memory::getMaxAllocSize() { return MAX_BUFFER_SIZE; } unsigned Memory::getNextBuffer() { if (m_freeBuffers.empty()) { return m_memory.size(); } else { unsigned b = m_freeBuffers.front(); m_freeBuffers.pop(); return b; } } void* Memory::getPointer(size_t address) const { size_t buffer = EXTRACT_BUFFER(address); // Bounds check if (!isAddressValid(address)) { return NULL; } return m_memory[buffer]->data + EXTRACT_OFFSET(address); } size_t Memory::getTotalAllocated() const { return m_totalAllocated; } bool Memory::isAddressValid(size_t address, size_t size) const { size_t buffer = EXTRACT_BUFFER(address); size_t offset = EXTRACT_OFFSET(address); if (buffer == 0 || buffer >= m_memory.size() || !m_memory[buffer] || offset+size > m_memory[buffer]->size) { return false; } return true; } bool Memory::load(unsigned char *dest, size_t address, size_t size) const { m_context->notifyMemoryLoad(this, address, size); // Bounds check if (!isAddressValid(address, size)) { return false; } // Get buffer size_t offset = EXTRACT_OFFSET(address); Buffer *src = m_memory[EXTRACT_BUFFER(address)]; // Load data memcpy(dest, src->data + offset, size); return true; } unsigned char* Memory::mapBuffer(size_t address, size_t offset, size_t size) { size_t buffer = EXTRACT_BUFFER(address); // Bounds check if (!isAddressValid(address, size)) { return NULL; } return m_memory[buffer]->data + offset + EXTRACT_OFFSET(address); } bool Memory::store(const unsigned char *source, size_t address, size_t size) { m_context->notifyMemoryStore(this, address, size, source); // Bounds check if (!isAddressValid(address, size)) { return false; } // Get buffer size_t offset = EXTRACT_OFFSET(address); Buffer *dst = m_memory[EXTRACT_BUFFER(address)]; // Store data memcpy(dst->data + offset, source, size); return true; } <commit_msg>Added mutex to fix global atomic operations.<commit_after>// Memory.cpp (Oclgrind) // Copyright (c) 2013-2015, James Price and Simon McIntosh-Smith, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "common.h" #include <cassert> #include <cmath> #include <cstring> #include <mutex> #include "Context.h" #include "Memory.h" #include "WorkGroup.h" #include "WorkItem.h" using namespace oclgrind; using namespace std; mutex atomicMutex; Memory::Memory(unsigned int addrSpace, const Context *context) { m_context = context; m_addressSpace = addrSpace; clear(); } Memory::~Memory() { clear(); } size_t Memory::allocateBuffer(size_t size, cl_mem_flags flags) { // Check requested size doesn't exceed maximum if (size > MAX_BUFFER_SIZE) { return 0; } // Find first unallocated buffer slot unsigned b = getNextBuffer(); if (b >= MAX_NUM_BUFFERS) { return 0; } // Create buffer Buffer *buffer = new Buffer; buffer->size = size; buffer->flags = flags; buffer->data = new unsigned char[size]; // Initialize contents to 0 memset(buffer->data, 0, size); if (b >= m_memory.size()) { m_memory.push_back(buffer); } else { m_memory[b] = buffer; } m_totalAllocated += size; size_t address = ((size_t)b) << NUM_ADDRESS_BITS; m_context->notifyMemoryAllocated(this, address, size, flags); return address; } uint32_t Memory::atomic(AtomicOp op, size_t address, uint32_t value) { m_context->notifyMemoryAtomicLoad(this, op, address, 4); m_context->notifyMemoryAtomicStore(this, op, address, 4); // Bounds check if (!isAddressValid(address, 4)) { return 0; } // Get buffer size_t offset = EXTRACT_OFFSET(address); Buffer *buffer = m_memory[EXTRACT_BUFFER(address)]; uint32_t *ptr = (uint32_t*)(buffer->data + offset); if (m_addressSpace == AddrSpaceGlobal) atomicMutex.lock(); uint32_t old = *ptr; switch(op) { case AtomicAdd: *ptr = old + value; break; case AtomicAnd: *ptr = old & value; break; case AtomicCmpXchg: FATAL_ERROR("AtomicCmpXchg in generic atomic handler"); break; case AtomicDec: *ptr = old - 1; break; case AtomicInc: *ptr = old + 1; break; case AtomicMax: *ptr = old > value ? old : value; break; case AtomicMin: *ptr = old < value ? old : value; break; case AtomicOr: *ptr = old | value; break; case AtomicSub: *ptr = old - value; break; case AtomicXchg: *ptr = value; break; case AtomicXor: *ptr = old ^ value; break; } if (m_addressSpace == AddrSpaceGlobal) atomicMutex.unlock(); return old; } uint32_t Memory::atomicCmpxchg(size_t address, uint32_t cmp, uint32_t value) { m_context->notifyMemoryAtomicLoad(this, AtomicCmpXchg, address, 4); // Bounds check if (!isAddressValid(address, 4)) { return 0; } // Get buffer size_t offset = EXTRACT_OFFSET(address); Buffer *buffer = m_memory[EXTRACT_BUFFER(address)]; uint32_t *ptr = (uint32_t*)(buffer->data + offset); if (m_addressSpace == AddrSpaceGlobal) atomicMutex.lock(); // Perform cmpxchg uint32_t old = *ptr; if (old == cmp) { *ptr = value; m_context->notifyMemoryAtomicStore(this, AtomicCmpXchg, address, 4); } if (m_addressSpace == AddrSpaceGlobal) atomicMutex.unlock(); return old; } void Memory::clear() { vector<Buffer*>::iterator itr; for (itr = m_memory.begin(); itr != m_memory.end(); itr++) { if (*itr) { if (!((*itr)->flags & CL_MEM_USE_HOST_PTR)) { delete[] (*itr)->data; } delete *itr; size_t address = (itr-m_memory.begin())<<NUM_ADDRESS_BITS; m_context->notifyMemoryDeallocated(this, address); } } m_memory.resize(1); m_memory[0] = NULL; m_freeBuffers = queue<unsigned>(); m_totalAllocated = 0; } Memory* Memory::clone() const { Memory *mem = new Memory(m_addressSpace, m_context); // Clone buffers mem->m_memory.resize(m_memory.size()); mem->m_memory[0] = NULL; for (unsigned i = 1; i < m_memory.size(); i++) { Buffer *src = m_memory[i]; Buffer *dst = new Buffer; dst->size = src->size; dst->flags = src->flags, dst->data = (src->flags&CL_MEM_USE_HOST_PTR) ? src->data : new unsigned char[src->size], memcpy(dst->data, src->data, src->size); mem->m_memory[i] = dst; m_context->notifyMemoryAllocated(mem, ((size_t)i<<NUM_ADDRESS_BITS), src->size, src->flags); } // Clone state mem->m_freeBuffers = m_freeBuffers; mem->m_totalAllocated = m_totalAllocated; return mem; } size_t Memory::createHostBuffer(size_t size, void *ptr, cl_mem_flags flags) { // Check requested size doesn't exceed maximum if (size > MAX_BUFFER_SIZE) { return 0; } // Find first unallocated buffer slot unsigned b = getNextBuffer(); if (b >= MAX_NUM_BUFFERS) { return 0; } // Create buffer Buffer *buffer = new Buffer; buffer->size = size; buffer->flags = flags; buffer->data = (unsigned char*)ptr; if (b >= m_memory.size()) { m_memory.push_back(buffer); } else { m_memory[b] = buffer; } m_totalAllocated += size; size_t address = ((size_t)b) << NUM_ADDRESS_BITS; m_context->notifyMemoryAllocated(this, address, size, flags); return address; } bool Memory::copy(size_t dst, size_t src, size_t size) { m_context->notifyMemoryLoad(this, src, size); // Check source address if (!isAddressValid(src, size)) { return false; } size_t src_offset = EXTRACT_OFFSET(src); Buffer *src_buffer = m_memory.at(EXTRACT_BUFFER(src)); m_context->notifyMemoryStore(this, dst, size, src_buffer->data + src_offset); // Check destination address if (!isAddressValid(dst, size)) { return false; } size_t dst_offset = EXTRACT_OFFSET(dst); Buffer *dst_buffer = m_memory.at(EXTRACT_BUFFER(dst)); // Copy data memcpy(dst_buffer->data + dst_offset, src_buffer->data + src_offset, size); return true; } void Memory::deallocateBuffer(size_t address) { unsigned buffer = EXTRACT_BUFFER(address); assert(buffer < m_memory.size() && m_memory[buffer]); if (!(m_memory[buffer]->flags & CL_MEM_USE_HOST_PTR)) { delete[] m_memory[buffer]->data; } m_totalAllocated -= m_memory[buffer]->size; m_freeBuffers.push(buffer); delete m_memory[buffer]; m_memory[buffer] = NULL; m_context->notifyMemoryDeallocated(this, address); } void Memory::dump() const { for (unsigned b = 0; b < m_memory.size(); b++) { if (!m_memory[b]->data) { continue; } for (unsigned i = 0; i < m_memory[b]->size; i++) { if (i%4 == 0) { cout << endl << hex << uppercase << setw(16) << setfill(' ') << right << ((((size_t)b)<<NUM_ADDRESS_BITS) | i) << ":"; } cout << " " << hex << uppercase << setw(2) << setfill('0') << (int)m_memory[b]->data[i]; } } cout << endl; } unsigned int Memory::getAddressSpace() const { return m_addressSpace; } const Memory::Buffer* Memory::getBuffer(size_t address) const { size_t buf = EXTRACT_BUFFER(address); if (buf == 0 || buf >= m_memory.size() || !m_memory[buf]->data) { return NULL; } return m_memory[buf]; } size_t Memory::getMaxAllocSize() { return MAX_BUFFER_SIZE; } unsigned Memory::getNextBuffer() { if (m_freeBuffers.empty()) { return m_memory.size(); } else { unsigned b = m_freeBuffers.front(); m_freeBuffers.pop(); return b; } } void* Memory::getPointer(size_t address) const { size_t buffer = EXTRACT_BUFFER(address); // Bounds check if (!isAddressValid(address)) { return NULL; } return m_memory[buffer]->data + EXTRACT_OFFSET(address); } size_t Memory::getTotalAllocated() const { return m_totalAllocated; } bool Memory::isAddressValid(size_t address, size_t size) const { size_t buffer = EXTRACT_BUFFER(address); size_t offset = EXTRACT_OFFSET(address); if (buffer == 0 || buffer >= m_memory.size() || !m_memory[buffer] || offset+size > m_memory[buffer]->size) { return false; } return true; } bool Memory::load(unsigned char *dest, size_t address, size_t size) const { m_context->notifyMemoryLoad(this, address, size); // Bounds check if (!isAddressValid(address, size)) { return false; } // Get buffer size_t offset = EXTRACT_OFFSET(address); Buffer *src = m_memory[EXTRACT_BUFFER(address)]; // Load data memcpy(dest, src->data + offset, size); return true; } unsigned char* Memory::mapBuffer(size_t address, size_t offset, size_t size) { size_t buffer = EXTRACT_BUFFER(address); // Bounds check if (!isAddressValid(address, size)) { return NULL; } return m_memory[buffer]->data + offset + EXTRACT_OFFSET(address); } bool Memory::store(const unsigned char *source, size_t address, size_t size) { m_context->notifyMemoryStore(this, address, size, source); // Bounds check if (!isAddressValid(address, size)) { return false; } // Get buffer size_t offset = EXTRACT_OFFSET(address); Buffer *dst = m_memory[EXTRACT_BUFFER(address)]; // Store data memcpy(dst->data + offset, source, size); return true; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) * * * * This file is part of LuxRays. * * * * LuxRays 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. * * * * LuxRays 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/>. * * * * LuxRays website: http://www.luxrender.net * ***************************************************************************/ #if !defined(WIN32) && !defined(__APPLE__) #include <GL/glx.h> #endif #include "luxrays/core/intersectiondevice.h" #include "luxrays/core/pixeldevice.h" #include "luxrays/core/context.h" #include "luxrays/kernels/kernels.h" namespace luxrays { //------------------------------------------------------------------------------ // DeviceDescription //------------------------------------------------------------------------------ void DeviceDescription::FilterOne(std::vector<DeviceDescription *> &deviceDescriptions) { int gpuIndex = -1; int cpuIndex = -1; for (size_t i = 0; i < deviceDescriptions.size(); ++i) { if ((cpuIndex == -1) && (deviceDescriptions[i]->GetType() == DEVICE_TYPE_NATIVE_THREAD)) cpuIndex = i; #if !defined(LUXRAYS_DISABLE_OPENCL) else if ((gpuIndex == -1) && (deviceDescriptions[i]->GetType() == DEVICE_TYPE_OPENCL) && (((OpenCLDeviceDescription *)deviceDescriptions[i])->GetOpenCLType() == OCL_DEVICE_TYPE_GPU)) { gpuIndex = i; break; } #endif } if (gpuIndex != -1) { std::vector<DeviceDescription *> selectedDev; selectedDev.push_back(deviceDescriptions[gpuIndex]); deviceDescriptions = selectedDev; } else if (gpuIndex != -1) { std::vector<DeviceDescription *> selectedDev; selectedDev.push_back(deviceDescriptions[cpuIndex]); deviceDescriptions = selectedDev; } else deviceDescriptions.clear(); } void DeviceDescription::Filter(const DeviceType type, std::vector<DeviceDescription *> &deviceDescriptions) { size_t i = 0; while (i < deviceDescriptions.size()) { if ((type != DEVICE_TYPE_ALL) && (deviceDescriptions[i]->GetType() != type)) { // Remove the device from the list deviceDescriptions.erase(deviceDescriptions.begin() + i); } else ++i; } } std::string DeviceDescription::GetDeviceType(const DeviceType type) { switch (type) { case DEVICE_TYPE_ALL: return "ALL"; case DEVICE_TYPE_NATIVE_THREAD: return "NATIVE_THREAD"; case DEVICE_TYPE_OPENCL: return "OPENCL"; case DEVICE_TYPE_VIRTUAL: return "VIRTUAL"; default: return "UNKNOWN"; } } //------------------------------------------------------------------------------ // Device //------------------------------------------------------------------------------ Device::Device(const Context *context, const DeviceType type, const unsigned int index) : deviceContext(context), deviceType(type) { deviceIndex = index; started = false; } Device::~Device() { } void Device::Start() { assert (!started); started = true; } void Device::Stop() { assert (started); started = false; } //------------------------------------------------------------------------------ // Native Device Description //------------------------------------------------------------------------------ void NativeThreadDeviceDescription::AddDeviceDescs(std::vector<DeviceDescription *> &descriptions) { unsigned int count = boost::thread::hardware_concurrency(); // Build the descriptions char buf[64]; for (size_t i = 0; i < count; ++i) { sprintf(buf, "NativeThread-%03d", (int)i); std::string deviceName = std::string(buf); descriptions.push_back(new NativeThreadDeviceDescription(deviceName, i)); } } //------------------------------------------------------------------------------ // OpenCL Device Description //------------------------------------------------------------------------------ #if !defined(LUXRAYS_DISABLE_OPENCL) std::string OpenCLDeviceDescription::GetDeviceType(const cl_int type) { switch (type) { case CL_DEVICE_TYPE_ALL: return "TYPE_ALL"; case CL_DEVICE_TYPE_DEFAULT: return "TYPE_DEFAULT"; case CL_DEVICE_TYPE_CPU: return "TYPE_CPU"; case CL_DEVICE_TYPE_GPU: return "TYPE_GPU"; default: return "TYPE_UNKNOWN"; } } std::string OpenCLDeviceDescription::GetDeviceType(const OpenCLDeviceType type) { switch (type) { case OCL_DEVICE_TYPE_ALL: return "ALL"; case OCL_DEVICE_TYPE_DEFAULT: return "DEFAULT"; case OCL_DEVICE_TYPE_CPU: return "CPU"; case OCL_DEVICE_TYPE_GPU: return "GPU"; default: return "UNKNOWN"; } } OpenCLDeviceType OpenCLDeviceDescription::GetOCLDeviceType(const cl_int type) { switch (type) { case CL_DEVICE_TYPE_ALL: return OCL_DEVICE_TYPE_ALL; case CL_DEVICE_TYPE_DEFAULT: return OCL_DEVICE_TYPE_DEFAULT; case CL_DEVICE_TYPE_CPU: return OCL_DEVICE_TYPE_CPU; case CL_DEVICE_TYPE_GPU: return OCL_DEVICE_TYPE_GPU; default: return OCL_DEVICE_TYPE_UNKNOWN; } } void OpenCLDeviceDescription::AddDeviceDescs( const cl::Platform &oclPlatform, const OpenCLDeviceType filter, std::vector<DeviceDescription *> &descriptions) { // Get the list of devices available on the platform VECTOR_CLASS<cl::Device> oclDevices; oclPlatform.getDevices(CL_DEVICE_TYPE_ALL, &oclDevices); // Build the descriptions for (size_t i = 0; i < oclDevices.size(); ++i) { OpenCLDeviceType type = GetOCLDeviceType(oclDevices[i].getInfo<CL_DEVICE_TYPE>()); if ((filter == OCL_DEVICE_TYPE_ALL) || (filter == type)) { OpenCLDeviceDescription *desc = new OpenCLDeviceDescription(oclDevices[i], i); descriptions.push_back(desc); } } } cl::Context &OpenCLDeviceDescription::GetOCLContext() const { if (!oclContext) { // Allocate a context with the selected device VECTOR_CLASS<cl::Device> devices; devices.push_back(oclDevice); cl::Platform platform = oclDevice.getInfo<CL_DEVICE_PLATFORM>(); if (enableOpenGLInterop) { #if defined (__APPLE__) CGLContextObj kCGLContext = CGLGetCurrentContext(); CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext); cl_context_properties cps[] = { CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup, 0 }; #if defined(APPLE_WORKAROUND) // TODO: find a btter way to handle APPLE odd behavior (i.e. it is not // possible to explicit select the OpenCL device oclContext = new cl::Context(cps); #else oclContext = new cl::Context(devices, cps); #endif #else #ifdef WIN32 cl_context_properties cps[] = { CL_GL_CONTEXT_KHR, (intptr_t)wglGetCurrentContext(), CL_WGL_HDC_KHR, (intptr_t)wglGetCurrentDC(), CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0 }; oclContext = new cl::Context(devices, cps); #else cl_context_properties cps[] = { CL_GL_CONTEXT_KHR, (intptr_t)glXGetCurrentContext(), CL_GLX_DISPLAY_KHR, (intptr_t)glXGetCurrentDisplay(), CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0 }; oclContext = new cl::Context(devices, cps); #endif #endif } else { cl_context_properties cps[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0 }; oclContext = new cl::Context(devices, cps); } } return *oclContext; } void OpenCLDeviceDescription::Filter(const OpenCLDeviceType type, std::vector<DeviceDescription *> &deviceDescriptions) { if (type == OCL_DEVICE_TYPE_ALL) return; size_t i = 0; while (i < deviceDescriptions.size()) { if ((deviceDescriptions[i]->GetType() == DEVICE_TYPE_OPENCL) && (((OpenCLDeviceDescription *)deviceDescriptions[i])->GetOpenCLType() != type)) { // Remove the device from the list deviceDescriptions.erase(deviceDescriptions.begin() + i); } else ++i; } } #endif //------------------------------------------------------------------------------ // IntersectionDevice //------------------------------------------------------------------------------ IntersectionDevice::IntersectionDevice(const Context *context, const DeviceType type, const unsigned int index) : Device(context, type, index) { dataSet = NULL; } IntersectionDevice::~IntersectionDevice() { } void IntersectionDevice::SetDataSet(const DataSet *newDataSet) { assert (!started); assert (newDataSet != NULL); assert (newDataSet->IsPreprocessed()); dataSet = newDataSet; } void IntersectionDevice::Start() { assert (dataSet != NULL); Device::Start(); statsStartTime = WallClockTime(); statsTotalRayCount = 0.0; statsDeviceIdleTime = 0.0; statsDeviceTotalTime = 0.0; } //------------------------------------------------------------------------------ // PixelDevice //------------------------------------------------------------------------------ PixelDevice::PixelDevice(const Context *context, const DeviceType type, const unsigned int index) : Device(context, type, index) { } PixelDevice::~PixelDevice() { } void PixelDevice::Init(const unsigned int w, const unsigned int h) { assert (!started); width = w; height = h; } void PixelDevice::Start() { Device::Start(); statsTotalSampleTime = 0.0; statsTotalSamplesCount = 0.0; } } <commit_msg>Rollback of the last MacOS related commit<commit_after>/*************************************************************************** * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) * * * * This file is part of LuxRays. * * * * LuxRays 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. * * * * LuxRays 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/>. * * * * LuxRays website: http://www.luxrender.net * ***************************************************************************/ #if !defined(WIN32) && !defined(__APPLE__) #include <GL/glx.h> #endif #include "luxrays/core/intersectiondevice.h" #include "luxrays/core/pixeldevice.h" #include "luxrays/core/context.h" #include "luxrays/kernels/kernels.h" namespace luxrays { //------------------------------------------------------------------------------ // DeviceDescription //------------------------------------------------------------------------------ void DeviceDescription::FilterOne(std::vector<DeviceDescription *> &deviceDescriptions) { int gpuIndex = -1; int cpuIndex = -1; for (size_t i = 0; i < deviceDescriptions.size(); ++i) { if ((cpuIndex == -1) && (deviceDescriptions[i]->GetType() == DEVICE_TYPE_NATIVE_THREAD)) cpuIndex = i; #if !defined(LUXRAYS_DISABLE_OPENCL) else if ((gpuIndex == -1) && (deviceDescriptions[i]->GetType() == DEVICE_TYPE_OPENCL) && (((OpenCLDeviceDescription *)deviceDescriptions[i])->GetOpenCLType() == OCL_DEVICE_TYPE_GPU)) { gpuIndex = i; break; } #endif } if (gpuIndex != -1) { std::vector<DeviceDescription *> selectedDev; selectedDev.push_back(deviceDescriptions[gpuIndex]); deviceDescriptions = selectedDev; } else if (gpuIndex != -1) { std::vector<DeviceDescription *> selectedDev; selectedDev.push_back(deviceDescriptions[cpuIndex]); deviceDescriptions = selectedDev; } else deviceDescriptions.clear(); } void DeviceDescription::Filter(const DeviceType type, std::vector<DeviceDescription *> &deviceDescriptions) { size_t i = 0; while (i < deviceDescriptions.size()) { if ((type != DEVICE_TYPE_ALL) && (deviceDescriptions[i]->GetType() != type)) { // Remove the device from the list deviceDescriptions.erase(deviceDescriptions.begin() + i); } else ++i; } } std::string DeviceDescription::GetDeviceType(const DeviceType type) { switch (type) { case DEVICE_TYPE_ALL: return "ALL"; case DEVICE_TYPE_NATIVE_THREAD: return "NATIVE_THREAD"; case DEVICE_TYPE_OPENCL: return "OPENCL"; case DEVICE_TYPE_VIRTUAL: return "VIRTUAL"; default: return "UNKNOWN"; } } //------------------------------------------------------------------------------ // Device //------------------------------------------------------------------------------ Device::Device(const Context *context, const DeviceType type, const unsigned int index) : deviceContext(context), deviceType(type) { deviceIndex = index; started = false; } Device::~Device() { } void Device::Start() { assert (!started); started = true; } void Device::Stop() { assert (started); started = false; } //------------------------------------------------------------------------------ // Native Device Description //------------------------------------------------------------------------------ void NativeThreadDeviceDescription::AddDeviceDescs(std::vector<DeviceDescription *> &descriptions) { unsigned int count = boost::thread::hardware_concurrency(); // Build the descriptions char buf[64]; for (size_t i = 0; i < count; ++i) { sprintf(buf, "NativeThread-%03d", (int)i); std::string deviceName = std::string(buf); descriptions.push_back(new NativeThreadDeviceDescription(deviceName, i)); } } //------------------------------------------------------------------------------ // OpenCL Device Description //------------------------------------------------------------------------------ #if !defined(LUXRAYS_DISABLE_OPENCL) std::string OpenCLDeviceDescription::GetDeviceType(const cl_int type) { switch (type) { case CL_DEVICE_TYPE_ALL: return "TYPE_ALL"; case CL_DEVICE_TYPE_DEFAULT: return "TYPE_DEFAULT"; case CL_DEVICE_TYPE_CPU: return "TYPE_CPU"; case CL_DEVICE_TYPE_GPU: return "TYPE_GPU"; default: return "TYPE_UNKNOWN"; } } std::string OpenCLDeviceDescription::GetDeviceType(const OpenCLDeviceType type) { switch (type) { case OCL_DEVICE_TYPE_ALL: return "ALL"; case OCL_DEVICE_TYPE_DEFAULT: return "DEFAULT"; case OCL_DEVICE_TYPE_CPU: return "CPU"; case OCL_DEVICE_TYPE_GPU: return "GPU"; default: return "UNKNOWN"; } } OpenCLDeviceType OpenCLDeviceDescription::GetOCLDeviceType(const cl_int type) { switch (type) { case CL_DEVICE_TYPE_ALL: return OCL_DEVICE_TYPE_ALL; case CL_DEVICE_TYPE_DEFAULT: return OCL_DEVICE_TYPE_DEFAULT; case CL_DEVICE_TYPE_CPU: return OCL_DEVICE_TYPE_CPU; case CL_DEVICE_TYPE_GPU: return OCL_DEVICE_TYPE_GPU; default: return OCL_DEVICE_TYPE_UNKNOWN; } } void OpenCLDeviceDescription::AddDeviceDescs( const cl::Platform &oclPlatform, const OpenCLDeviceType filter, std::vector<DeviceDescription *> &descriptions) { // Get the list of devices available on the platform VECTOR_CLASS<cl::Device> oclDevices; oclPlatform.getDevices(CL_DEVICE_TYPE_ALL, &oclDevices); // Build the descriptions for (size_t i = 0; i < oclDevices.size(); ++i) { OpenCLDeviceType type = GetOCLDeviceType(oclDevices[i].getInfo<CL_DEVICE_TYPE>()); if ((filter == OCL_DEVICE_TYPE_ALL) || (filter == type)) { OpenCLDeviceDescription *desc = new OpenCLDeviceDescription(oclDevices[i], i); descriptions.push_back(desc); } } } cl::Context &OpenCLDeviceDescription::GetOCLContext() const { if (!oclContext) { // Allocate a context with the selected device VECTOR_CLASS<cl::Device> devices; devices.push_back(oclDevice); cl::Platform platform = oclDevice.getInfo<CL_DEVICE_PLATFORM>(); if (enableOpenGLInterop) { #if defined (__APPLE__) CGLContextObj kCGLContext = CGLGetCurrentContext(); CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext); cl_context_properties cps[] = { CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup, 0 }; #else #ifdef WIN32 cl_context_properties cps[] = { CL_GL_CONTEXT_KHR, (intptr_t)wglGetCurrentContext(), CL_WGL_HDC_KHR, (intptr_t)wglGetCurrentDC(), CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0 }; #else cl_context_properties cps[] = { CL_GL_CONTEXT_KHR, (intptr_t)glXGetCurrentContext(), CL_GLX_DISPLAY_KHR, (intptr_t)glXGetCurrentDisplay(), CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0 }; #endif #endif oclContext = new cl::Context(devices, cps); } else { cl_context_properties cps[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0 }; oclContext = new cl::Context(devices, cps); } } return *oclContext; } void OpenCLDeviceDescription::Filter(const OpenCLDeviceType type, std::vector<DeviceDescription *> &deviceDescriptions) { if (type == OCL_DEVICE_TYPE_ALL) return; size_t i = 0; while (i < deviceDescriptions.size()) { if ((deviceDescriptions[i]->GetType() == DEVICE_TYPE_OPENCL) && (((OpenCLDeviceDescription *)deviceDescriptions[i])->GetOpenCLType() != type)) { // Remove the device from the list deviceDescriptions.erase(deviceDescriptions.begin() + i); } else ++i; } } #endif //------------------------------------------------------------------------------ // IntersectionDevice //------------------------------------------------------------------------------ IntersectionDevice::IntersectionDevice(const Context *context, const DeviceType type, const unsigned int index) : Device(context, type, index) { dataSet = NULL; } IntersectionDevice::~IntersectionDevice() { } void IntersectionDevice::SetDataSet(const DataSet *newDataSet) { assert (!started); assert (newDataSet != NULL); assert (newDataSet->IsPreprocessed()); dataSet = newDataSet; } void IntersectionDevice::Start() { assert (dataSet != NULL); Device::Start(); statsStartTime = WallClockTime(); statsTotalRayCount = 0.0; statsDeviceIdleTime = 0.0; statsDeviceTotalTime = 0.0; } //------------------------------------------------------------------------------ // PixelDevice //------------------------------------------------------------------------------ PixelDevice::PixelDevice(const Context *context, const DeviceType type, const unsigned int index) : Device(context, type, index) { } PixelDevice::~PixelDevice() { } void PixelDevice::Init(const unsigned int w, const unsigned int h) { assert (!started); width = w; height = h; } void PixelDevice::Start() { Device::Start(); statsTotalSampleTime = 0.0; statsTotalSamplesCount = 0.0; } } <|endoftext|>
<commit_before>/* - MuzicZapper - Copyright (C) 2011-2017 Sebastien Vavassori * * This program is free software; you can redistribute it and/or * modify it under the terms of the MIT License. * * 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 "player.h" #include <Core/Playlist> #include <QtCore/QDebug> #include <QtCore/QList> #include <QtCore/QUrl> #include <QtCore/QFileInfo> #include <QtCore/QModelIndex> #include <QtMultimedia/QMediaPlayer> #include <QtMultimedia/QMediaPlaylist> Player::Player(QObject *parent) : QObject(parent) , m_player(new QMediaPlayer(this)) , m_playlist(new Playlist(this)) { m_player->setPlaylist(m_playlist); connect(m_player, SIGNAL(metaDataAvailableChanged(bool)), SIGNAL(metaDataAvailableChanged(bool))); connect(m_player, SIGNAL(metaDataChanged()), SIGNAL(metaDataChanged())); connect(m_player, SIGNAL(metaDataChanged(QString,QVariant)), SIGNAL(metaDataChanged(QString,QVariant))); connect(m_player, SIGNAL(mediaChanged(QMediaContent)), SIGNAL(mediaChanged(QMediaContent))); connect(m_player, SIGNAL(currentMediaChanged(QMediaContent)), this, SLOT(onCurrentMediaChanged(QMediaContent))); connect(m_player, SIGNAL(stateChanged(QMediaPlayer::State)), SIGNAL(stateChanged(QMediaPlayer::State))); connect(m_player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus))); connect(m_player, SIGNAL(durationChanged(qint64)), SIGNAL(durationChanged(qint64))); connect(m_player, SIGNAL(positionChanged(qint64)), SIGNAL(positionChanged(qint64))); connect(m_player, SIGNAL(volumeChanged(int)), SIGNAL(volumeChanged(int))); connect(m_player, SIGNAL(mutedChanged(bool)), SIGNAL(mutedChanged(bool))); connect(m_player, SIGNAL(audioAvailableChanged(bool)), SIGNAL(audioAvailableChanged(bool))); connect(m_player, SIGNAL(videoAvailableChanged(bool)), SIGNAL(videoAvailableChanged(bool))); connect(m_player, SIGNAL(bufferStatusChanged(int)), SIGNAL(bufferStatusChanged(int))); connect(m_player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(onError(QMediaPlayer::Error))); connect(m_playlist, SIGNAL(mediaInserted(int,int)), this, SLOT(onMediaChanged(int,int))); connect(m_playlist, SIGNAL(mediaRemoved(int,int)), this, SLOT(onMediaChanged(int,int))); connect(m_playlist, SIGNAL(mediaChanged(int,int)), this, SLOT(onMediaChanged(int,int))); } Player::~Player() { } void Player::clear() { m_playlist->clear(); } Playlist *Player::playlist() const { return m_playlist; } /*********************************************************************************** ***********************************************************************************/ /* JSON Serialization */ void Player::read(const QJsonObject &json) { m_playlist->read(json); } void Player::write(QJsonObject &json) const { m_playlist->write(json); } /*********************************************************************************** ***********************************************************************************/ /*! \internal * \brief Check for ".m3u" playlists. */ static bool isPlaylist(const QUrl &url) { if (!url.isLocalFile()) return false; const QFileInfo fileInfo(url.toLocalFile()); return fileInfo.exists() && !fileInfo.suffix().compare(QLatin1String("m3u"), Qt::CaseInsensitive); } void Player::addToPlaylist(const QList<QUrl> urls) { foreach (const QUrl &url, urls) { if (isPlaylist(url)) m_playlist->load(url); else m_playlist->addMedia(url); } } /*********************************************************************************** ***********************************************************************************/ void Player::play() { m_player->play(); } void Player::pause() { m_player->pause(); } void Player::stop() { m_player->stop(); } void Player::next() { m_playlist->next(); } void Player::previous() { /* * Go to previous track if we are within the first 5 seconds of playback. * Otherwise, seek to the beginning. */ if (m_player->position() <= 5000) m_playlist->previous(); else m_player->setPosition(0); } /*********************************************************************************** ***********************************************************************************/ bool Player::isPlayerAvailable() const { return m_player->isAvailable(); m_player->supportedMimeTypes(); } QStringList Player::supportedMimeTypes() const { return m_player->supportedMimeTypes(); } /*********************************************************************************** ***********************************************************************************/ QString Player::errorString() const { return m_player->errorString(); } /*********************************************************************************** ***********************************************************************************/ bool Player::isMetaDataAvailable() const { return m_player->isMetaDataAvailable(); } QVariant Player::metaData(const QString &key) const { return m_player->metaData(key); } QStringList Player::availableMetaData() const { return m_player->availableMetaData(); } /*********************************************************************************** ***********************************************************************************/ //qint64 Player::position() const //{ // return m_player->duration(); //} // //void Player::setPosition(qint64 position) //{ // m_player->setPosition(position); //} qint64 Player::duration() const { return m_player->position(); } QMediaPlayer::State Player::state() const { return m_player->state(); } void Player::setVideoOutput(QVideoWidget *widget) { m_player->setVideoOutput(widget); } /*********************************************************************************** ***********************************************************************************/ int Player::volume() const { return m_player->volume(); } void Player::setVolume(int volume) { m_player->setVolume(volume); } /*********************************************************************************** ***********************************************************************************/ bool Player::isMuted() const { return m_player->isMuted(); } void Player::setMuted(bool muted) { m_player->setMuted(muted); } bool Player::isAudioAvailable() const { return m_player->isAudioAvailable(); } bool Player::isVideoAvailable() const { return m_player->isVideoAvailable(); } void Player::setPlaybackRate(qreal rate) { m_player->setPlaybackRate(rate); } /*********************************************************************************** ***********************************************************************************/ void Player::seek(int seconds) { m_player->setPosition(seconds * 1000); } void Player::jump(const QModelIndex &index) { if (index.isValid()) { m_playlist->setCurrentIndex(index.row()); m_player->play(); } } /*********************************************************************************** ***********************************************************************************/ void Player::onMediaChanged(int /*start*/, int /*end*/) { /* It simplifies the signal signature */ /* by removing the useless arguments. */ emit mediaChanged(); } /*********************************************************************************** ***********************************************************************************/ static inline Media::Error toMediaError(QMediaPlayer::Error e) { switch (e) { case QMediaPlayer::NoError: return Media::NoError; break; case QMediaPlayer::ResourceError: return Media::ResourceError; break; case QMediaPlayer::FormatError: return Media::FormatError; break; case QMediaPlayer::NetworkError: return Media::NetworkError; break; case QMediaPlayer::AccessDeniedError: return Media::AccessDeniedError; break; case QMediaPlayer::ServiceMissingError: return Media::ServiceMissingError; break; default: Q_UNREACHABLE(); break; } return Media::NoError; } void Player::onCurrentMediaChanged(const QMediaContent &media) { m_playlist->setMediaError(m_playlist->currentIndex(), Media::NoError); emit currentMediaChanged(media); } void Player::onError(QMediaPlayer::Error e) { m_playlist->setMediaError(m_playlist->currentIndex(), toMediaError(e)); emit error(e); } <commit_msg>added permanence for volume and mute on/off option (QSettings)<commit_after>/* - MuzicZapper - Copyright (C) 2011-2017 Sebastien Vavassori * * This program is free software; you can redistribute it and/or * modify it under the terms of the MIT License. * * 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 "player.h" #include <Core/Playlist> #include <QtCore/QDebug> #include <QtCore/QList> #include <QtCore/QUrl> #include <QtCore/QFileInfo> #include <QtCore/QModelIndex> #include <QtCore/QSettings> #include <QtMultimedia/QMediaPlayer> #include <QtMultimedia/QMediaPlaylist> static char STR_SETTING_VOLUME[] = "volume"; static char STR_SETTING_IS_MUTED[] = "isMuted"; Player::Player(QObject *parent) : QObject(parent) , m_player(new QMediaPlayer(this)) , m_playlist(new Playlist(this)) { m_player->setPlaylist(m_playlist); connect(m_player, SIGNAL(metaDataAvailableChanged(bool)), SIGNAL(metaDataAvailableChanged(bool))); connect(m_player, SIGNAL(metaDataChanged()), SIGNAL(metaDataChanged())); connect(m_player, SIGNAL(metaDataChanged(QString,QVariant)), SIGNAL(metaDataChanged(QString,QVariant))); connect(m_player, SIGNAL(mediaChanged(QMediaContent)), SIGNAL(mediaChanged(QMediaContent))); connect(m_player, SIGNAL(currentMediaChanged(QMediaContent)), this, SLOT(onCurrentMediaChanged(QMediaContent))); connect(m_player, SIGNAL(stateChanged(QMediaPlayer::State)), SIGNAL(stateChanged(QMediaPlayer::State))); connect(m_player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus))); connect(m_player, SIGNAL(durationChanged(qint64)), SIGNAL(durationChanged(qint64))); connect(m_player, SIGNAL(positionChanged(qint64)), SIGNAL(positionChanged(qint64))); connect(m_player, SIGNAL(volumeChanged(int)), SIGNAL(volumeChanged(int))); connect(m_player, SIGNAL(mutedChanged(bool)), SIGNAL(mutedChanged(bool))); connect(m_player, SIGNAL(audioAvailableChanged(bool)), SIGNAL(audioAvailableChanged(bool))); connect(m_player, SIGNAL(videoAvailableChanged(bool)), SIGNAL(videoAvailableChanged(bool))); connect(m_player, SIGNAL(bufferStatusChanged(int)), SIGNAL(bufferStatusChanged(int))); connect(m_player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(onError(QMediaPlayer::Error))); connect(m_playlist, SIGNAL(mediaInserted(int,int)), this, SLOT(onMediaChanged(int,int))); connect(m_playlist, SIGNAL(mediaRemoved(int,int)), this, SLOT(onMediaChanged(int,int))); connect(m_playlist, SIGNAL(mediaChanged(int,int)), this, SLOT(onMediaChanged(int,int))); QSettings settings; m_player->setVolume(settings.value(STR_SETTING_VOLUME, 50).toInt()); m_player->setMuted(settings.value(STR_SETTING_IS_MUTED, false).toBool()); } Player::~Player() { if(m_player) { QSettings settings; settings.setValue(STR_SETTING_VOLUME, m_player->volume()); settings.setValue(STR_SETTING_IS_MUTED, m_player->isMuted()); } } void Player::clear() { m_playlist->clear(); } Playlist *Player::playlist() const { return m_playlist; } /*********************************************************************************** ***********************************************************************************/ /* JSON Serialization */ void Player::read(const QJsonObject &json) { m_playlist->read(json); } void Player::write(QJsonObject &json) const { m_playlist->write(json); } /*********************************************************************************** ***********************************************************************************/ /*! \internal * \brief Check for ".m3u" playlists. */ static bool isPlaylist(const QUrl &url) { if (!url.isLocalFile()) return false; const QFileInfo fileInfo(url.toLocalFile()); return fileInfo.exists() && !fileInfo.suffix().compare(QLatin1String("m3u"), Qt::CaseInsensitive); } void Player::addToPlaylist(const QList<QUrl> urls) { foreach (const QUrl &url, urls) { if (isPlaylist(url)) m_playlist->load(url); else m_playlist->addMedia(url); } } /*********************************************************************************** ***********************************************************************************/ void Player::play() { m_player->play(); } void Player::pause() { m_player->pause(); } void Player::stop() { m_player->stop(); } void Player::next() { m_playlist->next(); } void Player::previous() { /* * Go to previous track if we are within the first 5 seconds of playback. * Otherwise, seek to the beginning. */ if (m_player->position() <= 5000) m_playlist->previous(); else m_player->setPosition(0); } /*********************************************************************************** ***********************************************************************************/ bool Player::isPlayerAvailable() const { return m_player->isAvailable(); m_player->supportedMimeTypes(); } QStringList Player::supportedMimeTypes() const { return m_player->supportedMimeTypes(); } /*********************************************************************************** ***********************************************************************************/ QString Player::errorString() const { return m_player->errorString(); } /*********************************************************************************** ***********************************************************************************/ bool Player::isMetaDataAvailable() const { return m_player->isMetaDataAvailable(); } QVariant Player::metaData(const QString &key) const { return m_player->metaData(key); } QStringList Player::availableMetaData() const { return m_player->availableMetaData(); } /*********************************************************************************** ***********************************************************************************/ //qint64 Player::position() const //{ // return m_player->duration(); //} // //void Player::setPosition(qint64 position) //{ // m_player->setPosition(position); //} qint64 Player::duration() const { return m_player->position(); } QMediaPlayer::State Player::state() const { return m_player->state(); } void Player::setVideoOutput(QVideoWidget *widget) { m_player->setVideoOutput(widget); } /*********************************************************************************** ***********************************************************************************/ int Player::volume() const { return m_player->volume(); } void Player::setVolume(int volume) { m_player->setVolume(volume); } /*********************************************************************************** ***********************************************************************************/ bool Player::isMuted() const { return m_player->isMuted(); } void Player::setMuted(bool muted) { m_player->setMuted(muted); } bool Player::isAudioAvailable() const { return m_player->isAudioAvailable(); } bool Player::isVideoAvailable() const { return m_player->isVideoAvailable(); } void Player::setPlaybackRate(qreal rate) { m_player->setPlaybackRate(rate); } /*********************************************************************************** ***********************************************************************************/ void Player::seek(int seconds) { m_player->setPosition(seconds * 1000); } void Player::jump(const QModelIndex &index) { if (index.isValid()) { m_playlist->setCurrentIndex(index.row()); m_player->play(); } } /*********************************************************************************** ***********************************************************************************/ void Player::onMediaChanged(int /*start*/, int /*end*/) { /* It simplifies the signal signature */ /* by removing the useless arguments. */ emit mediaChanged(); } /*********************************************************************************** ***********************************************************************************/ static inline Media::Error toMediaError(QMediaPlayer::Error e) { switch (e) { case QMediaPlayer::NoError: return Media::NoError; break; case QMediaPlayer::ResourceError: return Media::ResourceError; break; case QMediaPlayer::FormatError: return Media::FormatError; break; case QMediaPlayer::NetworkError: return Media::NetworkError; break; case QMediaPlayer::AccessDeniedError: return Media::AccessDeniedError; break; case QMediaPlayer::ServiceMissingError: return Media::ServiceMissingError; break; default: Q_UNREACHABLE(); break; } return Media::NoError; } void Player::onCurrentMediaChanged(const QMediaContent &media) { m_playlist->setMediaError(m_playlist->currentIndex(), Media::NoError); emit currentMediaChanged(media); } void Player::onError(QMediaPlayer::Error e) { m_playlist->setMediaError(m_playlist->currentIndex(), toMediaError(e)); emit error(e); } <|endoftext|>