text
stringlengths
54
60.6k
<commit_before>#include "Julian.h" #include "Tle.h" #include "SGP4.h" #include "Globals.h" #include "Observer.h" #include "CoordGeodetic.h" #include "CoordTopographic.h" #include <list> #include <string> #include <iomanip> #include <iostream> #include <fstream> #include <vector> #include <cstdlib> void RunTle(Tle tle, double start, double end, double inc) { double current = start; SGP4 model; model.SetTle(tle); bool running = true; bool first_run = true; std::cout << " " << std::setprecision(0) << tle.NoradNumber() << " xx" << std::endl; while (running) { try { double val; Eci eci; if (first_run && current != 0.0) { /* * make sure first run is always as zero */ val = 0.0; } else { /* * otherwise run as normal */ val = current; } model.FindPosition(eci, val); Vector position = eci.GetPosition(); Vector velocity = eci.GetVelocity(); std::cout << std::setprecision(8) << std::fixed; std::cout.width(17); std::cout << val << " "; std::cout.width(16); std::cout << position.GetX() << " "; std::cout.width(16); std::cout << position.GetY() << " "; std::cout.width(16); std::cout << position.GetZ() << " "; std::cout << std::setprecision(9) << std::fixed; std::cout.width(14); std::cout << velocity.GetX() << " "; std::cout.width(14); std::cout << velocity.GetY() << " "; std::cout.width(14); std::cout << velocity.GetZ() << std::endl; } catch (std::exception* ex) { std::cout << ex->what() << std::endl; running = false; } if ((first_run && current == 0.0) || !first_run) { if (current == end) running = false; else if (current + inc > end) current = end; else current += inc; } first_run = false; } } void tokenize(const std::string& str, std::vector<std::string>& tokens) { const std::string& delimiters = " "; /* * skip delimiters at beginning */ std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); /* * find first non-delimiter */ std::string::size_type pos = str.find_first_of(delimiters, last_pos); while (std::string::npos != pos || std::string::npos != last_pos) { /* * add found token to vector */ tokens.push_back(str.substr(last_pos, pos - last_pos)); /* * skip delimiters */ last_pos = str.find_first_not_of(delimiters, pos); /* * find next non-delimiter */ pos = str.find_first_of(delimiters, last_pos); } } void RunTest(const char* infile) { std::ifstream file; file.open(infile); if (!file.is_open()) { std::cerr << "Error opening file" << std::endl; return; } bool got_first_line = false; std::string line1; std::string line2; std::string parameters; while (!file.eof()) { std::string line; std::getline(file, line); /* * trim spaces */ Tle::TrimLeft(line); Tle::TrimRight(line); /* * skip blank lines or lines starting with # */ if (line.length() == 0 || line[0] == '#') { got_first_line = false; continue; } /* * find first line */ if (!got_first_line) { if (Tle::IsValidLine(line, 1)) { /* * store line and now read in second line */ got_first_line = true; line1 = line; } else { std::cerr << "Error: Badly formatted first line:" << std::endl; std::cerr << line << std::endl; } } else { /* * no second chances, second line should follow the first */ got_first_line = false; /* * split line, first 69 is the second line of the tle * the rest is the test parameters, if there is any */ line2 = line.substr(0, 69); double start = 0.0; double end = 1440.0; double inc = 120.0; if (line.length() > 69) { std::vector<std::string> tokens; parameters = line.substr(70, line.length() - 69); tokenize(parameters, tokens); if (tokens.size() >= 3) { start = atof(tokens[0].c_str()); end = atof(tokens[1].c_str()); inc = atof(tokens[2].c_str()); } } /* * following line must be the second line */ if (Tle::IsValidLine(line2, 2)) { Tle tle("Test", line1, line2); RunTle(tle, 0.0, 1440.0, 120.0); } else { std::cerr << "Error: Badly formatted second line:" << std::endl; std::cerr << line2 << std::endl; } } } /* * close file */ file.close(); return; } int main() { const char* file_name = "SGP4-VER.TLE"; RunTest(file_name); return 0; } <commit_msg>Use time parameters give in test file.<commit_after>#include "Julian.h" #include "Tle.h" #include "SGP4.h" #include "Globals.h" #include "Observer.h" #include "CoordGeodetic.h" #include "CoordTopographic.h" #include <list> #include <string> #include <iomanip> #include <iostream> #include <fstream> #include <vector> #include <cstdlib> void RunTle(Tle tle, double start, double end, double inc) { double current = start; SGP4 model; model.SetTle(tle); bool running = true; bool first_run = true; std::cout << " " << std::setprecision(0) << tle.NoradNumber() << " xx" << std::endl; while (running) { try { double val; Eci eci; if (first_run && current != 0.0) { /* * make sure first run is always as zero */ val = 0.0; } else { /* * otherwise run as normal */ val = current; } model.FindPosition(eci, val); Vector position = eci.GetPosition(); Vector velocity = eci.GetVelocity(); std::cout << std::setprecision(8) << std::fixed; std::cout.width(17); std::cout << val << " "; std::cout.width(16); std::cout << position.GetX() << " "; std::cout.width(16); std::cout << position.GetY() << " "; std::cout.width(16); std::cout << position.GetZ() << " "; std::cout << std::setprecision(9) << std::fixed; std::cout.width(14); std::cout << velocity.GetX() << " "; std::cout.width(14); std::cout << velocity.GetY() << " "; std::cout.width(14); std::cout << velocity.GetZ() << std::endl; } catch (std::exception* ex) { std::cout << ex->what() << std::endl; running = false; } if ((first_run && current == 0.0) || !first_run) { if (current == end) running = false; else if (current + inc > end) current = end; else current += inc; } first_run = false; } } void tokenize(const std::string& str, std::vector<std::string>& tokens) { const std::string& delimiters = " "; /* * skip delimiters at beginning */ std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); /* * find first non-delimiter */ std::string::size_type pos = str.find_first_of(delimiters, last_pos); while (std::string::npos != pos || std::string::npos != last_pos) { /* * add found token to vector */ tokens.push_back(str.substr(last_pos, pos - last_pos)); /* * skip delimiters */ last_pos = str.find_first_not_of(delimiters, pos); /* * find next non-delimiter */ pos = str.find_first_of(delimiters, last_pos); } } void RunTest(const char* infile) { std::ifstream file; file.open(infile); if (!file.is_open()) { std::cerr << "Error opening file" << std::endl; return; } bool got_first_line = false; std::string line1; std::string line2; std::string parameters; while (!file.eof()) { std::string line; std::getline(file, line); /* * trim spaces */ Tle::TrimLeft(line); Tle::TrimRight(line); /* * skip blank lines or lines starting with # */ if (line.length() == 0 || line[0] == '#') { got_first_line = false; continue; } /* * find first line */ if (!got_first_line) { if (Tle::IsValidLine(line, 1)) { /* * store line and now read in second line */ got_first_line = true; line1 = line; } else { std::cerr << "Error: Badly formatted first line:" << std::endl; std::cerr << line << std::endl; } } else { /* * no second chances, second line should follow the first */ got_first_line = false; /* * split line, first 69 is the second line of the tle * the rest is the test parameters, if there is any */ line2 = line.substr(0, 69); double start = 0.0; double end = 1440.0; double inc = 120.0; if (line.length() > 69) { std::vector<std::string> tokens; parameters = line.substr(70, line.length() - 69); tokenize(parameters, tokens); if (tokens.size() >= 3) { start = atof(tokens[0].c_str()); end = atof(tokens[1].c_str()); inc = atof(tokens[2].c_str()); } } /* * following line must be the second line */ if (Tle::IsValidLine(line2, 2)) { Tle tle("Test", line1, line2); RunTle(tle, start, end, inc); } else { std::cerr << "Error: Badly formatted second line:" << std::endl; std::cerr << line2 << std::endl; } } } /* * close file */ file.close(); return; } int main() { const char* file_name = "SGP4-VER.TLE"; RunTest(file_name); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2000-2004 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /// /// @file sim/main.cc /// #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <signal.h> #include <list> #include <string> #include <vector> #include "base/copyright.hh" #include "base/embedfile.hh" #include "base/inifile.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/pollevent.hh" #include "base/statistics.hh" #include "base/str.hh" #include "base/time.hh" #include "cpu/base_cpu.hh" #include "cpu/full_cpu/smt.hh" #include "sim/async.hh" #include "sim/builder.hh" #include "sim/configfile.hh" #include "sim/host.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_object.hh" #include "sim/stat_control.hh" #include "sim/stats.hh" #include "sim/universe.hh" #include "sim/pyconfig/pyconfig.hh" using namespace std; // See async.h. volatile bool async_event = false; volatile bool async_dump = false; volatile bool async_dumpreset = false; volatile bool async_exit = false; volatile bool async_io = false; volatile bool async_alarm = false; /// Stats signal handler. void dumpStatsHandler(int sigtype) { async_event = true; async_dump = true; } void dumprstStatsHandler(int sigtype) { async_event = true; async_dumpreset = true; } /// Exit signal handler. void exitNowHandler(int sigtype) { async_event = true; async_exit = true; } /// Abort signal handler. void abortHandler(int sigtype) { cerr << "Program aborted at cycle " << curTick << endl; #if TRACING_ON // dump trace buffer, if there is one Trace::theLog.dump(cerr); #endif } /// Simulator executable name const char *myProgName = ""; /// Show brief help message. void showBriefHelp(ostream &out) { char *prog = basename(myProgName); ccprintf(out, "Usage:\n"); ccprintf(out, "%s [-d <dir>] [-E <var>[=<val>]] [-I <dir>] [-P <python>]\n" " [--<var>=<val>] <config file>\n" "\n" " -d set the output directory to <dir>\n" " -E set the environment variable <var> to <val> (or 'True')\n" " -I add the directory <dir> to python's path\n" " -P execute <python> directly in the configuration\n" " --var=val set the python variable <var> to '<val>'\n" " <configfile> config file name (.py or .mpy)\n", prog); ccprintf(out, "%s -X\n -X extract embedded files\n", prog); ccprintf(out, "%s -h\n -h print long help\n", prog); } /// Show verbose help message. Includes parameter listing from /// showBriefHelp(), plus an exhaustive list of ini-file parameters /// and SimObjects (with their parameters). void showLongHelp(ostream &out) { showBriefHelp(out); out << endl << endl << "-----------------" << endl << "Global Parameters" << endl << "-----------------" << endl << endl; ParamContext::describeAllContexts(out); out << endl << endl << "-----------------" << endl << "Simulator Objects" << endl << "-----------------" << endl << endl; SimObjectClass::describeAllClasses(out); } /// Print welcome message. void sayHello(ostream &out) { extern const char *compileDate; // from date.cc ccprintf(out, "M5 Simulator System\n"); // display copyright ccprintf(out, "%s\n", briefCopyright); ccprintf(out, "M5 compiled on %d\n", compileDate); char *host = getenv("HOSTNAME"); if (!host) host = getenv("HOST"); if (host) ccprintf(out, "M5 executing on %s\n", host); ccprintf(out, "M5 simulation started %s\n", Time::start); } /// /// Echo the command line for posterity in such a way that it can be /// used to rerun the same simulation (given the same .ini files). /// void echoCommandLine(int argc, char **argv, ostream &out) { out << "command line: " << argv[0]; for (int i = 1; i < argc; i++) { string arg(argv[i]); out << ' '; // If the arg contains spaces, we need to quote it. // The rest of this is overkill to make it look purty. // print dashes first outside quotes int non_dash_pos = arg.find_first_not_of("-"); out << arg.substr(0, non_dash_pos); // print dashes string body = arg.substr(non_dash_pos); // the rest // if it's an assignment, handle the lhs & rhs separately int eq_pos = body.find("="); if (eq_pos == string::npos) { out << quote(body); } else { string lhs(body.substr(0, eq_pos)); string rhs(body.substr(eq_pos + 1)); out << quote(lhs) << "=" << quote(rhs); } } out << endl << endl; } char * getOptionString(int &index, int argc, char **argv) { char *option = argv[index] + 2; if (*option != '\0') return option; // We didn't find an argument, it must be in the next variable. if (++index >= argc) panic("option string for option '%s' not found", argv[index - 1]); return argv[index]; } int main(int argc, char **argv) { // Save off program name myProgName = argv[0]; signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths signal(SIGTRAP, SIG_IGN); signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats signal(SIGINT, exitNowHandler); // dump final stats and exit signal(SIGABRT, abortHandler); sayHello(cerr); bool configfile_found = false; PythonConfig pyconfig; string outdir; // Parse command-line options. // Since most of the complex options are handled through the // config database, we don't mess with getopts, and just parse // manually. for (int i = 1; i < argc; ++i) { char *arg_str = argv[i]; // if arg starts with '--', parse as a special python option // of the format --<python var>=<string value>, if the arg // starts with '-', it should be a simulator option with a // format similar to getopt. In any other case, treat the // option as a configuration file name and load it. if (arg_str[0] == '-' && arg_str[1] == '-') { string str = &arg_str[2]; string var, val; if (!split_first(str, var, val, '=')) panic("Could not parse configuration argument '%s'\n" "Expecting --<variable>=<value>\n", arg_str); pyconfig.setVariable(var, val); } else if (arg_str[0] == '-') { char *option; string var, val; // switch on second char switch (arg_str[1]) { case 'd': outdir = getOptionString(i, argc, argv); break; case 'h': showLongHelp(cerr); exit(1); case 'E': option = getOptionString(i, argc, argv); if (!split_first(option, var, val, '=')) val = "True"; if (setenv(var.c_str(), val.c_str(), true) == -1) panic("setenv: %s\n", strerror(errno)); break; case 'I': option = getOptionString(i, argc, argv); pyconfig.addPath(option); break; case 'P': option = getOptionString(i, argc, argv); pyconfig.writeLine(option); break; case 'X': { list<EmbedFile> lst; EmbedMap::all(lst); list<EmbedFile>::iterator i = lst.begin(); list<EmbedFile>::iterator end = lst.end(); while (i != end) { cprintf("Embedded File: %s\n", i->name); cout.write(i->data, i->length); ++i; } return 0; } default: showBriefHelp(cerr); panic("invalid argument '%s'\n", arg_str); } } else { string file(arg_str); string base, ext; if (!split_last(file, base, ext, '.') || ext != "py" && ext != "mpy") panic("Config file '%s' must end in '.py' or '.mpy'\n", file); pyconfig.load(file); configfile_found = true; } } if (outdir.empty()) { char *env = getenv("OUTPUT_DIR"); outdir = env ? env : "."; } simout.setDirectory(outdir); char *env = getenv("CONFIG_OUTPUT"); if (!env) env = "config.out"; configStream = simout.find(env); if (!configfile_found) panic("no configuration file specified!"); // The configuration database is now complete; start processing it. IniFile inifile; if (!pyconfig.output(inifile)) panic("Error processing python code"); // Initialize statistics database Stats::InitSimStats(); // Now process the configuration hierarchy and create the SimObjects. ConfigHierarchy configHierarchy(inifile); configHierarchy.build(); configHierarchy.createSimObjects(); // Parse and check all non-config-hierarchy parameters. ParamContext::parseAllContexts(inifile); ParamContext::checkAllContexts(); // Print hello message to stats file if it's actually a file. If // it's not (i.e. it's cout or cerr) then we already did it above. if (simout.isFile(*outputStream)) sayHello(*outputStream); // Echo command line and all parameter settings to stats file as well. echoCommandLine(argc, argv, *outputStream); ParamContext::showAllContexts(*configStream); // Do a second pass to finish initializing the sim objects SimObject::initAll(); // Restore checkpointed state, if any. configHierarchy.unserializeSimObjects(); // Done processing the configuration database. // Check for unreferenced entries. if (inifile.printUnreferenced()) panic("unreferenced sections/entries in the intermediate ini file"); SimObject::regAllStats(); // uncomment the following to get PC-based execution-time profile #ifdef DO_PROFILE init_profile((char *)&_init, (char *)&_fini); #endif // Check to make sure that the stats package is properly initialized Stats::check(); // Reset to put the stats in a consistent state. Stats::reset(); // Nothing to simulate if we don't have at least one CPU somewhere. if (BaseCPU::numSimulatedCPUs() == 0) { cerr << "Fatal: no CPUs to simulate." << endl; exit(1); } warn("Entering event queue. Starting simulation...\n"); SimStartup(); while (!mainEventQueue.empty()) { assert(curTick <= mainEventQueue.nextTick() && "event scheduled in the past"); // forward current cycle to the time of the first event on the // queue curTick = mainEventQueue.nextTick(); mainEventQueue.serviceOne(); if (async_event) { async_event = false; if (async_dump) { async_dump = false; using namespace Stats; SetupEvent(Dump, curTick); } if (async_dumpreset) { async_dumpreset = false; using namespace Stats; SetupEvent(Dump | Reset, curTick); } if (async_exit) { async_exit = false; new SimExitEvent("User requested STOP"); } if (async_io || async_alarm) { async_io = false; async_alarm = false; pollQueue.service(); } } } // This should never happen... every conceivable way for the // simulation to terminate (hit max cycles/insts, signal, // simulated system halts/exits) generates an exit event, so we // should never run out of events on the queue. exitNow("no events on event loop! All CPUs must be idle.", 1); return 0; } <commit_msg>Make code more portable.<commit_after>/* * Copyright (c) 2000-2004 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /// /// @file sim/main.cc /// #include <sys/types.h> #include <sys/stat.h> #include <libgen.h> #include <stdlib.h> #include <signal.h> #include <list> #include <string> #include <vector> #include "base/copyright.hh" #include "base/embedfile.hh" #include "base/inifile.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/pollevent.hh" #include "base/statistics.hh" #include "base/str.hh" #include "base/time.hh" #include "cpu/base_cpu.hh" #include "cpu/full_cpu/smt.hh" #include "sim/async.hh" #include "sim/builder.hh" #include "sim/configfile.hh" #include "sim/host.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_object.hh" #include "sim/stat_control.hh" #include "sim/stats.hh" #include "sim/universe.hh" #include "sim/pyconfig/pyconfig.hh" using namespace std; // See async.h. volatile bool async_event = false; volatile bool async_dump = false; volatile bool async_dumpreset = false; volatile bool async_exit = false; volatile bool async_io = false; volatile bool async_alarm = false; /// Stats signal handler. void dumpStatsHandler(int sigtype) { async_event = true; async_dump = true; } void dumprstStatsHandler(int sigtype) { async_event = true; async_dumpreset = true; } /// Exit signal handler. void exitNowHandler(int sigtype) { async_event = true; async_exit = true; } /// Abort signal handler. void abortHandler(int sigtype) { cerr << "Program aborted at cycle " << curTick << endl; #if TRACING_ON // dump trace buffer, if there is one Trace::theLog.dump(cerr); #endif } /// Simulator executable name const char *myProgName = ""; /// Show brief help message. void showBriefHelp(ostream &out) { char *prog = basename(myProgName); ccprintf(out, "Usage:\n"); ccprintf(out, "%s [-d <dir>] [-E <var>[=<val>]] [-I <dir>] [-P <python>]\n" " [--<var>=<val>] <config file>\n" "\n" " -d set the output directory to <dir>\n" " -E set the environment variable <var> to <val> (or 'True')\n" " -I add the directory <dir> to python's path\n" " -P execute <python> directly in the configuration\n" " --var=val set the python variable <var> to '<val>'\n" " <configfile> config file name (.py or .mpy)\n", prog); ccprintf(out, "%s -X\n -X extract embedded files\n", prog); ccprintf(out, "%s -h\n -h print long help\n", prog); } /// Show verbose help message. Includes parameter listing from /// showBriefHelp(), plus an exhaustive list of ini-file parameters /// and SimObjects (with their parameters). void showLongHelp(ostream &out) { showBriefHelp(out); out << endl << endl << "-----------------" << endl << "Global Parameters" << endl << "-----------------" << endl << endl; ParamContext::describeAllContexts(out); out << endl << endl << "-----------------" << endl << "Simulator Objects" << endl << "-----------------" << endl << endl; SimObjectClass::describeAllClasses(out); } /// Print welcome message. void sayHello(ostream &out) { extern const char *compileDate; // from date.cc ccprintf(out, "M5 Simulator System\n"); // display copyright ccprintf(out, "%s\n", briefCopyright); ccprintf(out, "M5 compiled on %d\n", compileDate); char *host = getenv("HOSTNAME"); if (!host) host = getenv("HOST"); if (host) ccprintf(out, "M5 executing on %s\n", host); ccprintf(out, "M5 simulation started %s\n", Time::start); } /// /// Echo the command line for posterity in such a way that it can be /// used to rerun the same simulation (given the same .ini files). /// void echoCommandLine(int argc, char **argv, ostream &out) { out << "command line: " << argv[0]; for (int i = 1; i < argc; i++) { string arg(argv[i]); out << ' '; // If the arg contains spaces, we need to quote it. // The rest of this is overkill to make it look purty. // print dashes first outside quotes int non_dash_pos = arg.find_first_not_of("-"); out << arg.substr(0, non_dash_pos); // print dashes string body = arg.substr(non_dash_pos); // the rest // if it's an assignment, handle the lhs & rhs separately int eq_pos = body.find("="); if (eq_pos == string::npos) { out << quote(body); } else { string lhs(body.substr(0, eq_pos)); string rhs(body.substr(eq_pos + 1)); out << quote(lhs) << "=" << quote(rhs); } } out << endl << endl; } char * getOptionString(int &index, int argc, char **argv) { char *option = argv[index] + 2; if (*option != '\0') return option; // We didn't find an argument, it must be in the next variable. if (++index >= argc) panic("option string for option '%s' not found", argv[index - 1]); return argv[index]; } int main(int argc, char **argv) { // Save off program name myProgName = argv[0]; signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths signal(SIGTRAP, SIG_IGN); signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats signal(SIGINT, exitNowHandler); // dump final stats and exit signal(SIGABRT, abortHandler); sayHello(cerr); bool configfile_found = false; PythonConfig pyconfig; string outdir; // Parse command-line options. // Since most of the complex options are handled through the // config database, we don't mess with getopts, and just parse // manually. for (int i = 1; i < argc; ++i) { char *arg_str = argv[i]; // if arg starts with '--', parse as a special python option // of the format --<python var>=<string value>, if the arg // starts with '-', it should be a simulator option with a // format similar to getopt. In any other case, treat the // option as a configuration file name and load it. if (arg_str[0] == '-' && arg_str[1] == '-') { string str = &arg_str[2]; string var, val; if (!split_first(str, var, val, '=')) panic("Could not parse configuration argument '%s'\n" "Expecting --<variable>=<value>\n", arg_str); pyconfig.setVariable(var, val); } else if (arg_str[0] == '-') { char *option; string var, val; // switch on second char switch (arg_str[1]) { case 'd': outdir = getOptionString(i, argc, argv); break; case 'h': showLongHelp(cerr); exit(1); case 'E': option = getOptionString(i, argc, argv); if (!split_first(option, var, val, '=')) val = "True"; if (setenv(var.c_str(), val.c_str(), true) == -1) panic("setenv: %s\n", strerror(errno)); break; case 'I': option = getOptionString(i, argc, argv); pyconfig.addPath(option); break; case 'P': option = getOptionString(i, argc, argv); pyconfig.writeLine(option); break; case 'X': { list<EmbedFile> lst; EmbedMap::all(lst); list<EmbedFile>::iterator i = lst.begin(); list<EmbedFile>::iterator end = lst.end(); while (i != end) { cprintf("Embedded File: %s\n", i->name); cout.write(i->data, i->length); ++i; } return 0; } default: showBriefHelp(cerr); panic("invalid argument '%s'\n", arg_str); } } else { string file(arg_str); string base, ext; if (!split_last(file, base, ext, '.') || ext != "py" && ext != "mpy") panic("Config file '%s' must end in '.py' or '.mpy'\n", file); pyconfig.load(file); configfile_found = true; } } if (outdir.empty()) { char *env = getenv("OUTPUT_DIR"); outdir = env ? env : "."; } simout.setDirectory(outdir); char *env = getenv("CONFIG_OUTPUT"); if (!env) env = "config.out"; configStream = simout.find(env); if (!configfile_found) panic("no configuration file specified!"); // The configuration database is now complete; start processing it. IniFile inifile; if (!pyconfig.output(inifile)) panic("Error processing python code"); // Initialize statistics database Stats::InitSimStats(); // Now process the configuration hierarchy and create the SimObjects. ConfigHierarchy configHierarchy(inifile); configHierarchy.build(); configHierarchy.createSimObjects(); // Parse and check all non-config-hierarchy parameters. ParamContext::parseAllContexts(inifile); ParamContext::checkAllContexts(); // Print hello message to stats file if it's actually a file. If // it's not (i.e. it's cout or cerr) then we already did it above. if (simout.isFile(*outputStream)) sayHello(*outputStream); // Echo command line and all parameter settings to stats file as well. echoCommandLine(argc, argv, *outputStream); ParamContext::showAllContexts(*configStream); // Do a second pass to finish initializing the sim objects SimObject::initAll(); // Restore checkpointed state, if any. configHierarchy.unserializeSimObjects(); // Done processing the configuration database. // Check for unreferenced entries. if (inifile.printUnreferenced()) panic("unreferenced sections/entries in the intermediate ini file"); SimObject::regAllStats(); // uncomment the following to get PC-based execution-time profile #ifdef DO_PROFILE init_profile((char *)&_init, (char *)&_fini); #endif // Check to make sure that the stats package is properly initialized Stats::check(); // Reset to put the stats in a consistent state. Stats::reset(); // Nothing to simulate if we don't have at least one CPU somewhere. if (BaseCPU::numSimulatedCPUs() == 0) { cerr << "Fatal: no CPUs to simulate." << endl; exit(1); } warn("Entering event queue. Starting simulation...\n"); SimStartup(); while (!mainEventQueue.empty()) { assert(curTick <= mainEventQueue.nextTick() && "event scheduled in the past"); // forward current cycle to the time of the first event on the // queue curTick = mainEventQueue.nextTick(); mainEventQueue.serviceOne(); if (async_event) { async_event = false; if (async_dump) { async_dump = false; using namespace Stats; SetupEvent(Dump, curTick); } if (async_dumpreset) { async_dumpreset = false; using namespace Stats; SetupEvent(Dump | Reset, curTick); } if (async_exit) { async_exit = false; new SimExitEvent("User requested STOP"); } if (async_io || async_alarm) { async_io = false; async_alarm = false; pollQueue.service(); } } } // This should never happen... every conceivable way for the // simulation to terminate (hit max cycles/insts, signal, // simulated system halts/exits) generates an exit event, so we // should never run out of events on the queue. exitNow("no events on event loop! All CPUs must be idle.", 1); return 0; } <|endoftext|>
<commit_before><commit_msg>Refactored object creation to functions and added a ground plane and gravity to the scene.<commit_after><|endoftext|>
<commit_before>// Copyright 2008, 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. // // NPAPI UnitTests. // // windows headers #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <atlbase.h> #include <comutil.h> // runtime headers #include <stdlib.h> #include <string.h> #include <memory.h> #include <ostream> #include "base/file_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/npapi_test_helper.h" #include "net/base/net_util.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kLongWaitTimeout = 30 * 1000; const int kShortWaitTimeout = 5 * 1000; std::ostream& operator<<(std::ostream& out, const CComBSTR &str) { // I love strings. I really do. That's why I make sure // to need 4 different types of strings to stream one out. TCHAR szFinal[1024]; _bstr_t bstrIntermediate(str); _stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate); return out << szFinal; } // Test passing arguments to a plugin. TEST_F(NPAPITester, Arguments) { std::wstring test_case = L"arguments.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("arguments", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test invoking many plugins within a single page. TEST_F(NPAPITester, ManyPlugins) { std::wstring test_case = L"many_plugins.html"; GURL url(GetTestUrl(L"npapi", test_case)); NavigateToURL(url); WaitForFinish("arguments", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "2", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "3", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "4", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "5", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "6", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "7", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "8", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "9", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "10", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "11", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "12", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "13", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "14", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "15", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test various calls to GetURL from a plugin. TEST_F(NPAPITester, GetURL) { std::wstring test_case = L"geturl.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("geturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test various calls to GetURL for javascript URLs with // non NULL targets from a plugin. TEST_F(NPAPITester, GetJavaScriptURL) { std::wstring test_case = L"get_javascript_url.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests that if an NPObject is proxies back to its original process, the // original pointer is returned and not a proxy. If this fails the plugin // will crash. TEST_F(NPAPITester, NPObjectProxy) { std::wstring test_case = L"npobject_proxy.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using NPN_GetURL // works without crashing or hanging TEST_F(NPAPITester, SelfDeletePluginGetUrl) { std::wstring test_case = L"self_delete_plugin_geturl.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_geturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using Invoke // works without crashing or hanging TEST_F(NPAPITester, SelfDeletePluginInvoke) { std::wstring test_case = L"self_delete_plugin_invoke.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_invoke", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script in the context of // a synchronous paint event works correctly TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"execute_script_delete_in_paint.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("execute_script_delete_in_paint", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"self_delete_plugin_stream.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_stream", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } // Tests if a plugin has a non zero window rect. TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) { show_window_ = true; std::wstring test_case = L"verify_plugin_window_rect.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"npobject_lifetime_test.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("npobject_lifetime_test", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } // Tests that we don't crash or assert if NPP_New fails TEST_F(NPAPIVisiblePluginTester, NewFails) { GURL url = GetTestUrl(L"npapi", L"new_fails.html"); NavigateToURL(url); WaitForFinish("new_fails", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { GURL url = GetTestUrl(L"npapi", L"execute_script_delete_in_npn_evaluate.html"); NavigateToURL(url); WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) { GURL url = GetTestUrl(L"npapi", L"get_javascript_open_popup_with_plugin.html"); NavigateToURL(url); WaitForFinish("plugin_popup_with_plugin_target", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } <commit_msg>Disable some failing UI tests for now.<commit_after>// Copyright 2008, 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. // // NPAPI UnitTests. // // windows headers #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <atlbase.h> #include <comutil.h> // runtime headers #include <stdlib.h> #include <string.h> #include <memory.h> #include <ostream> #include "base/file_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/npapi_test_helper.h" #include "net/base/net_util.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kLongWaitTimeout = 30 * 1000; const int kShortWaitTimeout = 5 * 1000; std::ostream& operator<<(std::ostream& out, const CComBSTR &str) { // I love strings. I really do. That's why I make sure // to need 4 different types of strings to stream one out. TCHAR szFinal[1024]; _bstr_t bstrIntermediate(str); _stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate); return out << szFinal; } // Test passing arguments to a plugin. TEST_F(NPAPITester, Arguments) { std::wstring test_case = L"arguments.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("arguments", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test invoking many plugins within a single page. TEST_F(NPAPITester, DISABLED_ManyPlugins) { std::wstring test_case = L"many_plugins.html"; GURL url(GetTestUrl(L"npapi", test_case)); NavigateToURL(url); WaitForFinish("arguments", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "2", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "3", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "4", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "5", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "6", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "7", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "8", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "9", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "10", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "11", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "12", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "13", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "14", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "15", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test various calls to GetURL from a plugin. TEST_F(NPAPITester, GetURL) { std::wstring test_case = L"geturl.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("geturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test various calls to GetURL for javascript URLs with // non NULL targets from a plugin. TEST_F(NPAPITester, GetJavaScriptURL) { std::wstring test_case = L"get_javascript_url.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests that if an NPObject is proxies back to its original process, the // original pointer is returned and not a proxy. If this fails the plugin // will crash. TEST_F(NPAPITester, NPObjectProxy) { std::wstring test_case = L"npobject_proxy.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using NPN_GetURL // works without crashing or hanging TEST_F(NPAPITester, SelfDeletePluginGetUrl) { std::wstring test_case = L"self_delete_plugin_geturl.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_geturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using Invoke // works without crashing or hanging TEST_F(NPAPITester, SelfDeletePluginInvoke) { std::wstring test_case = L"self_delete_plugin_invoke.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_invoke", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script in the context of // a synchronous paint event works correctly TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"execute_script_delete_in_paint.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("execute_script_delete_in_paint", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"self_delete_plugin_stream.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_stream", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } // Tests if a plugin has a non zero window rect. TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) { show_window_ = true; std::wstring test_case = L"verify_plugin_window_rect.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } TEST_F(NPAPIVisiblePluginTester, DISABLED_VerifyNPObjectLifetimeTest) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"npobject_lifetime_test.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("npobject_lifetime_test", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } // Tests that we don't crash or assert if NPP_New fails TEST_F(NPAPIVisiblePluginTester, NewFails) { GURL url = GetTestUrl(L"npapi", L"new_fails.html"); NavigateToURL(url); WaitForFinish("new_fails", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { GURL url = GetTestUrl(L"npapi", L"execute_script_delete_in_npn_evaluate.html"); NavigateToURL(url); WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) { GURL url = GetTestUrl(L"npapi", L"get_javascript_open_popup_with_plugin.html"); NavigateToURL(url); WaitForFinish("plugin_popup_with_plugin_target", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } <|endoftext|>
<commit_before>// Copyright 2008, 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. // // NPAPI UnitTests. // // windows headers #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <atlbase.h> #include <comutil.h> // runtime headers #include <stdlib.h> #include <string.h> #include <memory.h> #include <ostream> #include "base/file_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/npapi_test_helper.h" #include "net/base/net_util.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kLongWaitTimeout = 30 * 1000; const int kShortWaitTimeout = 5 * 1000; std::ostream& operator<<(std::ostream& out, const CComBSTR &str) { // I love strings. I really do. That's why I make sure // to need 4 different types of strings to stream one out. TCHAR szFinal[1024]; _bstr_t bstrIntermediate(str); _stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate); return out << szFinal; } // Test passing arguments to a plugin. TEST_F(NPAPITester, Arguments) { std::wstring test_case = L"arguments.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("arguments", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test invoking many plugins within a single page. TEST_F(NPAPITester, ManyPlugins) { std::wstring test_case = L"many_plugins.html"; GURL url(GetTestUrl(L"npapi", test_case)); NavigateToURL(url); WaitForFinish("arguments", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "2", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "3", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "4", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "5", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "6", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "7", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "8", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "9", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "10", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "11", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "12", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "13", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "14", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "15", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test various calls to GetURL from a plugin. TEST_F(NPAPITester, GetURL) { std::wstring test_case = L"geturl.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("geturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test various calls to GetURL for javascript URLs with // non NULL targets from a plugin. TEST_F(NPAPITester, GetJavaScriptURL) { std::wstring test_case = L"get_javascript_url.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests that if an NPObject is proxies back to its original process, the // original pointer is returned and not a proxy. If this fails the plugin // will crash. TEST_F(NPAPITester, NPObjectProxy) { std::wstring test_case = L"npobject_proxy.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using NPN_GetURL // works without crashing or hanging TEST_F(NPAPITester, SelfDeletePluginGetUrl) { std::wstring test_case = L"self_delete_plugin_geturl.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_geturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using Invoke // works without crashing or hanging TEST_F(NPAPITester, SelfDeletePluginInvoke) { std::wstring test_case = L"self_delete_plugin_invoke.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_invoke", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using Invoke with // a modal dialog showing works without crashing or hanging TEST_F(NPAPITester, SelfDeletePluginInvokeAlert) { std::wstring test_case = L"self_delete_plugin_invoke_alert.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); // Wait for the alert dialog and then close it. automation()->WaitForAppModalDialog(5000); scoped_ptr<WindowProxy> window(automation()->GetActiveWindow()); ASSERT_TRUE(window.get()); ASSERT_TRUE(window->SimulateOSKeyPress(VK_ESCAPE, 0)); WaitForFinish("self_delete_plugin_invoke_alert", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script in the context of // a synchronous paint event works correctly TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"execute_script_delete_in_paint.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("execute_script_delete_in_paint", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"self_delete_plugin_stream.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_stream", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } // Tests if a plugin has a non zero window rect. TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) { show_window_ = true; std::wstring test_case = L"verify_plugin_window_rect.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"npobject_lifetime_test.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("npobject_lifetime_test", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } // Tests that we don't crash or assert if NPP_New fails TEST_F(NPAPIVisiblePluginTester, NewFails) { GURL url = GetTestUrl(L"npapi", L"new_fails.html"); NavigateToURL(url); WaitForFinish("new_fails", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { GURL url = GetTestUrl(L"npapi", L"execute_script_delete_in_npn_evaluate.html"); NavigateToURL(url); WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) { GURL url = GetTestUrl(L"npapi", L"get_javascript_open_popup_with_plugin.html"); NavigateToURL(url); WaitForFinish("plugin_popup_with_plugin_target", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } <commit_msg>Disable NPAPITester.SelfDeletePluginInvokeAlert UI test. It doesn't seem to work on the buildbots. I need to find a better way to get the WindowProxy for the alert dialog.<commit_after>// Copyright 2008, 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. // // NPAPI UnitTests. // // windows headers #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <atlbase.h> #include <comutil.h> // runtime headers #include <stdlib.h> #include <string.h> #include <memory.h> #include <ostream> #include "base/file_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/npapi_test_helper.h" #include "net/base/net_util.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kLongWaitTimeout = 30 * 1000; const int kShortWaitTimeout = 5 * 1000; std::ostream& operator<<(std::ostream& out, const CComBSTR &str) { // I love strings. I really do. That's why I make sure // to need 4 different types of strings to stream one out. TCHAR szFinal[1024]; _bstr_t bstrIntermediate(str); _stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate); return out << szFinal; } // Test passing arguments to a plugin. TEST_F(NPAPITester, Arguments) { std::wstring test_case = L"arguments.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("arguments", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test invoking many plugins within a single page. TEST_F(NPAPITester, ManyPlugins) { std::wstring test_case = L"many_plugins.html"; GURL url(GetTestUrl(L"npapi", test_case)); NavigateToURL(url); WaitForFinish("arguments", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "2", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "3", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "4", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "5", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "6", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "7", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "8", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "9", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "10", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "11", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "12", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "13", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "14", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); WaitForFinish("arguments", "15", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test various calls to GetURL from a plugin. TEST_F(NPAPITester, GetURL) { std::wstring test_case = L"geturl.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("geturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Test various calls to GetURL for javascript URLs with // non NULL targets from a plugin. TEST_F(NPAPITester, GetJavaScriptURL) { std::wstring test_case = L"get_javascript_url.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests that if an NPObject is proxies back to its original process, the // original pointer is returned and not a proxy. If this fails the plugin // will crash. TEST_F(NPAPITester, NPObjectProxy) { std::wstring test_case = L"npobject_proxy.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using NPN_GetURL // works without crashing or hanging TEST_F(NPAPITester, SelfDeletePluginGetUrl) { std::wstring test_case = L"self_delete_plugin_geturl.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_geturl", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using Invoke // works without crashing or hanging TEST_F(NPAPITester, SelfDeletePluginInvoke) { std::wstring test_case = L"self_delete_plugin_invoke.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_invoke", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script using Invoke with // a modal dialog showing works without crashing or hanging TEST_F(NPAPITester, DISABLED_SelfDeletePluginInvokeAlert) { std::wstring test_case = L"self_delete_plugin_invoke_alert.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); // Wait for the alert dialog and then close it. automation()->WaitForAppModalDialog(5000); scoped_ptr<WindowProxy> window(automation()->GetActiveWindow()); ASSERT_TRUE(window.get()); ASSERT_TRUE(window->SimulateOSKeyPress(VK_ESCAPE, 0)); WaitForFinish("self_delete_plugin_invoke_alert", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } // Tests if a plugin executing a self deleting script in the context of // a synchronous paint event works correctly TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"execute_script_delete_in_paint.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("execute_script_delete_in_paint", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"self_delete_plugin_stream.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("self_delete_plugin_stream", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } // Tests if a plugin has a non zero window rect. TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) { show_window_ = true; std::wstring test_case = L"verify_plugin_window_rect.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { show_window_ = true; std::wstring test_case = L"npobject_lifetime_test.html"; GURL url = GetTestUrl(L"npapi", test_case); NavigateToURL(url); WaitForFinish("npobject_lifetime_test", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } // Tests that we don't crash or assert if NPP_New fails TEST_F(NPAPIVisiblePluginTester, NewFails) { GURL url = GetTestUrl(L"npapi", L"new_fails.html"); NavigateToURL(url); WaitForFinish("new_fails", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) { if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) { GURL url = GetTestUrl(L"npapi", L"execute_script_delete_in_npn_evaluate.html"); NavigateToURL(url); WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } } TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) { GURL url = GetTestUrl(L"npapi", L"get_javascript_open_popup_with_plugin.html"); NavigateToURL(url); WaitForFinish("plugin_popup_with_plugin_target", "1", url, kTestCompleteCookie, kTestCompleteSuccess, kShortWaitTimeout); } <|endoftext|>
<commit_before>#pragma once #define BEGIN_IOKIT_INCLUDE \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Winconsistent-missing-override\"") #define END_IOKIT_INCLUDE \ _Pragma("clang diagnostic pop") <commit_msg>add ignored warnings to BEGIN_IOKIT_INCLUDE<commit_after>#pragma once #define BEGIN_IOKIT_INCLUDE \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-W#warnings\"") \ _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \ _Pragma("clang diagnostic ignored \"-Winconsistent-missing-override\"") #define END_IOKIT_INCLUDE \ _Pragma("clang diagnostic pop") <|endoftext|>
<commit_before>#pragma once #include "lw/event/Promise.hpp" #include "lw/event/Promise.void.hpp" namespace lw { namespace event { template< typename T > inline Future< T > Promise< T >::future( void ){ return Future< T >( m_state ); } // -------------------------------------------------------------------------- // inline Future< void > Promise< void >::future( void ){ return Future< void >( m_state ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Result, typename Func, typename > Future< Result > Future< T >::_then( Func&& func ){ auto next = std::make_shared< Promise< Result > >(); auto prev = m_state; m_state->resolve = [ func, prev, next ]( T&& value ) mutable { func( std::move( value ), std::move( *next ) ); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]() mutable { next->reject(); prev->resolve = nullptr; prev.reset(); }; return next->future(); } // -------------------------------------------------------------------------- // template< typename T > template< typename Func, typename > Future<> Future< T >::_then( Func&& func ){ return then< void >( std::move( func ) ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Func, typename FuncResult, typename std::enable_if< IsFuture< FuncResult >::value >::type* > Future< typename FuncResult::result_type > Future< T >::_then( Func&& func ){ typedef typename FuncResult::result_type Result; return _then< Result >( [ func ]( T&& value, Promise< Result >&& promise ) mutable { func( std::move( value ) ).then( std::move( promise ) ); } ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Func, typename FuncResult, typename std::enable_if< !IsFuture< FuncResult >::value && !std::is_void< FuncResult >::value >::type* > Future< FuncResult > Future< T >::_then( Func&& func ){ return _then< FuncResult >( [ func ]( T&& value, Promise< FuncResult >&& promise ) mutable { promise.resolve( func( std::move( value ) ) ); } ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Func, typename FuncResult, typename std::enable_if< std::is_void< FuncResult >::value >::type* > Future<> Future< T >::_then( Func&& func ){ return _then([ func ]( T&& value, Promise<>&& promise ){ func( std::move( value ) ); promise.resolve(); }); } // -------------------------------------------------------------------------- // template< typename T > void Future< T >::then( promise_type&& promise ){ auto next = std::make_shared< promise_type >( std::move( promise ) ); auto prev = m_state; m_state->resolve = [ prev, next ]( T&& value ) mutable { next->resolve( std::move( value ) ); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]() mutable { next->reject(); prev->resolve = nullptr; prev.reset(); }; } // -------------------------------------------------------------------------- // template< typename Result, typename Func, typename > Future< Result > Future< void >::_then( Func&& func ){ auto next = std::make_shared< Promise< Result > >(); auto prev = m_state; m_state->resolve = [ func, prev, next ]() mutable { func( std::move( *next ) ); prev.reset(); }; return next->future(); } // -------------------------------------------------------------------------- // template< typename Func, typename > Future<> Future< void >::_then( Func&& func ){ return then< void >( std::move( func ) ); } // -------------------------------------------------------------------------- // template< typename Func, typename FuncResult, typename std::enable_if< IsFuture< FuncResult >::value >::type* > Future< typename FuncResult::result_type > Future< void >::_then( Func&& func ){ typedef typename FuncResult::result_type Result; return then< Result >([ func ]( Promise< Result >&& promise ){ func().then( std::move( promise ) ); }); } // -------------------------------------------------------------------------- // template< typename Func, typename FuncResult, typename std::enable_if< !IsFuture< FuncResult >::value && !std::is_void< FuncResult >::value >::type* > Future< FuncResult > Future< void >::_then( Func&& func ){ return then< FuncResult >([ func ]( Promise< FuncResult >&& promise ){ promise.resolve( func() ); }); } // -------------------------------------------------------------------------- // template< typename Func, typename FuncResult, typename std::enable_if< std::is_void< FuncResult >::value >::type* > Future< void > Future< void >::_then( Func&& func ){ return then< void >([ func ]( Promise< void >&& promise ){ func(); promise.resolve(); }); } // -------------------------------------------------------------------------- // inline void Future< void >::then( promise_type&& promise ){ auto next = std::make_shared< promise_type >( std::move( promise ) ); auto prev = m_state; m_state->resolve = [ prev, next ]() mutable { next->resolve(); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]() mutable { next->reject(); prev->resolve = nullptr; prev.reset(); }; } } } <commit_msg>Chain to thens<commit_after>#pragma once #include "lw/event/Promise.hpp" #include "lw/event/Promise.void.hpp" namespace lw { namespace event { template< typename T > inline Future< T > Promise< T >::future( void ){ return Future< T >( m_state ); } // -------------------------------------------------------------------------- // inline Future< void > Promise< void >::future( void ){ return Future< void >( m_state ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Result, typename Func, typename > Future< Result > Future< T >::_then( Func&& func ){ auto next = std::make_shared< Promise< Result > >(); auto prev = m_state; m_state->resolve = [ func, prev, next ]( T&& value ) mutable { func( std::move( value ), std::move( *next ) ); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]() mutable { next->reject(); prev->resolve = nullptr; prev.reset(); }; return next->future(); } // -------------------------------------------------------------------------- // template< typename T > template< typename Func, typename > Future<> Future< T >::_then( Func&& func ){ return then< void >( std::move( func ) ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Func, typename FuncResult, typename std::enable_if< IsFuture< FuncResult >::value >::type* > Future< typename FuncResult::result_type > Future< T >::_then( Func&& func ){ typedef typename FuncResult::result_type Result; return then< Result >( [ func ]( T&& value, Promise< Result >&& promise ) mutable { func( std::move( value ) ).then( std::move( promise ) ); } ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Func, typename FuncResult, typename std::enable_if< !IsFuture< FuncResult >::value && !std::is_void< FuncResult >::value >::type* > Future< FuncResult > Future< T >::_then( Func&& func ){ return then< FuncResult >( [ func ]( T&& value, Promise< FuncResult >&& promise ) mutable { promise.resolve( func( std::move( value ) ) ); } ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Func, typename FuncResult, typename std::enable_if< std::is_void< FuncResult >::value >::type* > Future<> Future< T >::_then( Func&& func ){ return then([ func ]( T&& value, Promise<>&& promise ){ func( std::move( value ) ); promise.resolve(); }); } // -------------------------------------------------------------------------- // template< typename T > void Future< T >::then( promise_type&& promise ){ auto next = std::make_shared< promise_type >( std::move( promise ) ); auto prev = m_state; m_state->resolve = [ prev, next ]( T&& value ) mutable { next->resolve( std::move( value ) ); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]() mutable { next->reject(); prev->resolve = nullptr; prev.reset(); }; } // -------------------------------------------------------------------------- // template< typename Result, typename Func, typename > Future< Result > Future< void >::_then( Func&& func ){ auto next = std::make_shared< Promise< Result > >(); auto prev = m_state; m_state->resolve = [ func, prev, next ]() mutable { func( std::move( *next ) ); prev.reset(); }; return next->future(); } // -------------------------------------------------------------------------- // template< typename Func, typename > Future<> Future< void >::_then( Func&& func ){ return then< void >( std::move( func ) ); } // -------------------------------------------------------------------------- // template< typename Func, typename FuncResult, typename std::enable_if< IsFuture< FuncResult >::value >::type* > Future< typename FuncResult::result_type > Future< void >::_then( Func&& func ){ typedef typename FuncResult::result_type Result; return then< Result >([ func ]( Promise< Result >&& promise ){ func().then( std::move( promise ) ); }); } // -------------------------------------------------------------------------- // template< typename Func, typename FuncResult, typename std::enable_if< !IsFuture< FuncResult >::value && !std::is_void< FuncResult >::value >::type* > Future< FuncResult > Future< void >::_then( Func&& func ){ return then< FuncResult >([ func ]( Promise< FuncResult >&& promise ){ promise.resolve( func() ); }); } // -------------------------------------------------------------------------- // template< typename Func, typename FuncResult, typename std::enable_if< std::is_void< FuncResult >::value >::type* > Future< void > Future< void >::_then( Func&& func ){ return then< void >([ func ]( Promise< void >&& promise ){ func(); promise.resolve(); }); } // -------------------------------------------------------------------------- // inline void Future< void >::then( promise_type&& promise ){ auto next = std::make_shared< promise_type >( std::move( promise ) ); auto prev = m_state; m_state->resolve = [ prev, next ]() mutable { next->resolve(); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]() mutable { next->reject(); prev->resolve = nullptr; prev.reset(); }; } } } <|endoftext|>
<commit_before>// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "line_printer.h" #include <stdio.h> #include <stdlib.h> #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #include <sys/ioctl.h> #include <termios.h> #include <sys/time.h> #endif #include "util.h" LinePrinter::LinePrinter() : have_blank_line_(true), console_locked_(false) { #ifndef _WIN32 const char* term = getenv("TERM"); smart_terminal_ = isatty(1) && term && string(term) != "dumb"; #else // Disable output buffer. It'd be nice to use line buffering but // MSDN says: "For some systems, [_IOLBF] provides line // buffering. However, for Win32, the behavior is the same as _IOFBF // - Full Buffering." setvbuf(stdout, NULL, _IONBF, 0); console_ = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbi; smart_terminal_ = GetConsoleScreenBufferInfo(console_, &csbi); #endif } void LinePrinter::Print(string to_print, LineType type) { if (console_locked_) { line_buffer_ = to_print; line_type_ = type; return; } #ifdef _WIN32 CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(console_, &csbi); #endif if (smart_terminal_) { #ifndef _WIN32 printf("\r"); // Print over previous line, if any. #else csbi.dwCursorPosition.X = 0; SetConsoleCursorPosition(console_, csbi.dwCursorPosition); #endif } if (smart_terminal_ && type == ELIDE) { #ifdef _WIN32 // Don't use the full width or console will move to next line. size_t width = static_cast<size_t>(csbi.dwSize.X) - 1; to_print = ElideMiddle(to_print, width); // We don't want to have the cursor spamming back and forth, so // use WriteConsoleOutput instead which updates the contents of // the buffer, but doesn't move the cursor position. GetConsoleScreenBufferInfo(console_, &csbi); COORD buf_size = { csbi.dwSize.X, 1 }; COORD zero_zero = { 0, 0 }; SMALL_RECT target = { csbi.dwCursorPosition.X, csbi.dwCursorPosition.Y, static_cast<SHORT>(csbi.dwCursorPosition.X + csbi.dwSize.X - 1), csbi.dwCursorPosition.Y }; CHAR_INFO* char_data = new CHAR_INFO[csbi.dwSize.X]; memset(char_data, 0, sizeof(CHAR_INFO) * csbi.dwSize.X); for (int i = 0; i < csbi.dwSize.X; ++i) { char_data[i].Char.AsciiChar = ' '; char_data[i].Attributes = csbi.wAttributes; } for (size_t i = 0; i < to_print.size(); ++i) char_data[i].Char.AsciiChar = to_print[i]; WriteConsoleOutput(console_, char_data, buf_size, zero_zero, &target); delete[] char_data; #else // Limit output to width of the terminal if provided so we don't cause // line-wrapping. winsize size; if ((ioctl(0, TIOCGWINSZ, &size) == 0) && size.ws_col) { to_print = ElideMiddle(to_print, size.ws_col); } printf("%s", to_print.c_str()); printf("\x1B[K"); // Clear to end of line. fflush(stdout); #endif have_blank_line_ = false; } else { printf("%s\n", to_print.c_str()); } } void LinePrinter::PrintOrBuffer(const char* data, size_t size) { if (console_locked_) { output_buffer_.append(data, size); } else { // Avoid printf and C strings, since the actual output might contain null // bytes like UTF-16 does (yuck). fwrite(data, 1, size, stdout); } } void LinePrinter::PrintOnNewLine(const string& to_print) { if (console_locked_ && !line_buffer_.empty()) { output_buffer_.append(line_buffer_); output_buffer_.append(1, '\n'); line_buffer_.clear(); } if (!have_blank_line_) { PrintOrBuffer("\n", 1); } if (!to_print.empty()) { PrintOrBuffer(&to_print[0], to_print.size()); } have_blank_line_ = to_print.empty() || *to_print.rbegin() == '\n'; } void LinePrinter::SetConsoleLocked(bool locked) { if (locked == console_locked_) return; if (locked) PrintOnNewLine(""); console_locked_ = locked; if (!locked) { PrintOnNewLine(output_buffer_); if (!line_buffer_.empty()) { Print(line_buffer_, line_type_); } output_buffer_.clear(); line_buffer_.clear(); } } <commit_msg>win: Let the "Pause" key or Ctrl-S pause output.<commit_after>// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "line_printer.h" #include <stdio.h> #include <stdlib.h> #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #include <sys/ioctl.h> #include <termios.h> #include <sys/time.h> #endif #include "util.h" LinePrinter::LinePrinter() : have_blank_line_(true), console_locked_(false) { #ifndef _WIN32 const char* term = getenv("TERM"); smart_terminal_ = isatty(1) && term && string(term) != "dumb"; #else // Disable output buffer. It'd be nice to use line buffering but // MSDN says: "For some systems, [_IOLBF] provides line // buffering. However, for Win32, the behavior is the same as _IOFBF // - Full Buffering." setvbuf(stdout, NULL, _IONBF, 0); console_ = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbi; smart_terminal_ = GetConsoleScreenBufferInfo(console_, &csbi); #endif } void LinePrinter::Print(string to_print, LineType type) { if (console_locked_) { line_buffer_ = to_print; line_type_ = type; return; } if (smart_terminal_) { printf("\r"); // Print over previous line, if any. // On Windows, calling a C library function writing to stdout also handles // pausing the executable when the "Pause" key or Ctrl-S is pressed. } if (smart_terminal_ && type == ELIDE) { #ifdef _WIN32 CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(console_, &csbi); // Don't use the full width or console will move to next line. size_t width = static_cast<size_t>(csbi.dwSize.X) - 1; to_print = ElideMiddle(to_print, width); // We don't want to have the cursor spamming back and forth, so // use WriteConsoleOutput instead which updates the contents of // the buffer, but doesn't move the cursor position. GetConsoleScreenBufferInfo(console_, &csbi); COORD buf_size = { csbi.dwSize.X, 1 }; COORD zero_zero = { 0, 0 }; SMALL_RECT target = { csbi.dwCursorPosition.X, csbi.dwCursorPosition.Y, static_cast<SHORT>(csbi.dwCursorPosition.X + csbi.dwSize.X - 1), csbi.dwCursorPosition.Y }; CHAR_INFO* char_data = new CHAR_INFO[csbi.dwSize.X]; memset(char_data, 0, sizeof(CHAR_INFO) * csbi.dwSize.X); for (int i = 0; i < csbi.dwSize.X; ++i) { char_data[i].Char.AsciiChar = ' '; char_data[i].Attributes = csbi.wAttributes; } for (size_t i = 0; i < to_print.size(); ++i) char_data[i].Char.AsciiChar = to_print[i]; WriteConsoleOutput(console_, char_data, buf_size, zero_zero, &target); delete[] char_data; #else // Limit output to width of the terminal if provided so we don't cause // line-wrapping. winsize size; if ((ioctl(0, TIOCGWINSZ, &size) == 0) && size.ws_col) { to_print = ElideMiddle(to_print, size.ws_col); } printf("%s", to_print.c_str()); printf("\x1B[K"); // Clear to end of line. fflush(stdout); #endif have_blank_line_ = false; } else { printf("%s\n", to_print.c_str()); } } void LinePrinter::PrintOrBuffer(const char* data, size_t size) { if (console_locked_) { output_buffer_.append(data, size); } else { // Avoid printf and C strings, since the actual output might contain null // bytes like UTF-16 does (yuck). fwrite(data, 1, size, stdout); } } void LinePrinter::PrintOnNewLine(const string& to_print) { if (console_locked_ && !line_buffer_.empty()) { output_buffer_.append(line_buffer_); output_buffer_.append(1, '\n'); line_buffer_.clear(); } if (!have_blank_line_) { PrintOrBuffer("\n", 1); } if (!to_print.empty()) { PrintOrBuffer(&to_print[0], to_print.size()); } have_blank_line_ = to_print.empty() || *to_print.rbegin() == '\n'; } void LinePrinter::SetConsoleLocked(bool locked) { if (locked == console_locked_) return; if (locked) PrintOnNewLine(""); console_locked_ = locked; if (!locked) { PrintOnNewLine(output_buffer_); if (!line_buffer_.empty()) { Print(line_buffer_, line_type_); } output_buffer_.clear(); line_buffer_.clear(); } } <|endoftext|>
<commit_before>/* * Author: Vladimir Ivan * * Copyright (c) 2017, University Of Edinburgh * 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 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 "task_map/CoM.h" REGISTER_TASKMAP_TYPE("CoM", exotica::CoM); namespace exotica { CoM::CoM() { } CoM::~CoM() { } void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if(phi.rows() != dim_) throw_named("Wrong size of phi!"); phi.setZero(); double M = mass_.sum(); if(M==0.0) return; KDL::Vector com; for(int i=0;i<Kinematics.Phi.rows();i++) { com += Kinematics.Phi(i).p*mass_(i); if (debug_) { com_marker_.points[i].x = Kinematics.Phi(i).p[0]; com_marker_.points[i].y = Kinematics.Phi(i).p[1]; com_marker_.points[i].z = Kinematics.Phi(i).p[2]; } } com = com / M; for(int i=0;i<dim_;i++) phi(i) = com[i]; if (debug_) { COM_marker_.pose.position.x = phi(0); COM_marker_.pose.position.y = phi(1); COM_marker_.pose.position.z = phi(2); COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now(); com_pub_.publish(com_marker_); COM_pub_.publish(COM_marker_); } } void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if(phi.rows() != dim_) throw_named("Wrong size of phi!"); if(J.rows() != dim_ || J.cols() != Kinematics.J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics.J(0).data.cols()); phi.setZero(); J.setZero(); KDL::Vector com; double M = mass_.sum(); if(M==0.0) return; for(int i=0;i<Kinematics.Phi.rows();i++) { com += Kinematics.Phi(i).p*mass_(i); J += mass_(i) / M * Kinematics.J(i).data.topRows(dim_); if (debug_) { com_marker_.points[i].x = Kinematics.Phi(i).p[0]; com_marker_.points[i].y = Kinematics.Phi(i).p[1]; com_marker_.points[i].z = Kinematics.Phi(i).p[2]; } } com =com / M; for(int i=0;i<dim_;i++) phi(i) = com[i]; if (debug_) { COM_marker_.pose.position.x = phi(0); COM_marker_.pose.position.y = phi(1); COM_marker_.pose.position.z = phi(2); COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now(); com_pub_.publish(com_marker_); COM_pub_.publish(COM_marker_); } } int CoM::taskSpaceDim() { return dim_; } void CoM::Initialize() { enable_z_ = init_.EnableZ; if (enable_z_) dim_ = 3; else dim_ = 2; if(Frames.size()>0) { // if (debug_) // HIGHLIGHT_NAMED("CoM", "Initialisation with " << Frames.size() << " passed into map."); mass_.resize(Frames.size()); for(int i=0; i<Frames.size(); i++) { if(Frames[i].FrameBLinkName!="") { throw_named("Requesting CoM frame with base other than root! '" << Frames[i].FrameALinkName << "'"); } Frames[i].FrameAOffset.p = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getCOG(); mass_(i) = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getMass(); Frames[i].FrameALinkName = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Parent->Segment.getName(); } } else { int N = scene_->getSolver().getTree().size()-1; mass_.resize(N); Frames.resize(N); // if (debug_) // HIGHLIGHT_NAMED("CoM", "Initialisation for tree of size " // << Frames.size()); for(int i=0; i<N; i++) { Frames[i].FrameALinkName = scene_->getSolver().getTree()[i+1]->Parent->Segment.getName(); Frames[i].FrameAOffset.p = scene_->getSolver().getTree()[i+1]->Segment.getInertia().getCOG(); mass_(i) = scene_->getSolver().getTree()[i+1]->Segment.getInertia().getMass(); // if (debug_) // HIGHLIGHT_NAMED( // "CoM-Initialize", // "LinkName: " << Frames[i].FrameALinkName // << ", mass: " << mass_(i) << ", CoG: (" // << Frames[i].FrameAOffset.p.x() << ", " // << Frames[i].FrameAOffset.p.y() << ", " // << Frames[i].FrameAOffset.p.z() << ")"); } } if (debug_) { InitDebug(); HIGHLIGHT_NAMED("CoM", "Total model mass: " << mass_.sum() << " kg"); } } void CoM::assignScene(Scene_ptr scene) { scene_ = scene; Initialize(); } void CoM::Instantiate(CoMInitializer& init) { init_ = init; } void CoM::InitDebug() { com_marker_.points.resize(Frames.size()); com_marker_.type = visualization_msgs::Marker::SPHERE_LIST; com_marker_.color.a = .7; com_marker_.color.r = 0.5; com_marker_.color.g = 0; com_marker_.color.b = 0; com_marker_.scale.x = com_marker_.scale.y = com_marker_.scale.z = .02; com_marker_.action = visualization_msgs::Marker::ADD; COM_marker_.type = visualization_msgs::Marker::CYLINDER; COM_marker_.color.a = 1; COM_marker_.color.r = 1; COM_marker_.color.g = 0; COM_marker_.color.b = 0; COM_marker_.scale.x = COM_marker_.scale.y = .15; COM_marker_.scale.z = .02; COM_marker_.action = visualization_msgs::Marker::ADD; com_marker_.header.frame_id = COM_marker_.header.frame_id = "exotica/" + scene_->getRootFrameName(); com_pub_ = Server::advertise<visualization_msgs::Marker>( object_name_ + "/coms_marker", 1, true); COM_pub_ = Server::advertise<visualization_msgs::Marker>( object_name_ + "/COM_marker", 1, true); } } <commit_msg>CoM: Fix CoM computation bug, fixes #134 The calculation of the Centre of Gravity of links was wrong as the relative frame was expressed in the parent rather than the child link's frame.<commit_after>/* * Author: Vladimir Ivan * * Copyright (c) 2017, University Of Edinburgh * 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 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 "task_map/CoM.h" REGISTER_TASKMAP_TYPE("CoM", exotica::CoM); namespace exotica { CoM::CoM() { } CoM::~CoM() { } void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if(phi.rows() != dim_) throw_named("Wrong size of phi!"); phi.setZero(); double M = mass_.sum(); if(M==0.0) return; KDL::Vector com; for(int i=0;i<Kinematics.Phi.rows();i++) { com += Kinematics.Phi(i).p*mass_(i); if (debug_) { com_marker_.points[i].x = Kinematics.Phi(i).p[0]; com_marker_.points[i].y = Kinematics.Phi(i).p[1]; com_marker_.points[i].z = Kinematics.Phi(i).p[2]; } } com = com / M; for(int i=0;i<dim_;i++) phi(i) = com[i]; if (debug_) { COM_marker_.pose.position.x = phi(0); COM_marker_.pose.position.y = phi(1); COM_marker_.pose.position.z = phi(2); COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now(); com_pub_.publish(com_marker_); COM_pub_.publish(COM_marker_); } } void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if(phi.rows() != dim_) throw_named("Wrong size of phi!"); if(J.rows() != dim_ || J.cols() != Kinematics.J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics.J(0).data.cols()); phi.setZero(); J.setZero(); KDL::Vector com; double M = mass_.sum(); if(M==0.0) return; for(int i=0;i<Kinematics.Phi.rows();i++) { com += Kinematics.Phi(i).p*mass_(i); J += mass_(i) / M * Kinematics.J(i).data.topRows(dim_); if (debug_) { com_marker_.points[i].x = Kinematics.Phi(i).p[0]; com_marker_.points[i].y = Kinematics.Phi(i).p[1]; com_marker_.points[i].z = Kinematics.Phi(i).p[2]; } } com =com / M; for(int i=0;i<dim_;i++) phi(i) = com[i]; if (debug_) { COM_marker_.pose.position.x = phi(0); COM_marker_.pose.position.y = phi(1); COM_marker_.pose.position.z = phi(2); COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now(); com_pub_.publish(com_marker_); COM_pub_.publish(COM_marker_); } } int CoM::taskSpaceDim() { return dim_; } void CoM::Initialize() { enable_z_ = init_.EnableZ; if (enable_z_) dim_ = 3; else dim_ = 2; if(Frames.size()>0) { // if (debug_) // HIGHLIGHT_NAMED("CoM", "Initialisation with " << Frames.size() << " passed into map."); mass_.resize(Frames.size()); for(int i=0; i<Frames.size(); i++) { if(Frames[i].FrameBLinkName!="") { throw_named("Requesting CoM frame with base other than root! '" << Frames[i].FrameALinkName << "'"); } Frames[i].FrameAOffset.p = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getCOG(); mass_(i) = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getMass(); Frames[i].FrameALinkName = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Parent->Segment.getName(); } } else { int N = scene_->getSolver().getTree().size()-1; mass_.resize(N); Frames.resize(N); // if (debug_) // HIGHLIGHT_NAMED("CoM", "Initialisation for tree of size " // << Frames.size()); for(int i=0; i<N; i++) { Frames[i].FrameALinkName = scene_->getSolver().getTree()[i+1]->Segment.getName(); Frames[i].FrameAOffset.p = scene_->getSolver().getTree()[i+1]->Segment.getInertia().getCOG(); mass_(i) = scene_->getSolver().getTree()[i+1]->Segment.getInertia().getMass(); // if (debug_) // HIGHLIGHT_NAMED( // "CoM-Initialize", // "LinkName: " << Frames[i].FrameALinkName // << ", mass: " << mass_(i) << ", CoG: (" // << Frames[i].FrameAOffset.p.x() << ", " // << Frames[i].FrameAOffset.p.y() << ", " // << Frames[i].FrameAOffset.p.z() << ")"); } } if (debug_) { InitDebug(); HIGHLIGHT_NAMED("CoM", "Total model mass: " << mass_.sum() << " kg"); } } void CoM::assignScene(Scene_ptr scene) { scene_ = scene; Initialize(); } void CoM::Instantiate(CoMInitializer& init) { init_ = init; } void CoM::InitDebug() { com_marker_.points.resize(Frames.size()); com_marker_.type = visualization_msgs::Marker::SPHERE_LIST; com_marker_.color.a = .7; com_marker_.color.r = 0.5; com_marker_.color.g = 0; com_marker_.color.b = 0; com_marker_.scale.x = com_marker_.scale.y = com_marker_.scale.z = .02; com_marker_.action = visualization_msgs::Marker::ADD; COM_marker_.type = visualization_msgs::Marker::CYLINDER; COM_marker_.color.a = 1; COM_marker_.color.r = 1; COM_marker_.color.g = 0; COM_marker_.color.b = 0; COM_marker_.scale.x = COM_marker_.scale.y = .15; COM_marker_.scale.z = .02; COM_marker_.action = visualization_msgs::Marker::ADD; com_marker_.header.frame_id = COM_marker_.header.frame_id = "exotica/" + scene_->getRootFrameName(); com_pub_ = Server::advertise<visualization_msgs::Marker>( object_name_ + "/coms_marker", 1, true); COM_pub_ = Server::advertise<visualization_msgs::Marker>( object_name_ + "/COM_marker", 1, true); } } <|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <ios> #include <ostream> #include <sstream> #include <string> #include "MacAddress.hpp" //============================================================================== // MacAddress constructor; initializes to all zeros //============================================================================== MacAddress::MacAddress() : Data(mac_address, MacAddress::length) { } //============================================================================== // MacAddress copy constructor; copies the address of the given MAC address //============================================================================== MacAddress::MacAddress(const MacAddress& mac_address) { *this = mac_address; } //============================================================================== // MacAddress constructor; initializes to match the given string //============================================================================== MacAddress::MacAddress(const std::string& mac_address_str) { *this = mac_address_str; } //============================================================================== // MacAddress destructor; does nothing since no dynamic memory is allocated //============================================================================== MacAddress::~MacAddress() { } //============================================================================== // Assigns one MAC address to another //============================================================================== MacAddress& MacAddress::operator=(const MacAddress& mac_address) { memcpy(&this->mac_address, &mac_address, MacAddress::length); return *this; } //============================================================================== // Assigns a string to a MAC address //============================================================================== MacAddress& MacAddress::operator=(const std::string& mac_address_str) { std::istringstream tempstream(mac_address_str); tempstream >> *this; return *this; } //============================================================================== // Allows the use of brackets to index into the MAC address //============================================================================== char& MacAddress::operator[](const unsigned int byteNum) { return mac_address[byteNum]; } //============================================================================== // Writes string representation of self to the ostream //============================================================================== std::ostream& operator<<(std::ostream& os, MacAddress& mac_address) { // 18 characters for the whole representation; 12 for the actual numbers, 5 // for the colons in-between, and 1 on the end for the null char mac_cstr[18]; mac_cstr[17] = 0; if (sprintf(mac_cstr, "%02x:%02x:%02x:%02x:%02x:%02x", mac_address[0], mac_address[1], mac_address[2], mac_address[3], mac_address[4], mac_address[5]) < 0) { // Something bad happened, so set the fail bit on the stream os.setstate(std::ios_base::failbit); } return os << mac_cstr; } //============================================================================== // Reads string representation of self from the istream //============================================================================== std::istream& operator>>(std::istream& is, MacAddress& mac_address) { // Grab 17 characters from the stream and store temporarily; we use the // number 18 below because the istream get function reads the argument - 1 char tempstr[18]; is.get(tempstr, 18); int tempmac[MacAddress::length]; // Scan the temporary string as a MAC address if (sscanf(tempstr, "%2x:%2x:%2x:%2x:%2x:%2x", &tempmac[0], &tempmac[1], &tempmac[2], &tempmac[3], &tempmac[4], &tempmac[5]) != MacAddress::length) { // We didn't convert all 6 bytes. Leave our internal state as-is but // set the fail bit on the stream so the user has some way of knowing is.setstate(std::ios_base::failbit); return is; } // Copy from temporary storage into permanent storage for (unsigned int i = 0; i < MacAddress::length; i++) { mac_address[i] = static_cast<unsigned char>(tempmac[i]); } // I feel like there may be a better way to implement this ... return is; } <commit_msg>Fixed bug where base class was not properly initialized by all constructors<commit_after>#include <cstdio> #include <cstring> #include <ios> #include <ostream> #include <sstream> #include <string> #include "MacAddress.hpp" //============================================================================== // MacAddress constructor; initializes to all zeros //============================================================================== MacAddress::MacAddress() : Data(mac_address, MacAddress::length) { } //============================================================================== // MacAddress constructor; initializes to match the given string //============================================================================== MacAddress::MacAddress(const std::string& mac_address_str) : Data(mac_address, MacAddress::length) { *this = mac_address_str; } //============================================================================== // MacAddress copy constructor; copies the address of the given MAC address //============================================================================== MacAddress::MacAddress(const MacAddress& mac_address) : Data(this->mac_address, MacAddress::length) { *this = mac_address; } //============================================================================== // MacAddress destructor; does nothing since no dynamic memory is allocated //============================================================================== MacAddress::~MacAddress() { } //============================================================================== // Assigns one MAC address to another //============================================================================== MacAddress& MacAddress::operator=(const MacAddress& mac_address) { memcpy(&this->mac_address, &mac_address, MacAddress::length); return *this; } //============================================================================== // Assigns a string to a MAC address //============================================================================== MacAddress& MacAddress::operator=(const std::string& mac_address_str) { std::istringstream tempstream(mac_address_str); tempstream >> *this; return *this; } //============================================================================== // Allows the use of brackets to index into the MAC address //============================================================================== char& MacAddress::operator[](const unsigned int byteNum) { return mac_address[byteNum]; } //============================================================================== // Writes string representation of self to the ostream //============================================================================== std::ostream& operator<<(std::ostream& os, MacAddress& mac_address) { // 18 characters for the whole representation; 12 for the actual numbers, 5 // for the colons in-between, and 1 on the end for the null char mac_cstr[18]; mac_cstr[17] = 0; if (sprintf(mac_cstr, "%02x:%02x:%02x:%02x:%02x:%02x", mac_address[0], mac_address[1], mac_address[2], mac_address[3], mac_address[4], mac_address[5]) < 0) { // Something bad happened, so set the fail bit on the stream os.setstate(std::ios_base::failbit); } return os << mac_cstr; } //============================================================================== // Reads string representation of self from the istream //============================================================================== std::istream& operator>>(std::istream& is, MacAddress& mac_address) { // Grab 17 characters from the stream and store temporarily; we use the // number 18 below because the istream get function reads the argument - 1 char tempstr[18]; is.get(tempstr, 18); int tempmac[MacAddress::length]; // Scan the temporary string as a MAC address if (sscanf(tempstr, "%2x:%2x:%2x:%2x:%2x:%2x", &tempmac[0], &tempmac[1], &tempmac[2], &tempmac[3], &tempmac[4], &tempmac[5]) != MacAddress::length) { // We didn't convert all 6 bytes. Leave our internal state as-is but // set the fail bit on the stream so the user has some way of knowing is.setstate(std::ios_base::failbit); return is; } // Copy from temporary storage into permanent storage for (unsigned int i = 0; i < MacAddress::length; i++) { mac_address[i] = static_cast<unsigned char>(tempmac[i]); } // I feel like there may be a better way to implement this ... return is; } <|endoftext|>
<commit_before><commit_msg>Fix globalPosition in Stl export<commit_after><|endoftext|>
<commit_before>#include "eps/eps.h" #include <cstdlib> #include <cstring> #include "obc_access.hpp" #include "terminal/terminal.h" using devices::eps::LCL; using devices::eps::BurnSwitch; using devices::eps::EPSDriver; static void Usage() { GetTerminal().Puts("eps enable_lcl|disable_lcl|power_cycle|disable_overheat|enable_burn_switch|hk_a|hk_b"); } static void Print(const char* prefix, const devices::eps::hk::MPPT_HK& hk) { GetTerminal().Printf("%s.SOL_VOLT\t%d\n", prefix, hk.SOL_VOLT.Value()); GetTerminal().Printf("%s.SOL_CURR\t%d\n", prefix, hk.SOL_CURR.Value()); GetTerminal().Printf("%s.SOL_OUT_VOLT\t%d\n", prefix, hk.SOL_OUT_VOLT.Value()); GetTerminal().Printf("%s.TEMP\t%d\n", prefix, hk.Temperature.Value()); GetTerminal().Printf("%s.STATE\t%d\n", prefix, num(hk.MpptState)); } static void Print(const char* prefix, const devices::eps::hk::DISTR_HK& hk) { GetTerminal().Printf("%s.CURR_3V3\t%d\n", prefix, hk.CURR_3V3.Value()); GetTerminal().Printf("%s.VOLT_3V3\t%d\n", prefix, hk.VOLT_3V3.Value()); GetTerminal().Printf("%s.CURR_5V\t%d\n", prefix, hk.CURR_5V.Value()); GetTerminal().Printf("%s.VOLT_5V\t%d\n", prefix, hk.VOLT_5V.Value()); GetTerminal().Printf("%s.CURR_VBAT\t%d\n", prefix, hk.CURR_VBAT.Value()); GetTerminal().Printf("%s.VOLT_VBAT\t%d\n", prefix, hk.VOLT_VBAT.Value()); GetTerminal().Printf("%s.LCL_STATE\t%d\n", prefix, num(hk.LCL_STATE)); GetTerminal().Printf("%s.LCL_FLAGB\t%d\n", prefix, num(hk.LCL_FLAGB)); } static void Print(const char* prefix, const devices::eps::hk::BATCPrimaryState& hk) { GetTerminal().Printf("%s.VOLT_A\t%d\n", prefix, hk.VOLT_A.Value()); GetTerminal().Printf("%s.CHRG_CURR\t%d\n", prefix, hk.ChargeCurrent.Value()); GetTerminal().Printf("%s.DCHRG_CURR\t%d\n", prefix, hk.DischargeCurrent.Value()); GetTerminal().Printf("%s.TEMP\t%d\n", prefix, hk.Temperature.Value()); GetTerminal().Printf("%s.STATE\t%d\n", prefix, num(hk.State)); } static void Print(const char* prefix, const devices::eps::hk::BATCSecondaryState& hk) { GetTerminal().Printf("%s.VOLT_B\t%d\n", prefix, hk.voltB.Value()); } static void Print(const char* prefix, const devices::eps::hk::BatteryPackPrimaryState hk) { GetTerminal().Printf("%s.TEMP_A\t%d\n", prefix, hk.temperatureA.Value()); GetTerminal().Printf("%s.TEMP_B\t%d\n", prefix, hk.temperatureB.Value()); } static void Print(const char* prefix, const devices::eps::hk::BatteryPackSecondaryState& hk) { GetTerminal().Printf("%s.TEMP_C\t%d\n", prefix, hk.temperatureC.Value()); } static void Print(const char* prefix, const devices::eps::hk::OtherControllerState& hk) { GetTerminal().Printf("%s.VOLT_3V3d\t%d\n", prefix, hk.VOLT_3V3d.Value()); } static void Print(const char* prefix, const devices::eps::hk::ThisControllerState& hk) { GetTerminal().Printf("%s.SAFETY_CTR\t%d\n", prefix, hk.safetyCounter); GetTerminal().Printf("%s.PWR_CYCLES\t%d\n", prefix, hk.powerCycleCount); GetTerminal().Printf("%s.UPTIME\t%ld\n", prefix, hk.uptime); GetTerminal().Printf("%s.TEMP\t%d\n", prefix, hk.temperature.Value()); GetTerminal().Printf("%s.SUPP_TEMP\t%d\n", prefix, hk.suppTemp.Value()); } static void Print(const char* prefix, devices::eps::hk::DCDC_HK& hk) { GetTerminal().Printf("%s.TEMP\t%d\n", prefix, hk.temperature.Value()); } void EPSCommand(std::uint16_t argc, char* argv[]) { if (argc == 0) { Usage(); return; } auto& eps = GetEPS(); if (strcmp(argv[0], "enable_lcl") == 0) { auto lcl = static_cast<LCL>(atoi(argv[1])); auto result = eps.EnableLCL(lcl); GetTerminal().Printf("%d", num(result)); return; } if (strcmp(argv[0], "disable_lcl") == 0) { auto lcl = static_cast<LCL>(atoi(argv[1])); auto result = eps.DisableLCL(lcl); GetTerminal().Printf("%d", num(result)); return; } if (strcmp(argv[0], "power_cycle") == 0) { bool result = false; if (strcmp(argv[1], "A") == 0) { result = eps.PowerCycle(EPSDriver::Controller::A); } else if (strcmp(argv[1], "B") == 0) { result = eps.PowerCycle(EPSDriver::Controller::B); } else if (strcmp(argv[1], "Auto") == 0) { result = eps.PowerCycle(); } GetTerminal().Puts(result ? "1" : "0"); return; } if (strcmp(argv[0], "disable_overheat") == 0) { bool result = false; if (strcmp(argv[1], "A") == 0) { result = eps.DisableOverheatSubmode(EPSDriver::Controller::A); } else if (strcmp(argv[1], "B") == 0) { result = eps.DisableOverheatSubmode(EPSDriver::Controller::B); } GetTerminal().Puts(result ? "1" : "0"); return; } if (strcmp(argv[0], "enable_burn_switch") == 0) { bool useMain = strcmp(argv[1], "1") == 0; auto burnSwitch = static_cast<BurnSwitch>(atoi(argv[2])); auto result = eps.EnableBurnSwitch(useMain, burnSwitch); GetTerminal().Printf("%d", num(result)); return; } if (strcmp(argv[0], "hk_a") == 0) { auto hk = eps.ReadHousekeepingA(); if (!hk.HasValue) { GetTerminal().Puts("Error"); return; } auto v = hk.Value; Print("MPPT_X", v.mpptX); Print("MPPT_Y_PLUS", v.mpptYPlus); Print("MPPT_Y_MINUS", v.mpptYMinus); Print("DISTR", v.distr); Print("BATC", v.batc); Print("BP", v.bp); Print("CTRLB", v.other); Print("CTRLA", v.current); Print("DCDC3V3", v.dcdc3V3); Print("DCDC5V", v.dcdc5V); return; } if (strcmp(argv[0], "hk_b") == 0) { auto hk = eps.ReadHousekeepingB(); if (!hk.HasValue) { GetTerminal().Puts("Error"); return; } auto v = hk.Value; Print("BP", v.bp); Print("BATC", v.batc); Print("CTRLA", v.other); Print("CTRLB", v.current); return; } if (strcmp(argv[0], "reset_watchdog") == 0) { bool result = false; if (strcmp(argv[1], "A") == 0) { result = eps.ResetWatchdog(EPSDriver::Controller::A) == devices::eps::ErrorCode::NoError; } else if (strcmp(argv[1], "B") == 0) { result = eps.ResetWatchdog(EPSDriver::Controller::B) == devices::eps::ErrorCode::NoError; } else if (strcmp(argv[1], "Both") == 0) { result = eps.ResetWatchdog(EPSDriver::Controller::A) == devices::eps::ErrorCode::NoError; result = result && eps.ResetWatchdog(EPSDriver::Controller::B) == devices::eps::ErrorCode::NoError; } GetTerminal().Puts(result ? "1" : "0"); return; } } <commit_msg>EPS HK/UPTIME printf specifier fix in OBC terminal<commit_after>#include "eps/eps.h" #include <cstdlib> #include <cstring> #include "obc_access.hpp" #include "terminal/terminal.h" using devices::eps::LCL; using devices::eps::BurnSwitch; using devices::eps::EPSDriver; static void Usage() { GetTerminal().Puts("eps enable_lcl|disable_lcl|power_cycle|disable_overheat|enable_burn_switch|hk_a|hk_b"); } static void Print(const char* prefix, const devices::eps::hk::MPPT_HK& hk) { GetTerminal().Printf("%s.SOL_VOLT\t%d\n", prefix, hk.SOL_VOLT.Value()); GetTerminal().Printf("%s.SOL_CURR\t%d\n", prefix, hk.SOL_CURR.Value()); GetTerminal().Printf("%s.SOL_OUT_VOLT\t%d\n", prefix, hk.SOL_OUT_VOLT.Value()); GetTerminal().Printf("%s.TEMP\t%d\n", prefix, hk.Temperature.Value()); GetTerminal().Printf("%s.STATE\t%d\n", prefix, num(hk.MpptState)); } static void Print(const char* prefix, const devices::eps::hk::DISTR_HK& hk) { GetTerminal().Printf("%s.CURR_3V3\t%d\n", prefix, hk.CURR_3V3.Value()); GetTerminal().Printf("%s.VOLT_3V3\t%d\n", prefix, hk.VOLT_3V3.Value()); GetTerminal().Printf("%s.CURR_5V\t%d\n", prefix, hk.CURR_5V.Value()); GetTerminal().Printf("%s.VOLT_5V\t%d\n", prefix, hk.VOLT_5V.Value()); GetTerminal().Printf("%s.CURR_VBAT\t%d\n", prefix, hk.CURR_VBAT.Value()); GetTerminal().Printf("%s.VOLT_VBAT\t%d\n", prefix, hk.VOLT_VBAT.Value()); GetTerminal().Printf("%s.LCL_STATE\t%d\n", prefix, num(hk.LCL_STATE)); GetTerminal().Printf("%s.LCL_FLAGB\t%d\n", prefix, num(hk.LCL_FLAGB)); } static void Print(const char* prefix, const devices::eps::hk::BATCPrimaryState& hk) { GetTerminal().Printf("%s.VOLT_A\t%d\n", prefix, hk.VOLT_A.Value()); GetTerminal().Printf("%s.CHRG_CURR\t%d\n", prefix, hk.ChargeCurrent.Value()); GetTerminal().Printf("%s.DCHRG_CURR\t%d\n", prefix, hk.DischargeCurrent.Value()); GetTerminal().Printf("%s.TEMP\t%d\n", prefix, hk.Temperature.Value()); GetTerminal().Printf("%s.STATE\t%d\n", prefix, num(hk.State)); } static void Print(const char* prefix, const devices::eps::hk::BATCSecondaryState& hk) { GetTerminal().Printf("%s.VOLT_B\t%d\n", prefix, hk.voltB.Value()); } static void Print(const char* prefix, const devices::eps::hk::BatteryPackPrimaryState hk) { GetTerminal().Printf("%s.TEMP_A\t%d\n", prefix, hk.temperatureA.Value()); GetTerminal().Printf("%s.TEMP_B\t%d\n", prefix, hk.temperatureB.Value()); } static void Print(const char* prefix, const devices::eps::hk::BatteryPackSecondaryState& hk) { GetTerminal().Printf("%s.TEMP_C\t%d\n", prefix, hk.temperatureC.Value()); } static void Print(const char* prefix, const devices::eps::hk::OtherControllerState& hk) { GetTerminal().Printf("%s.VOLT_3V3d\t%d\n", prefix, hk.VOLT_3V3d.Value()); } static void Print(const char* prefix, const devices::eps::hk::ThisControllerState& hk) { GetTerminal().Printf("%s.SAFETY_CTR\t%d\n", prefix, hk.safetyCounter); GetTerminal().Printf("%s.PWR_CYCLES\t%d\n", prefix, hk.powerCycleCount); GetTerminal().Printf("%s.UPTIME\t%lu\n", prefix, hk.uptime); GetTerminal().Printf("%s.TEMP\t%d\n", prefix, hk.temperature.Value()); GetTerminal().Printf("%s.SUPP_TEMP\t%d\n", prefix, hk.suppTemp.Value()); } static void Print(const char* prefix, devices::eps::hk::DCDC_HK& hk) { GetTerminal().Printf("%s.TEMP\t%d\n", prefix, hk.temperature.Value()); } void EPSCommand(std::uint16_t argc, char* argv[]) { if (argc == 0) { Usage(); return; } auto& eps = GetEPS(); if (strcmp(argv[0], "enable_lcl") == 0) { auto lcl = static_cast<LCL>(atoi(argv[1])); auto result = eps.EnableLCL(lcl); GetTerminal().Printf("%d", num(result)); return; } if (strcmp(argv[0], "disable_lcl") == 0) { auto lcl = static_cast<LCL>(atoi(argv[1])); auto result = eps.DisableLCL(lcl); GetTerminal().Printf("%d", num(result)); return; } if (strcmp(argv[0], "power_cycle") == 0) { bool result = false; if (strcmp(argv[1], "A") == 0) { result = eps.PowerCycle(EPSDriver::Controller::A); } else if (strcmp(argv[1], "B") == 0) { result = eps.PowerCycle(EPSDriver::Controller::B); } else if (strcmp(argv[1], "Auto") == 0) { result = eps.PowerCycle(); } GetTerminal().Puts(result ? "1" : "0"); return; } if (strcmp(argv[0], "disable_overheat") == 0) { bool result = false; if (strcmp(argv[1], "A") == 0) { result = eps.DisableOverheatSubmode(EPSDriver::Controller::A); } else if (strcmp(argv[1], "B") == 0) { result = eps.DisableOverheatSubmode(EPSDriver::Controller::B); } GetTerminal().Puts(result ? "1" : "0"); return; } if (strcmp(argv[0], "enable_burn_switch") == 0) { bool useMain = strcmp(argv[1], "1") == 0; auto burnSwitch = static_cast<BurnSwitch>(atoi(argv[2])); auto result = eps.EnableBurnSwitch(useMain, burnSwitch); GetTerminal().Printf("%d", num(result)); return; } if (strcmp(argv[0], "hk_a") == 0) { auto hk = eps.ReadHousekeepingA(); if (!hk.HasValue) { GetTerminal().Puts("Error"); return; } auto v = hk.Value; Print("MPPT_X", v.mpptX); Print("MPPT_Y_PLUS", v.mpptYPlus); Print("MPPT_Y_MINUS", v.mpptYMinus); Print("DISTR", v.distr); Print("BATC", v.batc); Print("BP", v.bp); Print("CTRLB", v.other); Print("CTRLA", v.current); Print("DCDC3V3", v.dcdc3V3); Print("DCDC5V", v.dcdc5V); return; } if (strcmp(argv[0], "hk_b") == 0) { auto hk = eps.ReadHousekeepingB(); if (!hk.HasValue) { GetTerminal().Puts("Error"); return; } auto v = hk.Value; Print("BP", v.bp); Print("BATC", v.batc); Print("CTRLA", v.other); Print("CTRLB", v.current); return; } if (strcmp(argv[0], "reset_watchdog") == 0) { bool result = false; if (strcmp(argv[1], "A") == 0) { result = eps.ResetWatchdog(EPSDriver::Controller::A) == devices::eps::ErrorCode::NoError; } else if (strcmp(argv[1], "B") == 0) { result = eps.ResetWatchdog(EPSDriver::Controller::B) == devices::eps::ErrorCode::NoError; } else if (strcmp(argv[1], "Both") == 0) { result = eps.ResetWatchdog(EPSDriver::Controller::A) == devices::eps::ErrorCode::NoError; result = result && eps.ResetWatchdog(EPSDriver::Controller::B) == devices::eps::ErrorCode::NoError; } GetTerminal().Puts(result ? "1" : "0"); return; } } <|endoftext|>
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/type_converter.h" #include "services/files/files_test_base.h" namespace mojo { namespace files { namespace { using FileImplTest = FilesTestBase; TEST_F(FileImplTest, CreateWriteCloseRenameOpenRead) { DirectoryPtr directory; GetTemporaryRoot(&directory); Error error; { // Create my_file. FilePtr file; error = ERROR_INTERNAL; directory->OpenFile("my_file", GetProxy(&file), kOpenFlagWrite | kOpenFlagCreate, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Write to it. std::vector<uint8_t> bytes_to_write; bytes_to_write.push_back(static_cast<uint8_t>('h')); bytes_to_write.push_back(static_cast<uint8_t>('e')); bytes_to_write.push_back(static_cast<uint8_t>('l')); bytes_to_write.push_back(static_cast<uint8_t>('l')); bytes_to_write.push_back(static_cast<uint8_t>('o')); error = ERROR_INTERNAL; uint32_t num_bytes_written = 0; file->Write(Array<uint8_t>::From(bytes_to_write), 0, WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); // Close it. error = ERROR_INTERNAL; file->Close(Capture(&error)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); } // Rename it. error = ERROR_INTERNAL; directory->Rename("my_file", "your_file", Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); { // Open my_file again. FilePtr file; error = ERROR_INTERNAL; directory->OpenFile("your_file", GetProxy(&file), kOpenFlagRead, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Read from it. Array<uint8_t> bytes_read; error = ERROR_INTERNAL; file->Read(3, 1, WHENCE_FROM_START, Capture(&error, &bytes_read)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_EQ(3u, bytes_read.size()); EXPECT_EQ(static_cast<uint8_t>('e'), bytes_read[0]); EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[1]); EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[2]); } // TODO(vtl): Test various open options. // TODO(vtl): Test read/write offset options. } // Note: Ignore nanoseconds, since it may not always be supported. We expect at // least second-resolution support though. TEST_F(FileImplTest, StatTouch) { DirectoryPtr directory; GetTemporaryRoot(&directory); Error error; // Create my_file. FilePtr file; error = ERROR_INTERNAL; directory->OpenFile("my_file", GetProxy(&file), kOpenFlagWrite | kOpenFlagCreate, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Stat it. error = ERROR_INTERNAL; FileInformationPtr file_info; file->Stat(Capture(&error, &file_info)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_FALSE(file_info.is_null()); EXPECT_EQ(FILE_TYPE_REGULAR_FILE, file_info->type); EXPECT_EQ(0, file_info->size); ASSERT_FALSE(file_info->atime.is_null()); EXPECT_GT(file_info->atime->seconds, 0); // Expect that it's not 1970-01-01. ASSERT_FALSE(file_info->mtime.is_null()); EXPECT_GT(file_info->mtime->seconds, 0); int64_t first_mtime = file_info->mtime->seconds; // Touch only the atime. error = ERROR_INTERNAL; TimespecOrNowPtr t(TimespecOrNow::New()); t->now = false; t->timespec = Timespec::New(); const int64_t kPartyTime1 = 1234567890; // Party like it's 2009-02-13. t->timespec->seconds = kPartyTime1; file->Touch(t.Pass(), nullptr, Capture(&error)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Stat again. error = ERROR_INTERNAL; file_info.reset(); file->Stat(Capture(&error, &file_info)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_FALSE(file_info.is_null()); ASSERT_FALSE(file_info->atime.is_null()); EXPECT_EQ(kPartyTime1, file_info->atime->seconds); ASSERT_FALSE(file_info->mtime.is_null()); EXPECT_EQ(first_mtime, file_info->mtime->seconds); // Touch only the mtime. t = TimespecOrNow::New(); t->now = false; t->timespec = Timespec::New(); const int64_t kPartyTime2 = 1425059525; // No time like the present. t->timespec->seconds = kPartyTime2; file->Touch(nullptr, t.Pass(), Capture(&error)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Stat again. error = ERROR_INTERNAL; file_info.reset(); file->Stat(Capture(&error, &file_info)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_FALSE(file_info.is_null()); ASSERT_FALSE(file_info->atime.is_null()); EXPECT_EQ(kPartyTime1, file_info->atime->seconds); ASSERT_FALSE(file_info->mtime.is_null()); EXPECT_EQ(kPartyTime2, file_info->mtime->seconds); // TODO(vtl): Also test non-zero file size. // TODO(vtl): Also test Touch() "now" options. // TODO(vtl): Also test touching both atime and mtime. // Close it. error = ERROR_INTERNAL; file->Close(Capture(&error)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); } TEST_F(FileImplTest, TellSeek) { DirectoryPtr directory; GetTemporaryRoot(&directory); Error error; // Create my_file. FilePtr file; error = ERROR_INTERNAL; directory->OpenFile("my_file", GetProxy(&file), kOpenFlagWrite | kOpenFlagCreate, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Write to it. std::vector<uint8_t> bytes_to_write(1000, '!'); error = ERROR_INTERNAL; uint32_t num_bytes_written = 0; file->Write(Array<uint8_t>::From(bytes_to_write), 0, WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); const int size = static_cast<int>(num_bytes_written); // Tell. error = ERROR_INTERNAL; int64_t position = -1; file->Tell(Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); // Should be at the end. EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size, position); // Seek back 100. error = ERROR_INTERNAL; position = -1; file->Seek(-100, WHENCE_FROM_CURRENT, Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size - 100, position); // Tell. error = ERROR_INTERNAL; position = -1; file->Tell(Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size - 100, position); // Seek to 123 from start. error = ERROR_INTERNAL; position = -1; file->Seek(123, WHENCE_FROM_START, Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(123, position); // Tell. error = ERROR_INTERNAL; position = -1; file->Tell(Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(123, position); // Seek to 123 back from end. error = ERROR_INTERNAL; position = -1; file->Seek(-123, WHENCE_FROM_END, Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size - 123, position); // Tell. error = ERROR_INTERNAL; position = -1; file->Tell(Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size - 123, position); // TODO(vtl): Check that seeking actually affects reading/writing. // TODO(vtl): Check that seeking can extend the file? // Close it. error = ERROR_INTERNAL; file->Close(Capture(&error)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); } TEST_F(FileImplTest, Dup) { DirectoryPtr directory; GetTemporaryRoot(&directory); Error error; // Create my_file. FilePtr file1; error = ERROR_INTERNAL; directory->OpenFile("my_file", GetProxy(&file1), kOpenFlagRead | kOpenFlagWrite | kOpenFlagCreate, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Write to it. std::vector<uint8_t> bytes_to_write; bytes_to_write.push_back(static_cast<uint8_t>('h')); bytes_to_write.push_back(static_cast<uint8_t>('e')); bytes_to_write.push_back(static_cast<uint8_t>('l')); bytes_to_write.push_back(static_cast<uint8_t>('l')); bytes_to_write.push_back(static_cast<uint8_t>('o')); error = ERROR_INTERNAL; uint32_t num_bytes_written = 0; file1->Write(Array<uint8_t>::From(bytes_to_write), 0, WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written)); ASSERT_TRUE(file1.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); const int end_hello_pos = static_cast<int>(num_bytes_written); // Dup it. FilePtr file2; error = ERROR_INTERNAL; file1->Dup(GetProxy(&file2), Capture(&error)); ASSERT_TRUE(file1.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // |file2| should have the same position. error = ERROR_INTERNAL; int64_t position = -1; file2->Tell(Capture(&error, &position)); ASSERT_TRUE(file2.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(end_hello_pos, position); // Write using |file2|. std::vector<uint8_t> more_bytes_to_write; more_bytes_to_write.push_back(static_cast<uint8_t>('w')); more_bytes_to_write.push_back(static_cast<uint8_t>('o')); more_bytes_to_write.push_back(static_cast<uint8_t>('r')); more_bytes_to_write.push_back(static_cast<uint8_t>('l')); more_bytes_to_write.push_back(static_cast<uint8_t>('d')); error = ERROR_INTERNAL; num_bytes_written = 0; file2->Write(Array<uint8_t>::From(more_bytes_to_write), 0, WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written)); ASSERT_TRUE(file2.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(more_bytes_to_write.size(), num_bytes_written); const int end_world_pos = end_hello_pos + static_cast<int>(num_bytes_written); // |file1| should have the same position. error = ERROR_INTERNAL; position = -1; file1->Tell(Capture(&error, &position)); ASSERT_TRUE(file1.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(end_world_pos, position); // Close |file1|. error = ERROR_INTERNAL; file1->Close(Capture(&error)); ASSERT_TRUE(file1.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Read everything using |file2|. Array<uint8_t> bytes_read; error = ERROR_INTERNAL; file2->Read(1000, 0, WHENCE_FROM_START, Capture(&error, &bytes_read)); ASSERT_TRUE(file2.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_EQ(static_cast<size_t>(end_world_pos), bytes_read.size()); // Just check the first and last bytes. EXPECT_EQ(static_cast<uint8_t>('h'), bytes_read[0]); EXPECT_EQ(static_cast<uint8_t>('d'), bytes_read[end_world_pos - 1]); // Close |file2|. error = ERROR_INTERNAL; file2->Close(Capture(&error)); ASSERT_TRUE(file2.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // TODO(vtl): Test that |file2| has the same open options as |file1|. } } // namespace } // namespace files } // namespace mojo <commit_msg>Test the files services's File::Truncate() implementation.<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/type_converter.h" #include "services/files/files_test_base.h" namespace mojo { namespace files { namespace { using FileImplTest = FilesTestBase; TEST_F(FileImplTest, CreateWriteCloseRenameOpenRead) { DirectoryPtr directory; GetTemporaryRoot(&directory); Error error; { // Create my_file. FilePtr file; error = ERROR_INTERNAL; directory->OpenFile("my_file", GetProxy(&file), kOpenFlagWrite | kOpenFlagCreate, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Write to it. std::vector<uint8_t> bytes_to_write; bytes_to_write.push_back(static_cast<uint8_t>('h')); bytes_to_write.push_back(static_cast<uint8_t>('e')); bytes_to_write.push_back(static_cast<uint8_t>('l')); bytes_to_write.push_back(static_cast<uint8_t>('l')); bytes_to_write.push_back(static_cast<uint8_t>('o')); error = ERROR_INTERNAL; uint32_t num_bytes_written = 0; file->Write(Array<uint8_t>::From(bytes_to_write), 0, WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); // Close it. error = ERROR_INTERNAL; file->Close(Capture(&error)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); } // Rename it. error = ERROR_INTERNAL; directory->Rename("my_file", "your_file", Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); { // Open my_file again. FilePtr file; error = ERROR_INTERNAL; directory->OpenFile("your_file", GetProxy(&file), kOpenFlagRead, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Read from it. Array<uint8_t> bytes_read; error = ERROR_INTERNAL; file->Read(3, 1, WHENCE_FROM_START, Capture(&error, &bytes_read)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_EQ(3u, bytes_read.size()); EXPECT_EQ(static_cast<uint8_t>('e'), bytes_read[0]); EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[1]); EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[2]); } // TODO(vtl): Test various open options. // TODO(vtl): Test read/write offset options. } // Note: Ignore nanoseconds, since it may not always be supported. We expect at // least second-resolution support though. TEST_F(FileImplTest, StatTouch) { DirectoryPtr directory; GetTemporaryRoot(&directory); Error error; // Create my_file. FilePtr file; error = ERROR_INTERNAL; directory->OpenFile("my_file", GetProxy(&file), kOpenFlagWrite | kOpenFlagCreate, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Stat it. error = ERROR_INTERNAL; FileInformationPtr file_info; file->Stat(Capture(&error, &file_info)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_FALSE(file_info.is_null()); EXPECT_EQ(FILE_TYPE_REGULAR_FILE, file_info->type); EXPECT_EQ(0, file_info->size); ASSERT_FALSE(file_info->atime.is_null()); EXPECT_GT(file_info->atime->seconds, 0); // Expect that it's not 1970-01-01. ASSERT_FALSE(file_info->mtime.is_null()); EXPECT_GT(file_info->mtime->seconds, 0); int64_t first_mtime = file_info->mtime->seconds; // Touch only the atime. error = ERROR_INTERNAL; TimespecOrNowPtr t(TimespecOrNow::New()); t->now = false; t->timespec = Timespec::New(); const int64_t kPartyTime1 = 1234567890; // Party like it's 2009-02-13. t->timespec->seconds = kPartyTime1; file->Touch(t.Pass(), nullptr, Capture(&error)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Stat again. error = ERROR_INTERNAL; file_info.reset(); file->Stat(Capture(&error, &file_info)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_FALSE(file_info.is_null()); ASSERT_FALSE(file_info->atime.is_null()); EXPECT_EQ(kPartyTime1, file_info->atime->seconds); ASSERT_FALSE(file_info->mtime.is_null()); EXPECT_EQ(first_mtime, file_info->mtime->seconds); // Touch only the mtime. t = TimespecOrNow::New(); t->now = false; t->timespec = Timespec::New(); const int64_t kPartyTime2 = 1425059525; // No time like the present. t->timespec->seconds = kPartyTime2; file->Touch(nullptr, t.Pass(), Capture(&error)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Stat again. error = ERROR_INTERNAL; file_info.reset(); file->Stat(Capture(&error, &file_info)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_FALSE(file_info.is_null()); ASSERT_FALSE(file_info->atime.is_null()); EXPECT_EQ(kPartyTime1, file_info->atime->seconds); ASSERT_FALSE(file_info->mtime.is_null()); EXPECT_EQ(kPartyTime2, file_info->mtime->seconds); // TODO(vtl): Also test non-zero file size. // TODO(vtl): Also test Touch() "now" options. // TODO(vtl): Also test touching both atime and mtime. } TEST_F(FileImplTest, TellSeek) { DirectoryPtr directory; GetTemporaryRoot(&directory); Error error; // Create my_file. FilePtr file; error = ERROR_INTERNAL; directory->OpenFile("my_file", GetProxy(&file), kOpenFlagWrite | kOpenFlagCreate, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Write to it. std::vector<uint8_t> bytes_to_write(1000, '!'); error = ERROR_INTERNAL; uint32_t num_bytes_written = 0; file->Write(Array<uint8_t>::From(bytes_to_write), 0, WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); const int size = static_cast<int>(num_bytes_written); // Tell. error = ERROR_INTERNAL; int64_t position = -1; file->Tell(Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); // Should be at the end. EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size, position); // Seek back 100. error = ERROR_INTERNAL; position = -1; file->Seek(-100, WHENCE_FROM_CURRENT, Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size - 100, position); // Tell. error = ERROR_INTERNAL; position = -1; file->Tell(Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size - 100, position); // Seek to 123 from start. error = ERROR_INTERNAL; position = -1; file->Seek(123, WHENCE_FROM_START, Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(123, position); // Tell. error = ERROR_INTERNAL; position = -1; file->Tell(Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(123, position); // Seek to 123 back from end. error = ERROR_INTERNAL; position = -1; file->Seek(-123, WHENCE_FROM_END, Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size - 123, position); // Tell. error = ERROR_INTERNAL; position = -1; file->Tell(Capture(&error, &position)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(size - 123, position); // TODO(vtl): Check that seeking actually affects reading/writing. // TODO(vtl): Check that seeking can extend the file? } TEST_F(FileImplTest, Dup) { DirectoryPtr directory; GetTemporaryRoot(&directory); Error error; // Create my_file. FilePtr file1; error = ERROR_INTERNAL; directory->OpenFile("my_file", GetProxy(&file1), kOpenFlagRead | kOpenFlagWrite | kOpenFlagCreate, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Write to it. std::vector<uint8_t> bytes_to_write; bytes_to_write.push_back(static_cast<uint8_t>('h')); bytes_to_write.push_back(static_cast<uint8_t>('e')); bytes_to_write.push_back(static_cast<uint8_t>('l')); bytes_to_write.push_back(static_cast<uint8_t>('l')); bytes_to_write.push_back(static_cast<uint8_t>('o')); error = ERROR_INTERNAL; uint32_t num_bytes_written = 0; file1->Write(Array<uint8_t>::From(bytes_to_write), 0, WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written)); ASSERT_TRUE(file1.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(bytes_to_write.size(), num_bytes_written); const int end_hello_pos = static_cast<int>(num_bytes_written); // Dup it. FilePtr file2; error = ERROR_INTERNAL; file1->Dup(GetProxy(&file2), Capture(&error)); ASSERT_TRUE(file1.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // |file2| should have the same position. error = ERROR_INTERNAL; int64_t position = -1; file2->Tell(Capture(&error, &position)); ASSERT_TRUE(file2.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(end_hello_pos, position); // Write using |file2|. std::vector<uint8_t> more_bytes_to_write; more_bytes_to_write.push_back(static_cast<uint8_t>('w')); more_bytes_to_write.push_back(static_cast<uint8_t>('o')); more_bytes_to_write.push_back(static_cast<uint8_t>('r')); more_bytes_to_write.push_back(static_cast<uint8_t>('l')); more_bytes_to_write.push_back(static_cast<uint8_t>('d')); error = ERROR_INTERNAL; num_bytes_written = 0; file2->Write(Array<uint8_t>::From(more_bytes_to_write), 0, WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written)); ASSERT_TRUE(file2.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(more_bytes_to_write.size(), num_bytes_written); const int end_world_pos = end_hello_pos + static_cast<int>(num_bytes_written); // |file1| should have the same position. error = ERROR_INTERNAL; position = -1; file1->Tell(Capture(&error, &position)); ASSERT_TRUE(file1.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(end_world_pos, position); // Close |file1|. error = ERROR_INTERNAL; file1->Close(Capture(&error)); ASSERT_TRUE(file1.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Read everything using |file2|. Array<uint8_t> bytes_read; error = ERROR_INTERNAL; file2->Read(1000, 0, WHENCE_FROM_START, Capture(&error, &bytes_read)); ASSERT_TRUE(file2.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_EQ(static_cast<size_t>(end_world_pos), bytes_read.size()); // Just check the first and last bytes. EXPECT_EQ(static_cast<uint8_t>('h'), bytes_read[0]); EXPECT_EQ(static_cast<uint8_t>('d'), bytes_read[end_world_pos - 1]); // TODO(vtl): Test that |file2| has the same open options as |file1|. } TEST_F(FileImplTest, Truncate) { const uint32_t kInitialSize = 1000; const uint32_t kTruncatedSize = 654; DirectoryPtr directory; GetTemporaryRoot(&directory); Error error; // Create my_file. FilePtr file; error = ERROR_INTERNAL; directory->OpenFile("my_file", GetProxy(&file), kOpenFlagWrite | kOpenFlagCreate, Capture(&error)); ASSERT_TRUE(directory.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Write to it. std::vector<uint8_t> bytes_to_write(kInitialSize, '!'); error = ERROR_INTERNAL; uint32_t num_bytes_written = 0; file->Write(Array<uint8_t>::From(bytes_to_write), 0, WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); EXPECT_EQ(kInitialSize, num_bytes_written); // Stat it. error = ERROR_INTERNAL; FileInformationPtr file_info; file->Stat(Capture(&error, &file_info)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_FALSE(file_info.is_null()); EXPECT_EQ(kInitialSize, file_info->size); // Truncate it. error = ERROR_INTERNAL; file->Truncate(kTruncatedSize, Capture(&error)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); // Stat again. error = ERROR_INTERNAL; file_info.reset(); file->Stat(Capture(&error, &file_info)); ASSERT_TRUE(file.WaitForIncomingMethodCall()); EXPECT_EQ(ERROR_OK, error); ASSERT_FALSE(file_info.is_null()); EXPECT_EQ(kTruncatedSize, file_info->size); } } // namespace } // namespace files } // namespace mojo <|endoftext|>
<commit_before>/** * @file llpanelmarketplaceinboxinventory.cpp * @brief LLInboxInventoryPanel class definition * * $LicenseInfo:firstyear=2009&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llpanelmarketplaceinboxinventory.h" #include "llfolderview.h" #include "llfoldervieweventlistener.h" #include "llinventorybridge.h" #include "llinventoryfunctions.h" #include "llpanellandmarks.h" #include "llplacesinventorybridge.h" #include "llviewerfoldertype.h" #define DEBUGGING_FRESHNESS 0 // // statics // static LLDefaultChildRegistry::Register<LLInboxInventoryPanel> r1("inbox_inventory_panel"); static LLDefaultChildRegistry::Register<LLInboxFolderViewFolder> r2("inbox_folder_view_folder"); // // LLInboxInventoryPanel Implementation // LLInboxInventoryPanel::LLInboxInventoryPanel(const LLInboxInventoryPanel::Params& p) : LLInventoryPanel(p) { } LLInboxInventoryPanel::~LLInboxInventoryPanel() { } // virtual void LLInboxInventoryPanel::buildFolderView(const LLInventoryPanel::Params& params) { // Determine the root folder in case specified, and // build the views starting with that folder. LLUUID root_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_INBOX, false, false); // leslie -- temporary HACK to work around sim not creating inbox with proper system folder type if (root_id.isNull()) { std::string start_folder_name(params.start_folder()); LLInventoryModel::cat_array_t* cats; LLInventoryModel::item_array_t* items; gInventory.getDirectDescendentsOf(gInventory.getRootFolderID(), cats, items); if (cats) { for (LLInventoryModel::cat_array_t::const_iterator cat_it = cats->begin(); cat_it != cats->end(); ++cat_it) { LLInventoryCategory* cat = *cat_it; if (cat->getName() == start_folder_name) { root_id = cat->getUUID(); break; } } } if (root_id == LLUUID::null) { llwarns << "No category found that matches inbox inventory panel start_folder: " << start_folder_name << llendl; } } // leslie -- end temporary HACK if (root_id == LLUUID::null) { llwarns << "Inbox inventory panel has no root folder!" << llendl; root_id = LLUUID::generateNewID(); } LLInvFVBridge* new_listener = mInvFVBridgeBuilder->createBridge(LLAssetType::AT_CATEGORY, LLAssetType::AT_CATEGORY, LLInventoryType::IT_CATEGORY, this, NULL, root_id); mFolderRoot = createFolderView(new_listener, params.use_label_suffix()); } LLFolderViewFolder * LLInboxInventoryPanel::createFolderViewFolder(LLInvFVBridge * bridge) { LLInboxFolderViewFolder::Params params; params.name = bridge->getDisplayName(); params.icon = bridge->getIcon(); params.icon_open = bridge->getOpenIcon(); if (mShowItemLinkOverlays) // if false, then links show up just like normal items { params.icon_overlay = LLUI::getUIImage("Inv_Link"); } params.root = mFolderRoot; params.listener = bridge; params.tool_tip = params.name; return LLUICtrlFactory::create<LLInboxFolderViewFolder>(params); } LLFolderViewItem * LLInboxInventoryPanel::createFolderViewItem(LLInvFVBridge * bridge) { LLFolderViewItem::Params params; params.name = bridge->getDisplayName(); params.icon = bridge->getIcon(); params.icon_open = bridge->getOpenIcon(); if (mShowItemLinkOverlays) // if false, then links show up just like normal items { params.icon_overlay = LLUI::getUIImage("Inv_Link"); } params.creation_date = bridge->getCreationDate(); params.root = mFolderRoot; params.listener = bridge; params.rect = LLRect (0, 0, 0, 0); params.tool_tip = params.name; return LLUICtrlFactory::create<LLInboxFolderViewItem>(params); } // // LLInboxFolderViewFolder Implementation // LLInboxFolderViewFolder::LLInboxFolderViewFolder(const Params& p) : LLFolderViewFolder(p) , LLBadgeOwner(getHandle()) , mFresh(false) { #if SUPPORTING_FRESH_ITEM_COUNT initBadgeParams(p.new_badge()); #endif } LLInboxFolderViewFolder::~LLInboxFolderViewFolder() { } // virtual void LLInboxFolderViewFolder::draw() { #if SUPPORTING_FRESH_ITEM_COUNT if (!badgeHasParent()) { addBadgeToParentPanel(); } setBadgeVisibility(mFresh); #endif LLFolderViewFolder::draw(); } void LLInboxFolderViewFolder::computeFreshness() { const std::string& last_expansion = gSavedPerAccountSettings.getString("LastInventoryInboxActivity"); if (!last_expansion.empty()) { LLDate saved_freshness_date = LLDate(last_expansion); mFresh = (mCreationDate > saved_freshness_date.secondsSinceEpoch()); #if DEBUGGING_FRESHNESS if (mFresh) { llinfos << "Item is fresh! -- creation " << mCreationDate << ", saved_freshness_date " << saved_freshness_date.secondsSinceEpoch() << llendl; } #endif } else { mFresh = true; } } void LLInboxFolderViewFolder::deFreshify() { mFresh = false; gSavedPerAccountSettings.setString("LastInventoryInboxActivity", LLDate::now().asString()); } void LLInboxFolderViewFolder::selectItem() { LLFolderViewFolder::selectItem(); deFreshify(); } void LLInboxFolderViewFolder::toggleOpen() { LLFolderViewFolder::toggleOpen(); deFreshify(); } void LLInboxFolderViewFolder::setCreationDate(time_t creation_date_utc) { mCreationDate = creation_date_utc; if (mParentFolder == mRoot) { computeFreshness(); } } // // LLInboxFolderViewItem Implementation // BOOL LLInboxFolderViewItem::handleDoubleClick(S32 x, S32 y, MASK mask) { return TRUE; } // eof <commit_msg>EXP-1194 FIX -- Update New tag behavior to update Newness timestamp when Received Items panel is open and do not auto open Received Items panel<commit_after>/** * @file llpanelmarketplaceinboxinventory.cpp * @brief LLInboxInventoryPanel class definition * * $LicenseInfo:firstyear=2009&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llpanelmarketplaceinboxinventory.h" #include "llfolderview.h" #include "llfoldervieweventlistener.h" #include "llinventorybridge.h" #include "llinventoryfunctions.h" #include "llpanellandmarks.h" #include "llplacesinventorybridge.h" #include "llviewerfoldertype.h" #define DEBUGGING_FRESHNESS 0 // // statics // static LLDefaultChildRegistry::Register<LLInboxInventoryPanel> r1("inbox_inventory_panel"); static LLDefaultChildRegistry::Register<LLInboxFolderViewFolder> r2("inbox_folder_view_folder"); // // LLInboxInventoryPanel Implementation // LLInboxInventoryPanel::LLInboxInventoryPanel(const LLInboxInventoryPanel::Params& p) : LLInventoryPanel(p) { } LLInboxInventoryPanel::~LLInboxInventoryPanel() { } // virtual void LLInboxInventoryPanel::buildFolderView(const LLInventoryPanel::Params& params) { // Determine the root folder in case specified, and // build the views starting with that folder. LLUUID root_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_INBOX, false, false); // leslie -- temporary HACK to work around sim not creating inbox with proper system folder type if (root_id.isNull()) { std::string start_folder_name(params.start_folder()); LLInventoryModel::cat_array_t* cats; LLInventoryModel::item_array_t* items; gInventory.getDirectDescendentsOf(gInventory.getRootFolderID(), cats, items); if (cats) { for (LLInventoryModel::cat_array_t::const_iterator cat_it = cats->begin(); cat_it != cats->end(); ++cat_it) { LLInventoryCategory* cat = *cat_it; if (cat->getName() == start_folder_name) { root_id = cat->getUUID(); break; } } } if (root_id == LLUUID::null) { llwarns << "No category found that matches inbox inventory panel start_folder: " << start_folder_name << llendl; } } // leslie -- end temporary HACK if (root_id == LLUUID::null) { llwarns << "Inbox inventory panel has no root folder!" << llendl; root_id = LLUUID::generateNewID(); } LLInvFVBridge* new_listener = mInvFVBridgeBuilder->createBridge(LLAssetType::AT_CATEGORY, LLAssetType::AT_CATEGORY, LLInventoryType::IT_CATEGORY, this, NULL, root_id); mFolderRoot = createFolderView(new_listener, params.use_label_suffix()); } LLFolderViewFolder * LLInboxInventoryPanel::createFolderViewFolder(LLInvFVBridge * bridge) { LLInboxFolderViewFolder::Params params; params.name = bridge->getDisplayName(); params.icon = bridge->getIcon(); params.icon_open = bridge->getOpenIcon(); if (mShowItemLinkOverlays) // if false, then links show up just like normal items { params.icon_overlay = LLUI::getUIImage("Inv_Link"); } params.root = mFolderRoot; params.listener = bridge; params.tool_tip = params.name; return LLUICtrlFactory::create<LLInboxFolderViewFolder>(params); } LLFolderViewItem * LLInboxInventoryPanel::createFolderViewItem(LLInvFVBridge * bridge) { LLFolderViewItem::Params params; params.name = bridge->getDisplayName(); params.icon = bridge->getIcon(); params.icon_open = bridge->getOpenIcon(); if (mShowItemLinkOverlays) // if false, then links show up just like normal items { params.icon_overlay = LLUI::getUIImage("Inv_Link"); } params.creation_date = bridge->getCreationDate(); params.root = mFolderRoot; params.listener = bridge; params.rect = LLRect (0, 0, 0, 0); params.tool_tip = params.name; return LLUICtrlFactory::create<LLInboxFolderViewItem>(params); } // // LLInboxFolderViewFolder Implementation // LLInboxFolderViewFolder::LLInboxFolderViewFolder(const Params& p) : LLFolderViewFolder(p) , LLBadgeOwner(getHandle()) , mFresh(false) { #if SUPPORTING_FRESH_ITEM_COUNT initBadgeParams(p.new_badge()); #endif } LLInboxFolderViewFolder::~LLInboxFolderViewFolder() { } // virtual void LLInboxFolderViewFolder::draw() { #if SUPPORTING_FRESH_ITEM_COUNT if (!badgeHasParent()) { addBadgeToParentPanel(); } setBadgeVisibility(mFresh); #endif LLFolderViewFolder::draw(); } void LLInboxFolderViewFolder::computeFreshness() { const std::string& last_expansion = gSavedPerAccountSettings.getString("LastInventoryInboxActivity"); if (!last_expansion.empty()) { // Inventory DB timezone is hardcoded to PDT or GMT-7, which is 7 hours behind GMT const time_t SEVEN_HOURS_IN_SECONDS = 7 * 60 * 60; const time_t saved_freshness_inventory_db_timezone = LLDate(last_expansion).secondsSinceEpoch() - SEVEN_HOURS_IN_SECONDS; mFresh = (mCreationDate > saved_freshness_inventory_db_timezone); #if DEBUGGING_FRESHNESS if (mFresh) { llinfos << "Item is fresh! -- creation " << mCreationDate << ", saved_freshness_date " << saved_freshness_inventory_db_timezone << llendl; } #endif } else { mFresh = true; } } void LLInboxFolderViewFolder::deFreshify() { mFresh = false; gSavedPerAccountSettings.setString("LastInventoryInboxActivity", LLDate::now().asString()); } void LLInboxFolderViewFolder::selectItem() { LLFolderViewFolder::selectItem(); deFreshify(); } void LLInboxFolderViewFolder::toggleOpen() { LLFolderViewFolder::toggleOpen(); deFreshify(); } void LLInboxFolderViewFolder::setCreationDate(time_t creation_date_utc) { mCreationDate = creation_date_utc; if (mParentFolder == mRoot) { computeFreshness(); } } // // LLInboxFolderViewItem Implementation // BOOL LLInboxFolderViewItem::handleDoubleClick(S32 x, S32 y, MASK mask) { return TRUE; } // eof <|endoftext|>
<commit_before>/* This file is a part of libcds - Concurrent Data Structures library (C) Copyright Maxim Khizhinsky ([email protected]) 2006-2016 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ 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. */ #include "pqueue_type.h" #include "item.h" namespace { static size_t s_nThreadCount = 8; static size_t s_nQueueSize = 2000000; class pqueue_pop: public cds_test::stress_fixture { typedef cds_test::stress_fixture base_class; protected: template <class PQueue> class Consumer: public cds_test::thread { typedef cds_test::thread base_class; public: Consumer( cds_test::thread_pool& pool, PQueue& queue ) : base_class( pool ) , m_Queue( queue ) {} Consumer( Consumer& src ) : base_class( src ) , m_Queue( src.m_Queue ) {} virtual thread * clone() { return new Consumer( *this ); } virtual void test() { typedef typename PQueue::value_type value_type; size_t nPrevKey; value_type val; if ( m_Queue.pop( val )) { ++m_nPopSuccess; nPrevKey = val.key; bool prevPopFailed = false; while ( m_Queue.pop( val )) { ++m_nPopSuccess; if ( val.key > nPrevKey ) { ++m_nPopError; m_arrFailedPops.emplace_back( failed_pops{ nPrevKey, val.key, static_cast<size_t>(-1) } ); prevPopFailed = true; } else if ( val.key == nPrevKey ) { ++m_nPopErrorEq; m_arrFailedPops.emplace_back( failed_pops{ nPrevKey, val.key, static_cast<size_t>(-1) } ); } else { if ( prevPopFailed ) m_arrFailedPops.back().next_key = val.key; prevPopFailed = false; } nPrevKey = val.key; } } else ++m_nPopFailed; } public: PQueue& m_Queue; size_t m_nPopError = 0; size_t m_nPopErrorEq = 0; size_t m_nPopSuccess = 0; size_t m_nPopFailed = 0; struct failed_pops { size_t prev_key; size_t popped_key; size_t next_key; }; std::vector< failed_pops > m_arrFailedPops; }; protected: template <class PQueue> void test( PQueue& q ) { cds_test::thread_pool& pool = get_pool(); propout() << std::make_pair( "thread_count", s_nThreadCount ) << std::make_pair( "push_count", s_nQueueSize ); // push { std::vector< size_t > arr; arr.reserve( s_nQueueSize ); for ( size_t i = 0; i < s_nQueueSize; ++i ) arr.push_back( i ); shuffle( arr.begin(), arr.end() ); size_t nPushError = 0; typedef typename PQueue::value_type value_type; for ( auto it = arr.begin(); it != arr.end(); ++it ) { if ( !q.push( value_type( *it ) )) ++nPushError; } s_nQueueSize -= nPushError; } // pop { pool.add( new Consumer<PQueue>( pool, q ), s_nThreadCount ); std::chrono::milliseconds duration = pool.run(); propout() << std::make_pair( "consumer_duration", duration ); // Analyze result size_t nTotalPopped = 0; size_t nTotalError = 0; size_t nTotalErrorEq = 0; size_t nTotalFailed = 0; for ( size_t i = 0; i < pool.size(); ++i ) { Consumer<PQueue>& cons = static_cast<Consumer<PQueue>&>( pool.get(i)); nTotalPopped += cons.m_nPopSuccess; nTotalError += cons.m_nPopError; nTotalErrorEq += cons.m_nPopErrorEq; nTotalFailed += cons.m_nPopFailed; if ( !cons.m_arrFailedPops.empty() ) { std::cerr << "Priority violations, thread " << i; for ( size_t k = 0; k < cons.m_arrFailedPops.size(); ++k ) { std::cerr << "\n " << "prev_key=" << cons.m_arrFailedPops[k].prev_key << " popped_key=" << cons.m_arrFailedPops[k].popped_key << " next_key=" << cons.m_arrFailedPops[k].next_key; } std::cerr << std::endl; } } propout() << std::make_pair( "total_popped", nTotalPopped ) << std::make_pair( "error_pop_double", nTotalErrorEq ) << std::make_pair( "error_priority_violation", nTotalError ); EXPECT_EQ( nTotalPopped, s_nQueueSize ); EXPECT_EQ( nTotalError, 0 ) << "priority violations"; EXPECT_EQ( nTotalErrorEq, 0 ) << "double key"; } propout() << q.statistics(); } public: static void SetUpTestCase() { cds_test::config const& cfg = get_config( "pqueue_pop" ); s_nThreadCount = cfg.get_size_t( "ThreadCount", s_nThreadCount ); s_nQueueSize = cfg.get_size_t( "QueueSize", s_nQueueSize ); if ( s_nThreadCount == 0 ) s_nThreadCount = 1; if ( s_nQueueSize == 0 ) s_nQueueSize = 1000; } //static void TearDownTestCase(); }; #define CDSSTRESS_MSPriorityQueue( fixture_t, pqueue_t ) \ TEST_F( fixture_t, pqueue_t ) \ { \ typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \ pqueue_type pq( s_nQueueSize + 1 ); \ test( pq ); \ } CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_less ) CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_less_stat ) CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_cmp ) //CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_mutex ) // too slow #define CDSSTRESS_MSPriorityQueue_static( fixture_t, pqueue_t ) \ TEST_F( fixture_t, pqueue_t ) \ { \ typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \ std::unique_ptr< pqueue_type > pq( new pqueue_type ); \ test( *pq.get() ); \ } //CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_less ) //CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_less_stat ) //CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_cmp ) //CDSSTRESS_MSPriorityQueue( pqueue_pop, 1MSPriorityQueue_static_mutex ) #define CDSSTRESS_PriorityQueue( fixture_t, pqueue_t ) \ TEST_F( fixture_t, pqueue_t ) \ { \ typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \ pqueue_type pq; \ test( pq ); \ } CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_vector ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_vector_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_deque ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_deque_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_deque ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_deque_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_stable_vector ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_stable_vector_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_min_stat ) // CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_max ) // CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_max_stat ) // CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_min ) // CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_min_stat ) #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_min_stat ) #endif CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpi_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpi_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpb_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpb_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpt_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpt_min ) #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_shb_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_shb_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_sht_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_sht_min ) #endif CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_vector_spin ) CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_vector_mutex ) CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_deque_spin ) CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_deque_mutex ) } // namespace <commit_msg>improved test error msg<commit_after>/* This file is a part of libcds - Concurrent Data Structures library (C) Copyright Maxim Khizhinsky ([email protected]) 2006-2016 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ 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. */ #include "pqueue_type.h" #include "item.h" namespace { static size_t s_nThreadCount = 8; static size_t s_nQueueSize = 2000000; class pqueue_pop: public cds_test::stress_fixture { typedef cds_test::stress_fixture base_class; protected: template <class PQueue> class Consumer: public cds_test::thread { typedef cds_test::thread base_class; public: Consumer( cds_test::thread_pool& pool, PQueue& queue ) : base_class( pool ) , m_Queue( queue ) {} Consumer( Consumer& src ) : base_class( src ) , m_Queue( src.m_Queue ) {} virtual thread * clone() { return new Consumer( *this ); } virtual void test() { typedef typename PQueue::value_type value_type; size_t nPrevKey; value_type val; if ( m_Queue.pop( val )) { ++m_nPopSuccess; nPrevKey = val.key; bool prevPopFailed = false; while ( m_Queue.pop( val )) { ++m_nPopSuccess; if ( val.key > nPrevKey ) { ++m_nPopError; m_arrFailedPops.emplace_back( failed_pops{ nPrevKey, val.key, static_cast<size_t>(-1) } ); prevPopFailed = true; } else if ( val.key == nPrevKey ) { ++m_nPopErrorEq; m_arrFailedPops.emplace_back( failed_pops{ nPrevKey, val.key, static_cast<size_t>(-1) } ); } else { if ( prevPopFailed ) m_arrFailedPops.back().next_key = val.key; prevPopFailed = false; } nPrevKey = val.key; } } else ++m_nPopFailed; } public: PQueue& m_Queue; size_t m_nPopError = 0; size_t m_nPopErrorEq = 0; size_t m_nPopSuccess = 0; size_t m_nPopFailed = 0; struct failed_pops { size_t prev_key; size_t popped_key; size_t next_key; }; std::vector< failed_pops > m_arrFailedPops; }; protected: template <class PQueue> void test( PQueue& q ) { cds_test::thread_pool& pool = get_pool(); propout() << std::make_pair( "thread_count", s_nThreadCount ) << std::make_pair( "push_count", s_nQueueSize ); // push { std::vector< size_t > arr; arr.reserve( s_nQueueSize ); for ( size_t i = 0; i < s_nQueueSize; ++i ) arr.push_back( i ); shuffle( arr.begin(), arr.end() ); size_t nPushError = 0; typedef typename PQueue::value_type value_type; for ( auto it = arr.begin(); it != arr.end(); ++it ) { if ( !q.push( value_type( *it ) )) ++nPushError; } s_nQueueSize -= nPushError; } // pop { pool.add( new Consumer<PQueue>( pool, q ), s_nThreadCount ); std::chrono::milliseconds duration = pool.run(); propout() << std::make_pair( "consumer_duration", duration ); // Analyze result size_t nTotalPopped = 0; size_t nTotalError = 0; size_t nTotalErrorEq = 0; size_t nTotalFailed = 0; for ( size_t i = 0; i < pool.size(); ++i ) { Consumer<PQueue>& cons = static_cast<Consumer<PQueue>&>( pool.get(i)); nTotalPopped += cons.m_nPopSuccess; nTotalError += cons.m_nPopError; nTotalErrorEq += cons.m_nPopErrorEq; nTotalFailed += cons.m_nPopFailed; if ( !cons.m_arrFailedPops.empty() ) { std::cerr << "Priority violations, thread " << i; for ( size_t k = 0; k < cons.m_arrFailedPops.size(); ++k ) { std::cerr << "\n " << "prev_key=" << cons.m_arrFailedPops[k].prev_key << " popped_key=" << cons.m_arrFailedPops[k].popped_key; if ( cons.m_arrFailedPops[k].next_key != static_cast<size_t>(-1) ) std::cerr << " next_key=" << cons.m_arrFailedPops[k].next_key; else std::cerr << " next_key unspecified"; } std::cerr << std::endl; } } propout() << std::make_pair( "total_popped", nTotalPopped ) << std::make_pair( "error_pop_double", nTotalErrorEq ) << std::make_pair( "error_priority_violation", nTotalError ); EXPECT_EQ( nTotalPopped, s_nQueueSize ); EXPECT_EQ( nTotalError, 0 ) << "priority violations"; EXPECT_EQ( nTotalErrorEq, 0 ) << "double key"; } propout() << q.statistics(); } public: static void SetUpTestCase() { cds_test::config const& cfg = get_config( "pqueue_pop" ); s_nThreadCount = cfg.get_size_t( "ThreadCount", s_nThreadCount ); s_nQueueSize = cfg.get_size_t( "QueueSize", s_nQueueSize ); if ( s_nThreadCount == 0 ) s_nThreadCount = 1; if ( s_nQueueSize == 0 ) s_nQueueSize = 1000; } //static void TearDownTestCase(); }; #define CDSSTRESS_MSPriorityQueue( fixture_t, pqueue_t ) \ TEST_F( fixture_t, pqueue_t ) \ { \ typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \ pqueue_type pq( s_nQueueSize + 1 ); \ test( pq ); \ } CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_less ) CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_less_stat ) CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_cmp ) //CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_mutex ) // too slow #define CDSSTRESS_MSPriorityQueue_static( fixture_t, pqueue_t ) \ TEST_F( fixture_t, pqueue_t ) \ { \ typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \ std::unique_ptr< pqueue_type > pq( new pqueue_type ); \ test( *pq.get() ); \ } //CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_less ) //CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_less_stat ) //CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_cmp ) //CDSSTRESS_MSPriorityQueue( pqueue_pop, 1MSPriorityQueue_static_mutex ) #define CDSSTRESS_PriorityQueue( fixture_t, pqueue_t ) \ TEST_F( fixture_t, pqueue_t ) \ { \ typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \ pqueue_type pq; \ test( pq ); \ } CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_vector ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_vector_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_deque ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_deque_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_deque ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_deque_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_stable_vector ) CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_stable_vector_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_min_stat ) // CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_max ) // CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_max_stat ) // CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_min ) // CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_min_stat ) #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_max ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_min ) CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_min_stat ) #endif CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_max_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_min_stat ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpi_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpi_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpb_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpb_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpt_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpt_min ) #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_shb_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_shb_min ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_sht_max ) CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_sht_min ) #endif CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_vector_spin ) CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_vector_mutex ) CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_deque_spin ) CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_deque_mutex ) } // namespace <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" #include "kernel/mem.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct OptMemPass : public Pass { OptMemPass() : Pass("opt_mem", "optimize memories") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" opt_mem [options] [selection]\n"); log("\n"); log("This pass performs various optimizations on memories in the design.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { log_header(design, "Executing OPT_MEM pass (optimize memories).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-nomux") { // mode_nomux = true; // continue; // } break; } extra_args(args, argidx, design); int total_count = 0; for (auto module : design->selected_modules()) { for (auto &mem : Mem::get_selected_memories(module)) { bool changed = false; for (auto &port : mem.wr_ports) { if (port.en.is_fully_zero()) { port.removed = true; changed = true; total_count++; } } if (changed) { mem.emit(); } if (mem.wr_ports.empty() && mem.inits.empty()) { mem.remove(); total_count++; } } } if (total_count) design->scratchpad_set_bool("opt.did_something", true); log("Performed a total of %d transformations.\n", total_count); } } OptMemPass; PRIVATE_NAMESPACE_END <commit_msg>opt_mem: Add reset/init value support.<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" #include "kernel/mem.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct OptMemPass : public Pass { OptMemPass() : Pass("opt_mem", "optimize memories") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" opt_mem [options] [selection]\n"); log("\n"); log("This pass performs various optimizations on memories in the design.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { log_header(design, "Executing OPT_MEM pass (optimize memories).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-nomux") { // mode_nomux = true; // continue; // } break; } extra_args(args, argidx, design); int total_count = 0; for (auto module : design->selected_modules()) { SigMap sigmap(module); FfInitVals initvals(&sigmap, module); for (auto &mem : Mem::get_selected_memories(module)) { bool changed = false; for (auto &port : mem.wr_ports) { if (port.en.is_fully_zero()) { port.removed = true; changed = true; total_count++; } } if (changed) { mem.emit(); } if (mem.wr_ports.empty() && mem.inits.empty()) { // The whole memory array will contain // only State::Sx, but the embedded read // registers could have reset or init values. // They will probably be optimized away by // opt_dff later. for (int i = 0; i < GetSize(mem.rd_ports); i++) { mem.extract_rdff(i, &initvals); auto &port = mem.rd_ports[i]; module->connect(port.data, Const(State::Sx, GetSize(port.data))); } mem.remove(); total_count++; } } } if (total_count) design->scratchpad_set_bool("opt.did_something", true); log("Performed a total of %d transformations.\n", total_count); } } OptMemPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>#include "graphics/sprite/animation.h" #include "graphics/sprite/animation_player.h" #include "graphics/sprite/sprite.h" #include <gsl/gsl_assert> #include "resources/resources.h" using namespace Halley; AnimationPlayer::AnimationPlayer(std::shared_ptr<const Animation> animation, const String& sequence, const String& direction) { setAnimation(animation, sequence, direction); } AnimationPlayer& AnimationPlayer::playOnce(const String& sequence, const std::optional<String>& nextLoopingSequence) { updateIfNeeded(); curSeq = nullptr; setSequence(sequence); seqLooping = false; nextSequence = nextLoopingSequence; return *this; } AnimationPlayer& AnimationPlayer::setAnimation(std::shared_ptr<const Animation> v, const String& sequence, const String& direction) { if (animation != v) { animation = v; if (animation) { observer.startObserving(*animation); } else { observer.stopObserving(); } curDir = nullptr; curSeq = nullptr; dirId = -1; } updateIfNeeded(); if (animation) { setSequence(sequence); setDirection(direction); } return *this; } AnimationPlayer& AnimationPlayer::setSequence(const String& sequence) { curSeqName = sequence; nextSequence = {}; updateIfNeeded(); if (animation && (!curSeq || curSeq->getName() != sequence)) { curSeqTime = 0; curFrameTime = 0; curFrame = 0; curFrameLen = 0; curLoopCount = 0; curSeq = &animation->getSequence(sequence); seqLen = curSeq->numFrames(); seqLooping = curSeq->isLooping(); seqNoFlip = curSeq->isNoFlip(); dirty = true; onSequenceStarted(); } return *this; } AnimationPlayer& AnimationPlayer::setDirection(int direction) { updateIfNeeded(); if (animation && dirId != direction) { auto newDir = &animation->getDirection(direction); if (curDir != newDir) { curDir = newDir; dirFlip = curDir->shouldFlip(); dirId = curDir->getId(); dirty = true; } } return *this; } AnimationPlayer& AnimationPlayer::setDirection(const String& direction) { curDirName = direction; updateIfNeeded(); if (animation && (!curDir || curDir->getName() != direction)) { auto newDir = &animation->getDirection(direction); if (curDir != newDir) { curDir = newDir; dirFlip = curDir->shouldFlip(); dirId = curDir->getId(); dirty = true; } } return *this; } bool AnimationPlayer::trySetSequence(const String& sequence) { updateIfNeeded(); if (animation && animation->hasSequence(sequence)) { setSequence(sequence); return true; } return false; } AnimationPlayer& AnimationPlayer::setApplyPivot(bool apply) { applyPivot = apply; return *this; } bool AnimationPlayer::isApplyingPivot() const { return applyPivot; } void AnimationPlayer::update(Time time) { updateIfNeeded(); if (!animation) { return; } if (dirty) { resolveSprite(); dirty = false; } const int prevFrame = curFrame; curSeqTime += time * playbackSpeed; curFrameTime += time * playbackSpeed; // Next frame time! if (curFrameTime >= curFrameLen) { for (int i = 0; i < 5 && curFrameTime >= curFrameLen; ++i) { curFrame++; curFrameTime -= curFrameLen; if (curFrame >= int(seqLen)) { if (seqLooping) { curFrame = 0; curSeqTime = curFrameTime; curLoopCount++; } else { curFrame = int(seqLen - 1); onSequenceDone(); } } } } if (curFrame != prevFrame) { resolveSprite(); } } void AnimationPlayer::updateSprite(Sprite& sprite) const { if (animation && hasUpdate) { if (materialOverride) { sprite.setMaterial(materialOverride, true); } else { sprite.setMaterial(animation->getMaterial(), true); } sprite.setSprite(*spriteData, false); if (applyPivot && spriteData->pivot.isValid()) { auto sz = sprite.getSize(); if (std::abs(sz.x) < 0.00001f) { sz.x = 1; } if (std::abs(sz.y) < 0.00001f) { sz.y = 1; } sprite.setPivot(spriteData->pivot + offsetPivot / sz); } sprite.setFlip(dirFlip && !seqNoFlip); if (visibleOverride) { sprite.setVisible(visibleOverride.value()); } hasUpdate = false; } } AnimationPlayer& AnimationPlayer::setMaterialOverride(std::shared_ptr<Material> material) { materialOverride = std::move(material); return *this; } std::shared_ptr<Material> AnimationPlayer::getMaterialOverride() const { return materialOverride; } std::shared_ptr<const Material> AnimationPlayer::getMaterial() const { return animation->getMaterial(); } bool AnimationPlayer::isPlaying() const { return playing; } String AnimationPlayer::getCurrentSequenceName() const { return curSeq ? curSeq->getName() : ""; } Time AnimationPlayer::getCurrentSequenceTime() const { return curSeqTime; } int AnimationPlayer::getCurrentSequenceFrame() const { return curFrame; } int AnimationPlayer::getCurrentSequenceLoopCount() const { return curLoopCount; } String AnimationPlayer::getCurrentDirectionName() const { return curDir ? curDir->getName() : "default"; } AnimationPlayer& AnimationPlayer::setPlaybackSpeed(float value) { playbackSpeed = value; return *this; } float AnimationPlayer::getPlaybackSpeed() const { return playbackSpeed; } const Animation& AnimationPlayer::getAnimation() const { return *animation; } std::shared_ptr<const Animation> AnimationPlayer::getAnimationPtr() const { return animation; } bool AnimationPlayer::hasAnimation() const { return static_cast<bool>(animation); } AnimationPlayer& AnimationPlayer::setOffsetPivot(Vector2f offset) { offsetPivot = offset; hasUpdate = true; return *this; } void AnimationPlayer::syncWith(const AnimationPlayer& masterAnimator, bool hideIfNotSynchronized) { setSequence(masterAnimator.getCurrentSequenceName()); setDirection(masterAnimator.getCurrentDirectionName()); visibleOverride = !hideIfNotSynchronized || getCurrentSequenceName() == masterAnimator.getCurrentSequenceName(); curFrame = clamp(masterAnimator.curFrame, 0, static_cast<int>(curSeq->numFrames()) - 1); curFrameTime = masterAnimator.curFrameTime; resolveSprite(); } void AnimationPlayer::stepFrames(int amount) { if (amount != 0) { curFrame = modulo(curFrame + amount, static_cast<int>(seqLen)); curFrameTime = 0; resolveSprite(); } } void AnimationPlayer::resolveSprite() { updateIfNeeded(); const auto& frame = curSeq->getFrame(curFrame); curFrameLen = std::max(1, frame.getDuration()) * 0.001; // 1ms minimum spriteData = &frame.getSprite(dirId); hasUpdate = true; } void AnimationPlayer::onSequenceStarted() { playing = true; } void AnimationPlayer::onSequenceDone() { if (nextSequence) { setSequence(nextSequence.value()); } else { playing = false; } } void AnimationPlayer::updateIfNeeded() { if (observer.needsUpdate()) { observer.update(); dirId = -1; curDir = nullptr; curSeq = nullptr; setSequence(curSeqName); setDirection(curDirName); } } ConfigNode ConfigNodeSerializer<AnimationPlayer>::serialize(const AnimationPlayer& player, ConfigNodeSerializationContext& context) { ConfigNode result = ConfigNode::MapType(); result["animation"] = player.hasAnimation() ? player.getAnimation().getAssetId() : ""; result["sequence"] = player.getCurrentSequenceName(); result["direction"] = player.getCurrentDirectionName(); result["applyPivot"] = player.isApplyingPivot(); result["playbackSpeed"] = player.getPlaybackSpeed(); return result; } AnimationPlayer ConfigNodeSerializer<AnimationPlayer>::deserialize(ConfigNodeSerializationContext& context, const ConfigNode& node) { auto animName = node["animation"].asString(""); auto anim = animName.isEmpty() ? std::shared_ptr<Animation>() : context.resources->get<Animation>(animName); auto player = AnimationPlayer(anim, node["sequence"].asString("default"), node["direction"].asString("default")); player.setApplyPivot(node["applyPivot"].asBool(true)); player.setPlaybackSpeed(node["playbackSpeed"].asFloat(1.0f)); return player; } <commit_msg>Fix issue with playing next animation in sequence.<commit_after>#include "graphics/sprite/animation.h" #include "graphics/sprite/animation_player.h" #include "graphics/sprite/sprite.h" #include <gsl/gsl_assert> #include "resources/resources.h" using namespace Halley; AnimationPlayer::AnimationPlayer(std::shared_ptr<const Animation> animation, const String& sequence, const String& direction) { setAnimation(animation, sequence, direction); } AnimationPlayer& AnimationPlayer::playOnce(const String& sequence, const std::optional<String>& nextLoopingSequence) { updateIfNeeded(); curSeq = nullptr; setSequence(sequence); seqLooping = false; nextSequence = nextLoopingSequence; return *this; } AnimationPlayer& AnimationPlayer::setAnimation(std::shared_ptr<const Animation> v, const String& sequence, const String& direction) { if (animation != v) { animation = v; if (animation) { observer.startObserving(*animation); } else { observer.stopObserving(); } curDir = nullptr; curSeq = nullptr; dirId = -1; } updateIfNeeded(); if (animation) { setSequence(sequence); setDirection(direction); } return *this; } AnimationPlayer& AnimationPlayer::setSequence(const String& _sequence) { curSeqName = _sequence; // DO NOT use _sequence after this, it can be a reference to nextSequence, which is changed on the next line nextSequence = {}; updateIfNeeded(); if (animation && (!curSeq || curSeq->getName() != curSeqName)) { curSeqTime = 0; curFrameTime = 0; curFrame = 0; curFrameLen = 0; curLoopCount = 0; curSeq = &animation->getSequence(curSeqName); seqLen = curSeq->numFrames(); seqLooping = curSeq->isLooping(); seqNoFlip = curSeq->isNoFlip(); dirty = true; onSequenceStarted(); } return *this; } AnimationPlayer& AnimationPlayer::setDirection(int direction) { updateIfNeeded(); if (animation && dirId != direction) { auto newDir = &animation->getDirection(direction); if (curDir != newDir) { curDir = newDir; dirFlip = curDir->shouldFlip(); dirId = curDir->getId(); dirty = true; } } return *this; } AnimationPlayer& AnimationPlayer::setDirection(const String& direction) { curDirName = direction; updateIfNeeded(); if (animation && (!curDir || curDir->getName() != direction)) { auto newDir = &animation->getDirection(direction); if (curDir != newDir) { curDir = newDir; dirFlip = curDir->shouldFlip(); dirId = curDir->getId(); dirty = true; } } return *this; } bool AnimationPlayer::trySetSequence(const String& sequence) { updateIfNeeded(); if (animation && animation->hasSequence(sequence)) { setSequence(sequence); return true; } return false; } AnimationPlayer& AnimationPlayer::setApplyPivot(bool apply) { applyPivot = apply; return *this; } bool AnimationPlayer::isApplyingPivot() const { return applyPivot; } void AnimationPlayer::update(Time time) { updateIfNeeded(); if (!animation) { return; } if (dirty) { resolveSprite(); dirty = false; } const int prevFrame = curFrame; curSeqTime += time * playbackSpeed; curFrameTime += time * playbackSpeed; // Next frame time! if (curFrameTime >= curFrameLen) { for (int i = 0; i < 5 && curFrameTime >= curFrameLen; ++i) { curFrame++; curFrameTime -= curFrameLen; if (curFrame >= int(seqLen)) { if (seqLooping) { curFrame = 0; curSeqTime = curFrameTime; curLoopCount++; } else { curFrame = int(seqLen - 1); onSequenceDone(); } } } } if (curFrame != prevFrame) { resolveSprite(); } } void AnimationPlayer::updateSprite(Sprite& sprite) const { if (animation && hasUpdate) { if (materialOverride) { sprite.setMaterial(materialOverride, true); } else { sprite.setMaterial(animation->getMaterial(), true); } sprite.setSprite(*spriteData, false); if (applyPivot && spriteData->pivot.isValid()) { auto sz = sprite.getSize(); if (std::abs(sz.x) < 0.00001f) { sz.x = 1; } if (std::abs(sz.y) < 0.00001f) { sz.y = 1; } sprite.setPivot(spriteData->pivot + offsetPivot / sz); } sprite.setFlip(dirFlip && !seqNoFlip); if (visibleOverride) { sprite.setVisible(visibleOverride.value()); } hasUpdate = false; } } AnimationPlayer& AnimationPlayer::setMaterialOverride(std::shared_ptr<Material> material) { materialOverride = std::move(material); return *this; } std::shared_ptr<Material> AnimationPlayer::getMaterialOverride() const { return materialOverride; } std::shared_ptr<const Material> AnimationPlayer::getMaterial() const { return animation->getMaterial(); } bool AnimationPlayer::isPlaying() const { return playing; } String AnimationPlayer::getCurrentSequenceName() const { return curSeq ? curSeq->getName() : ""; } Time AnimationPlayer::getCurrentSequenceTime() const { return curSeqTime; } int AnimationPlayer::getCurrentSequenceFrame() const { return curFrame; } int AnimationPlayer::getCurrentSequenceLoopCount() const { return curLoopCount; } String AnimationPlayer::getCurrentDirectionName() const { return curDir ? curDir->getName() : "default"; } AnimationPlayer& AnimationPlayer::setPlaybackSpeed(float value) { playbackSpeed = value; return *this; } float AnimationPlayer::getPlaybackSpeed() const { return playbackSpeed; } const Animation& AnimationPlayer::getAnimation() const { return *animation; } std::shared_ptr<const Animation> AnimationPlayer::getAnimationPtr() const { return animation; } bool AnimationPlayer::hasAnimation() const { return static_cast<bool>(animation); } AnimationPlayer& AnimationPlayer::setOffsetPivot(Vector2f offset) { offsetPivot = offset; hasUpdate = true; return *this; } void AnimationPlayer::syncWith(const AnimationPlayer& masterAnimator, bool hideIfNotSynchronized) { setSequence(masterAnimator.getCurrentSequenceName()); setDirection(masterAnimator.getCurrentDirectionName()); visibleOverride = !hideIfNotSynchronized || getCurrentSequenceName() == masterAnimator.getCurrentSequenceName(); curFrame = clamp(masterAnimator.curFrame, 0, static_cast<int>(curSeq->numFrames()) - 1); curFrameTime = masterAnimator.curFrameTime; resolveSprite(); } void AnimationPlayer::stepFrames(int amount) { if (amount != 0) { curFrame = modulo(curFrame + amount, static_cast<int>(seqLen)); curFrameTime = 0; resolveSprite(); } } void AnimationPlayer::resolveSprite() { updateIfNeeded(); const auto& frame = curSeq->getFrame(curFrame); curFrameLen = std::max(1, frame.getDuration()) * 0.001; // 1ms minimum spriteData = &frame.getSprite(dirId); hasUpdate = true; } void AnimationPlayer::onSequenceStarted() { playing = true; } void AnimationPlayer::onSequenceDone() { if (nextSequence) { setSequence(nextSequence.value()); } else { playing = false; } } void AnimationPlayer::updateIfNeeded() { if (observer.needsUpdate()) { observer.update(); dirId = -1; curDir = nullptr; curSeq = nullptr; setSequence(curSeqName); setDirection(curDirName); } } ConfigNode ConfigNodeSerializer<AnimationPlayer>::serialize(const AnimationPlayer& player, ConfigNodeSerializationContext& context) { ConfigNode result = ConfigNode::MapType(); result["animation"] = player.hasAnimation() ? player.getAnimation().getAssetId() : ""; result["sequence"] = player.getCurrentSequenceName(); result["direction"] = player.getCurrentDirectionName(); result["applyPivot"] = player.isApplyingPivot(); result["playbackSpeed"] = player.getPlaybackSpeed(); return result; } AnimationPlayer ConfigNodeSerializer<AnimationPlayer>::deserialize(ConfigNodeSerializationContext& context, const ConfigNode& node) { auto animName = node["animation"].asString(""); auto anim = animName.isEmpty() ? std::shared_ptr<Animation>() : context.resources->get<Animation>(animName); auto player = AnimationPlayer(anim, node["sequence"].asString("default"), node["direction"].asString("default")); player.setApplyPivot(node["applyPivot"].asBool(true)); player.setPlaybackSpeed(node["playbackSpeed"].asFloat(1.0f)); return player; } <|endoftext|>
<commit_before><commit_msg>Update CfgFunctions.hpp<commit_after><|endoftext|>
<commit_before>//===-- llvm/CodeGen/PseudoSourceValue.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PseudoSourceValue class. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/PseudoSourceValue.h" #include "llvm/DerivedTypes.h" #include "llvm/LLVMContext.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/raw_ostream.h" #include <map> using namespace llvm; static ManagedStatic<PseudoSourceValue[4]> PSVs; const PseudoSourceValue *PseudoSourceValue::getStack() { return &(*PSVs)[0]; } const PseudoSourceValue *PseudoSourceValue::getGOT() { return &(*PSVs)[1]; } const PseudoSourceValue *PseudoSourceValue::getJumpTable() { return &(*PSVs)[2]; } const PseudoSourceValue *PseudoSourceValue::getConstantPool() { return &(*PSVs)[3]; } static const char *const PSVNames[] = { "Stack", "GOT", "JumpTable", "ConstantPool" }; // FIXME: THIS IS A HACK!!!! // Eventually these should be uniqued on LLVMContext rather than in a managed // static. For now, we can safely use the global context for the time being to // squeak by. PseudoSourceValue::PseudoSourceValue(enum ValueTy Subclass) : Value(Type::getInt8PtrTy(getGlobalContext()), Subclass) {} void PseudoSourceValue::printCustom(raw_ostream &O) const { O << PSVNames[this - *PSVs]; } static ManagedStatic<std::map<int, const PseudoSourceValue *> > FSValues; const PseudoSourceValue *PseudoSourceValue::getFixedStack(int FI) { const PseudoSourceValue *&V = (*FSValues)[FI]; if (!V) V = new FixedStackPseudoSourceValue(FI); return V; } bool PseudoSourceValue::isConstant(const MachineFrameInfo *) const { if (this == getStack()) return false; if (this == getGOT() || this == getConstantPool() || this == getJumpTable()) return true; llvm_unreachable("Unknown PseudoSourceValue!"); return false; } bool PseudoSourceValue::isAliased(const MachineFrameInfo *MFI) const { if (this == getStack() || this == getGOT() || this == getConstantPool() || this == getJumpTable()) return false; llvm_unreachable("Unknown PseudoSourceValue!"); return true; } bool PseudoSourceValue::mayAlias(const MachineFrameInfo *MFI) const { if (this == getGOT() || this == getConstantPool() || this == getJumpTable()) return false; return true; } bool FixedStackPseudoSourceValue::isConstant(const MachineFrameInfo *MFI) const{ return MFI && MFI->isImmutableObjectIndex(FI); } bool FixedStackPseudoSourceValue::isAliased(const MachineFrameInfo *MFI) const { // Negative frame indices are used for special things that don't // appear in LLVM IR. Non-negative indices may be used for things // like static allocas. if (!MFI) return FI >= 0; // Spill slots should not alias others. return !MFI->isFixedObjectIndex(FI) && !MFI->isSpillSlotObjectIndex(FI); } bool FixedStackPseudoSourceValue::mayAlias(const MachineFrameInfo *MFI) const { if (!MFI) return true; // Spill slots will not alias any LLVM IR value. return !MFI->isSpillSlotObjectIndex(FI); } void FixedStackPseudoSourceValue::printCustom(raw_ostream &OS) const { OS << "FixedStack" << FI; } <commit_msg>Fix memcheck-found leaks: one false positive from using new[], and one true positive where pointers would be leaked on llvm_shutdown.<commit_after>//===-- llvm/CodeGen/PseudoSourceValue.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PseudoSourceValue class. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/PseudoSourceValue.h" #include "llvm/DerivedTypes.h" #include "llvm/LLVMContext.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Mutex.h" #include <map> using namespace llvm; namespace { struct PSVGlobalsTy { // PseudoSourceValues are immutable so don't need locking. const PseudoSourceValue PSVs[4]; sys::Mutex Lock; // Guards FSValues, but not the values inside it. std::map<int, const PseudoSourceValue *> FSValues; PSVGlobalsTy() : PSVs() {} ~PSVGlobalsTy() { for (std::map<int, const PseudoSourceValue *>::iterator I = FSValues.begin(), E = FSValues.end(); I != E; ++I) { delete I->second; } } }; static ManagedStatic<PSVGlobalsTy> PSVGlobals; } // anonymous namespace const PseudoSourceValue *PseudoSourceValue::getStack() { return &PSVGlobals->PSVs[0]; } const PseudoSourceValue *PseudoSourceValue::getGOT() { return &PSVGlobals->PSVs[1]; } const PseudoSourceValue *PseudoSourceValue::getJumpTable() { return &PSVGlobals->PSVs[2]; } const PseudoSourceValue *PseudoSourceValue::getConstantPool() { return &PSVGlobals->PSVs[3]; } static const char *const PSVNames[] = { "Stack", "GOT", "JumpTable", "ConstantPool" }; // FIXME: THIS IS A HACK!!!! // Eventually these should be uniqued on LLVMContext rather than in a managed // static. For now, we can safely use the global context for the time being to // squeak by. PseudoSourceValue::PseudoSourceValue(enum ValueTy Subclass) : Value(Type::getInt8PtrTy(getGlobalContext()), Subclass) {} void PseudoSourceValue::printCustom(raw_ostream &O) const { O << PSVNames[this - PSVGlobals->PSVs]; } const PseudoSourceValue *PseudoSourceValue::getFixedStack(int FI) { PSVGlobalsTy &PG = *PSVGlobals; sys::ScopedLock locked(PG.Lock); const PseudoSourceValue *&V = PG.FSValues[FI]; if (!V) V = new FixedStackPseudoSourceValue(FI); return V; } bool PseudoSourceValue::isConstant(const MachineFrameInfo *) const { if (this == getStack()) return false; if (this == getGOT() || this == getConstantPool() || this == getJumpTable()) return true; llvm_unreachable("Unknown PseudoSourceValue!"); return false; } bool PseudoSourceValue::isAliased(const MachineFrameInfo *MFI) const { if (this == getStack() || this == getGOT() || this == getConstantPool() || this == getJumpTable()) return false; llvm_unreachable("Unknown PseudoSourceValue!"); return true; } bool PseudoSourceValue::mayAlias(const MachineFrameInfo *MFI) const { if (this == getGOT() || this == getConstantPool() || this == getJumpTable()) return false; return true; } bool FixedStackPseudoSourceValue::isConstant(const MachineFrameInfo *MFI) const{ return MFI && MFI->isImmutableObjectIndex(FI); } bool FixedStackPseudoSourceValue::isAliased(const MachineFrameInfo *MFI) const { // Negative frame indices are used for special things that don't // appear in LLVM IR. Non-negative indices may be used for things // like static allocas. if (!MFI) return FI >= 0; // Spill slots should not alias others. return !MFI->isFixedObjectIndex(FI) && !MFI->isSpillSlotObjectIndex(FI); } bool FixedStackPseudoSourceValue::mayAlias(const MachineFrameInfo *MFI) const { if (!MFI) return true; // Spill slots will not alias any LLVM IR value. return !MFI->isSpillSlotObjectIndex(FI); } void FixedStackPseudoSourceValue::printCustom(raw_ostream &OS) const { OS << "FixedStack" << FI; } <|endoftext|>
<commit_before>// Copyright © 2015 Mikko Ronkainen <[email protected]> // License: MIT, see the LICENSE file. #include <cassert> #include <stdexcept> #include <GL/gl3w.h> #include "Rendering/Framebuffer.h" #include "App.h" #include "Utils/Log.h" #include "Utils/Settings.h" #include "Utils/GLHelper.h" using namespace Raycer; Framebuffer::Framebuffer() { } void Framebuffer::initialize() { Settings& settings = App::getSettings(); App::getLog().logInfo("Initializing framebuffer"); glGenTextures(1, &imageTextureId); glGenTextures(1, &framebufferTextureId); GLHelper::checkError("Could not create OpenGL textures"); glBindTexture(GL_TEXTURE_2D, imageTextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, framebufferTextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); GLHelper::checkError("Could not set OpenGL texture parameters"); resampleProgramId = GLHelper::buildProgram(settings.framebuffer.resampleVertexShader, settings.framebuffer.resampleFragmentShader); filterProgramId = GLHelper::buildProgram(settings.framebuffer.filterVertexShader, settings.framebuffer.filterFragmentShader); resampleTextureUniformId = glGetUniformLocation(resampleProgramId, "texture0"); resampleTextureWidthUniformId = glGetUniformLocation(resampleProgramId, "textureWidth"); resampleTextureHeightUniformId = glGetUniformLocation(resampleProgramId, "textureHeight"); resampleTexelWidthUniformId = glGetUniformLocation(resampleProgramId, "texelWidth"); resampleTexelHeightUniformId = glGetUniformLocation(resampleProgramId, "texelHeight"); filterTextureUniformId = glGetUniformLocation(filterProgramId, "texture0"); filterTextureWidthUniformId = glGetUniformLocation(filterProgramId, "textureWidth"); filterTextureHeightUniformId = glGetUniformLocation(filterProgramId, "textureHeight"); filterTexelWidthUniformId = glGetUniformLocation(filterProgramId, "texelWidth"); filterTexelHeightUniformId = glGetUniformLocation(filterProgramId, "texelHeight"); GLHelper::checkError("Could not get GLSL uniforms"); const GLfloat vertexData[] = { -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, }; glGenBuffers(1, &vertexBufferId); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferId); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glGenVertexArrays(1, &vaoId); glBindVertexArray(vaoId); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat))); glBindVertexArray(0); GLHelper::checkError("Could not set OpenGL buffer parameters"); setWindowSize(settings.window.width, settings.window.height); glGenFramebuffers(1, &framebufferId); glBindFramebuffer(GL_FRAMEBUFFER, framebufferId); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, framebufferTextureId, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw std::runtime_error("Could not initialize OpenGL framebuffer"); glBindFramebuffer(GL_FRAMEBUFFER, 0); GLHelper::checkError("Could not set OpenGL framebuffer parameters"); } void Framebuffer::resize(int width, int height) { assert(width > 0 && height > 0); App::getLog().logInfo("Resizing framebuffer to %sx%s", width, height); image.resize(width, height); floatPixelData.resize(width * height * sizeof(float) * 4); // reserve the texture memory on the device glBindTexture(GL_TEXTURE_2D, imageTextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)width, (GLsizei)height, 0, GL_RGBA, GL_FLOAT, 0); glBindTexture(GL_TEXTURE_2D, 0); GLHelper::checkError("Could not reserve OpenGL texture memory"); clear(); } void Framebuffer::setWindowSize(int width, int height) { assert(width > 0 && height > 0); windowWidth = width; windowHeight = height; glBindTexture(GL_TEXTURE_2D, framebufferTextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)windowWidth, (GLsizei)windowHeight, 0, GL_RGBA, GL_FLOAT, 0); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); } void Framebuffer::clear() { image.clear(); } void Framebuffer::clear(const Color& color) { image.clear(color); } void Framebuffer::render() { Settings& settings = App::getSettings(); int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); /* Resampling pass */ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, imageTextureId); glUseProgram(resampleProgramId); glUniform1i(resampleTextureUniformId, 0); glUniform1f(resampleTextureWidthUniformId, (float)imageWidth); glUniform1f(resampleTextureHeightUniformId, (float)imageHeight); glUniform1f(resampleTexelWidthUniformId, 1.0f / (float)imageWidth); glUniform1f(resampleTexelHeightUniformId, 1.0f / (float)imageHeight); if (!settings.openCL.enabled) { std::vector<Color>& imagePixelData = image.getPixelData(); // convert image data from Color to float array for (int i = 0; i < (int)imagePixelData.size(); ++i) { int pixelIndex = i * 4; floatPixelData[pixelIndex] = (float)imagePixelData[i].r; floatPixelData[pixelIndex + 1] = (float)imagePixelData[i].g; floatPixelData[pixelIndex + 2] = (float)imagePixelData[i].b; floatPixelData[pixelIndex + 3] = (float)imagePixelData[i].a; } glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)imageWidth, (GLsizei)imageHeight, GL_RGBA, GL_FLOAT, &floatPixelData[0]); GLHelper::checkError("Could not upload OpenGL texture data"); } glBindFramebuffer(GL_FRAMEBUFFER, framebufferId); glBindVertexArray(vaoId); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); /* Filtering pass */ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, framebufferTextureId); glUseProgram(filterProgramId); glUniform1i(filterTextureUniformId, 0); glUniform1f(filterTextureWidthUniformId, (float)windowWidth); glUniform1f(filterTextureHeightUniformId, (float)windowHeight); glUniform1f(filterTexelWidthUniformId, 1.0f / (float)windowWidth); glUniform1f(filterTexelHeightUniformId, 1.0f / (float)windowHeight); glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindVertexArray(vaoId); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); GLHelper::checkError("Could not render the framebuffer"); } void Framebuffer::enableSmoothing(bool state) { glBindTexture(GL_TEXTURE_2D, imageTextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, state ? GL_LINEAR : GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, state ? GL_LINEAR : GL_NEAREST); glBindTexture(GL_TEXTURE_2D, framebufferTextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, state ? GL_LINEAR : GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, state ? GL_LINEAR : GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); GLHelper::checkError("Could not set OpenGL texture parameters"); } int Framebuffer::getWidth() const { return image.getWidth(); } int Framebuffer::getHeight() const { return image.getHeight(); } Image& Framebuffer::getImage() { return image; } GLuint Framebuffer::getImageTextureId() const { return imageTextureId; } <commit_msg>Fixed framebuffer texture format<commit_after>// Copyright © 2015 Mikko Ronkainen <[email protected]> // License: MIT, see the LICENSE file. #include <cassert> #include <stdexcept> #include <GL/gl3w.h> #include "Rendering/Framebuffer.h" #include "App.h" #include "Utils/Log.h" #include "Utils/Settings.h" #include "Utils/GLHelper.h" using namespace Raycer; Framebuffer::Framebuffer() { } void Framebuffer::initialize() { Settings& settings = App::getSettings(); App::getLog().logInfo("Initializing framebuffer"); glGenTextures(1, &imageTextureId); glGenTextures(1, &framebufferTextureId); GLHelper::checkError("Could not create OpenGL textures"); glBindTexture(GL_TEXTURE_2D, imageTextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, framebufferTextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); GLHelper::checkError("Could not set OpenGL texture parameters"); resampleProgramId = GLHelper::buildProgram(settings.framebuffer.resampleVertexShader, settings.framebuffer.resampleFragmentShader); filterProgramId = GLHelper::buildProgram(settings.framebuffer.filterVertexShader, settings.framebuffer.filterFragmentShader); resampleTextureUniformId = glGetUniformLocation(resampleProgramId, "texture0"); resampleTextureWidthUniformId = glGetUniformLocation(resampleProgramId, "textureWidth"); resampleTextureHeightUniformId = glGetUniformLocation(resampleProgramId, "textureHeight"); resampleTexelWidthUniformId = glGetUniformLocation(resampleProgramId, "texelWidth"); resampleTexelHeightUniformId = glGetUniformLocation(resampleProgramId, "texelHeight"); filterTextureUniformId = glGetUniformLocation(filterProgramId, "texture0"); filterTextureWidthUniformId = glGetUniformLocation(filterProgramId, "textureWidth"); filterTextureHeightUniformId = glGetUniformLocation(filterProgramId, "textureHeight"); filterTexelWidthUniformId = glGetUniformLocation(filterProgramId, "texelWidth"); filterTexelHeightUniformId = glGetUniformLocation(filterProgramId, "texelHeight"); GLHelper::checkError("Could not get GLSL uniforms"); const GLfloat vertexData[] = { -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, }; glGenBuffers(1, &vertexBufferId); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferId); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glGenVertexArrays(1, &vaoId); glBindVertexArray(vaoId); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat))); glBindVertexArray(0); GLHelper::checkError("Could not set OpenGL buffer parameters"); setWindowSize(settings.window.width, settings.window.height); glGenFramebuffers(1, &framebufferId); glBindFramebuffer(GL_FRAMEBUFFER, framebufferId); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, framebufferTextureId, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw std::runtime_error("Could not initialize OpenGL framebuffer"); glBindFramebuffer(GL_FRAMEBUFFER, 0); GLHelper::checkError("Could not set OpenGL framebuffer parameters"); } void Framebuffer::resize(int width, int height) { assert(width > 0 && height > 0); App::getLog().logInfo("Resizing framebuffer to %sx%s", width, height); image.resize(width, height); floatPixelData.resize(width * height * sizeof(float) * 4); // reserve the texture memory on the device glBindTexture(GL_TEXTURE_2D, imageTextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, (GLsizei)width, (GLsizei)height, 0, GL_RGBA, GL_FLOAT, 0); glBindTexture(GL_TEXTURE_2D, 0); GLHelper::checkError("Could not reserve OpenGL texture memory"); clear(); } void Framebuffer::setWindowSize(int width, int height) { assert(width > 0 && height > 0); windowWidth = width; windowHeight = height; glBindTexture(GL_TEXTURE_2D, framebufferTextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, (GLsizei)windowWidth, (GLsizei)windowHeight, 0, GL_RGBA, GL_FLOAT, 0); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); } void Framebuffer::clear() { image.clear(); } void Framebuffer::clear(const Color& color) { image.clear(color); } void Framebuffer::render() { Settings& settings = App::getSettings(); int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); /* Resampling pass */ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, imageTextureId); glUseProgram(resampleProgramId); glUniform1i(resampleTextureUniformId, 0); glUniform1f(resampleTextureWidthUniformId, (float)imageWidth); glUniform1f(resampleTextureHeightUniformId, (float)imageHeight); glUniform1f(resampleTexelWidthUniformId, 1.0f / (float)imageWidth); glUniform1f(resampleTexelHeightUniformId, 1.0f / (float)imageHeight); if (!settings.openCL.enabled) { std::vector<Color>& imagePixelData = image.getPixelData(); // convert image data from Color to float array for (int i = 0; i < (int)imagePixelData.size(); ++i) { int pixelIndex = i * 4; floatPixelData[pixelIndex] = (float)imagePixelData[i].r; floatPixelData[pixelIndex + 1] = (float)imagePixelData[i].g; floatPixelData[pixelIndex + 2] = (float)imagePixelData[i].b; floatPixelData[pixelIndex + 3] = (float)imagePixelData[i].a; } glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)imageWidth, (GLsizei)imageHeight, GL_RGBA, GL_FLOAT, &floatPixelData[0]); GLHelper::checkError("Could not upload OpenGL texture data"); } glBindFramebuffer(GL_FRAMEBUFFER, framebufferId); glBindVertexArray(vaoId); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); /* Filtering pass */ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, framebufferTextureId); glUseProgram(filterProgramId); glUniform1i(filterTextureUniformId, 0); glUniform1f(filterTextureWidthUniformId, (float)windowWidth); glUniform1f(filterTextureHeightUniformId, (float)windowHeight); glUniform1f(filterTexelWidthUniformId, 1.0f / (float)windowWidth); glUniform1f(filterTexelHeightUniformId, 1.0f / (float)windowHeight); glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindVertexArray(vaoId); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); GLHelper::checkError("Could not render the framebuffer"); } void Framebuffer::enableSmoothing(bool state) { glBindTexture(GL_TEXTURE_2D, imageTextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, state ? GL_LINEAR : GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, state ? GL_LINEAR : GL_NEAREST); glBindTexture(GL_TEXTURE_2D, framebufferTextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, state ? GL_LINEAR : GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, state ? GL_LINEAR : GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); GLHelper::checkError("Could not set OpenGL texture parameters"); } int Framebuffer::getWidth() const { return image.getWidth(); } int Framebuffer::getHeight() const { return image.getHeight(); } Image& Framebuffer::getImage() { return image; } GLuint Framebuffer::getImageTextureId() const { return imageTextureId; } <|endoftext|>
<commit_before>/** \file json_grep.cc * \brief A simple tool for performing single lookups in a JSON file. * \author Dr. Johannes Ruscheinski * * \copyright (C) 2017, Library of the University of Tübingen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <cstdlib> #include "FileUtil.h" #include "JSON.h" #include "util.h" void Usage() { std::cerr << "Usage: " << ::progname << " [--print] json_input_file [lookup_path [default]]\n"; std::exit(EXIT_FAILURE); } int main(int /*argc*/, char *argv[]) { ::progname = *argv; ++argv; if (*argv == nullptr) Usage(); bool print(false); if (std::strcmp(*argv, "--print") == 0) { print = true; ++argv; } if (*argv == nullptr) Usage(); const std::string json_input_filename(*argv); ++argv; std::string lookup_path; if (*argv != nullptr) { lookup_path = *argv; ++argv; } std::string default_value; if (*argv != nullptr) { default_value = *argv; ++argv; } try { std::string json_document; if (not FileUtil::ReadString(json_input_filename, &json_document)) logger->error("could not read \"" + json_input_filename + "\"!"); JSON::Parser parser(json_document); std::shared_ptr<JSON::JSONNode> tree; if (not parser.parse(&tree)) { std::cerr << ::progname << ": " << parser.getErrorMessage() << '\n'; return EXIT_FAILURE; } if (print) std::cout << tree->toString() << '\n'; if (not lookup_path.empty()) std::cerr << lookup_path << ": " << (default_value.empty() ? JSON::LookupString(lookup_path, tree) : JSON::LookupString(lookup_path, tree), default_value) << '\n'; } catch (const std::exception &x) { logger->error("caught exception: " + std::string(x.what())); } } <commit_msg>Update json_grep.cc<commit_after>/** \file json_grep.cc * \brief A simple tool for performing single lookups in a JSON file. * \author Dr. Johannes Ruscheinski * * \copyright (C) 2017,2018 Library of the University of Tübingen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstdlib> #include "FileUtil.h" #include "JSON.h" #include "util.h" void Usage() { std::cerr << "Usage: " << ::progname << " [--print] json_input_file [lookup_path [default]]\n"; std::exit(EXIT_FAILURE); } int main(int /*argc*/, char *argv[]) { ::progname = *argv; ++argv; if (*argv == nullptr) Usage(); bool print(false); if (std::strcmp(*argv, "--print") == 0) { print = true; ++argv; } if (*argv == nullptr) Usage(); const std::string json_input_filename(*argv); ++argv; std::string lookup_path; if (*argv != nullptr) { lookup_path = *argv; ++argv; } std::string default_value; if (*argv != nullptr) { default_value = *argv; ++argv; } try { std::string json_document; if (not FileUtil::ReadString(json_input_filename, &json_document)) logger->error("could not read \"" + json_input_filename + "\"!"); JSON::Parser parser(json_document); std::shared_ptr<JSON::JSONNode> tree; if (not parser.parse(&tree)) { std::cerr << ::progname << ": " << parser.getErrorMessage() << '\n'; return EXIT_FAILURE; } if (print) std::cout << tree->toString() << '\n'; if (not lookup_path.empty()) std::cerr << lookup_path << ": " << (default_value.empty() ? JSON::LookupString(lookup_path, tree) : JSON::LookupString(lookup_path, tree), default_value) << '\n'; } catch (const std::exception &x) { logger->error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>//===- lib/ReaderWriter/MachO/ObjCPass.cpp -------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // //===----------------------------------------------------------------------===// #include "ArchHandler.h" #include "File.h" #include "MachOPasses.h" #include "lld/Core/DefinedAtom.h" #include "lld/Core/File.h" #include "lld/Core/LLVM.h" #include "lld/Core/Reference.h" #include "lld/Core/Simple.h" #include "lld/ReaderWriter/MachOLinkingContext.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" namespace lld { namespace mach_o { /// /// ObjC Image Info Atom created by the ObjC pass. /// class ObjCImageInfoAtom : public SimpleDefinedAtom { public: ObjCImageInfoAtom(const File &file, MachOLinkingContext::ObjCConstraint objCConstraint, uint32_t swiftVersion) : SimpleDefinedAtom(file) { Data.info.version = 0; switch (objCConstraint) { case MachOLinkingContext::objc_unknown: llvm_unreachable("Shouldn't run the objc pass without a constraint"); case MachOLinkingContext::objc_supports_gc: case MachOLinkingContext::objc_gc_only: llvm_unreachable("GC is not supported"); case MachOLinkingContext::objc_retainReleaseForSimulator: // The retain/release for simulator flag is already the correct // encoded value for the data so just set it here. Data.info.flags = (uint32_t)objCConstraint; break; case MachOLinkingContext::objc_retainRelease: // We don't need to encode this flag, so just leave the flags as 0. Data.info.flags = 0; break; } Data.info.flags |= (swiftVersion << 8); } ~ObjCImageInfoAtom() override = default; ContentType contentType() const override { return DefinedAtom::typeObjCImageInfo; } Alignment alignment() const override { return 4; } uint64_t size() const override { return 8; } ContentPermissions permissions() const override { return DefinedAtom::permR__; } ArrayRef<uint8_t> rawContent() const override { return llvm::makeArrayRef(Data.bytes, size()); } private: struct objc_image_info { uint32_t version; uint32_t flags; }; union { objc_image_info info; uint8_t bytes[8]; } Data; }; class ObjCPass : public Pass { public: ObjCPass(const MachOLinkingContext &context) : _ctx(context), _file(*_ctx.make_file<MachOFile>("<mach-o objc pass>")) { _file.setOrdinal(_ctx.getNextOrdinalAndIncrement()); } llvm::Error perform(SimpleFile &mergedFile) override { // Add the image info. mergedFile.addAtom(*getImageInfo()); return llvm::Error::success(); } private: const DefinedAtom* getImageInfo() { return new (_file.allocator()) ObjCImageInfoAtom(_file, _ctx.objcConstraint(), _ctx.swiftVersion()); } const MachOLinkingContext &_ctx; MachOFile &_file; }; void addObjCPass(PassManager &pm, const MachOLinkingContext &ctx) { pm.add(llvm::make_unique<ObjCPass>(ctx)); } } // end namespace mach_o } // end namespace lld <commit_msg>Fix ObjCPass on big-endian host<commit_after>//===- lib/ReaderWriter/MachO/ObjCPass.cpp -------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // //===----------------------------------------------------------------------===// #include "ArchHandler.h" #include "File.h" #include "MachONormalizedFileBinaryUtils.h" #include "MachOPasses.h" #include "lld/Core/DefinedAtom.h" #include "lld/Core/File.h" #include "lld/Core/LLVM.h" #include "lld/Core/Reference.h" #include "lld/Core/Simple.h" #include "lld/ReaderWriter/MachOLinkingContext.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" namespace lld { namespace mach_o { /// /// ObjC Image Info Atom created by the ObjC pass. /// class ObjCImageInfoAtom : public SimpleDefinedAtom { public: ObjCImageInfoAtom(const File &file, bool isBig, MachOLinkingContext::ObjCConstraint objCConstraint, uint32_t swiftVersion) : SimpleDefinedAtom(file) { Data.info.version = 0; switch (objCConstraint) { case MachOLinkingContext::objc_unknown: llvm_unreachable("Shouldn't run the objc pass without a constraint"); case MachOLinkingContext::objc_supports_gc: case MachOLinkingContext::objc_gc_only: llvm_unreachable("GC is not supported"); case MachOLinkingContext::objc_retainReleaseForSimulator: // The retain/release for simulator flag is already the correct // encoded value for the data so just set it here. Data.info.flags = (uint32_t)objCConstraint; break; case MachOLinkingContext::objc_retainRelease: // We don't need to encode this flag, so just leave the flags as 0. Data.info.flags = 0; break; } Data.info.flags |= (swiftVersion << 8); normalized::write32(Data.bytes + 4, Data.info.flags, isBig); } ~ObjCImageInfoAtom() override = default; ContentType contentType() const override { return DefinedAtom::typeObjCImageInfo; } Alignment alignment() const override { return 4; } uint64_t size() const override { return 8; } ContentPermissions permissions() const override { return DefinedAtom::permR__; } ArrayRef<uint8_t> rawContent() const override { return llvm::makeArrayRef(Data.bytes, size()); } private: struct objc_image_info { uint32_t version; uint32_t flags; }; union { objc_image_info info; uint8_t bytes[8]; } Data; }; class ObjCPass : public Pass { public: ObjCPass(const MachOLinkingContext &context) : _ctx(context), _file(*_ctx.make_file<MachOFile>("<mach-o objc pass>")) { _file.setOrdinal(_ctx.getNextOrdinalAndIncrement()); } llvm::Error perform(SimpleFile &mergedFile) override { // Add the image info. mergedFile.addAtom(*getImageInfo()); return llvm::Error::success(); } private: const DefinedAtom* getImageInfo() { bool IsBig = MachOLinkingContext::isBigEndian(_ctx.arch()); return new (_file.allocator()) ObjCImageInfoAtom(_file, IsBig, _ctx.objcConstraint(), _ctx.swiftVersion()); } const MachOLinkingContext &_ctx; MachOFile &_file; }; void addObjCPass(PassManager &pm, const MachOLinkingContext &ctx) { pm.add(llvm::make_unique<ObjCPass>(ctx)); } } // end namespace mach_o } // end namespace lld <|endoftext|>
<commit_before>//===--- Generics.cpp ---- Utilities for transforming generics ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "generic-specializer" #include "swift/Strings.h" #include "swift/SILOptimizer/Utils/Generics.h" #include "swift/SILOptimizer/Utils/GenericCloner.h" using namespace swift; // Create a new apply based on an old one, but with a different // function being applied. ApplySite swift::replaceWithSpecializedFunction(ApplySite AI, SILFunction *NewF) { SILLocation Loc = AI.getLoc(); ArrayRef<Substitution> Subst; SmallVector<SILValue, 4> Arguments; for (auto &Op : AI.getArgumentOperands()) { Arguments.push_back(Op.get()); } SILBuilderWithScope Builder(AI.getInstruction()); FunctionRefInst *FRI = Builder.createFunctionRef(Loc, NewF); if (auto *TAI = dyn_cast<TryApplyInst>(AI)) return Builder.createTryApply(Loc, FRI, TAI->getSubstCalleeSILType(), {}, Arguments, TAI->getNormalBB(), TAI->getErrorBB()); if (auto *A = dyn_cast<ApplyInst>(AI)) return Builder.createApply(Loc, FRI, Arguments, A->isNonThrowing()); if (auto *PAI = dyn_cast<PartialApplyInst>(AI)) return Builder.createPartialApply(Loc, FRI, PAI->getSubstCalleeSILType(), {}, Arguments, PAI->getType()); llvm_unreachable("unhandled kind of apply"); } /// Try to convert definition into declaration. static bool convertExternalDefinitionIntoDeclaration(SILFunction *F) { // Bail if it is a declaration already. if (!F->isDefinition()) return false; // Bail if there is no external implementation of this function. if (!F->isAvailableExternally()) return false; // Bail if has a shared visibility, as there are no guarantees // that an implementation is available elsewhere. if (hasSharedVisibility(F->getLinkage())) return false; // Make this definition a declaration by removing the body of a function. F->convertToDeclaration(); assert(F->isExternalDeclaration() && "Function should be an external declaration"); DEBUG(llvm::dbgs() << " removed external function " << F->getName() << "\n"); return true; } /// Check of a given name could be a name of a white-listed /// specialization. bool swift::isWhitelistedSpecialization(StringRef SpecName) { // The whitelist of classes and functions from the stdlib, // whose specializations we want to preserve. ArrayRef<StringRef> Whitelist = { "Array", "_ArrayBuffer", "_ContiguousArrayBuffer", "Range", "RangeGenerator", "_allocateUninitializedArray", "UTF8", "UTF16", "String", "_StringBuffer", "_toStringReadOnlyPrintable", }; // TODO: Once there is an efficient API to check if // a given symbol is a specialization of a specific type, // use it instead. Doing demangling just for this check // is just wasteful. auto DemangledNameString = swift::Demangle::demangleSymbolAsString(SpecName); StringRef DemangledName = DemangledNameString; auto pos = DemangledName.find("generic ", 0); if (pos == StringRef::npos) return false; // Create "of Swift" llvm::SmallString<64> OfString; llvm::raw_svector_ostream buffer(OfString); buffer << "of "; buffer << STDLIB_NAME <<'.'; StringRef OfStr = buffer.str(); pos = DemangledName.find(OfStr, pos); if (pos == StringRef::npos) return false; pos += OfStr.size(); for(auto Name: Whitelist) { auto pos1 = DemangledName.find(Name, pos); if (pos1 == pos && !isalpha(DemangledName[pos1+Name.size()])) { return true; } } return false; } /// Cache a specialization. /// For now, it is performed only for specializations in the /// standard library. But in the future, one could think of /// maintaining a cache of optimized specializations. /// /// Mark specializations as public, so that they can be used /// by user applications. These specializations are supposed to be /// used only by -Onone compiled code. They should be never inlined. static bool cacheSpecialization(SILModule &M, SILFunction *F) { // Do not remove functions from the white-list. Keep them around. // Change their linkage to public, so that other applications can refer to it. if (M.getOptions().Optimization >= SILOptions::SILOptMode::Optimize && F->getLinkage() != SILLinkage::Public && F->getModule().getSwiftModule()->getName().str() == SWIFT_ONONE_SUPPORT) { if (F->getLinkage() != SILLinkage::Public && isWhitelistedSpecialization(F->getName())) { DEBUG( auto DemangledNameString = swift::Demangle::demangleSymbolAsString(F->getName()); StringRef DemangledName = DemangledNameString; llvm::dbgs() << "Keep specialization: " << DemangledName << " : " << F->getName() << "\n"); // Make it public, so that others can refer to it. // // NOTE: This function may refer to non-public symbols, which may lead to // problems, if you ever try to inline this function. Therefore, these // specializations should only be used to refer to them, but should never // be inlined! The general rule could be: Never inline specializations // from stdlib! // // NOTE: Making these specializations public at this point breaks // some optimizations. Therefore, just mark the function. // DeadFunctionElimination pass will check if the function is marked // and preserve it if required. F->setKeepAsPublic(true); return true; } } return false; } /// Try to look up an existing specialization in the specialization cache. /// If it is found, it tries to link this specialization. /// /// For now, it performs a lookup only in the standard library. /// But in the future, one could think of maintaining a cache /// of optimized specializations. static SILFunction *lookupExistingSpecialization(SILModule &M, StringRef FunctionName) { // Try to link existing specialization only in -Onone mode. // All other compilation modes perform specialization themselves. // TODO: Cache optimized specializations and perform lookup here? // TODO: Only check that this function exists, but don't read // its body. It can save some compile-time. if (isWhitelistedSpecialization(FunctionName) && M.linkFunction(FunctionName, SILOptions::LinkingMode::LinkNormal)) return M.lookUpFunction(FunctionName); return nullptr; } SILFunction *swift::getExistingSpecialization(SILModule &M, StringRef FunctionName) { auto *Specialization = lookupExistingSpecialization(M, FunctionName); if (!Specialization) return nullptr; if (hasPublicVisibility(Specialization->getLinkage())) { // The bodies of existing specializations cannot be used, // as they may refer to non-public symbols. if (Specialization->isDefinition()) Specialization->convertToDeclaration(); Specialization->setLinkage(SILLinkage::PublicExternal); // Ignore body for -Onone and -Odebug. assert((Specialization->isExternalDeclaration() || convertExternalDefinitionIntoDeclaration(Specialization)) && "Could not remove body of the found specialization"); if (!Specialization->isExternalDeclaration() && !convertExternalDefinitionIntoDeclaration(Specialization)) { DEBUG( llvm::dbgs() << "Could not remove body of specialization: " << FunctionName << '\n'); } DEBUG( llvm::dbgs() << "Found existing specialization for: " << FunctionName << '\n'; llvm::dbgs() << swift::Demangle::demangleSymbolAsString( Specialization->getName()) << "\n\n"); } else { // Forget about this function. DEBUG(llvm::dbgs() << "Cannot reuse the specialization: " << swift::Demangle::demangleSymbolAsString(Specialization->getName()) <<"\n"); return nullptr; } return Specialization; } ApplySite swift::trySpecializeApplyOfGeneric(ApplySite Apply, SILFunction *&NewFunction, CloneCollector &Collector) { NewFunction = nullptr; assert(Apply.hasSubstitutions() && "Expected an apply with substitutions!"); auto *F = cast<FunctionRefInst>(Apply.getCallee())->getReferencedFunction(); assert(F->isDefinition() && "Expected definition to specialize!"); if (!F->shouldOptimize()) { DEBUG(llvm::dbgs() << " Cannot specialize function " << F->getName() << " marked to be excluded from optimizations.\n"); return ApplySite(); } DEBUG(llvm::dbgs() << " ApplyInst: " << *Apply.getInstruction()); // Create the substitution maps. TypeSubstitutionMap InterfaceSubs; TypeSubstitutionMap ContextSubs; if (F->getLoweredFunctionType()->getGenericSignature()) InterfaceSubs = F->getLoweredFunctionType()->getGenericSignature() ->getSubstitutionMap(Apply.getSubstitutions()); if (F->getContextGenericParams()) ContextSubs = F->getContextGenericParams() ->getSubstitutionMap(Apply.getSubstitutions()); // We do not support partial specialization. if (hasUnboundGenericTypes(InterfaceSubs)) { DEBUG(llvm::dbgs() << " Cannot specialize with interface subs.\n"); return ApplySite(); } if (hasDynamicSelfTypes(InterfaceSubs)) { DEBUG(llvm::dbgs() << " Cannot specialize with dynamic self.\n"); return ApplySite(); } std::string ClonedName; { ArrayRef<Substitution> Subs = Apply.getSubstitutions(); Mangle::Mangler M; GenericSpecializationMangler Mangler(M, F, Subs); Mangler.mangle(); ClonedName = M.finalize(); } DEBUG(llvm::dbgs() << " Specialized function " << ClonedName << '\n'); auto &M = Apply.getInstruction()->getModule(); // If we already have this specialization, reuse it. auto NewF = M.lookUpFunction(ClonedName); if (NewF) { #ifndef NDEBUG // Make sure that NewF's subst type matches the expected type. auto Subs = Apply.getSubstitutions(); auto FTy = F->getLoweredFunctionType()->substGenericArgs(M, M.getSwiftModule(), Subs); assert(FTy == NewF->getLoweredFunctionType() && "Previously specialized function does not match expected type."); #endif } else { // Do not create any new specializations at Onone. if (M.getOptions().Optimization <= SILOptions::SILOptMode::None) return ApplySite(); DEBUG( if (M.getOptions().Optimization <= SILOptions::SILOptMode::Debug) { llvm::dbgs() << "Creating a specialization: " << ClonedName << "\n"; }); // Create a new function. NewF = GenericCloner::cloneFunction(F, InterfaceSubs, ContextSubs, ClonedName, Apply, Collector.getCallback()); NewFunction = NewF; // Check if this specialization should be cached. cacheSpecialization(M, NewF); } return replaceWithSpecializedFunction(Apply, NewF); } <commit_msg>Simplify a search for an existing generic specialization.<commit_after>//===--- Generics.cpp ---- Utilities for transforming generics ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "generic-specializer" #include "swift/Strings.h" #include "swift/SILOptimizer/Utils/Generics.h" #include "swift/SILOptimizer/Utils/GenericCloner.h" using namespace swift; // Create a new apply based on an old one, but with a different // function being applied. ApplySite swift::replaceWithSpecializedFunction(ApplySite AI, SILFunction *NewF) { SILLocation Loc = AI.getLoc(); ArrayRef<Substitution> Subst; SmallVector<SILValue, 4> Arguments; for (auto &Op : AI.getArgumentOperands()) { Arguments.push_back(Op.get()); } SILBuilderWithScope Builder(AI.getInstruction()); FunctionRefInst *FRI = Builder.createFunctionRef(Loc, NewF); if (auto *TAI = dyn_cast<TryApplyInst>(AI)) return Builder.createTryApply(Loc, FRI, TAI->getSubstCalleeSILType(), {}, Arguments, TAI->getNormalBB(), TAI->getErrorBB()); if (auto *A = dyn_cast<ApplyInst>(AI)) return Builder.createApply(Loc, FRI, Arguments, A->isNonThrowing()); if (auto *PAI = dyn_cast<PartialApplyInst>(AI)) return Builder.createPartialApply(Loc, FRI, PAI->getSubstCalleeSILType(), {}, Arguments, PAI->getType()); llvm_unreachable("unhandled kind of apply"); } /// Try to convert definition into declaration. static bool convertExternalDefinitionIntoDeclaration(SILFunction *F) { // Bail if it is a declaration already. if (!F->isDefinition()) return false; // Bail if there is no external implementation of this function. if (!F->isAvailableExternally()) return false; // Bail if has a shared visibility, as there are no guarantees // that an implementation is available elsewhere. if (hasSharedVisibility(F->getLinkage())) return false; // Make this definition a declaration by removing the body of a function. F->convertToDeclaration(); assert(F->isExternalDeclaration() && "Function should be an external declaration"); DEBUG(llvm::dbgs() << " removed external function " << F->getName() << "\n"); return true; } /// Check of a given name could be a name of a white-listed /// specialization. bool swift::isWhitelistedSpecialization(StringRef SpecName) { // The whitelist of classes and functions from the stdlib, // whose specializations we want to preserve. ArrayRef<StringRef> Whitelist = { "Array", "_ArrayBuffer", "_ContiguousArrayBuffer", "Range", "RangeGenerator", "_allocateUninitializedArray", "UTF8", "UTF16", "String", "_StringBuffer", "_toStringReadOnlyPrintable", }; // TODO: Once there is an efficient API to check if // a given symbol is a specialization of a specific type, // use it instead. Doing demangling just for this check // is just wasteful. auto DemangledNameString = swift::Demangle::demangleSymbolAsString(SpecName); StringRef DemangledName = DemangledNameString; auto pos = DemangledName.find("generic ", 0); if (pos == StringRef::npos) return false; // Create "of Swift" llvm::SmallString<64> OfString; llvm::raw_svector_ostream buffer(OfString); buffer << "of "; buffer << STDLIB_NAME <<'.'; StringRef OfStr = buffer.str(); pos = DemangledName.find(OfStr, pos); if (pos == StringRef::npos) return false; pos += OfStr.size(); for(auto Name: Whitelist) { auto pos1 = DemangledName.find(Name, pos); if (pos1 == pos && !isalpha(DemangledName[pos1+Name.size()])) { return true; } } return false; } /// Cache a specialization. /// For now, it is performed only for specializations in the /// standard library. But in the future, one could think of /// maintaining a cache of optimized specializations. /// /// Mark specializations as public, so that they can be used /// by user applications. These specializations are supposed to be /// used only by -Onone compiled code. They should be never inlined. static bool cacheSpecialization(SILModule &M, SILFunction *F) { // Do not remove functions from the white-list. Keep them around. // Change their linkage to public, so that other applications can refer to it. if (M.getOptions().Optimization >= SILOptions::SILOptMode::Optimize && F->getLinkage() != SILLinkage::Public && F->getModule().getSwiftModule()->getName().str() == SWIFT_ONONE_SUPPORT) { if (F->getLinkage() != SILLinkage::Public && isWhitelistedSpecialization(F->getName())) { DEBUG( auto DemangledNameString = swift::Demangle::demangleSymbolAsString(F->getName()); StringRef DemangledName = DemangledNameString; llvm::dbgs() << "Keep specialization: " << DemangledName << " : " << F->getName() << "\n"); // Make it public, so that others can refer to it. // // NOTE: This function may refer to non-public symbols, which may lead to // problems, if you ever try to inline this function. Therefore, these // specializations should only be used to refer to them, but should never // be inlined! The general rule could be: Never inline specializations // from stdlib! // // NOTE: Making these specializations public at this point breaks // some optimizations. Therefore, just mark the function. // DeadFunctionElimination pass will check if the function is marked // and preserve it if required. F->setKeepAsPublic(true); return true; } } return false; } /// Try to look up an existing specialization in the specialization cache. /// If it is found, it tries to link this specialization. /// /// For now, it performs a lookup only in the standard library. /// But in the future, one could think of maintaining a cache /// of optimized specializations. static SILFunction *lookupExistingSpecialization(SILModule &M, StringRef FunctionName) { // Try to link existing specialization only in -Onone mode. // All other compilation modes perform specialization themselves. // TODO: Cache optimized specializations and perform lookup here? // Only check that this function exists, but don't read // its body. It can save some compile-time. if (isWhitelistedSpecialization(FunctionName)) return M.hasFunction(FunctionName, SILLinkage::PublicExternal); return nullptr; } SILFunction *swift::getExistingSpecialization(SILModule &M, StringRef FunctionName) { // First check if the module contains a required specialization already. auto *Specialization = M.lookUpFunction(FunctionName); if (Specialization) return Specialization; // Then check if the required specialization can be found elsewhere. Specialization = lookupExistingSpecialization(M, FunctionName); if (!Specialization) return nullptr; assert(hasPublicVisibility(Specialization->getLinkage()) && "Pre-specializations should have public visibility"); Specialization->setLinkage(SILLinkage::PublicExternal); assert(Specialization->isExternalDeclaration() && "Specialization should be a public external declaration"); DEBUG(llvm::dbgs() << "Found existing specialization for: " << FunctionName << '\n'; llvm::dbgs() << swift::Demangle::demangleSymbolAsString( Specialization->getName()) << "\n\n"); return Specialization; } ApplySite swift::trySpecializeApplyOfGeneric(ApplySite Apply, SILFunction *&NewFunction, CloneCollector &Collector) { NewFunction = nullptr; assert(Apply.hasSubstitutions() && "Expected an apply with substitutions!"); auto *F = cast<FunctionRefInst>(Apply.getCallee())->getReferencedFunction(); assert(F->isDefinition() && "Expected definition to specialize!"); if (!F->shouldOptimize()) { DEBUG(llvm::dbgs() << " Cannot specialize function " << F->getName() << " marked to be excluded from optimizations.\n"); return ApplySite(); } DEBUG(llvm::dbgs() << " ApplyInst: " << *Apply.getInstruction()); // Create the substitution maps. TypeSubstitutionMap InterfaceSubs; TypeSubstitutionMap ContextSubs; if (F->getLoweredFunctionType()->getGenericSignature()) InterfaceSubs = F->getLoweredFunctionType()->getGenericSignature() ->getSubstitutionMap(Apply.getSubstitutions()); if (F->getContextGenericParams()) ContextSubs = F->getContextGenericParams() ->getSubstitutionMap(Apply.getSubstitutions()); // We do not support partial specialization. if (hasUnboundGenericTypes(InterfaceSubs)) { DEBUG(llvm::dbgs() << " Cannot specialize with interface subs.\n"); return ApplySite(); } if (hasDynamicSelfTypes(InterfaceSubs)) { DEBUG(llvm::dbgs() << " Cannot specialize with dynamic self.\n"); return ApplySite(); } std::string ClonedName; { ArrayRef<Substitution> Subs = Apply.getSubstitutions(); Mangle::Mangler M; GenericSpecializationMangler Mangler(M, F, Subs); Mangler.mangle(); ClonedName = M.finalize(); } DEBUG(llvm::dbgs() << " Specialized function " << ClonedName << '\n'); auto &M = Apply.getInstruction()->getModule(); // If we already have this specialization, reuse it. auto NewF = M.lookUpFunction(ClonedName); if (NewF) { #ifndef NDEBUG // Make sure that NewF's subst type matches the expected type. auto Subs = Apply.getSubstitutions(); auto FTy = F->getLoweredFunctionType()->substGenericArgs(M, M.getSwiftModule(), Subs); assert(FTy == NewF->getLoweredFunctionType() && "Previously specialized function does not match expected type."); #endif } else { // Do not create any new specializations at Onone. if (M.getOptions().Optimization <= SILOptions::SILOptMode::None) return ApplySite(); DEBUG( if (M.getOptions().Optimization <= SILOptions::SILOptMode::Debug) { llvm::dbgs() << "Creating a specialization: " << ClonedName << "\n"; }); // Create a new function. NewF = GenericCloner::cloneFunction(F, InterfaceSubs, ContextSubs, ClonedName, Apply, Collector.getCallback()); NewFunction = NewF; // Check if this specialization should be cached. cacheSpecialization(M, NewF); } return replaceWithSpecializedFunction(Apply, NewF); } <|endoftext|>
<commit_before>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2015,2016 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <memory> #include <stdexcept> #include <unordered_set> #include <vector> #include <cstdio> #include <cstdlib> #include "Leader.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "util.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << progname << " [--verbose] marc_data\n"; std::exit(EXIT_FAILURE); } void ProcessRecords(const bool verbose, const bool input_is_xml, File * const input) { std::string raw_record; unsigned record_count(0), max_record_length(0), max_local_block_count(0); std::unordered_set<std::string> control_numbers; std::map<Leader::RecordType, unsigned> record_types_and_counts; while (const MarcUtil::Record record = input_is_xml ? MarcUtil::Record::XmlFactory(input) : MarcUtil::Record::BinaryFactory(input)) { ++record_count; const std::vector<std::string> &fields(record.getFields()); if (unlikely(fields.empty())) Error("record #" + std::to_string(record_count) + " has zero fields!"); const std::string &control_number(fields[0]); const Leader::RecordType record_type(record.getRecordType()); ++record_types_and_counts[record_type]; if (verbose and record_type == Leader::RecordType::UNKNOWN) std::cerr << "Unknown record type '" << record.getLeader()[6] << "' for PPN " << control_number << ".\n"; std::string err_msg; if (not input_is_xml and not record.recordSeemsCorrect(&err_msg)) Error("record #" + std::to_string(record_count) + " is malformed: " + err_msg); if (control_numbers.find(control_number) != control_numbers.end()) Error("found at least one duplicate control number: " + control_number); control_numbers.insert(control_number); const Leader &leader(record.getLeader()); const unsigned record_length(leader.getRecordLength()); if (record_length > max_record_length) max_record_length = record_length; std::vector<std::pair<size_t, size_t>> local_block_boundaries; const size_t local_block_count(record.findAllLocalDataBlocks(&local_block_boundaries)); if (local_block_count > max_local_block_count) max_local_block_count = local_block_count; } std::cout << "Data set contains " << record_count << " MARC record(s).\n"; std::cout << "Largest record contains " << max_record_length << " bytes.\n"; std::cout << "The record with the largest number of \"local\" blocks has " << max_local_block_count << " local blocks.\n"; std::cout << "Counted " << record_types_and_counts[Leader::RecordType::BIBLIOGRAPHIC] << " bibliographic record(s), " << record_types_and_counts[Leader::RecordType::AUTHORITY] << " classification record(s), " << record_types_and_counts[Leader::RecordType::CLASSIFICATION] << " authority record(s), and " << record_types_and_counts[Leader::RecordType::UNKNOWN] << " record(s) of unknown record type.\n"; } int main(int argc, char *argv[]) { progname = argv[0]; if (argc < 2) Usage(); const bool verbose(std::strcmp(argv[1], "--verbose") == 0); if (verbose) --argc, ++argv; if (argc != 2) Usage(); const std::string marc_input_filename(argv[1]); const std::string media_type(MediaTypeUtil::GetFileMediaType(marc_input_filename)); if (unlikely(media_type.empty())) Error("can't determine media type of \"" + marc_input_filename + "\"!"); if (media_type != "application/xml" and media_type != "application/marc") Error("\"input_filename\" is neither XML nor MARC-21 data!"); const bool input_is_xml(media_type == "application/xml"); File marc_input(marc_input_filename, "r"); if (not marc_input) Error("can't open \"" + marc_input_filename + "\" for reading!"); try { ProcessRecords(verbose, input_is_xml, &marc_input); } catch (const std::exception &e) { Error("Caught exception: " + std::string(e.what())); } } <commit_msg>Added a new optional flag.<commit_after>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2015,2016 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <memory> #include <stdexcept> #include <unordered_set> #include <vector> #include <cstdio> #include <cstdlib> #include "Leader.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "util.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] [--report-duplicate-ids] marc_data\n" << " If \"--report-duplicate-ids\" has been specified, the occurrence of duplicate ID's\n" << " will be reported, if it has not been sepcified, the programme will abort when it\n" << " it encounters the first duplicate ID.\n\n"; std::exit(EXIT_FAILURE); } void ProcessRecords(const bool verbose, const bool input_is_xml, const bool report_duplicate_ids, File * const input) { std::string raw_record; unsigned record_count(0), max_record_length(0), max_local_block_count(0), duplicate_id_count(0); std::unordered_set<std::string> control_numbers; std::map<Leader::RecordType, unsigned> record_types_and_counts; while (const MarcUtil::Record record = input_is_xml ? MarcUtil::Record::XmlFactory(input) : MarcUtil::Record::BinaryFactory(input)) { ++record_count; const std::vector<std::string> &fields(record.getFields()); if (unlikely(fields.empty())) Error("record #" + std::to_string(record_count) + " has zero fields!"); const std::string &control_number(fields[0]); const Leader::RecordType record_type(record.getRecordType()); ++record_types_and_counts[record_type]; if (verbose and record_type == Leader::RecordType::UNKNOWN) std::cerr << "Unknown record type '" << record.getLeader()[6] << "' for PPN " << control_number << ".\n"; std::string err_msg; if (not input_is_xml and not record.recordSeemsCorrect(&err_msg)) Error("record #" + std::to_string(record_count) + " is malformed: " + err_msg); if (control_numbers.find(control_number) != control_numbers.end()) { if (report_duplicate_ids) { std::cerr << "Found a duplicate control number: " << control_number << ".\n"; ++duplicate_id_count; } else Error("found at least one duplicate control number: " + control_number); } else control_numbers.insert(control_number); const Leader &leader(record.getLeader()); const unsigned record_length(leader.getRecordLength()); if (record_length > max_record_length) max_record_length = record_length; std::vector<std::pair<size_t, size_t>> local_block_boundaries; const size_t local_block_count(record.findAllLocalDataBlocks(&local_block_boundaries)); if (local_block_count > max_local_block_count) max_local_block_count = local_block_count; } std::cout << "Data set contains " << record_count << " MARC record(s).\n"; std::cout << "Largest record contains " << max_record_length << " bytes.\n"; std::cout << "The record with the largest number of \"local\" blocks has " << max_local_block_count << " local blocks.\n"; std::cout << "Counted " << record_types_and_counts[Leader::RecordType::BIBLIOGRAPHIC] << " bibliographic record(s), " << record_types_and_counts[Leader::RecordType::AUTHORITY] << " classification record(s), " << record_types_and_counts[Leader::RecordType::CLASSIFICATION] << " authority record(s), and " << record_types_and_counts[Leader::RecordType::UNKNOWN] << " record(s) of unknown record type.\n"; if (report_duplicate_ids) std::cout << "Found " << duplicate_id_count << " records w/ duplicate ID's.\n"; } int main(int argc, char *argv[]) { progname = argv[0]; if (argc < 2) Usage(); const bool verbose(std::strcmp(argv[1], "--verbose") == 0); if (verbose) --argc, ++argv; const bool report_duplicate_ids(std::strcmp(argv[1], "--report-duplicate-ids") == 0); if (report_duplicate_ids) --argc, ++argv; if (argc != 2) Usage(); const std::string marc_input_filename(argv[1]); const std::string media_type(MediaTypeUtil::GetFileMediaType(marc_input_filename)); if (unlikely(media_type.empty())) Error("can't determine media type of \"" + marc_input_filename + "\"!"); if (media_type != "application/xml" and media_type != "application/marc") Error("\"input_filename\" is neither XML nor MARC-21 data!"); const bool input_is_xml(media_type == "application/xml"); File marc_input(marc_input_filename, "r"); if (not marc_input) Error("can't open \"" + marc_input_filename + "\" for reading!"); try { ProcessRecords(verbose, input_is_xml, report_duplicate_ids, &marc_input); } catch (const std::exception &e) { Error("Caught exception: " + std::string(e.what())); } } <|endoftext|>
<commit_before>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <memory> #include <stdexcept> #include <unordered_set> #include <vector> #include <cstdio> #include <cstdlib> #include "Leader.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "util.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << progname << " marc_data\n"; std::exit(EXIT_FAILURE); } void ProcessRecords(const bool input_is_xml, File * const input) { std::string raw_record; unsigned record_count(0), max_record_length(0), max_local_block_count(0); std::unordered_set<std::string> control_numbers; std::map<MarcUtil::Record::RecordType, unsigned> record_types_and_counts; while (const MarcUtil::Record record = input_is_xml ? MarcUtil::Record::XmlFactory(input) : MarcUtil::Record::BinaryFactory(input)) { ++record_count; ++record_types_and_counts[record.getRecordType()]; std::string err_msg; if (not input_is_xml and not record.recordSeemsCorrect(&err_msg)) Error("record #" + std::to_string(record_count) + " is malformed: " + err_msg); const std::vector<std::string> &fields(record.getFields()); if (unlikely(fields.empty())) Error("record #" + std::to_string(record_count) + " has zero fields!"); const std::string &control_number(fields[0]); if (control_numbers.find(control_number) != control_numbers.end()) Error("found at least one duplicate control number: " + control_number); control_numbers.insert(control_number); const Leader &leader(record.getLeader()); const unsigned record_length(leader.getRecordLength()); if (record_length > max_record_length) max_record_length = record_length; std::vector<std::pair<size_t, size_t>> local_block_boundaries; const size_t local_block_count(record.findAllLocalDataBlocks(&local_block_boundaries)); if (local_block_count > max_local_block_count) max_local_block_count = local_block_count; } std::cout << "Data set contains " << record_count << " MARC record(s).\n"; std::cout << "Largest record contains " << max_record_length << " bytes.\n"; std::cout << "The record with the largest number of \"local\" blocks has " << max_local_block_count << " local blocks.\n"; std::cout << "Counted " << record_types_and_counts[MarcUtil::Record::BIBLIOGRAPHIC] << " bibliographic record(s), " << record_types_and_counts[MarcUtil::Record::AUTHORITY] << " authority record(s), and " << record_types_and_counts[MarcUtil::Record::UNKNOWN] << " record(s) of unknown record type.\n"; } int main(int argc, char *argv[]) { progname = argv[0]; if (argc != 2) Usage(); const std::string marc_input_filename(argv[1]); const std::string media_type(MediaTypeUtil::GetFileMediaType(marc_input_filename)); if (unlikely(media_type.empty())) Error("can't determine media type of \"" + marc_input_filename + "\"!"); if (media_type != "application/xml" and media_type != "application/marc") Error("\"input_filename\" is neither XML nor MARC-21 data!"); const bool input_is_xml(media_type == "application/xml"); File marc_input(marc_input_filename, input_is_xml ? "r" : "rb"); if (not marc_input) Error("can't open \"" + marc_input_filename + "\" for reading!"); try { ProcessRecords(input_is_xml, &marc_input); } catch (const std::exception &e) { Error("Caught exception: " + std::string(e.what())); } } <commit_msg>Added a --verbose optional flag.<commit_after>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2015,2016 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <memory> #include <stdexcept> #include <unordered_set> #include <vector> #include <cstdio> #include <cstdlib> #include "Leader.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "util.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << progname << " [--verbose] marc_data\n"; std::exit(EXIT_FAILURE); } void ProcessRecords(const bool verbose, const bool input_is_xml, File * const input) { std::string raw_record; unsigned record_count(0), max_record_length(0), max_local_block_count(0); std::unordered_set<std::string> control_numbers; std::map<MarcUtil::Record::RecordType, unsigned> record_types_and_counts; while (const MarcUtil::Record record = input_is_xml ? MarcUtil::Record::XmlFactory(input) : MarcUtil::Record::BinaryFactory(input)) { ++record_count; const std::vector<std::string> &fields(record.getFields()); if (unlikely(fields.empty())) Error("record #" + std::to_string(record_count) + " has zero fields!"); const std::string &control_number(fields[0]); const MarcUtil::Record::RecordType record_type(record.getRecordType()); ++record_types_and_counts[record_type]; if (verbose and record_type == MarcUtil::Record::UNKNOWN) std::cerr << "Unknown record type '" << record.getLeader()[6] << "' for PPN " << control_number << ".\n"; std::string err_msg; if (not input_is_xml and not record.recordSeemsCorrect(&err_msg)) Error("record #" + std::to_string(record_count) + " is malformed: " + err_msg); if (control_numbers.find(control_number) != control_numbers.end()) Error("found at least one duplicate control number: " + control_number); control_numbers.insert(control_number); const Leader &leader(record.getLeader()); const unsigned record_length(leader.getRecordLength()); if (record_length > max_record_length) max_record_length = record_length; std::vector<std::pair<size_t, size_t>> local_block_boundaries; const size_t local_block_count(record.findAllLocalDataBlocks(&local_block_boundaries)); if (local_block_count > max_local_block_count) max_local_block_count = local_block_count; } std::cout << "Data set contains " << record_count << " MARC record(s).\n"; std::cout << "Largest record contains " << max_record_length << " bytes.\n"; std::cout << "The record with the largest number of \"local\" blocks has " << max_local_block_count << " local blocks.\n"; std::cout << "Counted " << record_types_and_counts[MarcUtil::Record::BIBLIOGRAPHIC] << " bibliographic record(s), " << record_types_and_counts[MarcUtil::Record::AUTHORITY] << " authority record(s), and " << record_types_and_counts[MarcUtil::Record::UNKNOWN] << " record(s) of unknown record type.\n"; } int main(int argc, char *argv[]) { progname = argv[0]; if (argc < 2) Usage(); const bool verbose(std::strcmp(argv[1], "--verbose") == 0); if (verbose) --argc, ++argv; if (argc != 2) Usage(); const std::string marc_input_filename(argv[1]); const std::string media_type(MediaTypeUtil::GetFileMediaType(marc_input_filename)); if (unlikely(media_type.empty())) Error("can't determine media type of \"" + marc_input_filename + "\"!"); if (media_type != "application/xml" and media_type != "application/marc") Error("\"input_filename\" is neither XML nor MARC-21 data!"); const bool input_is_xml(media_type == "application/xml"); File marc_input(marc_input_filename, input_is_xml ? "r" : "rb"); if (not marc_input) Error("can't open \"" + marc_input_filename + "\" for reading!"); try { ProcessRecords(verbose, input_is_xml, &marc_input); } catch (const std::exception &e) { Error("Caught exception: " + std::string(e.what())); } } <|endoftext|>
<commit_before>#include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) (x).begin(),(x).end() using namespace std; using ll = long long; using ld = long double; const int INF = 1e9; int main() { return 0; } <commit_msg>add rep class deprecated rep macro<commit_after>#include <bits/stdc++.h> using namespace std; class rep { struct repi { size_t it; repi() : it(0) { } repi(size_t n) : it(n) {} bool operator==(const repi &rhs) const { return it == rhs.it; } bool operator!=(const repi &rhs) const { return it != rhs.it; } size_t& operator*() { return it; } repi& operator++() { ++it; return *this; } }; size_t i; public: rep(size_t n) : i(n) { } repi begin() const { return 0; } repi end() const { return i; } }; using ll = long long; using ld = long double; const int INF = 1e9; int main() { return 0; } <|endoftext|>
<commit_before>#include "util/init.h" #include <event2/thread.h> #include <evhtp.h> #include <gflags/gflags.h> #include <glog/logging.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <unistd.h> #include <string> #include "config.h" #include "log/ct_extensions.h" #include "proto/cert_serializer.h" #include "version.h" using std::string; namespace util { namespace { void LibEventLog(int severity, const char* msg) { const string msg_s(msg); switch (severity) { case EVENT_LOG_DEBUG: VLOG(1) << msg_s; break; case EVENT_LOG_MSG: LOG(INFO) << msg_s; break; case EVENT_LOG_WARN: LOG(WARNING) << msg_s; break; case EVENT_LOG_ERR: LOG(ERROR) << msg_s; break; default: LOG(ERROR) << "LibEvent(?): " << msg_s; break; } } } // namespace void InitCT(int* argc, char** argv[]) { google::SetVersionString(cert_trans::kBuildVersion); google::ParseCommandLineFlags(argc, argv, true); google::InitGoogleLogging(*argv[0]); google::InstallFailureSignalHandler(); ConfigureSerializerForV1CT(); event_set_log_callback(&LibEventLog); evthread_use_pthreads(); // Set-up OpenSSL for multithreaded use: evhtp_ssl_use_threads(); OpenSSL_add_all_algorithms(); ERR_load_BIO_strings(); ERR_load_crypto_strings(); SSL_load_error_strings(); SSL_library_init(); cert_trans::LoadCtExtensions(); LOG(INFO) << "Build version: " << google::VersionString(); #ifdef ENABLE_HARDENING LOG(INFO) << "Binary built with hardening enabled."; #else LOG(WARNING) << "Binary built with hardening DISABLED."; #endif } } // namespace util <commit_msg>Don't force callers of util::InitCT() to be CT V1.<commit_after>#include "util/init.h" #include <event2/thread.h> #include <evhtp.h> #include <gflags/gflags.h> #include <glog/logging.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <unistd.h> #include <string> #include "config.h" #include "log/ct_extensions.h" #include "proto/cert_serializer.h" #include "version.h" using std::string; namespace util { namespace { void LibEventLog(int severity, const char* msg) { const string msg_s(msg); switch (severity) { case EVENT_LOG_DEBUG: VLOG(1) << msg_s; break; case EVENT_LOG_MSG: LOG(INFO) << msg_s; break; case EVENT_LOG_WARN: LOG(WARNING) << msg_s; break; case EVENT_LOG_ERR: LOG(ERROR) << msg_s; break; default: LOG(ERROR) << "LibEvent(?): " << msg_s; break; } } } // namespace void InitCT(int* argc, char** argv[]) { google::SetVersionString(cert_trans::kBuildVersion); google::ParseCommandLineFlags(argc, argv, true); google::InitGoogleLogging(*argv[0]); google::InstallFailureSignalHandler(); event_set_log_callback(&LibEventLog); evthread_use_pthreads(); // Set-up OpenSSL for multithreaded use: evhtp_ssl_use_threads(); OpenSSL_add_all_algorithms(); ERR_load_BIO_strings(); ERR_load_crypto_strings(); SSL_load_error_strings(); SSL_library_init(); cert_trans::LoadCtExtensions(); LOG(INFO) << "Build version: " << google::VersionString(); #ifdef ENABLE_HARDENING LOG(INFO) << "Binary built with hardening enabled."; #else LOG(WARNING) << "Binary built with hardening DISABLED."; #endif } } // namespace util <|endoftext|>
<commit_before>#pragma once #include <algorithm> #include <chrono> #include <random> #include <string> #include <type_traits> template<typename T> inline T gcd(T a, T b) { while (b != 0) { a %= b; std::swap(a, b); } return a; } template<typename T> inline T lcm(const T& a, const T& b) { return a / gcd(a, b) * b; } template<typename T> constexpr inline T sqr(const T& x) { return x * x; } template<class T> inline bool isPrime(const T& n) // Straightforward checking in O(sqrt(N)) { if (n < 2) { return false; } T kk = (T)sqrt(n + 0.); for (T i = 2; i <= kk; ++i) { if (!(n % i)) { return false; } } return true; } inline void eratosthenes_sieve(std::vector<bool>& prime) { if (prime.size() < 2) { prime.assign(prime.size(), false); return; } prime.assign(prime.size(), true); prime[0] = prime[1] = false; for (size_t i = 4; i < prime.size(); i += 2) { prime[i] = false; } for (size_t i = 3; i * i < prime.size(); i += 2) { if (prime[i]) { const size_t delta = i << 1; for (size_t j = i * i; j < prime.size(); j += delta) { prime[j] = false; } } } } inline void primesVector(bool prime[], const int n, int primes[], int& primesCnt) { if (n < 2) { primesCnt = 0; return; } primesCnt = 1; primes[0] = 2; for (int i = 3; i < n; i += 2) { if (prime[i]) { primes[primesCnt++] = i; } } } template<class T> T factorial(T n, const T& mod = 1000000007) { long long ret = 1; for (int i = 2; i <= n; ++i) { ret = (ret * i) % mod; } return ret % mod; } template<typename T, typename U> inline T binpow(T a, U b) { static_assert(std::is_integral<U>::value, "Degree must be integral. For real degree use pow."); T ret = 1; while (b != 0) { if ((b & 1) != 0) { ret *= a; } a *= a; b >>= 1; } return ret; } template<typename T, typename U, typename Q> inline T binpow(T a, U b, Q mod) { static_assert(std::is_integral<U>::value, "Degree must be integral. For real degree use pow."); long long ret = 1; a %= mod; while (b != 0) { if ((b & 1) != 0) { ret = ret * a % mod; } a = a * a % mod; b >>= 1; } return ret % mod; } template<class T> int digitSum(T n) { int res = 0; n = abs(n); while (n) { res += n % 10; n /= 10; } return res; } template<class T> int digitCount(T n) { int res = 0; n = abs(n); while (n) { ++res; n /= 10; } return res; } template<class T> T eulerFunction(T n) { T res = n; for (T i = 2; i * i <= n; ++i) { if (!(n % i)) { while (!(n % i)) { n /= i; } res -= res / i; } } if (n > 1) { res -= res / n; } return res; } template<typename T, typename U> T inverseElement(const T n, const U mod) // inverse element for prime mod { return binpow(static_cast<long long>(n), mod - 2, mod); } inline void inverseElementForSegment(int r[], const int n, const int mod) // inverse element for prime mod for numbers [1; mod - 1] { r[1] = 1; for (int i = 2; i < n; ++i) { r[i] = (mod - static_cast<long long>(mod) / i * r[mod % i] % mod) % mod; } } template<class T> T inverseElementCompMod(const T n, const T mod) // inverse element for composite mod using formula inv(n) = n^(phi(mod) - 1) { return binpow(n, eulerFunction(mod) - 1, mod); } template<class T, size_t N> void binomialCoefficients(T (&c)[N][N]) { for (int i = 0; i < N; ++i) { c[i][0] = c[i][i] = 1; for (int j = 1; j < i; ++j) { c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; } } } template<class T, size_t N> void binomialCoefficients(T (&c)[N][N], const T mod) { for (int i = 0; i < N; ++i) { c[i][0] = c[i][i] = 1; for (int j = 1; j < i; ++j) { c[i][j] = c[i - 1][j - 1]; add_mod(c[i][j], c[i - 1][j], mod); } for (int j = i + 1; j < N; ++j) { c[i][j] = 0; } } } template<class T> std::string toRoman(T n) { const int ValsCount = 13; const int Vals[] = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 }; const char * Digits[] = { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" }; std::string res = ""; int x = ValsCount - 1; while (n) { while (Vals[x] > n) { --x; } n -= Vals[x]; res += Digits[x]; } return res; } void calcPowers(long long deg[], long long base, int n) { deg[0] = 1; for (int i = 1; i <= n; ++i) { deg[i] = deg[i - 1] * base; } } template<class T> void calcPowers(T deg[], T base, int n, T MOD) { deg[0] = 1 % MOD; for (int i = 1; i <= n; ++i) { deg[i] = (long long)deg[i - 1] * base % MOD; } } inline uint32_t abs(const uint32_t x) { return x; } inline uint64_t abs(const uint64_t x) { return x; } template<typename T> inline bool is_leap_year(const T year) { return year % 400 == 0 || (year % 100 != 0 && (year & 3) == 0); } namespace Random { static std::chrono::system_clock::rep GetRandSeed() { return std::chrono::system_clock::now().time_since_epoch().count(); } static std::mt19937_64 gen(GetRandSeed()); static std::uniform_int_distribution<long long> distrib(0, std::numeric_limits<long long>::max()); template<typename T> static T get(T r) { return distrib(gen) % r; } template<typename T> static T get(T l, T r) { return get(r - l + 1) + l; } }; <commit_msg>Refactored calc_powers() method.<commit_after>#pragma once #include <algorithm> #include <chrono> #include <random> #include <string> #include <type_traits> template<typename T> inline T gcd(T a, T b) { while (b != 0) { a %= b; std::swap(a, b); } return a; } template<typename T> inline T lcm(const T& a, const T& b) { return a / gcd(a, b) * b; } template<typename T> constexpr inline T sqr(const T& x) { return x * x; } template<class T> inline bool isPrime(const T& n) // Straightforward checking in O(sqrt(N)) { if (n < 2) { return false; } T kk = (T)sqrt(n + 0.); for (T i = 2; i <= kk; ++i) { if (!(n % i)) { return false; } } return true; } inline void eratosthenes_sieve(std::vector<bool>& prime) { if (prime.size() < 2) { prime.assign(prime.size(), false); return; } prime.assign(prime.size(), true); prime[0] = prime[1] = false; for (size_t i = 4; i < prime.size(); i += 2) { prime[i] = false; } for (size_t i = 3; i * i < prime.size(); i += 2) { if (prime[i]) { const size_t delta = i << 1; for (size_t j = i * i; j < prime.size(); j += delta) { prime[j] = false; } } } } inline void primesVector(bool prime[], const int n, int primes[], int& primesCnt) { if (n < 2) { primesCnt = 0; return; } primesCnt = 1; primes[0] = 2; for (int i = 3; i < n; i += 2) { if (prime[i]) { primes[primesCnt++] = i; } } } template<class T> T factorial(T n, const T& mod = 1000000007) { long long ret = 1; for (int i = 2; i <= n; ++i) { ret = (ret * i) % mod; } return ret % mod; } template<typename T, typename U> inline T binpow(T a, U b) { static_assert(std::is_integral<U>::value, "Degree must be integral. For real degree use pow."); T ret = 1; while (b != 0) { if ((b & 1) != 0) { ret *= a; } a *= a; b >>= 1; } return ret; } template<typename T, typename U, typename Q> inline T binpow(T a, U b, Q mod) { static_assert(std::is_integral<U>::value, "Degree must be integral. For real degree use pow."); long long ret = 1; a %= mod; while (b != 0) { if ((b & 1) != 0) { ret = ret * a % mod; } a = a * a % mod; b >>= 1; } return ret % mod; } template<class T> int digitSum(T n) { int res = 0; n = abs(n); while (n) { res += n % 10; n /= 10; } return res; } template<class T> int digitCount(T n) { int res = 0; n = abs(n); while (n) { ++res; n /= 10; } return res; } template<class T> T eulerFunction(T n) { T res = n; for (T i = 2; i * i <= n; ++i) { if (!(n % i)) { while (!(n % i)) { n /= i; } res -= res / i; } } if (n > 1) { res -= res / n; } return res; } template<typename T, typename U> T inverseElement(const T n, const U mod) // inverse element for prime mod { return binpow(static_cast<long long>(n), mod - 2, mod); } inline void inverseElementForSegment(int r[], const int n, const int mod) // inverse element for prime mod for numbers [1; mod - 1] { r[1] = 1; for (int i = 2; i < n; ++i) { r[i] = (mod - static_cast<long long>(mod) / i * r[mod % i] % mod) % mod; } } template<class T> T inverseElementCompMod(const T n, const T mod) // inverse element for composite mod using formula inv(n) = n^(phi(mod) - 1) { return binpow(n, eulerFunction(mod) - 1, mod); } template<class T, size_t N> void binomialCoefficients(T (&c)[N][N]) { for (int i = 0; i < N; ++i) { c[i][0] = c[i][i] = 1; for (int j = 1; j < i; ++j) { c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; } } } template<class T, size_t N> void binomialCoefficients(T (&c)[N][N], const T mod) { for (int i = 0; i < N; ++i) { c[i][0] = c[i][i] = 1; for (int j = 1; j < i; ++j) { c[i][j] = c[i - 1][j - 1]; add_mod(c[i][j], c[i - 1][j], mod); } for (int j = i + 1; j < N; ++j) { c[i][j] = 0; } } } template<class T> std::string toRoman(T n) { const int ValsCount = 13; const int Vals[] = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 }; const char * Digits[] = { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" }; std::string res = ""; int x = ValsCount - 1; while (n) { while (Vals[x] > n) { --x; } n -= Vals[x]; res += Digits[x]; } return res; } template<typename T> void calc_powers(std::vector<T>& deg, const T base) { deg[0] = 1; for (size_t i = 1; i < deg.size(); ++i) { deg[i] = deg[i - 1] * base; } } inline uint32_t abs(const uint32_t x) { return x; } inline uint64_t abs(const uint64_t x) { return x; } template<typename T> inline bool is_leap_year(const T year) { return year % 400 == 0 || (year % 100 != 0 && (year & 3) == 0); } namespace Random { static std::chrono::system_clock::rep GetRandSeed() { return std::chrono::system_clock::now().time_since_epoch().count(); } static std::mt19937_64 gen(GetRandSeed()); static std::uniform_int_distribution<long long> distrib(0, std::numeric_limits<long long>::max()); template<typename T> static T get(T r) { return distrib(gen) % r; } template<typename T> static T get(T l, T r) { return get(r - l + 1) + l; } }; <|endoftext|>
<commit_before>#include "dbmanager.h" using namespace std; // Constructor connects to sqlite database DbManager::DbManager() { db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("VLN1-Hopur23.sqlite"); db.open(); } // Optional order, Name, Gender, BirthYear, DeathYear. Optional filter DESC and ASC vector<Scientist> DbManager::getScientists(QString QSorder, QString QSfilter) { vector<Scientist> scientists; QSqlQuery querySort(db); querySort.prepare("SELECT * FROM Scientists ORDER BY " + QSorder + " " + QSfilter); querySort.exec(); while (querySort.next()) { int scientistID = querySort.value("ScientistID").toUInt(); string name = querySort.value("Name").toString().toStdString(); string gender = querySort.value("Gender").toString().toStdString(); int yearOfBirth = querySort.value("Birthyear").toUInt(); int yearOfDeath = querySort.value("Deathyear").toUInt(); Scientist scientist(scientistID, name, gender, yearOfBirth, yearOfDeath); scientists.push_back(scientist); } return scientists; } bool DbManager::addScientist(const Scientist& scientist) const { //bool message = ""; QSqlQuery queryAdd(db); queryAdd.prepare("INSERT INTO scientists (Name, Gender, BirthYear, DeathYear) VALUES (:Name, :Gender, :BirthYear, :DeathYear)"); queryAdd.bindValue(":Name", QString::fromStdString(scientist.getName())); queryAdd.bindValue(":Gender", QString::fromStdString(scientist.getGender())); queryAdd.bindValue(":BirthYear", scientist.getYearOfBirth()); queryAdd.bindValue(":DeathYear", scientist.getYearOfDeath()); if(queryAdd.exec()) { //message = "Scientist added successfully! "; return true; } else { //message = "Add scientist failed! "; return false; } //return message; } // Deletes scientist with chosen ID number from database void DbManager::deleteScientist(const int ID) { QSqlQuery queryDelete(db); queryDelete.prepare("DELETE FROM Scientists WHERE ScientistID = (:ScientistID)"); queryDelete.bindValue(":ScientistID",ID); queryDelete.exec(); } // Gets computer and his information from database(SQL) and reads into Computer vector // Optional (QS)order, Name, Gender, BirthYear, DeathYear. Optional (QS)filter DESC and ASC vector<Computer> DbManager::getComputers(QString QSorder, QString QSfilter) { vector<Computer> computers; QSqlQuery query(db); query.prepare("SELECT * FROM Computers ORDER BY " + QSorder + " " + QSfilter); query.exec(); while (query.next()) { int computerID = query.value("ComputerID").toUInt(); string name = query.value("Name").toString().toStdString(); int yearBuilt = query.value("Yearbuilt").toUInt(); string type = query.value("Type").toString().toStdString(); bool built = query.value("Built").toBool(); Computer computer(computerID, name, yearBuilt, type, built); computers.push_back(computer); } return computers; } <<<<<<< HEAD bool DbManager::addComputer(const Computer& computer) const { bool cMessage = ""; QSqlQuery queryAdd; queryAdd.prepare("INSERT INTO computers (ComputerID ,Name, Yearbuilt, Type, Built) VALUES (:ComputerID, :Name, :Yearbuilt, :Type, :Built)"); queryAdd.bindValue(":ComputerID", computer.getComputerID()); queryAdd.bindValue(":Name", QString::fromStdString(computer.getName())); queryAdd.bindValue(":Yearbuilt", computer.getYearBuilt()); queryAdd.bindValue(":Type", QString::fromStdString(computer.getType())); queryAdd.bindValue(":Built", computer.getBuilt()); if(queryAdd.exec()) { cMessage = "Computer added successfully! "; return true; } else { cMessage = "Add computer failed! "; return false; } return cMessage; } ======= // Returns vector with all computers associated with the scientist/s vector<Computer> DbManager::intersectScientist(const string& id) { vector<Computer> intersectedComputers; >>>>>>> 07259779bec07ba2b5f942867eae55fb4f26c3e6 QSqlQuery intersectQuery(db); intersectQuery.prepare("SELECT * FROM Computers INNER JOIN Computers_Scientists ON Computers.ComputerID = Computers_Scientists.ComputerID INNER JOIN Scientists ON Scientists.ScientistID = Computers_Scientists.ScientistID WHERE Scientists.ScientistID = :id"); intersectQuery.bindValue(":id", QString::fromStdString(id)); intersectQuery.exec(); while (intersectQuery.next()) { int computerID = intersectQuery.value("ComputerID").toUInt(); string name = intersectQuery.value("Name").toString().toStdString(); int yearBuilt = intersectQuery.value("Yearbuilt").toUInt(); string type = intersectQuery.value("Type").toString().toStdString(); bool built = intersectQuery.value("Built").toBool(); Computer computer(computerID, name, yearBuilt, type, built); intersectedComputers.push_back(computer); } return intersectedComputers; } // Returns vector with all computers associated with the scientist/s vector<Scientist> DbManager::intersectComputer(const string& id) { vector<Scientist> intersectedScientists; QSqlQuery intersectQuery(db); intersectQuery.prepare("SELECT * FROM Scientists INNER JOIN Computers_Scientists ON Scientists.ScientistID = Computers_Scientists.ScientistID INNER JOIN Computers ON Computers.ComputerID = Computers_Scientists.ComputerID WHERE Computers.ComputerID = :id"); intersectQuery.bindValue(":id", QString::fromStdString(id)); intersectQuery.exec(); while (intersectQuery.next()) { int scientistID = intersectQuery.value("ScientistID").toUInt(); string name = intersectQuery.value("Name").toString().toStdString(); string gender = intersectQuery.value("Gender").toString().toStdString(); int yearOfBirth = intersectQuery.value("Birthyear").toUInt(); int yearOfDeath = intersectQuery.value("Deathyear").toUInt(); Scientist scientist(scientistID, name, gender, yearOfBirth, yearOfDeath); intersectedScientists.push_back(scientist); } return intersectedScientists; } // Gets the info on Scientist which is searced for vector<Scientist> DbManager::searchScientist(const string& searchData) { vector<Scientist> foundScientist; db.open(); QSqlQuery query(db); if (isdigit(searchData.at(0))) { query.exec("SELECT * FROM Scientists WHERE (Birthyear || Deathyear) LIKE '%" + QString::fromStdString(searchData) + "%'"); } else { query.exec("SELECT * FROM Scientists WHERE (Name || Gender) LIKE '%" + QString::fromStdString(searchData) + "%'"); } while (query.next()) { int scientistID = query.value("ScientistID").toUInt(); string name = query.value("Name").toString().toStdString(); string gender = query.value("Gender").toString().toStdString(); int yearOfBirth = query.value("Birthyear").toUInt(); int yearOfDeath = query.value("Deathyear").toUInt(); Scientist scientist(scientistID, name, gender, yearOfBirth, yearOfDeath); foundScientist.push_back(scientist); } return foundScientist; } // Gets the info on Computer which is searched for vector<Computer> DbManager::searchComputer(string& searchData) { vector<Computer> foundComputer; QSqlQuery query(db); if (isdigit(searchData.at(0))) { query.exec("SELECT * FROM Computers WHERE (Yearbuilt) LIKE '%" + QString::fromStdString(searchData) + "%'"); } else { query.exec("SELECT * FROM Computers WHERE (Name || Type) LIKE '%" + QString::fromStdString(searchData) + "%'"); } while(query.next()) { int computerID = query.value("ComputerID").toUInt(); string name = query.value("Name").toString().toStdString(); int yearBuilt = query.value("Yearbuilt").toUInt(); string type = query.value("Type").toString().toStdString(); bool built = query.value("Built").toBool(); Computer computer(computerID, name, yearBuilt, type, built); foundComputer.push_back(computer); } return foundComputer; } <commit_msg>more fix<commit_after>#include "dbmanager.h" using namespace std; // Constructor connects to sqlite database DbManager::DbManager() { db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("VLN1-Hopur23.sqlite"); db.open(); } // Optional order, Name, Gender, BirthYear, DeathYear. Optional filter DESC and ASC vector<Scientist> DbManager::getScientists(QString QSorder, QString QSfilter) { vector<Scientist> scientists; QSqlQuery querySort(db); querySort.prepare("SELECT * FROM Scientists ORDER BY " + QSorder + " " + QSfilter); querySort.exec(); while (querySort.next()) { int scientistID = querySort.value("ScientistID").toUInt(); string name = querySort.value("Name").toString().toStdString(); string gender = querySort.value("Gender").toString().toStdString(); int yearOfBirth = querySort.value("Birthyear").toUInt(); int yearOfDeath = querySort.value("Deathyear").toUInt(); Scientist scientist(scientistID, name, gender, yearOfBirth, yearOfDeath); scientists.push_back(scientist); } return scientists; } bool DbManager::addScientist(const Scientist& scientist) const { //bool message = ""; QSqlQuery queryAdd(db); queryAdd.prepare("INSERT INTO scientists (Name, Gender, BirthYear, DeathYear) VALUES (:Name, :Gender, :BirthYear, :DeathYear)"); queryAdd.bindValue(":Name", QString::fromStdString(scientist.getName())); queryAdd.bindValue(":Gender", QString::fromStdString(scientist.getGender())); queryAdd.bindValue(":BirthYear", scientist.getYearOfBirth()); queryAdd.bindValue(":DeathYear", scientist.getYearOfDeath()); if(queryAdd.exec()) { //message = "Scientist added successfully! "; return true; } else { //message = "Add scientist failed! "; return false; } //return message; } // Deletes scientist with chosen ID number from database void DbManager::deleteScientist(const int ID) { QSqlQuery queryDelete(db); queryDelete.prepare("DELETE FROM Scientists WHERE ScientistID = (:ScientistID)"); queryDelete.bindValue(":ScientistID",ID); queryDelete.exec(); } // Gets computer and his information from database(SQL) and reads into Computer vector // Optional (QS)order, Name, Gender, BirthYear, DeathYear. Optional (QS)filter DESC and ASC vector<Computer> DbManager::getComputers(QString QSorder, QString QSfilter) { vector<Computer> computers; QSqlQuery query(db); query.prepare("SELECT * FROM Computers ORDER BY " + QSorder + " " + QSfilter); query.exec(); while (query.next()) { int computerID = query.value("ComputerID").toUInt(); string name = query.value("Name").toString().toStdString(); int yearBuilt = query.value("Yearbuilt").toUInt(); string type = query.value("Type").toString().toStdString(); bool built = query.value("Built").toBool(); Computer computer(computerID, name, yearBuilt, type, built); computers.push_back(computer); } return computers; } bool DbManager::addComputer(const Computer& computer) const { bool cMessage = ""; QSqlQuery queryAdd; queryAdd.prepare("INSERT INTO computers (ComputerID ,Name, Yearbuilt, Type, Built) VALUES (:ComputerID, :Name, :Yearbuilt, :Type, :Built)"); queryAdd.bindValue(":ComputerID", computer.getComputerID()); queryAdd.bindValue(":Name", QString::fromStdString(computer.getName())); queryAdd.bindValue(":Yearbuilt", computer.getYearBuilt()); queryAdd.bindValue(":Type", QString::fromStdString(computer.getType())); queryAdd.bindValue(":Built", computer.getBuilt()); if(queryAdd.exec()) { cMessage = "Computer added successfully! "; return true; } else { cMessage = "Add computer failed! "; return false; } return cMessage; } // Returns vector with all computers associated with the scientist/s vector<Computer> DbManager::intersectScientist(const string& id) { vector<Computer> intersectedComputers; QSqlQuery intersectQuery(db); intersectQuery.prepare("SELECT * FROM Computers INNER JOIN Computers_Scientists ON Computers.ComputerID = Computers_Scientists.ComputerID INNER JOIN Scientists ON Scientists.ScientistID = Computers_Scientists.ScientistID WHERE Scientists.ScientistID = :id"); intersectQuery.bindValue(":id", QString::fromStdString(id)); intersectQuery.exec(); while (intersectQuery.next()) { int computerID = intersectQuery.value("ComputerID").toUInt(); string name = intersectQuery.value("Name").toString().toStdString(); int yearBuilt = intersectQuery.value("Yearbuilt").toUInt(); string type = intersectQuery.value("Type").toString().toStdString(); bool built = intersectQuery.value("Built").toBool(); Computer computer(computerID, name, yearBuilt, type, built); intersectedComputers.push_back(computer); } return intersectedComputers; } // Returns vector with all computers associated with the scientist/s vector<Scientist> DbManager::intersectComputer(const string& id) { vector<Scientist> intersectedScientists; QSqlQuery intersectQuery(db); intersectQuery.prepare("SELECT * FROM Scientists INNER JOIN Computers_Scientists ON Scientists.ScientistID = Computers_Scientists.ScientistID INNER JOIN Computers ON Computers.ComputerID = Computers_Scientists.ComputerID WHERE Computers.ComputerID = :id"); intersectQuery.bindValue(":id", QString::fromStdString(id)); intersectQuery.exec(); while (intersectQuery.next()) { int scientistID = intersectQuery.value("ScientistID").toUInt(); string name = intersectQuery.value("Name").toString().toStdString(); string gender = intersectQuery.value("Gender").toString().toStdString(); int yearOfBirth = intersectQuery.value("Birthyear").toUInt(); int yearOfDeath = intersectQuery.value("Deathyear").toUInt(); Scientist scientist(scientistID, name, gender, yearOfBirth, yearOfDeath); intersectedScientists.push_back(scientist); } return intersectedScientists; } // Gets the info on Scientist which is searced for vector<Scientist> DbManager::searchScientist(const string& searchData) { vector<Scientist> foundScientist; db.open(); QSqlQuery query(db); if (isdigit(searchData.at(0))) { query.exec("SELECT * FROM Scientists WHERE (Birthyear || Deathyear) LIKE '%" + QString::fromStdString(searchData) + "%'"); } else { query.exec("SELECT * FROM Scientists WHERE (Name || Gender) LIKE '%" + QString::fromStdString(searchData) + "%'"); } while (query.next()) { int scientistID = query.value("ScientistID").toUInt(); string name = query.value("Name").toString().toStdString(); string gender = query.value("Gender").toString().toStdString(); int yearOfBirth = query.value("Birthyear").toUInt(); int yearOfDeath = query.value("Deathyear").toUInt(); Scientist scientist(scientistID, name, gender, yearOfBirth, yearOfDeath); foundScientist.push_back(scientist); } return foundScientist; } // Gets the info on Computer which is searched for vector<Computer> DbManager::searchComputer(string& searchData) { vector<Computer> foundComputer; QSqlQuery query(db); if (isdigit(searchData.at(0))) { query.exec("SELECT * FROM Computers WHERE (Yearbuilt) LIKE '%" + QString::fromStdString(searchData) + "%'"); } else { query.exec("SELECT * FROM Computers WHERE (Name || Type) LIKE '%" + QString::fromStdString(searchData) + "%'"); } while(query.next()) { int computerID = query.value("ComputerID").toUInt(); string name = query.value("Name").toString().toStdString(); int yearBuilt = query.value("Yearbuilt").toUInt(); string type = query.value("Type").toString().toStdString(); bool built = query.value("Built").toBool(); Computer computer(computerID, name, yearBuilt, type, built); foundComputer.push_back(computer); } return foundComputer; } <|endoftext|>
<commit_before>/** * @file FunctionApproximator.cpp * @brief FunctionApproximator class source file. * @author Freek Stulp * * This file is part of DmpBbo, a set of libraries and programs for the * black-box optimization of dynamical movement primitives. * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech * * DmpBbo is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>. */ #include "functionapproximators/FunctionApproximator.hpp" #include "functionapproximators/ModelParameters.hpp" #include "functionapproximators/MetaParameters.hpp" #include "functionapproximators/UnifiedModel.hpp" #include "dmpbbo_io/EigenFileIO.hpp" #include "dmpbbo_io/EigenBoostSerialization.hpp" #include "dmpbbo_io/BoostSerializationToString.hpp" #include <iostream> #include <fstream> #include <eigen3/Eigen/Core> #include <boost/filesystem.hpp> // Required only for train(inputs,outputs,save_directory) using namespace std; using namespace Eigen; /** \ingroup FunctionApproximators */ namespace DmpBbo { /******************************************************************************/ FunctionApproximator::FunctionApproximator(const MetaParameters *const meta_parameters, const ModelParameters *const model_parameters) { // At least one of them should not be NULL assert(meta_parameters!=NULL || model_parameters!=NULL); if (meta_parameters==NULL) meta_parameters_ = NULL; else meta_parameters_ = meta_parameters->clone(); if (model_parameters==NULL) model_parameters_ = NULL; else model_parameters_ = model_parameters->clone(); // If both meta- and model-parameters were set, check if they have the same expected input dim. if (meta_parameters_!=NULL && model_parameters_!=NULL) assert(model_parameters_->getExpectedInputDim()==meta_parameters_->getExpectedInputDim()); } FunctionApproximator::FunctionApproximator(const ModelParameters *const model_parameters) { assert(model_parameters!=NULL); meta_parameters_ = NULL; model_parameters_ = model_parameters->clone(); } FunctionApproximator::~FunctionApproximator(void) { delete meta_parameters_; delete model_parameters_; } /******************************************************************************/ const MetaParameters* FunctionApproximator::getMetaParameters(void) const { return meta_parameters_; }; /******************************************************************************/ const ModelParameters* FunctionApproximator::getModelParameters(void) const { return model_parameters_; }; /******************************************************************************/ void FunctionApproximator::setModelParameters(ModelParameters* model_parameters) { if (model_parameters_!=NULL) { delete model_parameters_; model_parameters_ = NULL; } model_parameters_ = model_parameters; } UnifiedModel* FunctionApproximator::getUnifiedModel(void) const { return model_parameters_->toUnifiedModel(); } int FunctionApproximator::getExpectedInputDim(void) const { if (model_parameters_!=NULL) return model_parameters_->getExpectedInputDim(); else return meta_parameters_->getExpectedInputDim(); } int FunctionApproximator::getExpectedOutputDim(void) const { if (model_parameters_!=NULL) return model_parameters_->getExpectedOutputDim(); else return meta_parameters_->getExpectedOutputDim(); } void FunctionApproximator::reTrain(const Eigen::Ref<const Eigen::MatrixXd>& inputs, const Eigen::Ref<const Eigen::MatrixXd>& targets) { delete model_parameters_; model_parameters_ = NULL; train(inputs,targets); } void FunctionApproximator::reTrain(const Eigen::Ref<const Eigen::MatrixXd>& inputs, const Eigen::Ref<const Eigen::MatrixXd>& targets, std::string save_directory, bool overwrite) { delete model_parameters_; model_parameters_ = NULL; train(inputs,targets,save_directory,overwrite); } void FunctionApproximator::getParameterVectorSelectedMinMax(Eigen::VectorXd& min, Eigen::VectorXd& max) const { if (model_parameters_==NULL) { cerr << __FILE__ << ":" << __LINE__ << ": Warning: Trying to access model parameters of the function approximator, but it has not been trained yet. Returning empty parameter vector." << endl; min.resize(0); max.resize(0); return; } model_parameters_->getParameterVectorSelectedMinMax(min,max); } /******************************************************************************/ bool FunctionApproximator::checkModelParametersInitialized(void) const { if (model_parameters_==NULL) { cerr << "Warning: Trying to access model parameters of the function approximator, but it has not been trained yet. Returning empty parameter vector." << endl; return false; } return true; } /******************************************************************************/ void FunctionApproximator::getParameterVectorSelected(VectorXd& values, bool normalized) const { if (checkModelParametersInitialized()) model_parameters_->getParameterVectorSelected(values, normalized); else values.resize(0); } /******************************************************************************/ int FunctionApproximator::getParameterVectorSelectedSize(void) const { if (checkModelParametersInitialized()) return model_parameters_->getParameterVectorSelectedSize(); else return 0; } void FunctionApproximator::setParameterVectorSelected(const VectorXd& values, bool normalized) { if (checkModelParametersInitialized()) model_parameters_->setParameterVectorSelected(values, normalized); } void FunctionApproximator::setSelectedParameters(const set<string>& selected_values_labels) { if (checkModelParametersInitialized()) model_parameters_->setSelectedParameters(selected_values_labels); } void FunctionApproximator::getSelectableParameters(set<string>& labels) const { if (checkModelParametersInitialized()) model_parameters_->getSelectableParameters(labels); else labels.clear(); } void FunctionApproximator::getParameterVectorMask(const std::set<std::string> selected_values_labels, Eigen::VectorXi& selected_mask) const { if (checkModelParametersInitialized()) model_parameters_->getParameterVectorMask(selected_values_labels,selected_mask); else selected_mask.resize(0); }; int FunctionApproximator::getParameterVectorAllSize(void) const { if (checkModelParametersInitialized()) return model_parameters_->getParameterVectorAllSize(); else return 0; }; void FunctionApproximator::getParameterVectorAll(Eigen::VectorXd& values) const { if (checkModelParametersInitialized()) model_parameters_->getParameterVectorAll(values); else values.resize(0); }; void FunctionApproximator::setParameterVectorAll(const Eigen::VectorXd& values) { if (checkModelParametersInitialized()) model_parameters_->setParameterVectorAll(values); }; string FunctionApproximator::toString(void) const { string name = "FunctionApproximator"+getName(); RETURN_STRING_FROM_BOOST_SERIALIZATION_XML(name.c_str()); } void FunctionApproximator::generateInputsGrid(const Eigen::VectorXd& min, const Eigen::VectorXd& max, const Eigen::VectorXi& n_samples_per_dim, Eigen::MatrixXd& inputs_grid) { int n_dims = min.size(); assert(n_dims==max.size()); assert(n_dims==n_samples_per_dim.size()); if (n_dims==1) { inputs_grid = VectorXd::LinSpaced(n_samples_per_dim[0], min[0], max[0]); } else if (n_dims==2) { int n_samples = n_samples_per_dim[0]*n_samples_per_dim[1]; inputs_grid = MatrixXd::Zero(n_samples, n_dims); VectorXd x1 = VectorXd::LinSpaced(n_samples_per_dim[0], min[0], max[0]); VectorXd x2 = VectorXd::LinSpaced(n_samples_per_dim[1], min[1], max[1]); for (int ii=0; ii<x1.size(); ii++) { for (int jj=0; jj<x2.size(); jj++) { inputs_grid(ii*x2.size()+jj,0) = x1[ii]; inputs_grid(ii*x2.size()+jj,1) = x2[jj]; } } } else { cerr << __FILE__ << ":" << __LINE__ << ":"; cerr << "Can only generate input grids for n_dims<3, but found " << n_dims << endl; } } bool FunctionApproximator::saveGridData(const VectorXd& min, const VectorXd& max, const VectorXi& n_samples_per_dim, string save_directory, bool overwrite) const { if (save_directory.empty()) return true; //MatrixXd inputs; //FunctionApproximator::generateInputsGrid(min, max, n_samples_per_dim, inputs); if (model_parameters_==NULL) return false; UnifiedModel* mp_unified = model_parameters_->toUnifiedModel(); if (mp_unified==NULL) return false; return mp_unified->saveGridData(min,max,n_samples_per_dim,save_directory,overwrite); } void FunctionApproximator::train(const Eigen::Ref<const Eigen::MatrixXd>& inputs, const Eigen::Ref<const Eigen::MatrixXd>& targets, std::string save_directory, bool overwrite) { train(inputs,targets); if (save_directory.empty()) return; if (!isTrained()) return; if (getExpectedInputDim()<3) { VectorXd min = inputs.colwise().minCoeff(); VectorXd max = inputs.colwise().maxCoeff(); int n_samples_per_dim = 100; if (getExpectedInputDim()==2) n_samples_per_dim = 40; VectorXi n_samples_per_dim_vec = VectorXi::Constant(getExpectedInputDim(),n_samples_per_dim); MatrixXd inputs_grid; FunctionApproximator::generateInputsGrid(min, max, n_samples_per_dim_vec, inputs_grid); MatrixXd outputs_grid(inputs_grid.rows(),getExpectedOutputDim()); predict(inputs_grid,outputs_grid); saveMatrix(save_directory,"n_samples_per_dim.txt",n_samples_per_dim_vec,overwrite); saveMatrix(save_directory,"inputs_grid.txt",inputs_grid,overwrite); saveMatrix(save_directory,"outputs_grid.txt",outputs_grid,overwrite); MatrixXd variances_grid(inputs_grid.rows(),getExpectedOutputDim()); predictVariance(inputs_grid,variances_grid); if (!variances_grid.size()==0) { variances_grid = variances_grid.array().sqrt(); saveMatrix(save_directory,"variances_grid.txt",variances_grid,overwrite); } saveGridData(min, max, n_samples_per_dim_vec, save_directory, overwrite); } MatrixXd outputs(inputs.rows(),getExpectedOutputDim()); predict(inputs,outputs); // saveMatrix does not accept Ref, but only Matrix MatrixXd save_matrix; save_matrix = inputs; saveMatrix(save_directory,"inputs.txt",save_matrix,overwrite); save_matrix = targets; saveMatrix(save_directory,"targets.txt",save_matrix,overwrite); save_matrix = outputs; saveMatrix(save_directory,"outputs.txt",save_matrix,overwrite); string filename = save_directory+"/plotdata.py"; ofstream outfile; outfile.open(filename.c_str()); if (!outfile.is_open()) { cerr << __FILE__ << ":" << __LINE__ << ":"; cerr << "Could not open file " << filename << " for writing." << endl; } else { // Python code generation in C++. Rock 'n' roll! ;-) if (inputs.cols()==2) { outfile << "from mpl_toolkits.mplot3d import Axes3D \n"; } outfile << "import numpy \n"; outfile << "import matplotlib.pyplot as plt \n"; outfile << "directory = '" << save_directory << "' \n"; outfile << "inputs = numpy.loadtxt(directory+'/inputs.txt') \n"; outfile << "targets = numpy.loadtxt(directory+'/targets.txt') \n"; outfile << "outputs = numpy.loadtxt(directory+'/outputs.txt') \n"; outfile << "fig = plt.figure() \n"; if (inputs.cols()==2) { outfile << "ax = Axes3D(fig) \n"; outfile << "ax.plot(inputs[:,0],inputs[:,1],targets, '.', label='targets',color='black') \n"; outfile << "ax.plot(inputs[:,0],inputs[:,1],outputs, '.', label='predictions',color='red')\n"; outfile << "ax.set_xlabel('input_1'); ax.set_ylabel('input_2'); ax.set_zlabel('output') \n"; outfile << "ax.legend(loc='lower right') \n"; } else { outfile << "plt.plot(inputs,targets, '.', label='targets',color='black') \n"; outfile << "plt.plot(inputs,outputs, '.', label='predictions',color='red') \n"; outfile << "plt.xlabel('input'); plt.ylabel('output'); \n"; outfile << "plt.legend(loc='lower right') \n"; } outfile << "plt.show() \n"; outfile << endl; outfile.close(); //cout << " ______________________________________________________________" << endl; //cout << " | Plot saved data with:" << " 'python " << filename << "'." << endl; //cout << " |______________________________________________________________" << endl; } } void FunctionApproximator::setParameterVectorModifierPrivate(std::string modifier, bool new_value) { model_parameters_->setParameterVectorModifier(modifier,new_value); } } <commit_msg>Generated plotdata.py scripts use relative directory now.<commit_after>/** * @file FunctionApproximator.cpp * @brief FunctionApproximator class source file. * @author Freek Stulp * * This file is part of DmpBbo, a set of libraries and programs for the * black-box optimization of dynamical movement primitives. * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech * * DmpBbo is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>. */ #include "functionapproximators/FunctionApproximator.hpp" #include "functionapproximators/ModelParameters.hpp" #include "functionapproximators/MetaParameters.hpp" #include "functionapproximators/UnifiedModel.hpp" #include "dmpbbo_io/EigenFileIO.hpp" #include "dmpbbo_io/EigenBoostSerialization.hpp" #include "dmpbbo_io/BoostSerializationToString.hpp" #include <iostream> #include <fstream> #include <eigen3/Eigen/Core> #include <boost/filesystem.hpp> // Required only for train(inputs,outputs,save_directory) using namespace std; using namespace Eigen; /** \ingroup FunctionApproximators */ namespace DmpBbo { /******************************************************************************/ FunctionApproximator::FunctionApproximator(const MetaParameters *const meta_parameters, const ModelParameters *const model_parameters) { // At least one of them should not be NULL assert(meta_parameters!=NULL || model_parameters!=NULL); if (meta_parameters==NULL) meta_parameters_ = NULL; else meta_parameters_ = meta_parameters->clone(); if (model_parameters==NULL) model_parameters_ = NULL; else model_parameters_ = model_parameters->clone(); // If both meta- and model-parameters were set, check if they have the same expected input dim. if (meta_parameters_!=NULL && model_parameters_!=NULL) assert(model_parameters_->getExpectedInputDim()==meta_parameters_->getExpectedInputDim()); } FunctionApproximator::FunctionApproximator(const ModelParameters *const model_parameters) { assert(model_parameters!=NULL); meta_parameters_ = NULL; model_parameters_ = model_parameters->clone(); } FunctionApproximator::~FunctionApproximator(void) { delete meta_parameters_; delete model_parameters_; } /******************************************************************************/ const MetaParameters* FunctionApproximator::getMetaParameters(void) const { return meta_parameters_; }; /******************************************************************************/ const ModelParameters* FunctionApproximator::getModelParameters(void) const { return model_parameters_; }; /******************************************************************************/ void FunctionApproximator::setModelParameters(ModelParameters* model_parameters) { if (model_parameters_!=NULL) { delete model_parameters_; model_parameters_ = NULL; } model_parameters_ = model_parameters; } UnifiedModel* FunctionApproximator::getUnifiedModel(void) const { return model_parameters_->toUnifiedModel(); } int FunctionApproximator::getExpectedInputDim(void) const { if (model_parameters_!=NULL) return model_parameters_->getExpectedInputDim(); else return meta_parameters_->getExpectedInputDim(); } int FunctionApproximator::getExpectedOutputDim(void) const { if (model_parameters_!=NULL) return model_parameters_->getExpectedOutputDim(); else return meta_parameters_->getExpectedOutputDim(); } void FunctionApproximator::reTrain(const Eigen::Ref<const Eigen::MatrixXd>& inputs, const Eigen::Ref<const Eigen::MatrixXd>& targets) { delete model_parameters_; model_parameters_ = NULL; train(inputs,targets); } void FunctionApproximator::reTrain(const Eigen::Ref<const Eigen::MatrixXd>& inputs, const Eigen::Ref<const Eigen::MatrixXd>& targets, std::string save_directory, bool overwrite) { delete model_parameters_; model_parameters_ = NULL; train(inputs,targets,save_directory,overwrite); } void FunctionApproximator::getParameterVectorSelectedMinMax(Eigen::VectorXd& min, Eigen::VectorXd& max) const { if (model_parameters_==NULL) { cerr << __FILE__ << ":" << __LINE__ << ": Warning: Trying to access model parameters of the function approximator, but it has not been trained yet. Returning empty parameter vector." << endl; min.resize(0); max.resize(0); return; } model_parameters_->getParameterVectorSelectedMinMax(min,max); } /******************************************************************************/ bool FunctionApproximator::checkModelParametersInitialized(void) const { if (model_parameters_==NULL) { cerr << "Warning: Trying to access model parameters of the function approximator, but it has not been trained yet. Returning empty parameter vector." << endl; return false; } return true; } /******************************************************************************/ void FunctionApproximator::getParameterVectorSelected(VectorXd& values, bool normalized) const { if (checkModelParametersInitialized()) model_parameters_->getParameterVectorSelected(values, normalized); else values.resize(0); } /******************************************************************************/ int FunctionApproximator::getParameterVectorSelectedSize(void) const { if (checkModelParametersInitialized()) return model_parameters_->getParameterVectorSelectedSize(); else return 0; } void FunctionApproximator::setParameterVectorSelected(const VectorXd& values, bool normalized) { if (checkModelParametersInitialized()) model_parameters_->setParameterVectorSelected(values, normalized); } void FunctionApproximator::setSelectedParameters(const set<string>& selected_values_labels) { if (checkModelParametersInitialized()) model_parameters_->setSelectedParameters(selected_values_labels); } void FunctionApproximator::getSelectableParameters(set<string>& labels) const { if (checkModelParametersInitialized()) model_parameters_->getSelectableParameters(labels); else labels.clear(); } void FunctionApproximator::getParameterVectorMask(const std::set<std::string> selected_values_labels, Eigen::VectorXi& selected_mask) const { if (checkModelParametersInitialized()) model_parameters_->getParameterVectorMask(selected_values_labels,selected_mask); else selected_mask.resize(0); }; int FunctionApproximator::getParameterVectorAllSize(void) const { if (checkModelParametersInitialized()) return model_parameters_->getParameterVectorAllSize(); else return 0; }; void FunctionApproximator::getParameterVectorAll(Eigen::VectorXd& values) const { if (checkModelParametersInitialized()) model_parameters_->getParameterVectorAll(values); else values.resize(0); }; void FunctionApproximator::setParameterVectorAll(const Eigen::VectorXd& values) { if (checkModelParametersInitialized()) model_parameters_->setParameterVectorAll(values); }; string FunctionApproximator::toString(void) const { string name = "FunctionApproximator"+getName(); RETURN_STRING_FROM_BOOST_SERIALIZATION_XML(name.c_str()); } void FunctionApproximator::generateInputsGrid(const Eigen::VectorXd& min, const Eigen::VectorXd& max, const Eigen::VectorXi& n_samples_per_dim, Eigen::MatrixXd& inputs_grid) { int n_dims = min.size(); assert(n_dims==max.size()); assert(n_dims==n_samples_per_dim.size()); if (n_dims==1) { inputs_grid = VectorXd::LinSpaced(n_samples_per_dim[0], min[0], max[0]); } else if (n_dims==2) { int n_samples = n_samples_per_dim[0]*n_samples_per_dim[1]; inputs_grid = MatrixXd::Zero(n_samples, n_dims); VectorXd x1 = VectorXd::LinSpaced(n_samples_per_dim[0], min[0], max[0]); VectorXd x2 = VectorXd::LinSpaced(n_samples_per_dim[1], min[1], max[1]); for (int ii=0; ii<x1.size(); ii++) { for (int jj=0; jj<x2.size(); jj++) { inputs_grid(ii*x2.size()+jj,0) = x1[ii]; inputs_grid(ii*x2.size()+jj,1) = x2[jj]; } } } else { cerr << __FILE__ << ":" << __LINE__ << ":"; cerr << "Can only generate input grids for n_dims<3, but found " << n_dims << endl; } } bool FunctionApproximator::saveGridData(const VectorXd& min, const VectorXd& max, const VectorXi& n_samples_per_dim, string save_directory, bool overwrite) const { if (save_directory.empty()) return true; //MatrixXd inputs; //FunctionApproximator::generateInputsGrid(min, max, n_samples_per_dim, inputs); if (model_parameters_==NULL) return false; UnifiedModel* mp_unified = model_parameters_->toUnifiedModel(); if (mp_unified==NULL) return false; return mp_unified->saveGridData(min,max,n_samples_per_dim,save_directory,overwrite); } void FunctionApproximator::train(const Eigen::Ref<const Eigen::MatrixXd>& inputs, const Eigen::Ref<const Eigen::MatrixXd>& targets, std::string save_directory, bool overwrite) { train(inputs,targets); if (save_directory.empty()) return; if (!isTrained()) return; if (getExpectedInputDim()<3) { VectorXd min = inputs.colwise().minCoeff(); VectorXd max = inputs.colwise().maxCoeff(); int n_samples_per_dim = 100; if (getExpectedInputDim()==2) n_samples_per_dim = 40; VectorXi n_samples_per_dim_vec = VectorXi::Constant(getExpectedInputDim(),n_samples_per_dim); MatrixXd inputs_grid; FunctionApproximator::generateInputsGrid(min, max, n_samples_per_dim_vec, inputs_grid); MatrixXd outputs_grid(inputs_grid.rows(),getExpectedOutputDim()); predict(inputs_grid,outputs_grid); saveMatrix(save_directory,"n_samples_per_dim.txt",n_samples_per_dim_vec,overwrite); saveMatrix(save_directory,"inputs_grid.txt",inputs_grid,overwrite); saveMatrix(save_directory,"outputs_grid.txt",outputs_grid,overwrite); MatrixXd variances_grid(inputs_grid.rows(),getExpectedOutputDim()); predictVariance(inputs_grid,variances_grid); if (!variances_grid.size()==0) { variances_grid = variances_grid.array().sqrt(); saveMatrix(save_directory,"variances_grid.txt",variances_grid,overwrite); } saveGridData(min, max, n_samples_per_dim_vec, save_directory, overwrite); } MatrixXd outputs(inputs.rows(),getExpectedOutputDim()); predict(inputs,outputs); // saveMatrix does not accept Ref, but only Matrix MatrixXd save_matrix; save_matrix = inputs; saveMatrix(save_directory,"inputs.txt",save_matrix,overwrite); save_matrix = targets; saveMatrix(save_directory,"targets.txt",save_matrix,overwrite); save_matrix = outputs; saveMatrix(save_directory,"outputs.txt",save_matrix,overwrite); string filename = save_directory+"/plotdata.py"; ofstream outfile; outfile.open(filename.c_str()); if (!outfile.is_open()) { cerr << __FILE__ << ":" << __LINE__ << ":"; cerr << "Could not open file " << filename << " for writing." << endl; } else { // Python code generation in C++. Rock 'n' roll! ;-) if (inputs.cols()==2) { outfile << "from mpl_toolkits.mplot3d import Axes3D \n"; } outfile << "import numpy \n"; outfile << "import matplotlib.pyplot as plt \n"; outfile << "directory = '" << "./" << "' \n"; outfile << "inputs = numpy.loadtxt(directory+'/inputs.txt') \n"; outfile << "targets = numpy.loadtxt(directory+'/targets.txt') \n"; outfile << "outputs = numpy.loadtxt(directory+'/outputs.txt') \n"; outfile << "fig = plt.figure() \n"; if (inputs.cols()==2) { outfile << "ax = Axes3D(fig) \n"; outfile << "ax.plot(inputs[:,0],inputs[:,1],targets, '.', label='targets',color='black') \n"; outfile << "ax.plot(inputs[:,0],inputs[:,1],outputs, '.', label='predictions',color='red')\n"; outfile << "ax.set_xlabel('input_1'); ax.set_ylabel('input_2'); ax.set_zlabel('output') \n"; outfile << "ax.legend(loc='lower right') \n"; } else { outfile << "plt.plot(inputs,targets, '.', label='targets',color='black') \n"; outfile << "plt.plot(inputs,outputs, '.', label='predictions',color='red') \n"; outfile << "plt.xlabel('input'); plt.ylabel('output'); \n"; outfile << "plt.legend(loc='lower right') \n"; } outfile << "plt.show() \n"; outfile << endl; outfile.close(); //cout << " ______________________________________________________________" << endl; //cout << " | Plot saved data with:" << " 'python " << filename << "'." << endl; //cout << " |______________________________________________________________" << endl; } } void FunctionApproximator::setParameterVectorModifierPrivate(std::string modifier, bool new_value) { model_parameters_->setParameterVectorModifier(modifier,new_value); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: syswin.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-04-11 18:13:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_SYSWIN_HXX #define _SV_SYSWIN_HXX #ifndef _SV_SV_H #include <vcl/sv.h> #endif #ifndef _VCL_DLLAPI_H #include <vcl/dllapi.h> #endif #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif class ModalDialog; class MenuBar; class TaskPaneList; // -------------- // - Icon-Types - // -------------- #define ICON_DEFAULT 0 #define ICON_SO_DEFAULT 1 #define ICON_TEXT_DOCUMENT 2 #define ICON_TEXT_TEMPLATE 3 #define ICON_SPREADSHEET_DOCUMENT 4 #define ICON_SPREADSHEET_TEMPLATE 5 #define ICON_DRAWING_DOCUMENT 6 #define ICON_DRAWING_TEMPLATE 7 #define ICON_PRESENTATION_DOCUMENT 8 #define ICON_PRESENTATION_TEMPLATE 9 #define ICON_PRESENTATION_COMPRESSED 10 #define ICON_GLOBAL_DOCUMENT 11 #define ICON_HTML_DOCUMENT 12 #define ICON_CHART_DOCUMENT 13 #define ICON_DATABASE_DOCUMENT 14 #define ICON_MATH_DOCUMENT 15 #define ICON_TEMPLATE 16 #define ICON_MACROLIBRARY 17 #define ICON_PLAYER 100 #define ICON_SETUP 500 // ------------------- // - WindowStateData - // ------------------- #define WINDOWSTATE_MASK_X ((ULONG)0x00000001) #define WINDOWSTATE_MASK_Y ((ULONG)0x00000002) #define WINDOWSTATE_MASK_WIDTH ((ULONG)0x00000004) #define WINDOWSTATE_MASK_HEIGHT ((ULONG)0x00000008) #define WINDOWSTATE_MASK_STATE ((ULONG)0x00000010) #define WINDOWSTATE_MASK_MINIMIZED ((ULONG)0x00000020) #define WINDOWSTATE_MASK_MAXIMIZED_X ((ULONG)0x00000100) #define WINDOWSTATE_MASK_MAXIMIZED_Y ((ULONG)0x00000200) #define WINDOWSTATE_MASK_MAXIMIZED_WIDTH ((ULONG)0x00000400) #define WINDOWSTATE_MASK_MAXIMIZED_HEIGHT ((ULONG)0x00000800) #define WINDOWSTATE_MASK_POS (WINDOWSTATE_MASK_X | WINDOWSTATE_MASK_Y) #define WINDOWSTATE_MASK_ALL (WINDOWSTATE_MASK_X | WINDOWSTATE_MASK_Y | WINDOWSTATE_MASK_WIDTH | WINDOWSTATE_MASK_HEIGHT | WINDOWSTATE_MASK_MAXIMIZED_X | WINDOWSTATE_MASK_MAXIMIZED_Y | WINDOWSTATE_MASK_MAXIMIZED_WIDTH | WINDOWSTATE_MASK_MAXIMIZED_HEIGHT | WINDOWSTATE_MASK_STATE | WINDOWSTATE_MASK_MINIMIZED) #define WINDOWSTATE_STATE_NORMAL ((ULONG)0x00000001) #define WINDOWSTATE_STATE_MINIMIZED ((ULONG)0x00000002) #define WINDOWSTATE_STATE_MAXIMIZED ((ULONG)0x00000004) #define WINDOWSTATE_STATE_ROLLUP ((ULONG)0x00000008) #define WINDOWSTATE_STATE_MAXIMIZED_HORZ ((ULONG)0x00000010) #define WINDOWSTATE_STATE_MAXIMIZED_VERT ((ULONG)0x00000020) class VCL_DLLPUBLIC WindowStateData { private: sal_uInt32 mnValidMask; int mnX; long mnY; unsigned int mnWidth; unsigned int mnHeight; int mnMaximizedX; int mnMaximizedY; unsigned int mnMaximizedWidth; unsigned int mnMaximizedHeight; sal_uInt32 mnState; public: WindowStateData() { mnValidMask = mnX = mnY = mnWidth = mnHeight = mnState = 0; mnMaximizedX = mnMaximizedY = mnMaximizedWidth = mnMaximizedHeight = 0; } void SetMask( ULONG nValidMask ) { mnValidMask = nValidMask; } sal_uInt32 GetMask() const { return mnValidMask; } void SetX( int nX ) { mnX = nX; } int GetX() const { return mnX; } void SetY( int nY ) { mnY = nY; } unsigned int GetY() const { return mnY; } void SetWidth( unsigned int nWidth ) { mnWidth = nWidth; } unsigned int GetWidth() const { return mnWidth; } void SetHeight( unsigned int nHeight ) { mnHeight = nHeight; } unsigned int GetHeight() const { return mnHeight; } void SetState( sal_uInt32 nState ) { mnState = nState; } sal_uInt32 GetState() const { return mnState; } void SetMaximizedX( int nRX ) { mnMaximizedX = nRX; } int GetMaximizedX() const { return mnMaximizedX; } void SetMaximizedY( int nRY ) { mnMaximizedY = nRY; } int GetMaximizedY() const { return mnMaximizedY; } void SetMaximizedWidth( unsigned int nRWidth ) { mnMaximizedWidth = nRWidth; } unsigned int GetMaximizedWidth() const { return mnMaximizedWidth; } void SetMaximizedHeight( unsigned int nRHeight ) { mnMaximizedHeight = nRHeight; } unsigned int GetMaximizedHeight() const { return mnMaximizedHeight; } }; // ---------------------- // - SystemWindow-Types - // ---------------------- #define MENUBAR_MODE_NORMAL ((USHORT)0) #define MENUBAR_MODE_HIDE ((USHORT)1) #define TITLE_BUTTON_DOCKING ((USHORT)1) #define TITLE_BUTTON_HIDE ((USHORT)2) #define TITLE_BUTTON_MENU ((USHORT)4) // ---------------- // - SystemWindow - // ---------------- class VCL_DLLPUBLIC SystemWindow : public Window { friend class WorkWindow; class ImplData; private: MenuBar* mpMenuBar; Size maOrgSize; Size maRollUpOutSize; Size maMinOutSize; BOOL mbPined; BOOL mbRollUp; BOOL mbRollFunc; BOOL mbDockBtn; BOOL mbHideBtn; BOOL mbSysChild; USHORT mnMenuBarMode; USHORT mnIcon; ImplData* mpImplData; //#if 0 // _SOLAR__PRIVATE public: using Window::ImplIsInTaskPaneList; SAL_DLLPRIVATE BOOL ImplIsInTaskPaneList( Window* pWin ); //#endif private: // Default construction is forbidden and not implemented. SystemWindow(); // Copy assignment is forbidden and not implemented. SystemWindow (const SystemWindow &); SystemWindow & operator= (const SystemWindow &); protected: // Single argument ctors shall be explicit. explicit SystemWindow( WindowType nType ); void SetWindowStateData( const WindowStateData& rData ); public: ~SystemWindow(); virtual long Notify( NotifyEvent& rNEvt ); virtual long PreNotify( NotifyEvent& rNEvt ); virtual BOOL Close(); virtual void TitleButtonClick( USHORT nButton ); virtual void Pin(); virtual void Roll(); virtual void Resizing( Size& rSize ); void SetIcon( USHORT nIcon ); USHORT GetIcon() const { return mnIcon; } void SetZLevel( BYTE nLevel ); BYTE GetZLevel() const; void EnableSaveBackground( BOOL bSave = TRUE ); BOOL IsSaveBackgroundEnabled() const; void ShowTitleButton( USHORT nButton, BOOL bVisible = TRUE ); BOOL IsTitleButtonVisible( USHORT nButton ) const; void SetPin( BOOL bPin ); BOOL IsPined() const { return mbPined; } void RollUp(); void RollDown(); BOOL IsRollUp() const { return mbRollUp; } void SetRollUpOutputSizePixel( const Size& rSize ) { maRollUpOutSize = rSize; } Size GetRollUpOutputSizePixel() const { return maRollUpOutSize; } void SetMinOutputSizePixel( const Size& rSize ); const Size& GetMinOutputSizePixel() const { return maMinOutSize; } void SetMaxOutputSizePixel( const Size& rSize ); const Size& GetMaxOutputSizePixel() const; Size GetResizeOutputSizePixel() const; void SetWindowState( const ByteString& rStr ); ByteString GetWindowState( ULONG nMask = WINDOWSTATE_MASK_ALL ) const; void SetMenuBar( MenuBar* pMenuBar ); MenuBar* GetMenuBar() const { return mpMenuBar; } void SetMenuBarMode( USHORT nMode ); USHORT GetMenuBarMode() const { return mnMenuBarMode; } TaskPaneList* GetTaskPaneList(); void GetWindowStateData( WindowStateData& rData ) const; }; #endif // _SV_SYSWIN_HXX <commit_msg>INTEGRATION: CWS vcl84 (1.2.200); FILE MERGED 2007/10/29 11:12:35 pl 1.2.200.1: #i83080# protect against wrong input<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: syswin.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2007-12-12 13:19:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_SYSWIN_HXX #define _SV_SYSWIN_HXX #ifndef _SV_SV_H #include <vcl/sv.h> #endif #ifndef _VCL_DLLAPI_H #include <vcl/dllapi.h> #endif #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif class ModalDialog; class MenuBar; class TaskPaneList; // -------------- // - Icon-Types - // -------------- #define ICON_DEFAULT 0 #define ICON_SO_DEFAULT 1 #define ICON_TEXT_DOCUMENT 2 #define ICON_TEXT_TEMPLATE 3 #define ICON_SPREADSHEET_DOCUMENT 4 #define ICON_SPREADSHEET_TEMPLATE 5 #define ICON_DRAWING_DOCUMENT 6 #define ICON_DRAWING_TEMPLATE 7 #define ICON_PRESENTATION_DOCUMENT 8 #define ICON_PRESENTATION_TEMPLATE 9 #define ICON_PRESENTATION_COMPRESSED 10 #define ICON_GLOBAL_DOCUMENT 11 #define ICON_HTML_DOCUMENT 12 #define ICON_CHART_DOCUMENT 13 #define ICON_DATABASE_DOCUMENT 14 #define ICON_MATH_DOCUMENT 15 #define ICON_TEMPLATE 16 #define ICON_MACROLIBRARY 17 #define ICON_PLAYER 100 #define ICON_SETUP 500 // ------------------- // - WindowStateData - // ------------------- #define WINDOWSTATE_MASK_X ((ULONG)0x00000001) #define WINDOWSTATE_MASK_Y ((ULONG)0x00000002) #define WINDOWSTATE_MASK_WIDTH ((ULONG)0x00000004) #define WINDOWSTATE_MASK_HEIGHT ((ULONG)0x00000008) #define WINDOWSTATE_MASK_STATE ((ULONG)0x00000010) #define WINDOWSTATE_MASK_MINIMIZED ((ULONG)0x00000020) #define WINDOWSTATE_MASK_MAXIMIZED_X ((ULONG)0x00000100) #define WINDOWSTATE_MASK_MAXIMIZED_Y ((ULONG)0x00000200) #define WINDOWSTATE_MASK_MAXIMIZED_WIDTH ((ULONG)0x00000400) #define WINDOWSTATE_MASK_MAXIMIZED_HEIGHT ((ULONG)0x00000800) #define WINDOWSTATE_MASK_POS (WINDOWSTATE_MASK_X | WINDOWSTATE_MASK_Y) #define WINDOWSTATE_MASK_ALL (WINDOWSTATE_MASK_X | WINDOWSTATE_MASK_Y | WINDOWSTATE_MASK_WIDTH | WINDOWSTATE_MASK_HEIGHT | WINDOWSTATE_MASK_MAXIMIZED_X | WINDOWSTATE_MASK_MAXIMIZED_Y | WINDOWSTATE_MASK_MAXIMIZED_WIDTH | WINDOWSTATE_MASK_MAXIMIZED_HEIGHT | WINDOWSTATE_MASK_STATE | WINDOWSTATE_MASK_MINIMIZED) #define WINDOWSTATE_STATE_NORMAL ((ULONG)0x00000001) #define WINDOWSTATE_STATE_MINIMIZED ((ULONG)0x00000002) #define WINDOWSTATE_STATE_MAXIMIZED ((ULONG)0x00000004) #define WINDOWSTATE_STATE_ROLLUP ((ULONG)0x00000008) #define WINDOWSTATE_STATE_MAXIMIZED_HORZ ((ULONG)0x00000010) #define WINDOWSTATE_STATE_MAXIMIZED_VERT ((ULONG)0x00000020) class VCL_DLLPUBLIC WindowStateData { private: sal_uInt32 mnValidMask; int mnX; int mnY; unsigned int mnWidth; unsigned int mnHeight; int mnMaximizedX; int mnMaximizedY; unsigned int mnMaximizedWidth; unsigned int mnMaximizedHeight; sal_uInt32 mnState; public: WindowStateData() { mnValidMask = mnX = mnY = mnWidth = mnHeight = mnState = 0; mnMaximizedX = mnMaximizedY = mnMaximizedWidth = mnMaximizedHeight = 0; } void SetMask( ULONG nValidMask ) { mnValidMask = nValidMask; } sal_uInt32 GetMask() const { return mnValidMask; } void SetX( int nX ) { mnX = nX; } int GetX() const { return mnX; } void SetY( int nY ) { mnY = nY; } int GetY() const { return mnY; } void SetWidth( unsigned int nWidth ) { mnWidth = nWidth; } unsigned int GetWidth() const { return mnWidth; } void SetHeight( unsigned int nHeight ) { mnHeight = nHeight; } unsigned int GetHeight() const { return mnHeight; } void SetState( sal_uInt32 nState ) { mnState = nState; } sal_uInt32 GetState() const { return mnState; } void SetMaximizedX( int nRX ) { mnMaximizedX = nRX; } int GetMaximizedX() const { return mnMaximizedX; } void SetMaximizedY( int nRY ) { mnMaximizedY = nRY; } int GetMaximizedY() const { return mnMaximizedY; } void SetMaximizedWidth( unsigned int nRWidth ) { mnMaximizedWidth = nRWidth; } unsigned int GetMaximizedWidth() const { return mnMaximizedWidth; } void SetMaximizedHeight( unsigned int nRHeight ) { mnMaximizedHeight = nRHeight; } unsigned int GetMaximizedHeight() const { return mnMaximizedHeight; } }; // ---------------------- // - SystemWindow-Types - // ---------------------- #define MENUBAR_MODE_NORMAL ((USHORT)0) #define MENUBAR_MODE_HIDE ((USHORT)1) #define TITLE_BUTTON_DOCKING ((USHORT)1) #define TITLE_BUTTON_HIDE ((USHORT)2) #define TITLE_BUTTON_MENU ((USHORT)4) // ---------------- // - SystemWindow - // ---------------- class VCL_DLLPUBLIC SystemWindow : public Window { friend class WorkWindow; class ImplData; private: MenuBar* mpMenuBar; Size maOrgSize; Size maRollUpOutSize; Size maMinOutSize; BOOL mbPined; BOOL mbRollUp; BOOL mbRollFunc; BOOL mbDockBtn; BOOL mbHideBtn; BOOL mbSysChild; USHORT mnMenuBarMode; USHORT mnIcon; ImplData* mpImplData; //#if 0 // _SOLAR__PRIVATE public: using Window::ImplIsInTaskPaneList; SAL_DLLPRIVATE BOOL ImplIsInTaskPaneList( Window* pWin ); //#endif private: // Default construction is forbidden and not implemented. SystemWindow(); // Copy assignment is forbidden and not implemented. SystemWindow (const SystemWindow &); SystemWindow & operator= (const SystemWindow &); protected: // Single argument ctors shall be explicit. explicit SystemWindow( WindowType nType ); void SetWindowStateData( const WindowStateData& rData ); public: ~SystemWindow(); virtual long Notify( NotifyEvent& rNEvt ); virtual long PreNotify( NotifyEvent& rNEvt ); virtual BOOL Close(); virtual void TitleButtonClick( USHORT nButton ); virtual void Pin(); virtual void Roll(); virtual void Resizing( Size& rSize ); void SetIcon( USHORT nIcon ); USHORT GetIcon() const { return mnIcon; } void SetZLevel( BYTE nLevel ); BYTE GetZLevel() const; void EnableSaveBackground( BOOL bSave = TRUE ); BOOL IsSaveBackgroundEnabled() const; void ShowTitleButton( USHORT nButton, BOOL bVisible = TRUE ); BOOL IsTitleButtonVisible( USHORT nButton ) const; void SetPin( BOOL bPin ); BOOL IsPined() const { return mbPined; } void RollUp(); void RollDown(); BOOL IsRollUp() const { return mbRollUp; } void SetRollUpOutputSizePixel( const Size& rSize ) { maRollUpOutSize = rSize; } Size GetRollUpOutputSizePixel() const { return maRollUpOutSize; } void SetMinOutputSizePixel( const Size& rSize ); const Size& GetMinOutputSizePixel() const { return maMinOutSize; } void SetMaxOutputSizePixel( const Size& rSize ); const Size& GetMaxOutputSizePixel() const; Size GetResizeOutputSizePixel() const; void SetWindowState( const ByteString& rStr ); ByteString GetWindowState( ULONG nMask = WINDOWSTATE_MASK_ALL ) const; void SetMenuBar( MenuBar* pMenuBar ); MenuBar* GetMenuBar() const { return mpMenuBar; } void SetMenuBarMode( USHORT nMode ); USHORT GetMenuBarMode() const { return mnMenuBarMode; } TaskPaneList* GetTaskPaneList(); void GetWindowStateData( WindowStateData& rData ) const; }; #endif // _SV_SYSWIN_HXX <|endoftext|>
<commit_before>/* Sirikata libproxyobject -- COLLADA Document Importer * ColladaDocumentImporter.cpp * * Copyright (c) 2009, Mark C. Barnes * 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 Sirikata 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 "ColladaDocumentImporter.hpp" #include <cassert> #include <iostream> #include <sirikata/proxyobject/Meshdata.hpp> /// FIXME: need a culling strategy for this mom std::map<std::string, Meshdata*> meshstore; long Meshdata_counter=1000; namespace Sirikata { namespace Models { ColladaDocumentImporter::ColladaDocumentImporter ( Transfer::URI const& uri, std::tr1::weak_ptr<ProxyMeshObject>pp ) : mDocument ( new ColladaDocument ( uri ) ), mState ( IDLE ), mProxyPtr(pp) { assert((std::cout << "MCB: ColladaDocumentImporter::ColladaDocumentImporter() entered, uri: " << uri << std::endl,true)); // SHA256 hash = SHA256::computeDigest(uri.toString()); /// rest of system uses hash // lastURIString = hash.convertToHexString(); // lastURIString = uri.toString(); if (meshstore.find(mDocument->getURI().toString()) != meshstore.end()) SILOG(collada,fatal,"Got duplicate request for collada document import."); meshstore[mDocument->getURI().toString()] = new Meshdata(); meshstore[mDocument->getURI().toString()]->uri = mDocument->getURI().toString(); } ColladaDocumentImporter::~ColladaDocumentImporter () { assert((std::cout << "MCB: ColladaDocumentImporter::~ColladaDocumentImporter() entered" << std::endl,true)); } ///////////////////////////////////////////////////////////////////// ColladaDocumentPtr ColladaDocumentImporter::getDocument () const { if(!(mState == FINISHED)) { SILOG(collada,fatal,"STATE != Finished reached: malformed COLLADA document"); } return mDocument; } void ColladaDocumentImporter::postProcess () { assert((std::cout << "MCB: ColladaDocumentImporter::postProcess() entered" << std::endl,true)); } ///////////////////////////////////////////////////////////////////// // overrides from COLLADAFW::IWriter void ColladaDocumentImporter::cancel ( COLLADAFW::String const& errorMessage ) { assert((std::cout << "MCB: ColladaDocumentImporter::cancel(" << errorMessage << ") entered" << std::endl,true)); mState = CANCELLED; } void ColladaDocumentImporter::start () { assert((std::cout << "MCB: ColladaDocumentImporter::start() entered" << std::endl,true)); mState = STARTED; } void ColladaDocumentImporter::finish () { assert((std::cout << "MCB: ColladaDocumentImporter::finish() entered" << std::endl,true)); postProcess (); if (meshstore[mDocument->getURI().toString()]->geometry.size() > 0) { // std::tr1::shared_ptr<ProxyMeshObject>(mProxyPtr).get()->meshParsed( mDocument->getURI().toString(), // meshstore[mDocument->getURI().toString()] ); std::tr1::shared_ptr<ProxyMeshObject>(spp)(mProxyPtr); spp->meshParsed( mDocument->getURI().toString(), meshstore[mDocument->getURI().toString()] ); } mState = FINISHED; } bool ColladaDocumentImporter::writeGlobalAsset ( COLLADAFW::FileInfo const* asset ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeGLobalAsset(" << asset << ") entered" << std::endl,true)); bool ok = mDocument->import ( *this, *asset ); meshstore[mDocument->getURI().toString()]->up_axis=asset->getUpAxisType(); return ok; } bool ColladaDocumentImporter::writeScene ( COLLADAFW::Scene const* scene ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeScene(" << scene << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeVisualScene ( COLLADAFW::VisualScene const* visualScene ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeVisualScene(" << visualScene << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeLibraryNodes ( COLLADAFW::LibraryNodes const* libraryNodes ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeLibraryNodes(" << libraryNodes << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeGeometry ( COLLADAFW::Geometry const* geometry ) { String uri = mDocument->getURI().toString(); assert((std::cout << "MCB: ColladaDocumentImporter::writeGeometry(" << geometry << ") entered" << std::endl,true)); COLLADAFW::Mesh const* mesh = dynamic_cast<COLLADAFW::Mesh const*>(geometry); if (!mesh) { std::cerr << "ERROR: we only support collada Mesh\n"; assert(false); } SubMeshGeometry* submesh = new SubMeshGeometry(); submesh->name = mesh->getName(); //COLLADAFW::MeshVertexData const v(mesh->getPositions()); // private data error! COLLADAFW::MeshVertexData const* verts(&(mesh->getPositions())); // but this works? COLLADAFW::MeshVertexData const* norms(&(mesh->getNormals())); COLLADAFW::MeshVertexData const* UVs(&(mesh->getUVCoords())); COLLADAFW::MeshPrimitiveArray const* primitives(&(mesh->getMeshPrimitives())); if (!(*primitives)[0]->getPrimitiveType()==COLLADAFW::MeshPrimitive::TRIANGLES) { std::cerr << "ERROR: we only support collada MeshPrimitive::TRIANGLES\n"; assert(false); } COLLADAFW::UIntValuesArray const* pi(&((*primitives)[0]->getPositionIndices())); COLLADAFW::UIntValuesArray const* ni(&((*primitives)[0]->getNormalIndices())); COLLADAFW::IndexList const* uv_ilist((*primitives)[0]->getUVCoordIndices(0)); // FIXME 0 assert(uv_ilist->getStride() == 2); COLLADAFW::UIntValuesArray const* uvi(&(uv_ilist->getIndices())); int vcnt = verts->getValuesCount(); int ncnt = norms->getValuesCount(); unsigned int icnt = pi->getCount(); int uvcnt = UVs->getValuesCount(); if (icnt != ni->getCount()) { std::cerr << "ERROR: position indices and normal indices differ in length!\n"; assert(false); } if (icnt != uvi->getCount()) { std::cerr << "ERROR: position indices and normal indices differ in length!\n"; assert(false); } COLLADAFW::FloatArray const* vdata = verts->getFloatValues(); COLLADAFW::FloatArray const* ndata = norms->getFloatValues(); COLLADAFW::FloatArray const* uvdata = UVs->getFloatValues(); if (vdata && ndata) { float const* raw = vdata->getData(); for (int i=0; i<vcnt; i+=3) { submesh->positions.push_back(Vector3f(raw[i],raw[i+1],raw[i+2])); } raw = ndata->getData(); for (int i=0; i<ncnt; i+=3) { submesh->normals.push_back(Vector3f(raw[i],raw[i+1],raw[i+2])); } if (uvdata) { raw = uvdata->getData(); for (int i=0; i<uvcnt; i+=2) { submesh->texUVs.push_back(Vector2f(raw[i],raw[i+1])); } } unsigned int const* praw = pi->getData(); unsigned int const* nraw = ni->getData(); unsigned int const* uvraw = uvi->getData(); for (unsigned int i=0; i<icnt; i++) { submesh->position_indices.push_back(praw[i]); submesh->normal_indices.push_back(nraw[i]); submesh->texUV_indices.push_back(uvraw[i]); } } else { std::cerr << "ERROR: ColladaDocumentImporter::writeGeometry: we only support floats right now\n"; assert(false); } meshstore[uri]->geometry.push_back(submesh); bool ok = mDocument->import ( *this, *geometry ); return ok; } bool ColladaDocumentImporter::writeMaterial ( COLLADAFW::Material const* material ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeMaterial(" << material << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeEffect ( COLLADAFW::Effect const* effect ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeEffect(" << effect << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeCamera ( COLLADAFW::Camera const* camera ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeCamera(" << camera << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeImage ( COLLADAFW::Image const* image ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeImage(" << image << ") entered" << std::endl,true)); // This sucks, but we currently handle only one texture. Prefer the first one. if (meshstore[mDocument->getURI().toString()]->texture.size() == 0) meshstore[mDocument->getURI().toString()]->texture = image->getImageURI().getURIString(); /// not really -- among other sins, lowercase! return true; } bool ColladaDocumentImporter::writeLight ( COLLADAFW::Light const* light ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeLight(" << light << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeAnimation ( COLLADAFW::Animation const* animation ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeAnimation(" << animation << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeAnimationList ( COLLADAFW::AnimationList const* animationList ) { assert((std::cout << "MCB: ColladaDocumentImporter::ColladaDocumentImporter() entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeSkinControllerData ( COLLADAFW::SkinControllerData const* skinControllerData ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeSkinControllerData(" << skinControllerData << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeController ( COLLADAFW::Controller const* controller ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeController(" << controller << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeFormulas ( COLLADAFW::Formulas const* formulas ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeFormulas(" << formulas << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeKinematicsScene ( COLLADAFW::KinematicsScene const* kinematicsScene ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeKinematicsScene(" << kinematicsScene << ") entered" << std::endl,true)); return true; } } // namespace Models } // namespace Sirikata <commit_msg>Fix Collada UV parsing to handle no UV coords.<commit_after>/* Sirikata libproxyobject -- COLLADA Document Importer * ColladaDocumentImporter.cpp * * Copyright (c) 2009, Mark C. Barnes * 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 Sirikata 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 "ColladaDocumentImporter.hpp" #include <cassert> #include <iostream> #include <sirikata/proxyobject/Meshdata.hpp> /// FIXME: need a culling strategy for this mom std::map<std::string, Meshdata*> meshstore; long Meshdata_counter=1000; namespace Sirikata { namespace Models { ColladaDocumentImporter::ColladaDocumentImporter ( Transfer::URI const& uri, std::tr1::weak_ptr<ProxyMeshObject>pp ) : mDocument ( new ColladaDocument ( uri ) ), mState ( IDLE ), mProxyPtr(pp) { assert((std::cout << "MCB: ColladaDocumentImporter::ColladaDocumentImporter() entered, uri: " << uri << std::endl,true)); // SHA256 hash = SHA256::computeDigest(uri.toString()); /// rest of system uses hash // lastURIString = hash.convertToHexString(); // lastURIString = uri.toString(); if (meshstore.find(mDocument->getURI().toString()) != meshstore.end()) SILOG(collada,fatal,"Got duplicate request for collada document import."); meshstore[mDocument->getURI().toString()] = new Meshdata(); meshstore[mDocument->getURI().toString()]->uri = mDocument->getURI().toString(); } ColladaDocumentImporter::~ColladaDocumentImporter () { assert((std::cout << "MCB: ColladaDocumentImporter::~ColladaDocumentImporter() entered" << std::endl,true)); } ///////////////////////////////////////////////////////////////////// ColladaDocumentPtr ColladaDocumentImporter::getDocument () const { if(!(mState == FINISHED)) { SILOG(collada,fatal,"STATE != Finished reached: malformed COLLADA document"); } return mDocument; } void ColladaDocumentImporter::postProcess () { assert((std::cout << "MCB: ColladaDocumentImporter::postProcess() entered" << std::endl,true)); } ///////////////////////////////////////////////////////////////////// // overrides from COLLADAFW::IWriter void ColladaDocumentImporter::cancel ( COLLADAFW::String const& errorMessage ) { assert((std::cout << "MCB: ColladaDocumentImporter::cancel(" << errorMessage << ") entered" << std::endl,true)); mState = CANCELLED; } void ColladaDocumentImporter::start () { assert((std::cout << "MCB: ColladaDocumentImporter::start() entered" << std::endl,true)); mState = STARTED; } void ColladaDocumentImporter::finish () { assert((std::cout << "MCB: ColladaDocumentImporter::finish() entered" << std::endl,true)); postProcess (); if (meshstore[mDocument->getURI().toString()]->geometry.size() > 0) { // std::tr1::shared_ptr<ProxyMeshObject>(mProxyPtr).get()->meshParsed( mDocument->getURI().toString(), // meshstore[mDocument->getURI().toString()] ); std::tr1::shared_ptr<ProxyMeshObject>(spp)(mProxyPtr); spp->meshParsed( mDocument->getURI().toString(), meshstore[mDocument->getURI().toString()] ); } mState = FINISHED; } bool ColladaDocumentImporter::writeGlobalAsset ( COLLADAFW::FileInfo const* asset ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeGLobalAsset(" << asset << ") entered" << std::endl,true)); bool ok = mDocument->import ( *this, *asset ); meshstore[mDocument->getURI().toString()]->up_axis=asset->getUpAxisType(); return ok; } bool ColladaDocumentImporter::writeScene ( COLLADAFW::Scene const* scene ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeScene(" << scene << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeVisualScene ( COLLADAFW::VisualScene const* visualScene ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeVisualScene(" << visualScene << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeLibraryNodes ( COLLADAFW::LibraryNodes const* libraryNodes ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeLibraryNodes(" << libraryNodes << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeGeometry ( COLLADAFW::Geometry const* geometry ) { String uri = mDocument->getURI().toString(); assert((std::cout << "MCB: ColladaDocumentImporter::writeGeometry(" << geometry << ") entered" << std::endl,true)); COLLADAFW::Mesh const* mesh = dynamic_cast<COLLADAFW::Mesh const*>(geometry); if (!mesh) { std::cerr << "ERROR: we only support collada Mesh\n"; assert(false); } SubMeshGeometry* submesh = new SubMeshGeometry(); submesh->name = mesh->getName(); //COLLADAFW::MeshVertexData const v(mesh->getPositions()); // private data error! COLLADAFW::MeshVertexData const* verts(&(mesh->getPositions())); // but this works? COLLADAFW::MeshVertexData const* norms(&(mesh->getNormals())); COLLADAFW::MeshVertexData const* UVs(&(mesh->getUVCoords())); COLLADAFW::MeshPrimitiveArray const* primitives(&(mesh->getMeshPrimitives())); if (!(*primitives)[0]->getPrimitiveType()==COLLADAFW::MeshPrimitive::TRIANGLES) { std::cerr << "ERROR: we only support collada MeshPrimitive::TRIANGLES\n"; assert(false); } COLLADAFW::UIntValuesArray const* pi(&((*primitives)[0]->getPositionIndices())); COLLADAFW::UIntValuesArray const* ni(&((*primitives)[0]->getNormalIndices())); COLLADAFW::UIntValuesArray const* uvi = NULL; if ( ((*primitives)[0]->getUVCoordIndicesArray()).getCount() > 0 ) { COLLADAFW::IndexList const* uv_ilist = ((*primitives)[0]->getUVCoordIndices(0)); // FIXME 0 assert(uv_ilist->getStride() == 2); uvi = (&(uv_ilist->getIndices())); } int vcnt = verts->getValuesCount(); int ncnt = norms->getValuesCount(); unsigned int icnt = pi->getCount(); int uvcnt = UVs->getValuesCount(); if (icnt != ni->getCount()) { std::cerr << "ERROR: position indices and normal indices differ in length!\n"; assert(false); } if (uvi != NULL && icnt != uvi->getCount()) { std::cerr << "ERROR: position indices and normal indices differ in length!\n"; assert(false); } COLLADAFW::FloatArray const* vdata = verts->getFloatValues(); COLLADAFW::FloatArray const* ndata = norms->getFloatValues(); COLLADAFW::FloatArray const* uvdata = UVs->getFloatValues(); if (vdata && ndata) { float const* raw = vdata->getData(); for (int i=0; i<vcnt; i+=3) { submesh->positions.push_back(Vector3f(raw[i],raw[i+1],raw[i+2])); } raw = ndata->getData(); for (int i=0; i<ncnt; i+=3) { submesh->normals.push_back(Vector3f(raw[i],raw[i+1],raw[i+2])); } if (uvdata) { raw = uvdata->getData(); for (int i=0; i<uvcnt; i+=2) { submesh->texUVs.push_back(Vector2f(raw[i],raw[i+1])); } } unsigned int const* praw = pi->getData(); unsigned int const* nraw = ni->getData(); unsigned int const* uvraw = uvi != NULL ? uvi->getData() : NULL; for (unsigned int i=0; i<icnt; i++) { submesh->position_indices.push_back(praw[i]); submesh->normal_indices.push_back(nraw[i]); if (uvi != NULL) submesh->texUV_indices.push_back(uvraw[i]); } } else { std::cerr << "ERROR: ColladaDocumentImporter::writeGeometry: we only support floats right now\n"; assert(false); } meshstore[uri]->geometry.push_back(submesh); bool ok = mDocument->import ( *this, *geometry ); return ok; } bool ColladaDocumentImporter::writeMaterial ( COLLADAFW::Material const* material ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeMaterial(" << material << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeEffect ( COLLADAFW::Effect const* effect ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeEffect(" << effect << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeCamera ( COLLADAFW::Camera const* camera ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeCamera(" << camera << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeImage ( COLLADAFW::Image const* image ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeImage(" << image << ") entered" << std::endl,true)); // This sucks, but we currently handle only one texture. Prefer the first one. if (meshstore[mDocument->getURI().toString()]->texture.size() == 0) meshstore[mDocument->getURI().toString()]->texture = image->getImageURI().getURIString(); /// not really -- among other sins, lowercase! return true; } bool ColladaDocumentImporter::writeLight ( COLLADAFW::Light const* light ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeLight(" << light << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeAnimation ( COLLADAFW::Animation const* animation ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeAnimation(" << animation << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeAnimationList ( COLLADAFW::AnimationList const* animationList ) { assert((std::cout << "MCB: ColladaDocumentImporter::ColladaDocumentImporter() entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeSkinControllerData ( COLLADAFW::SkinControllerData const* skinControllerData ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeSkinControllerData(" << skinControllerData << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeController ( COLLADAFW::Controller const* controller ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeController(" << controller << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeFormulas ( COLLADAFW::Formulas const* formulas ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeFormulas(" << formulas << ") entered" << std::endl,true)); return true; } bool ColladaDocumentImporter::writeKinematicsScene ( COLLADAFW::KinematicsScene const* kinematicsScene ) { assert((std::cout << "MCB: ColladaDocumentImporter::writeKinematicsScene(" << kinematicsScene << ") entered" << std::endl,true)); return true; } } // namespace Models } // namespace Sirikata <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ftnfrm.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2006-02-01 14:23:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FTNFRM_HXX #define _FTNFRM_HXX #include "layfrm.hxx" class SwCntntFrm; class SwTxtFtn; class SwBorderAttrs; class SwFtnFrm; //Fuer Fussnoten gibt es einen Speziellen Bereich auf der Seite. Dieser //Bereich ist ein SwFtnContFrm. //Jede Fussnote ist durch einen SwFtnFrm abgegrenzt, dieser nimmt die //Fussnotenabsaetze auf. SwFtnFrm koennen aufgespalten werden, sie gehen //dann auf einer anderen Seite weiter. class SwFtnContFrm: public SwLayoutFrm { public: SwFtnContFrm( SwFrmFmt* ); const SwFtnFrm* FindFootNote() const; virtual SwTwips ShrinkFrm( SwTwips, SZPTR BOOL bTst = FALSE, BOOL bInfo = FALSE ); virtual SwTwips GrowFrm( SwTwips, SZPTR BOOL bTst = FALSE, BOOL bInfo = FALSE ); virtual void Format( const SwBorderAttrs *pAttrs = 0 ); virtual void PaintBorder( const SwRect &, const SwPageFrm *pPage, const SwBorderAttrs & ) const; void PaintLine( const SwRect &, const SwPageFrm * ) const; }; class SwFtnFrm: public SwLayoutFrm { //Zeiger auf den FtnFrm in dem die Fussnote weitergefuehrt wird: // 0 wenn kein Follow vorhanden, // this beim letzten // der Follow sonst. SwFtnFrm *pFollow; SwFtnFrm *pMaster; //Der FtnFrm dessen Follow ich bin. SwCntntFrm *pRef; //In diesem CntntFrm steht die Fussnotenref. SwTxtFtn *pAttr; //Fussnotenattribut (zum wiedererkennen) BOOL bBackMoveLocked : 1; //Absaetze in dieser Fussnote duerfen derzeit //nicht rueckwaerts fliessen. // --> OD 2005-05-18 #i49383# - control unlock of position of lower anchored objects. bool mbUnlockPosOfLowerObjs : 1; // <-- #ifndef PRODUCT protected: virtual SwTwips ShrinkFrm( SwTwips, SZPTR BOOL bTst = FALSE, BOOL bInfo = FALSE ); virtual SwTwips GrowFrm ( SwTwips, SZPTR BOOL bTst = FALSE, BOOL bInfo = FALSE ); #endif public: SwFtnFrm( SwFrmFmt*, SwCntntFrm*, SwTxtFtn* ); virtual void Cut(); virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 ); BOOL operator<( const SwTxtFtn* pTxtFtn ) const; #ifdef PRODUCT const SwCntntFrm *GetRef() const { return pRef; } SwCntntFrm *GetRef() { return pRef; } #else //JP 15.10.2001: in a non pro version test if the attribute has the same // meaning which his reference is const SwCntntFrm *GetRef() const; SwCntntFrm *GetRef(); #endif const SwCntntFrm *GetRefFromAttr() const; SwCntntFrm *GetRefFromAttr(); const SwFtnFrm *GetFollow() const { return pFollow; } SwFtnFrm *GetFollow() { return pFollow; } const SwFtnFrm *GetMaster() const { return pMaster; } SwFtnFrm *GetMaster() { return pMaster; } const SwTxtFtn *GetAttr() const { return pAttr; } SwTxtFtn *GetAttr() { return pAttr; } void SetFollow( SwFtnFrm *pNew ) { pFollow = pNew; } void SetMaster( SwFtnFrm *pNew ) { pMaster = pNew; } void SetRef ( SwCntntFrm *pNew ) { pRef = pNew; } void InvalidateNxtFtnCnts( SwPageFrm* pPage ); void LockBackMove() { bBackMoveLocked = TRUE; } void UnlockBackMove() { bBackMoveLocked = FALSE;} BOOL IsBackMoveLocked() { return bBackMoveLocked; } // Verhindert, dass der letzte Inhalt den SwFtnFrm mitloescht (Cut()) inline void ColLock() { bColLocked = TRUE; } inline void ColUnlock() { bColLocked = FALSE; } // --> OD 2005-05-18 #i49383# inline void UnlockPosOfLowerObjs() { mbUnlockPosOfLowerObjs = true; } inline void KeepLockPosOfLowerObjs() { mbUnlockPosOfLowerObjs = false; } inline bool IsUnlockPosOfLowerObjs() { return mbUnlockPosOfLowerObjs; } // <-- /** search for last content in the current footnote frame OD 2005-12-02 #i27138# @author OD @return SwCntntFrm* pointer to found last content frame. NULL, if none is found. */ SwCntntFrm* FindLastCntnt(); }; #endif //_FTNFRM_HXX <commit_msg>INTEGRATION: CWS swnewtable (1.8.358); FILE MERGED 2006/11/03 15:15:55 fme 1.8.358.1: #i4032# New table concept<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ftnfrm.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2007-02-28 15:45:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FTNFRM_HXX #define _FTNFRM_HXX #include "layfrm.hxx" class SwCntntFrm; class SwTxtFtn; class SwBorderAttrs; class SwFtnFrm; //Fuer Fussnoten gibt es einen Speziellen Bereich auf der Seite. Dieser //Bereich ist ein SwFtnContFrm. //Jede Fussnote ist durch einen SwFtnFrm abgegrenzt, dieser nimmt die //Fussnotenabsaetze auf. SwFtnFrm koennen aufgespalten werden, sie gehen //dann auf einer anderen Seite weiter. class SwFtnContFrm: public SwLayoutFrm { public: SwFtnContFrm( SwFrmFmt* ); const SwFtnFrm* FindFootNote() const; virtual SwTwips ShrinkFrm( SwTwips, BOOL bTst = FALSE, BOOL bInfo = FALSE ); virtual SwTwips GrowFrm ( SwTwips, BOOL bTst = FALSE, BOOL bInfo = FALSE ); virtual void Format( const SwBorderAttrs *pAttrs = 0 ); virtual void PaintBorder( const SwRect &, const SwPageFrm *pPage, const SwBorderAttrs & ) const; void PaintLine( const SwRect &, const SwPageFrm * ) const; }; class SwFtnFrm: public SwLayoutFrm { //Zeiger auf den FtnFrm in dem die Fussnote weitergefuehrt wird: // 0 wenn kein Follow vorhanden, // this beim letzten // der Follow sonst. SwFtnFrm *pFollow; SwFtnFrm *pMaster; //Der FtnFrm dessen Follow ich bin. SwCntntFrm *pRef; //In diesem CntntFrm steht die Fussnotenref. SwTxtFtn *pAttr; //Fussnotenattribut (zum wiedererkennen) BOOL bBackMoveLocked : 1; //Absaetze in dieser Fussnote duerfen derzeit //nicht rueckwaerts fliessen. // --> OD 2005-05-18 #i49383# - control unlock of position of lower anchored objects. bool mbUnlockPosOfLowerObjs : 1; // <-- #ifndef PRODUCT protected: virtual SwTwips ShrinkFrm( SwTwips, BOOL bTst = FALSE, BOOL bInfo = FALSE ); virtual SwTwips GrowFrm ( SwTwips, BOOL bTst = FALSE, BOOL bInfo = FALSE ); #endif public: SwFtnFrm( SwFrmFmt*, SwCntntFrm*, SwTxtFtn* ); virtual void Cut(); virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 ); BOOL operator<( const SwTxtFtn* pTxtFtn ) const; #ifdef PRODUCT const SwCntntFrm *GetRef() const { return pRef; } SwCntntFrm *GetRef() { return pRef; } #else //JP 15.10.2001: in a non pro version test if the attribute has the same // meaning which his reference is const SwCntntFrm *GetRef() const; SwCntntFrm *GetRef(); #endif const SwCntntFrm *GetRefFromAttr() const; SwCntntFrm *GetRefFromAttr(); const SwFtnFrm *GetFollow() const { return pFollow; } SwFtnFrm *GetFollow() { return pFollow; } const SwFtnFrm *GetMaster() const { return pMaster; } SwFtnFrm *GetMaster() { return pMaster; } const SwTxtFtn *GetAttr() const { return pAttr; } SwTxtFtn *GetAttr() { return pAttr; } void SetFollow( SwFtnFrm *pNew ) { pFollow = pNew; } void SetMaster( SwFtnFrm *pNew ) { pMaster = pNew; } void SetRef ( SwCntntFrm *pNew ) { pRef = pNew; } void InvalidateNxtFtnCnts( SwPageFrm* pPage ); void LockBackMove() { bBackMoveLocked = TRUE; } void UnlockBackMove() { bBackMoveLocked = FALSE;} BOOL IsBackMoveLocked() { return bBackMoveLocked; } // Verhindert, dass der letzte Inhalt den SwFtnFrm mitloescht (Cut()) inline void ColLock() { bColLocked = TRUE; } inline void ColUnlock() { bColLocked = FALSE; } // --> OD 2005-05-18 #i49383# inline void UnlockPosOfLowerObjs() { mbUnlockPosOfLowerObjs = true; } inline void KeepLockPosOfLowerObjs() { mbUnlockPosOfLowerObjs = false; } inline bool IsUnlockPosOfLowerObjs() { return mbUnlockPosOfLowerObjs; } // <-- /** search for last content in the current footnote frame OD 2005-12-02 #i27138# @author OD @return SwCntntFrm* pointer to found last content frame. NULL, if none is found. */ SwCntntFrm* FindLastCntnt(); }; #endif //_FTNFRM_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: toxhlp.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 04:02:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TOXHLP_HXX #define _TOXHLP_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _SWUNODEF_HXX #include <swunodef.hxx> #endif namespace drafts { namespace com { namespace sun { namespace star { namespace i18n { class XExtendedIndexEntrySupplier; } namespace lang { class XMultiServiceFactory; } }}}}; class String; class IndexEntrySupplierWrapper { STAR_NMSPC::lang::Locale aLcl; STAR_NMSPC::uno::Reference < com::sun::star::i18n::XExtendedIndexEntrySupplier > xIES; public: IndexEntrySupplierWrapper( const STAR_NMSPC::lang::Locale& rLcl, STAR_REFERENCE( lang::XMultiServiceFactory )& rxMSF ); ~IndexEntrySupplierWrapper(); String GetIndexKey( const String& rTxt, const String& rTxtReading, const STAR_NMSPC::lang::Locale& rLocale ) const; String GetFollowingText( BOOL bMorePages ) const; STAR_NMSPC::uno::Sequence< ::rtl::OUString > GetAlgorithmList( const STAR_NMSPC::lang::Locale& rLcl ) const; sal_Bool LoadAlgorithm( const STAR_NMSPC::lang::Locale& rLcl, const String& sSortAlgorithm, long nOptions ) const; sal_Int16 CompareIndexEntry( const String& rTxt1, const String& rTxtReading1, const STAR_NMSPC::lang::Locale& rLcl1, const String& rTxt2, const String& rTxtReading2, const STAR_NMSPC::lang::Locale& rLcl2 ) const; }; #endif <commit_msg>INTEGRATION: CWS swwarnings (1.5.710); FILE MERGED 2007/03/05 12:45:28 tl 1.5.710.2: #i69287# warning-free code 2007/02/27 13:07:04 tl 1.5.710.1: #i69287# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: toxhlp.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:59:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TOXHLP_HXX #define _TOXHLP_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _SWUNODEF_HXX #include <swunodef.hxx> #endif namespace com { namespace sun { namespace star { namespace i18n { class XExtendedIndexEntrySupplier; } namespace lang { class XMultiServiceFactory; } }}} class String; class IndexEntrySupplierWrapper { STAR_NMSPC::lang::Locale aLcl; STAR_NMSPC::uno::Reference < com::sun::star::i18n::XExtendedIndexEntrySupplier > xIES; public: IndexEntrySupplierWrapper( const STAR_NMSPC::lang::Locale& rLcl, STAR_REFERENCE( lang::XMultiServiceFactory )& rxMSF ); ~IndexEntrySupplierWrapper(); String GetIndexKey( const String& rTxt, const String& rTxtReading, const STAR_NMSPC::lang::Locale& rLocale ) const; String GetFollowingText( BOOL bMorePages ) const; STAR_NMSPC::uno::Sequence< ::rtl::OUString > GetAlgorithmList( const STAR_NMSPC::lang::Locale& rLcl ) const; sal_Bool LoadAlgorithm( const STAR_NMSPC::lang::Locale& rLcl, const String& sSortAlgorithm, long nOptions ) const; sal_Int16 CompareIndexEntry( const String& rTxt1, const String& rTxtReading1, const STAR_NMSPC::lang::Locale& rLcl1, const String& rTxt2, const String& rTxtReading2, const STAR_NMSPC::lang::Locale& rLcl2 ) const; }; #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2015 WinT 3794 <http://wint3794.org> * * 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 <QByteArray> #include <QUdpSocket> #include <QHostAddress> #include "Packets.h" QUdpSocket _SOCKET; unsigned short _INDEX (0); const int _TARGET_PORT (1110); QByteArray DS_GenerateControlPacket (DS_ControlPacket packet) { _INDEX += 1; int byte1 = 0x00; int byte2 = 0x00; int byte3 = 0x01; if (_INDEX <= 0xff) byte2 = _INDEX; else if (_INDEX <= 0xffff) { int index = _INDEX; while (index > 0xff) { index -= 0xff; byte1 += 0x01; } byte2 = copy; } else DS_ResetIndex(); QByteArray data; data.append ((char) byte1); data.append ((char) byte2); data.append ((char) byte3); data.append ((char) packet.mode); data.append ((char) packet.status); data.append ((char) packet.alliance); return data; } void DS_SendControlPacket (DS_ControlPacket packet, QString host) { QByteArray data = DS_GenerateControlPacket (packet); _SOCKET.writeDatagram (data.data(), data.size(), QHostAddress (host), _TARGET_PORT); } void DS_ResetIndex() { _INDEX = 0; } <commit_msg>Update Packets.cpp<commit_after>/* * Copyright (c) 2015 WinT 3794 <http://wint3794.org> * * 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 <QByteArray> #include <QUdpSocket> #include <QHostAddress> #include "Packets.h" QUdpSocket _SOCKET; unsigned short _INDEX (0); const int _TARGET_PORT (1110); QByteArray DS_GenerateControlPacket (DS_ControlPacket packet) { _INDEX += 1; int byte1 = 0x00; int byte2 = 0x00; int byte3 = 0x01; if (_INDEX <= 0xff) byte2 = _INDEX; else if (_INDEX <= 0xffff) { int index = _INDEX; while (index > 0xff) { index -= 0xff; byte1 += 0x01; } byte2 = index; } else DS_ResetIndex(); QByteArray data; data.append ((char) byte1); data.append ((char) byte2); data.append ((char) byte3); data.append ((char) packet.mode); data.append ((char) packet.status); data.append ((char) packet.alliance); return data; } void DS_SendControlPacket (DS_ControlPacket packet, QString host) { QByteArray data = DS_GenerateControlPacket (packet); _SOCKET.writeDatagram (data.data(), data.size(), QHostAddress (host), _TARGET_PORT); } void DS_ResetIndex() { _INDEX = 0; } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/JoynrRuntime.h" #include "joynr/Settings.h" #include "runtimes/libjoynr-runtime/websocket/LibJoynrWebSocketRuntime.h" #include "joynr/Future.h" namespace joynr { JoynrRuntime* JoynrRuntime::createRuntime(const std::string& pathToLibjoynrSettings, const std::string& pathToMessagingSettings) { return createRuntime(createSettings(pathToLibjoynrSettings, pathToMessagingSettings)); } JoynrRuntime* JoynrRuntime::createRuntime(std::unique_ptr<Settings> settings) { Future<std::unique_ptr<JoynrRuntime>> runtimeFuture; auto onSuccessCallback = [&runtimeFuture](std::unique_ptr<JoynrRuntime> createdRuntime) { runtimeFuture.onSuccess(std::move(createdRuntime)); }; auto onErrorCallback = [](exceptions::JoynrRuntimeException&) {}; createRuntimeAsync( std::move(settings), std::move(onSuccessCallback), std::move(onErrorCallback)); std::unique_ptr<JoynrRuntime> runtime; runtimeFuture.get(runtime); return runtime.release(); } void JoynrRuntime::createRuntimeAsync( const std::string& pathToLibjoynrSettings, std::function<void(std::unique_ptr<JoynrRuntime> createdRuntime)> runtimeCreatedCallback, std::function<void(exceptions::JoynrRuntimeException& exception)> runtimeCreationErrorCallback, const std::string& pathToMessagingSettings) { createRuntimeAsync(createSettings(pathToLibjoynrSettings, pathToMessagingSettings), runtimeCreatedCallback, runtimeCreationErrorCallback); } void JoynrRuntime::createRuntimeAsync( std::unique_ptr<Settings> settings, std::function<void(std::unique_ptr<JoynrRuntime> createdRuntime)> runtimeCreatedCallback, std::function<void(exceptions::JoynrRuntimeException& exception)> runtimeCreationErrorCallback) { std::ignore = runtimeCreationErrorCallback; struct ConfigurableDeleter { bool enabled = true; void operator()(JoynrRuntime* ptr) { if (enabled) { delete ptr; } } }; std::shared_ptr<LibJoynrWebSocketRuntime> runtime( new LibJoynrWebSocketRuntime(std::move(settings)), ConfigurableDeleter()); auto runtimeCreatedCallbackWrapper = [ runtime, runtimeCreatedCallback = std::move(runtimeCreatedCallback) ]() { // Workaround. Can't move an unique_ptr into the lambda std::unique_ptr<LibJoynrWebSocketRuntime> createdRuntime(runtime.get()); std::get_deleter<ConfigurableDeleter>(runtime)->enabled = false; runtimeCreatedCallback(std::move(createdRuntime)); }; runtime->connect(std::move(runtimeCreatedCallbackWrapper)); } std::unique_ptr<Settings> JoynrRuntime::createSettings(const std::string& pathToLibjoynrSettings, const std::string& pathToMessagingSettings) { auto settings = std::make_unique<Settings>(pathToLibjoynrSettings); Settings messagingSettings{pathToMessagingSettings}; Settings::merge(messagingSettings, *settings, false); return settings; } } // namespace joynr <commit_msg>[C++] Forward exceptions in sync createRuntime method to caller<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/JoynrRuntime.h" #include "joynr/Settings.h" #include "runtimes/libjoynr-runtime/websocket/LibJoynrWebSocketRuntime.h" #include "joynr/Future.h" namespace joynr { JoynrRuntime* JoynrRuntime::createRuntime(const std::string& pathToLibjoynrSettings, const std::string& pathToMessagingSettings) { return createRuntime(createSettings(pathToLibjoynrSettings, pathToMessagingSettings)); } JoynrRuntime* JoynrRuntime::createRuntime(std::unique_ptr<Settings> settings) { Future<std::unique_ptr<JoynrRuntime>> runtimeFuture; auto onSuccessCallback = [&runtimeFuture](std::unique_ptr<JoynrRuntime> createdRuntime) { runtimeFuture.onSuccess(std::move(createdRuntime)); }; auto onErrorCallback = [&runtimeFuture](exceptions::JoynrRuntimeException& exception) { runtimeFuture.onError( std::shared_ptr<joynr::exceptions::JoynrException>(exception.clone())); }; createRuntimeAsync( std::move(settings), std::move(onSuccessCallback), std::move(onErrorCallback)); std::unique_ptr<JoynrRuntime> runtime; runtimeFuture.get(runtime); return runtime.release(); } void JoynrRuntime::createRuntimeAsync( const std::string& pathToLibjoynrSettings, std::function<void(std::unique_ptr<JoynrRuntime> createdRuntime)> runtimeCreatedCallback, std::function<void(exceptions::JoynrRuntimeException& exception)> runtimeCreationErrorCallback, const std::string& pathToMessagingSettings) { createRuntimeAsync(createSettings(pathToLibjoynrSettings, pathToMessagingSettings), runtimeCreatedCallback, runtimeCreationErrorCallback); } void JoynrRuntime::createRuntimeAsync( std::unique_ptr<Settings> settings, std::function<void(std::unique_ptr<JoynrRuntime> createdRuntime)> runtimeCreatedCallback, std::function<void(exceptions::JoynrRuntimeException& exception)> runtimeCreationErrorCallback) { std::ignore = runtimeCreationErrorCallback; struct ConfigurableDeleter { bool enabled = true; void operator()(JoynrRuntime* ptr) { if (enabled) { delete ptr; } } }; std::shared_ptr<LibJoynrWebSocketRuntime> runtime( new LibJoynrWebSocketRuntime(std::move(settings)), ConfigurableDeleter()); auto runtimeCreatedCallbackWrapper = [ runtime, runtimeCreatedCallback = std::move(runtimeCreatedCallback) ]() { // Workaround. Can't move an unique_ptr into the lambda std::unique_ptr<LibJoynrWebSocketRuntime> createdRuntime(runtime.get()); std::get_deleter<ConfigurableDeleter>(runtime)->enabled = false; runtimeCreatedCallback(std::move(createdRuntime)); }; runtime->connect(std::move(runtimeCreatedCallbackWrapper)); } std::unique_ptr<Settings> JoynrRuntime::createSettings(const std::string& pathToLibjoynrSettings, const std::string& pathToMessagingSettings) { auto settings = std::make_unique<Settings>(pathToLibjoynrSettings); Settings messagingSettings{pathToMessagingSettings}; Settings::merge(messagingSettings, *settings, false); return settings; } } // namespace joynr <|endoftext|>
<commit_before>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "ARMTargetMachine.h" #include "ARMMCAsmInfo.h" #include "ARMFrameInfo.h" #include "ARM.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; static cl::opt<bool> DisableIfConversion("disable-arm-if-conversion",cl::Hidden, cl::desc("Disable if-conversion pass")); static const MCAsmInfo *createMCAsmInfo(const Target &T, const StringRef &TT) { Triple TheTriple(TT); switch (TheTriple.getOS()) { case Triple::Darwin: return new ARMMCAsmInfoDarwin(); default: return new ARMELFMCAsmInfo(); } } extern "C" void LLVMInitializeARMTarget() { // Register the target. RegisterTargetMachine<ARMTargetMachine> X(TheARMTarget); RegisterTargetMachine<ThumbTargetMachine> Y(TheThumbTarget); // Register the target asm info. RegisterAsmInfoFn A(TheARMTarget, createMCAsmInfo); RegisterAsmInfoFn B(TheThumbTarget, createMCAsmInfo); } /// TargetMachine ctor - Create an ARM architecture model. /// ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const std::string &TT, const std::string &FS, bool isThumb) : LLVMTargetMachine(T, TT), Subtarget(TT, FS, isThumb), FrameInfo(Subtarget), JITInfo(), InstrItins(Subtarget.getInstrItineraryData()) { DefRelocModel = getRelocationModel(); } ARMTargetMachine::ARMTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, false), InstrInfo(Subtarget), DataLayout(Subtarget.isAPCS_ABI() ? std::string("e-p:32:32-f64:32:32-i64:32:32") : std::string("e-p:32:32-f64:64:64-i64:64:64")), TLInfo(*this) { } ThumbTargetMachine::ThumbTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, true), InstrInfo(Subtarget.hasThumb2() ? ((ARMBaseInstrInfo*)new Thumb2InstrInfo(Subtarget)) : ((ARMBaseInstrInfo*)new Thumb1InstrInfo(Subtarget))), DataLayout(Subtarget.isAPCS_ABI() ? std::string("e-p:32:32-f64:32:32-i64:32:32-" "i16:16:32-i8:8:32-i1:8:32-a:0:32") : std::string("e-p:32:32-f64:64:64-i64:64:64-" "i16:16:32-i8:8:32-i1:8:32-a:0:32")), TLInfo(*this) { } // Pass Pipeline Configuration bool ARMBaseTargetMachine::addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { PM.add(createARMISelDag(*this)); return false; } bool ARMBaseTargetMachine::addPreRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (Subtarget.hasNEON()) PM.add(createNEONPreAllocPass()); // FIXME: temporarily disabling load / store optimization pass for Thumb mode. if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb()) PM.add(createARMLoadStoreOptimizationPass(true)); return true; } bool ARMBaseTargetMachine::addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { // FIXME: temporarily disabling load / store optimization pass for Thumb1 mode. if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass()); if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb1Only()) PM.add(createIfConverterPass()); if (Subtarget.isThumb2()) { PM.add(createThumb2ITBlockPass()); PM.add(createThumb2SizeReductionPass()); } PM.add(createARMConstantIslandPass()); return true; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, MachineCodeEmitter &MCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMCodeEmitterPass(*this, MCE)); return false; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, JITCodeEmitter &JCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMJITCodeEmitterPass(*this, JCE)); return false; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, ObjectCodeEmitter &OCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMObjectCodeEmitterPass(*this, OCE)); return false; } bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, MachineCodeEmitter &MCE) { // Machine code emitter pass for ARM. PM.add(createARMCodeEmitterPass(*this, MCE)); return false; } bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, JITCodeEmitter &JCE) { // Machine code emitter pass for ARM. PM.add(createARMJITCodeEmitterPass(*this, JCE)); return false; } bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, ObjectCodeEmitter &OCE) { // Machine code emitter pass for ARM. PM.add(createARMObjectCodeEmitterPass(*this, OCE)); return false; } <commit_msg>Really remove this option.<commit_after>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "ARMTargetMachine.h" #include "ARMMCAsmInfo.h" #include "ARMFrameInfo.h" #include "ARM.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; static const MCAsmInfo *createMCAsmInfo(const Target &T, const StringRef &TT) { Triple TheTriple(TT); switch (TheTriple.getOS()) { case Triple::Darwin: return new ARMMCAsmInfoDarwin(); default: return new ARMELFMCAsmInfo(); } } extern "C" void LLVMInitializeARMTarget() { // Register the target. RegisterTargetMachine<ARMTargetMachine> X(TheARMTarget); RegisterTargetMachine<ThumbTargetMachine> Y(TheThumbTarget); // Register the target asm info. RegisterAsmInfoFn A(TheARMTarget, createMCAsmInfo); RegisterAsmInfoFn B(TheThumbTarget, createMCAsmInfo); } /// TargetMachine ctor - Create an ARM architecture model. /// ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const std::string &TT, const std::string &FS, bool isThumb) : LLVMTargetMachine(T, TT), Subtarget(TT, FS, isThumb), FrameInfo(Subtarget), JITInfo(), InstrItins(Subtarget.getInstrItineraryData()) { DefRelocModel = getRelocationModel(); } ARMTargetMachine::ARMTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, false), InstrInfo(Subtarget), DataLayout(Subtarget.isAPCS_ABI() ? std::string("e-p:32:32-f64:32:32-i64:32:32") : std::string("e-p:32:32-f64:64:64-i64:64:64")), TLInfo(*this) { } ThumbTargetMachine::ThumbTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, true), InstrInfo(Subtarget.hasThumb2() ? ((ARMBaseInstrInfo*)new Thumb2InstrInfo(Subtarget)) : ((ARMBaseInstrInfo*)new Thumb1InstrInfo(Subtarget))), DataLayout(Subtarget.isAPCS_ABI() ? std::string("e-p:32:32-f64:32:32-i64:32:32-" "i16:16:32-i8:8:32-i1:8:32-a:0:32") : std::string("e-p:32:32-f64:64:64-i64:64:64-" "i16:16:32-i8:8:32-i1:8:32-a:0:32")), TLInfo(*this) { } // Pass Pipeline Configuration bool ARMBaseTargetMachine::addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { PM.add(createARMISelDag(*this)); return false; } bool ARMBaseTargetMachine::addPreRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (Subtarget.hasNEON()) PM.add(createNEONPreAllocPass()); // FIXME: temporarily disabling load / store optimization pass for Thumb mode. if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb()) PM.add(createARMLoadStoreOptimizationPass(true)); return true; } bool ARMBaseTargetMachine::addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { // FIXME: temporarily disabling load / store optimization pass for Thumb1 mode. if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass()); if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb1Only()) PM.add(createIfConverterPass()); if (Subtarget.isThumb2()) { PM.add(createThumb2ITBlockPass()); PM.add(createThumb2SizeReductionPass()); } PM.add(createARMConstantIslandPass()); return true; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, MachineCodeEmitter &MCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMCodeEmitterPass(*this, MCE)); return false; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, JITCodeEmitter &JCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMJITCodeEmitterPass(*this, JCE)); return false; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, ObjectCodeEmitter &OCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMObjectCodeEmitterPass(*this, OCE)); return false; } bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, MachineCodeEmitter &MCE) { // Machine code emitter pass for ARM. PM.add(createARMCodeEmitterPass(*this, MCE)); return false; } bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, JITCodeEmitter &JCE) { // Machine code emitter pass for ARM. PM.add(createARMJITCodeEmitterPass(*this, JCE)); return false; } bool ARMBaseTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, ObjectCodeEmitter &OCE) { // Machine code emitter pass for ARM. PM.add(createARMObjectCodeEmitterPass(*this, OCE)); return false; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: componentmodule.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2003-03-25 16:03:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _EXTENSIONS_COMPONENT_MODULE_HXX_ #define _EXTENSIONS_COMPONENT_MODULE_HXX_ /** you may find this file helpfull if you implement a component (in it's own library) which can't use the usual infrastructure.<br/> More precise, you find helper classes to ease the use of resources and the registration of services. <p> You need to define a preprocessor variable COMPMOD_NAMESPACE in order to use this file. Set it to a string which should be used as namespace for the classes defined herein.</p> */ #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _TOOLS_RESID_HXX #include <tools/resid.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif class ResMgr; //......................................................................... namespace COMPMOD_NAMESPACE { //......................................................................... typedef ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > (SAL_CALL *FactoryInstantiation) ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rServiceManager, const ::rtl::OUString & _rComponentName, ::cppu::ComponentInstantiation _pCreateFunction, const ::com::sun::star::uno::Sequence< ::rtl::OUString > & _rServiceNames, rtl_ModuleCount* _pModuleCounter ); //========================================================================= //= OModule //========================================================================= class OModuleImpl; class OModule { friend class OModuleResourceClient; private: OModule(); // not implemented. OModule is a static class protected: // resource administration static ::osl::Mutex s_aMutex; /// access safety static sal_Int32 s_nClients; /// number of registered clients static OModuleImpl* s_pImpl; /// impl class. lives as long as at least one client for the module is registered static ::rtl::OString s_sResPrefix; // auto registration administration static ::com::sun::star::uno::Sequence< ::rtl::OUString >* s_pImplementationNames; static ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::rtl::OUString > >* s_pSupportedServices; static ::com::sun::star::uno::Sequence< sal_Int64 >* s_pCreationFunctionPointers; static ::com::sun::star::uno::Sequence< sal_Int64 >* s_pFactoryFunctionPointers; public: // cna be set as long as no resource has been accessed ... static void setResourceFilePrefix(const ::rtl::OString& _rPrefix); /// get the vcl res manager of the module static ResMgr* getResManager(); /** register a component implementing a service with the given data. @param _rImplementationName the implementation name of the component @param _rServiceNames the services the component supports @param _pCreateFunction a function for creating an instance of the component @param _pFactoryFunction a function for creating a factory for that component @see revokeComponent */ static void registerComponent( const ::rtl::OUString& _rImplementationName, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rServiceNames, ::cppu::ComponentInstantiation _pCreateFunction, FactoryInstantiation _pFactoryFunction); /** revoke the registration for the specified component @param _rImplementationName the implementation name of the component */ static void revokeComponent( const ::rtl::OUString& _rImplementationName); /** write the registration information of all known components <p>writes the registration information of all components which are currently registered into the specified registry.<p/> <p>Usually used from within component_writeInfo.<p/> @param _rxServiceManager the service manager @param _rRootKey the registry key under which the information will be stored @return sal_True if the registration of all implementations was successfull, sal_False otherwise */ static sal_Bool writeComponentInfos( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxServiceManager, const ::com::sun::star::uno::Reference< ::com::sun::star::registry::XRegistryKey >& _rRootKey); /** creates a Factory for the component with the given implementation name. <p>Usually used from within component_getFactory.<p/> @param _rxServiceManager a pointer to an XMultiServiceFactory interface as got in component_getFactory @param _pImplementationName the implementation name of the component @return the XInterface access to a factory for the component */ static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getComponentFactory( const ::rtl::OUString& _rImplementationName, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxServiceManager ); protected: /// register a client for the module static void registerClient(); /// revoke a client for the module static void revokeClient(); private: /** ensure that the impl class exists @precond m_aMutex is guarded when this method gets called */ static void ensureImpl(); }; //========================================================================= //= OModuleResourceClient //========================================================================= /** base class for objects which uses any global module-specific ressources */ class OModuleResourceClient { public: OModuleResourceClient() { OModule::registerClient(); } ~OModuleResourceClient() { OModule::revokeClient(); } }; //========================================================================= //= ModuleRes //========================================================================= /** specialized ResId, using the ressource manager provided by the global module */ class ModuleRes : public ::ResId { public: ModuleRes(USHORT _nId) : ResId(_nId, OModule::getResManager()) { } }; //========================================================================== //= OMultiInstanceAutoRegistration //========================================================================== template <class TYPE> class OMultiInstanceAutoRegistration { public: /** automatically registeres a multi instance component <p>Assumed that the template argument has the three methods <ul> <li><code>static ::rtl::OUString getImplementationName_Static()</code><li/> <li><code>static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static()</code><li/> <li><code>static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&)</code> </li> <ul/> the instantiation of this object will automatically register the class via <method>OModule::registerComponent</method>. <p/> The factory creation function used is <code>::cppu::createSingleFactory</code>. @see OOneInstanceAutoRegistration */ OMultiInstanceAutoRegistration(); ~OMultiInstanceAutoRegistration(); }; template <class TYPE> OMultiInstanceAutoRegistration<TYPE>::OMultiInstanceAutoRegistration() { OModule::registerComponent( TYPE::getImplementationName_Static(), TYPE::getSupportedServiceNames_Static(), TYPE::Create, ::cppu::createSingleFactory ); } template <class TYPE> OMultiInstanceAutoRegistration<TYPE>::~OMultiInstanceAutoRegistration() { OModule::revokeComponent(TYPE::getImplementationName_Static()); } //========================================================================== //= OOneInstanceAutoRegistration //========================================================================== template <class TYPE> class OOneInstanceAutoRegistration { public: /** automatically registeres a single instance component <p>Assumed that the template argument has the three methods <ul> <li><code>static ::rtl::OUString getImplementationName_Static()</code><li/> <li><code>static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static()</code><li/> <li><code>static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&)</code> </li> <ul/> the instantiation of this object will automatically register the class via <method>OModule::registerComponent</method>. <p/> The factory creation function used is <code>::cppu::createOneInstanceFactory</code>. @see OOneInstanceAutoRegistration */ OOneInstanceAutoRegistration(); ~OOneInstanceAutoRegistration(); }; template <class TYPE> OOneInstanceAutoRegistration<TYPE>::OOneInstanceAutoRegistration() { OModule::registerComponent( TYPE::getImplementationName_Static(), TYPE::getSupportedServiceNames_Static(), TYPE::Create, ::cppu::createOneInstanceFactory ); } template <class TYPE> OOneInstanceAutoRegistration<TYPE>::~OOneInstanceAutoRegistration() { OModule::revokeComponent(TYPE::getImplementationName_Static()); } //......................................................................... } // namespace COMPMOD_NAMESPACE //......................................................................... #endif // _EXTENSIONS_COMPONENT_MODULE_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.3.504); FILE MERGED 2005/09/05 12:59:05 rt 1.3.504.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: componentmodule.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:34:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EXTENSIONS_COMPONENT_MODULE_HXX_ #define _EXTENSIONS_COMPONENT_MODULE_HXX_ /** you may find this file helpfull if you implement a component (in it's own library) which can't use the usual infrastructure.<br/> More precise, you find helper classes to ease the use of resources and the registration of services. <p> You need to define a preprocessor variable COMPMOD_NAMESPACE in order to use this file. Set it to a string which should be used as namespace for the classes defined herein.</p> */ #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _TOOLS_RESID_HXX #include <tools/resid.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif class ResMgr; //......................................................................... namespace COMPMOD_NAMESPACE { //......................................................................... typedef ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > (SAL_CALL *FactoryInstantiation) ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rServiceManager, const ::rtl::OUString & _rComponentName, ::cppu::ComponentInstantiation _pCreateFunction, const ::com::sun::star::uno::Sequence< ::rtl::OUString > & _rServiceNames, rtl_ModuleCount* _pModuleCounter ); //========================================================================= //= OModule //========================================================================= class OModuleImpl; class OModule { friend class OModuleResourceClient; private: OModule(); // not implemented. OModule is a static class protected: // resource administration static ::osl::Mutex s_aMutex; /// access safety static sal_Int32 s_nClients; /// number of registered clients static OModuleImpl* s_pImpl; /// impl class. lives as long as at least one client for the module is registered static ::rtl::OString s_sResPrefix; // auto registration administration static ::com::sun::star::uno::Sequence< ::rtl::OUString >* s_pImplementationNames; static ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::rtl::OUString > >* s_pSupportedServices; static ::com::sun::star::uno::Sequence< sal_Int64 >* s_pCreationFunctionPointers; static ::com::sun::star::uno::Sequence< sal_Int64 >* s_pFactoryFunctionPointers; public: // cna be set as long as no resource has been accessed ... static void setResourceFilePrefix(const ::rtl::OString& _rPrefix); /// get the vcl res manager of the module static ResMgr* getResManager(); /** register a component implementing a service with the given data. @param _rImplementationName the implementation name of the component @param _rServiceNames the services the component supports @param _pCreateFunction a function for creating an instance of the component @param _pFactoryFunction a function for creating a factory for that component @see revokeComponent */ static void registerComponent( const ::rtl::OUString& _rImplementationName, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rServiceNames, ::cppu::ComponentInstantiation _pCreateFunction, FactoryInstantiation _pFactoryFunction); /** revoke the registration for the specified component @param _rImplementationName the implementation name of the component */ static void revokeComponent( const ::rtl::OUString& _rImplementationName); /** write the registration information of all known components <p>writes the registration information of all components which are currently registered into the specified registry.<p/> <p>Usually used from within component_writeInfo.<p/> @param _rxServiceManager the service manager @param _rRootKey the registry key under which the information will be stored @return sal_True if the registration of all implementations was successfull, sal_False otherwise */ static sal_Bool writeComponentInfos( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxServiceManager, const ::com::sun::star::uno::Reference< ::com::sun::star::registry::XRegistryKey >& _rRootKey); /** creates a Factory for the component with the given implementation name. <p>Usually used from within component_getFactory.<p/> @param _rxServiceManager a pointer to an XMultiServiceFactory interface as got in component_getFactory @param _pImplementationName the implementation name of the component @return the XInterface access to a factory for the component */ static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getComponentFactory( const ::rtl::OUString& _rImplementationName, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxServiceManager ); protected: /// register a client for the module static void registerClient(); /// revoke a client for the module static void revokeClient(); private: /** ensure that the impl class exists @precond m_aMutex is guarded when this method gets called */ static void ensureImpl(); }; //========================================================================= //= OModuleResourceClient //========================================================================= /** base class for objects which uses any global module-specific ressources */ class OModuleResourceClient { public: OModuleResourceClient() { OModule::registerClient(); } ~OModuleResourceClient() { OModule::revokeClient(); } }; //========================================================================= //= ModuleRes //========================================================================= /** specialized ResId, using the ressource manager provided by the global module */ class ModuleRes : public ::ResId { public: ModuleRes(USHORT _nId) : ResId(_nId, OModule::getResManager()) { } }; //========================================================================== //= OMultiInstanceAutoRegistration //========================================================================== template <class TYPE> class OMultiInstanceAutoRegistration { public: /** automatically registeres a multi instance component <p>Assumed that the template argument has the three methods <ul> <li><code>static ::rtl::OUString getImplementationName_Static()</code><li/> <li><code>static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static()</code><li/> <li><code>static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&)</code> </li> <ul/> the instantiation of this object will automatically register the class via <method>OModule::registerComponent</method>. <p/> The factory creation function used is <code>::cppu::createSingleFactory</code>. @see OOneInstanceAutoRegistration */ OMultiInstanceAutoRegistration(); ~OMultiInstanceAutoRegistration(); }; template <class TYPE> OMultiInstanceAutoRegistration<TYPE>::OMultiInstanceAutoRegistration() { OModule::registerComponent( TYPE::getImplementationName_Static(), TYPE::getSupportedServiceNames_Static(), TYPE::Create, ::cppu::createSingleFactory ); } template <class TYPE> OMultiInstanceAutoRegistration<TYPE>::~OMultiInstanceAutoRegistration() { OModule::revokeComponent(TYPE::getImplementationName_Static()); } //========================================================================== //= OOneInstanceAutoRegistration //========================================================================== template <class TYPE> class OOneInstanceAutoRegistration { public: /** automatically registeres a single instance component <p>Assumed that the template argument has the three methods <ul> <li><code>static ::rtl::OUString getImplementationName_Static()</code><li/> <li><code>static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static()</code><li/> <li><code>static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&)</code> </li> <ul/> the instantiation of this object will automatically register the class via <method>OModule::registerComponent</method>. <p/> The factory creation function used is <code>::cppu::createOneInstanceFactory</code>. @see OOneInstanceAutoRegistration */ OOneInstanceAutoRegistration(); ~OOneInstanceAutoRegistration(); }; template <class TYPE> OOneInstanceAutoRegistration<TYPE>::OOneInstanceAutoRegistration() { OModule::registerComponent( TYPE::getImplementationName_Static(), TYPE::getSupportedServiceNames_Static(), TYPE::Create, ::cppu::createOneInstanceFactory ); } template <class TYPE> OOneInstanceAutoRegistration<TYPE>::~OOneInstanceAutoRegistration() { OModule::revokeComponent(TYPE::getImplementationName_Static()); } //......................................................................... } // namespace COMPMOD_NAMESPACE //......................................................................... #endif // _EXTENSIONS_COMPONENT_MODULE_HXX_ <|endoftext|>
<commit_before>/// HEADER #include "assign_feature_classifications.h" /// PROJECT #include <csapex/model/node_modifier.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex_ml/features_message.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex/msg/io.h> #include <csapex/param/parameter_factory.h> CSAPEX_REGISTER_CLASS(csapex::AssignFeatureClassifications, csapex::Node) using namespace csapex; using namespace connection_types; AssignFeatureClassifications::AssignFeatureClassifications() { } void AssignFeatureClassifications::setup(NodeModifier &node_modifier) { in_features_ = node_modifier.addInput<GenericVectorMessage, FeaturesMessage>("Features"); in_labels_ = node_modifier.addOptionalInput<GenericVectorMessage, int>("Classifications"); out_ = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Labelled features"); } void AssignFeatureClassifications::setupParameters(Parameterizable &parameters) { parameters.addParameter(param::ParameterFactory::declareRange("label", 0, 255, 0, 1), label_); } void AssignFeatureClassifications::process() { std::shared_ptr<std::vector<FeaturesMessage> const> in_features = msg::getMessage<GenericVectorMessage, FeaturesMessage>(in_features_); std::shared_ptr<std::vector<FeaturesMessage>> out_features = std::make_shared<std::vector<FeaturesMessage>>(); if(msg::hasMessage(in_labels_)) { std::shared_ptr<std::vector<int> const> in_labels = msg::getMessage<GenericVectorMessage, int>(in_labels_); if(in_features->size() != in_labels->size()) throw std::runtime_error("Label count != FeatureMsg count!"); for(std::size_t i = 0 ; i < in_features->size() ; ++i) { FeaturesMessage feature = in_features->at(i); int label = (int) in_labels->at(i); feature.classification = label; out_features->emplace_back(feature); } } else { for(FeaturesMessage feature : *in_features) { feature.classification = label_; out_features->emplace_back(feature); } } msg::publish<GenericVectorMessage, FeaturesMessage>(out_, out_features); } <commit_msg>ml: improve error message<commit_after>/// HEADER #include "assign_feature_classifications.h" /// PROJECT #include <csapex/model/node_modifier.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex_ml/features_message.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex/msg/io.h> #include <csapex/param/parameter_factory.h> CSAPEX_REGISTER_CLASS(csapex::AssignFeatureClassifications, csapex::Node) using namespace csapex; using namespace connection_types; AssignFeatureClassifications::AssignFeatureClassifications() { } void AssignFeatureClassifications::setup(NodeModifier &node_modifier) { in_features_ = node_modifier.addInput<GenericVectorMessage, FeaturesMessage>("Features"); in_labels_ = node_modifier.addOptionalInput<GenericVectorMessage, int>("Classifications"); out_ = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Labelled features"); } void AssignFeatureClassifications::setupParameters(Parameterizable &parameters) { parameters.addParameter(param::ParameterFactory::declareRange("label", 0, 255, 0, 1), label_); } void AssignFeatureClassifications::process() { std::shared_ptr<std::vector<FeaturesMessage> const> in_features = msg::getMessage<GenericVectorMessage, FeaturesMessage>(in_features_); std::shared_ptr<std::vector<FeaturesMessage>> out_features = std::make_shared<std::vector<FeaturesMessage>>(); if(msg::hasMessage(in_labels_)) { std::shared_ptr<std::vector<int> const> in_labels = msg::getMessage<GenericVectorMessage, int>(in_labels_); if(in_features->size() != in_labels->size()) throw std::runtime_error("Label count (" + std::to_string(in_labels->size()) + ") != FeatureMsg count (" + std::to_string(in_features->size()) + ")!"); for(std::size_t i = 0 ; i < in_features->size() ; ++i) { FeaturesMessage feature = in_features->at(i); int label = (int) in_labels->at(i); feature.classification = label; out_features->emplace_back(feature); } } else { for(FeaturesMessage feature : *in_features) { feature.classification = label_; out_features->emplace_back(feature); } } msg::publish<GenericVectorMessage, FeaturesMessage>(out_, out_features); } <|endoftext|>
<commit_before>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "ARMTargetMachine.h" #include "ARMMCAsmInfo.h" #include "ARMFrameInfo.h" #include "ARM.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; static cl::opt<bool> EarlyITBlockFormation("thumb2-early-it-blocks", cl::Hidden, cl::desc("Form IT blocks early before register allocation"), cl::init(false)); static MCAsmInfo *createMCAsmInfo(const Target &T, StringRef TT) { Triple TheTriple(TT); switch (TheTriple.getOS()) { case Triple::Darwin: return new ARMMCAsmInfoDarwin(); default: return new ARMELFMCAsmInfo(); } } extern "C" void LLVMInitializeARMTarget() { // Register the target. RegisterTargetMachine<ARMTargetMachine> X(TheARMTarget); RegisterTargetMachine<ThumbTargetMachine> Y(TheThumbTarget); // Register the target asm info. RegisterAsmInfoFn A(TheARMTarget, createMCAsmInfo); RegisterAsmInfoFn B(TheThumbTarget, createMCAsmInfo); } /// TargetMachine ctor - Create an ARM architecture model. /// ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const std::string &TT, const std::string &FS, bool isThumb) : LLVMTargetMachine(T, TT), Subtarget(TT, FS, isThumb), FrameInfo(Subtarget), JITInfo(), InstrItins(Subtarget.getInstrItineraryData()) { DefRelocModel = getRelocationModel(); } ARMTargetMachine::ARMTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, false), InstrInfo(Subtarget), DataLayout(Subtarget.isAPCS_ABI() ? std::string("e-p:32:32-f64:32:32-i64:32:32-n32") : std::string("e-p:32:32-f64:64:64-i64:64:64-n32")), TLInfo(*this), TSInfo(*this) { } ThumbTargetMachine::ThumbTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, true), InstrInfo(Subtarget.hasThumb2() ? ((ARMBaseInstrInfo*)new Thumb2InstrInfo(Subtarget)) : ((ARMBaseInstrInfo*)new Thumb1InstrInfo(Subtarget))), DataLayout(Subtarget.isAPCS_ABI() ? std::string("e-p:32:32-f64:32:32-i64:32:32-" "i16:16:32-i8:8:32-i1:8:32-a:0:32-n32") : std::string("e-p:32:32-f64:64:64-i64:64:64-" "i16:16:32-i8:8:32-i1:8:32-a:0:32-n32")), TLInfo(*this), TSInfo(*this) { } // Pass Pipeline Configuration bool ARMBaseTargetMachine::addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { PM.add(createARMISelDag(*this, OptLevel)); return false; } bool ARMBaseTargetMachine::addPreRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (Subtarget.hasNEON()) PM.add(createNEONPreAllocPass()); // FIXME: temporarily disabling load / store optimization pass for Thumb1. if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass(true)); if (OptLevel != CodeGenOpt::None && Subtarget.isThumb2() && EarlyITBlockFormation) PM.add(createThumb2ITBlockPass(true)); return true; } bool ARMBaseTargetMachine::addPreSched2(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { // FIXME: temporarily disabling load / store optimization pass for Thumb1. if (OptLevel != CodeGenOpt::None) { if (!Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass()); if (Subtarget.hasNEON()) PM.add(createNEONMoveFixPass()); } // Expand some pseudo instructions into multiple instructions to allow // proper scheduling. PM.add(createARMExpandPseudoPass()); if (OptLevel != CodeGenOpt::None) { if (!Subtarget.isThumb1Only()) PM.add(createIfConverterPass()); if (Subtarget.isThumb2()) PM.add(createThumb2ITBlockPass()); } return true; } bool ARMBaseTargetMachine::addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (Subtarget.isThumb2()) PM.add(createThumb2SizeReductionPass()); PM.add(createARMConstantIslandPass()); return true; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, JITCodeEmitter &JCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMJITCodeEmitterPass(*this, JCE)); return false; } <commit_msg>Oops. IT block formation pass needs to be run at any optimization level.<commit_after>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "ARMTargetMachine.h" #include "ARMMCAsmInfo.h" #include "ARMFrameInfo.h" #include "ARM.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; static cl::opt<bool> EarlyITBlockFormation("thumb2-early-it-blocks", cl::Hidden, cl::desc("Form IT blocks early before register allocation"), cl::init(false)); static MCAsmInfo *createMCAsmInfo(const Target &T, StringRef TT) { Triple TheTriple(TT); switch (TheTriple.getOS()) { case Triple::Darwin: return new ARMMCAsmInfoDarwin(); default: return new ARMELFMCAsmInfo(); } } extern "C" void LLVMInitializeARMTarget() { // Register the target. RegisterTargetMachine<ARMTargetMachine> X(TheARMTarget); RegisterTargetMachine<ThumbTargetMachine> Y(TheThumbTarget); // Register the target asm info. RegisterAsmInfoFn A(TheARMTarget, createMCAsmInfo); RegisterAsmInfoFn B(TheThumbTarget, createMCAsmInfo); } /// TargetMachine ctor - Create an ARM architecture model. /// ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const std::string &TT, const std::string &FS, bool isThumb) : LLVMTargetMachine(T, TT), Subtarget(TT, FS, isThumb), FrameInfo(Subtarget), JITInfo(), InstrItins(Subtarget.getInstrItineraryData()) { DefRelocModel = getRelocationModel(); } ARMTargetMachine::ARMTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, false), InstrInfo(Subtarget), DataLayout(Subtarget.isAPCS_ABI() ? std::string("e-p:32:32-f64:32:32-i64:32:32-n32") : std::string("e-p:32:32-f64:64:64-i64:64:64-n32")), TLInfo(*this), TSInfo(*this) { } ThumbTargetMachine::ThumbTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, true), InstrInfo(Subtarget.hasThumb2() ? ((ARMBaseInstrInfo*)new Thumb2InstrInfo(Subtarget)) : ((ARMBaseInstrInfo*)new Thumb1InstrInfo(Subtarget))), DataLayout(Subtarget.isAPCS_ABI() ? std::string("e-p:32:32-f64:32:32-i64:32:32-" "i16:16:32-i8:8:32-i1:8:32-a:0:32-n32") : std::string("e-p:32:32-f64:64:64-i64:64:64-" "i16:16:32-i8:8:32-i1:8:32-a:0:32-n32")), TLInfo(*this), TSInfo(*this) { } // Pass Pipeline Configuration bool ARMBaseTargetMachine::addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { PM.add(createARMISelDag(*this, OptLevel)); return false; } bool ARMBaseTargetMachine::addPreRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (Subtarget.hasNEON()) PM.add(createNEONPreAllocPass()); // FIXME: temporarily disabling load / store optimization pass for Thumb1. if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass(true)); if (Subtarget.isThumb2() && EarlyITBlockFormation) PM.add(createThumb2ITBlockPass(true)); return true; } bool ARMBaseTargetMachine::addPreSched2(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { // FIXME: temporarily disabling load / store optimization pass for Thumb1. if (OptLevel != CodeGenOpt::None) { if (!Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass()); if (Subtarget.hasNEON()) PM.add(createNEONMoveFixPass()); } // Expand some pseudo instructions into multiple instructions to allow // proper scheduling. PM.add(createARMExpandPseudoPass()); if (OptLevel != CodeGenOpt::None) { if (!Subtarget.isThumb1Only()) PM.add(createIfConverterPass()); } if (Subtarget.isThumb2()) PM.add(createThumb2ITBlockPass()); return true; } bool ARMBaseTargetMachine::addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (Subtarget.isThumb2()) PM.add(createThumb2SizeReductionPass()); PM.add(createARMConstantIslandPass()); return true; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, JITCodeEmitter &JCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMJITCodeEmitterPass(*this, JCE)); return false; } <|endoftext|>
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "bin/builtin.h" #include "bin/eventhandler.h" #include "bin/log.h" #include "bin/socket.h" bool Socket::Initialize() { int err; WSADATA winsock_data; WORD version_requested = MAKEWORD(1, 0); err = WSAStartup(version_requested, &winsock_data); if (err != 0) { Log::PrintErr("Unable to initialize Winsock: %d\n", WSAGetLastError()); } return err == 0; } intptr_t Socket::Available(intptr_t fd) { ClientSocket* client_socket = reinterpret_cast<ClientSocket*>(fd); return client_socket->Available(); } intptr_t Socket::Read(intptr_t fd, void* buffer, intptr_t num_bytes) { Handle* handle = reinterpret_cast<Handle*>(fd); return handle->Read(buffer, num_bytes); } intptr_t Socket::Write(intptr_t fd, const void* buffer, intptr_t num_bytes) { Handle* handle = reinterpret_cast<Handle*>(fd); return handle->Write(buffer, num_bytes); } intptr_t Socket::GetPort(intptr_t fd) { ASSERT(reinterpret_cast<Handle*>(fd)->is_socket()); SocketHandle* socket_handle = reinterpret_cast<SocketHandle*>(fd); struct sockaddr_in socket_address; socklen_t size = sizeof(socket_address); if (getsockname(socket_handle->socket(), reinterpret_cast<struct sockaddr *>(&socket_address), &size)) { Log::PrintErr("Error getsockname: %s\n", strerror(errno)); return 0; } return ntohs(socket_address.sin_port); } bool Socket::GetRemotePeer(intptr_t fd, char *host, intptr_t *port) { ASSERT(reinterpret_cast<Handle*>(fd)->is_socket()); SocketHandle* socket_handle = reinterpret_cast<SocketHandle*>(fd); struct sockaddr_in socket_address; socklen_t size = sizeof(socket_address); if (getpeername(socket_handle->socket(), reinterpret_cast<struct sockaddr *>(&socket_address), &size)) { Log::PrintErr("Error getpeername: %s\n", strerror(errno)); return false; } *port = ntohs(socket_address.sin_port); // Clear the port before calling WSAAddressToString as WSAAddressToString // includes the port in the formatted string. socket_address.sin_port = 0; DWORD len = INET_ADDRSTRLEN; int err = WSAAddressToString(reinterpret_cast<LPSOCKADDR>(&socket_address), sizeof(socket_address), NULL, host, &len); if (err != 0) { Log::PrintErr("Error WSAAddressToString: %d\n", WSAGetLastError()); return false; } return true; } intptr_t Socket::CreateConnect(const char* host, const intptr_t port) { SOCKET s = socket(AF_INET, SOCK_STREAM, 0); if (s == INVALID_SOCKET) { return -1; } linger l; l.l_onoff = 1; l.l_linger = 10; int status = setsockopt(s, SOL_SOCKET, SO_LINGER, reinterpret_cast<char*>(&l), sizeof(l)); if (status != NO_ERROR) { FATAL("Failed setting SO_LINGER on socket"); } // Perform a name lookup for an IPv4 address. struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; struct addrinfo* result = NULL; status = getaddrinfo(host, 0, &hints, &result); if (status != NO_ERROR) { return -1; } // Copy IPv4 address and set the port. struct sockaddr_in server_address; memcpy(&server_address, reinterpret_cast<sockaddr_in *>(result->ai_addr), sizeof(server_address)); server_address.sin_port = htons(port); freeaddrinfo(result); // Free data allocated by getaddrinfo. status = connect( s, reinterpret_cast<struct sockaddr*>(&server_address), sizeof(server_address)); if (status == SOCKET_ERROR) { DWORD rc = WSAGetLastError(); closesocket(s); SetLastError(rc); return -1; } ClientSocket* client_socket = new ClientSocket(s); return reinterpret_cast<intptr_t>(client_socket); } void Socket::GetError(intptr_t fd, OSError* os_error) { Handle* handle = reinterpret_cast<Handle*>(fd); os_error->SetCodeAndMessage(OSError::kSystem, handle->last_error()); } intptr_t Socket::GetStdioHandle(int num) { HANDLE handle; switch (num) { case 0: handle = GetStdHandle(STD_INPUT_HANDLE); break; case 1: handle = GetStdHandle(STD_OUTPUT_HANDLE); break; case 2: handle = GetStdHandle(STD_ERROR_HANDLE); break; default: UNREACHABLE(); } if (handle == INVALID_HANDLE_VALUE) { return -1; } FileHandle* file_handle = new FileHandle(handle); if (file_handle == NULL) return -1; file_handle->MarkDoesNotSupportOverlappedIO(); return reinterpret_cast<intptr_t>(file_handle); } intptr_t ServerSocket::Accept(intptr_t fd) { ListenSocket* listen_socket = reinterpret_cast<ListenSocket*>(fd); ClientSocket* client_socket = listen_socket->Accept(); if (client_socket != NULL) { return reinterpret_cast<intptr_t>(client_socket); } else { return -1; } } const char* Socket::LookupIPv4Address(char* host, OSError** os_error) { // Perform a name lookup for an IPv4 address. struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; struct addrinfo* info = NULL; int status = getaddrinfo(host, 0, &hints, &info); if (status != 0) { ASSERT(*os_error == NULL); *os_error = new OSError(status, gai_strerror(status), OSError::kGetAddressInfo); return NULL; } // Convert the address into IPv4 dotted decimal notation. char* buffer = reinterpret_cast<char*>(malloc(INET_ADDRSTRLEN)); sockaddr_in *sockaddr = reinterpret_cast<sockaddr_in *>(info->ai_addr); // Clear the port before calling WSAAddressToString as WSAAddressToString // includes the port in the formatted string. DWORD len = INET_ADDRSTRLEN; int err = WSAAddressToString(reinterpret_cast<LPSOCKADDR>(sockaddr), sizeof(sockaddr_in), NULL, buffer, &len); if (err != 0) { free(buffer); return NULL; } return buffer; } intptr_t ServerSocket::CreateBindListen(const char* host, intptr_t port, intptr_t backlog) { unsigned long socket_addr = inet_addr(host); // NOLINT if (socket_addr == INADDR_NONE) { return -5; } SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s == INVALID_SOCKET) { return -1; } BOOL optval = true; int status = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&optval), sizeof(optval)); if (status == SOCKET_ERROR) { DWORD rc = WSAGetLastError(); closesocket(s); SetLastError(rc); return -1; } sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = socket_addr; addr.sin_port = htons(port); status = bind(s, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)); if (status == SOCKET_ERROR) { DWORD rc = WSAGetLastError(); closesocket(s); SetLastError(rc); return -1; } status = listen(s, backlog); if (status == SOCKET_ERROR) { DWORD rc = WSAGetLastError(); closesocket(s); SetLastError(rc); return -1; } ListenSocket* listen_socket = new ListenSocket(s); return reinterpret_cast<intptr_t>(listen_socket); } <commit_msg>Fix extraction of error messages on Windows from getaddrinfo.<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "bin/builtin.h" #include "bin/eventhandler.h" #include "bin/log.h" #include "bin/socket.h" bool Socket::Initialize() { int err; WSADATA winsock_data; WORD version_requested = MAKEWORD(1, 0); err = WSAStartup(version_requested, &winsock_data); if (err != 0) { Log::PrintErr("Unable to initialize Winsock: %d\n", WSAGetLastError()); } return err == 0; } intptr_t Socket::Available(intptr_t fd) { ClientSocket* client_socket = reinterpret_cast<ClientSocket*>(fd); return client_socket->Available(); } intptr_t Socket::Read(intptr_t fd, void* buffer, intptr_t num_bytes) { Handle* handle = reinterpret_cast<Handle*>(fd); return handle->Read(buffer, num_bytes); } intptr_t Socket::Write(intptr_t fd, const void* buffer, intptr_t num_bytes) { Handle* handle = reinterpret_cast<Handle*>(fd); return handle->Write(buffer, num_bytes); } intptr_t Socket::GetPort(intptr_t fd) { ASSERT(reinterpret_cast<Handle*>(fd)->is_socket()); SocketHandle* socket_handle = reinterpret_cast<SocketHandle*>(fd); struct sockaddr_in socket_address; socklen_t size = sizeof(socket_address); if (getsockname(socket_handle->socket(), reinterpret_cast<struct sockaddr *>(&socket_address), &size)) { Log::PrintErr("Error getsockname: %s\n", strerror(errno)); return 0; } return ntohs(socket_address.sin_port); } bool Socket::GetRemotePeer(intptr_t fd, char *host, intptr_t *port) { ASSERT(reinterpret_cast<Handle*>(fd)->is_socket()); SocketHandle* socket_handle = reinterpret_cast<SocketHandle*>(fd); struct sockaddr_in socket_address; socklen_t size = sizeof(socket_address); if (getpeername(socket_handle->socket(), reinterpret_cast<struct sockaddr *>(&socket_address), &size)) { Log::PrintErr("Error getpeername: %s\n", strerror(errno)); return false; } *port = ntohs(socket_address.sin_port); // Clear the port before calling WSAAddressToString as WSAAddressToString // includes the port in the formatted string. socket_address.sin_port = 0; DWORD len = INET_ADDRSTRLEN; int err = WSAAddressToString(reinterpret_cast<LPSOCKADDR>(&socket_address), sizeof(socket_address), NULL, host, &len); if (err != 0) { Log::PrintErr("Error WSAAddressToString: %d\n", WSAGetLastError()); return false; } return true; } intptr_t Socket::CreateConnect(const char* host, const intptr_t port) { SOCKET s = socket(AF_INET, SOCK_STREAM, 0); if (s == INVALID_SOCKET) { return -1; } linger l; l.l_onoff = 1; l.l_linger = 10; int status = setsockopt(s, SOL_SOCKET, SO_LINGER, reinterpret_cast<char*>(&l), sizeof(l)); if (status != NO_ERROR) { FATAL("Failed setting SO_LINGER on socket"); } // Perform a name lookup for an IPv4 address. struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; struct addrinfo* result = NULL; status = getaddrinfo(host, 0, &hints, &result); if (status != NO_ERROR) { return -1; } // Copy IPv4 address and set the port. struct sockaddr_in server_address; memcpy(&server_address, reinterpret_cast<sockaddr_in *>(result->ai_addr), sizeof(server_address)); server_address.sin_port = htons(port); freeaddrinfo(result); // Free data allocated by getaddrinfo. status = connect( s, reinterpret_cast<struct sockaddr*>(&server_address), sizeof(server_address)); if (status == SOCKET_ERROR) { DWORD rc = WSAGetLastError(); closesocket(s); SetLastError(rc); return -1; } ClientSocket* client_socket = new ClientSocket(s); return reinterpret_cast<intptr_t>(client_socket); } void Socket::GetError(intptr_t fd, OSError* os_error) { Handle* handle = reinterpret_cast<Handle*>(fd); os_error->SetCodeAndMessage(OSError::kSystem, handle->last_error()); } intptr_t Socket::GetStdioHandle(int num) { HANDLE handle; switch (num) { case 0: handle = GetStdHandle(STD_INPUT_HANDLE); break; case 1: handle = GetStdHandle(STD_OUTPUT_HANDLE); break; case 2: handle = GetStdHandle(STD_ERROR_HANDLE); break; default: UNREACHABLE(); } if (handle == INVALID_HANDLE_VALUE) { return -1; } FileHandle* file_handle = new FileHandle(handle); if (file_handle == NULL) return -1; file_handle->MarkDoesNotSupportOverlappedIO(); return reinterpret_cast<intptr_t>(file_handle); } intptr_t ServerSocket::Accept(intptr_t fd) { ListenSocket* listen_socket = reinterpret_cast<ListenSocket*>(fd); ClientSocket* client_socket = listen_socket->Accept(); if (client_socket != NULL) { return reinterpret_cast<intptr_t>(client_socket); } else { return -1; } } const char* Socket::LookupIPv4Address(char* host, OSError** os_error) { // Perform a name lookup for an IPv4 address. struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; struct addrinfo* info = NULL; int status = getaddrinfo(host, 0, &hints, &info); if (status != 0) { ASSERT(*os_error == NULL); DWORD error_code = WSAGetLastError(); SetLastError(error_code); *os_error = new OSError(); return NULL; } // Convert the address into IPv4 dotted decimal notation. char* buffer = reinterpret_cast<char*>(malloc(INET_ADDRSTRLEN)); sockaddr_in *sockaddr = reinterpret_cast<sockaddr_in *>(info->ai_addr); // Clear the port before calling WSAAddressToString as WSAAddressToString // includes the port in the formatted string. DWORD len = INET_ADDRSTRLEN; int err = WSAAddressToString(reinterpret_cast<LPSOCKADDR>(sockaddr), sizeof(sockaddr_in), NULL, buffer, &len); if (err != 0) { free(buffer); return NULL; } return buffer; } intptr_t ServerSocket::CreateBindListen(const char* host, intptr_t port, intptr_t backlog) { unsigned long socket_addr = inet_addr(host); // NOLINT if (socket_addr == INADDR_NONE) { return -5; } SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s == INVALID_SOCKET) { return -1; } BOOL optval = true; int status = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&optval), sizeof(optval)); if (status == SOCKET_ERROR) { DWORD rc = WSAGetLastError(); closesocket(s); SetLastError(rc); return -1; } sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = socket_addr; addr.sin_port = htons(port); status = bind(s, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)); if (status == SOCKET_ERROR) { DWORD rc = WSAGetLastError(); closesocket(s); SetLastError(rc); return -1; } status = listen(s, backlog); if (status == SOCKET_ERROR) { DWORD rc = WSAGetLastError(); closesocket(s); SetLastError(rc); return -1; } ListenSocket* listen_socket = new ListenSocket(s); return reinterpret_cast<intptr_t>(listen_socket); } <|endoftext|>
<commit_before>//===-- ARM64Subtarget.cpp - ARM64 Subtarget Information --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ARM64 specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "ARM64InstrInfo.h" #include "ARM64Subtarget.h" #include "llvm/ADT/SmallVector.h" #include "llvm/CodeGen/MachineScheduler.h" #include "llvm/IR/GlobalValue.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; #define DEBUG_TYPE "arm64-subtarget" #define GET_SUBTARGETINFO_CTOR #define GET_SUBTARGETINFO_TARGET_DESC #include "ARM64GenSubtargetInfo.inc" ARM64Subtarget::ARM64Subtarget(const std::string &TT, const std::string &CPU, const std::string &FS, bool LittleEndian) : ARM64GenSubtargetInfo(TT, CPU, FS), ARMProcFamily(Others), HasFPARMv8(false), HasNEON(false), HasCrypto(false), HasZeroCycleRegMove(false), HasZeroCycleZeroing(false), CPUString(CPU), TargetTriple(TT), IsLittleEndian(LittleEndian) { // Determine default and user-specified characteristics if (CPUString.empty()) CPUString = "generic"; ParseSubtargetFeatures(CPUString, FS); } /// ClassifyGlobalReference - Find the target operand flags that describe /// how a global value should be referenced for the current subtarget. unsigned char ARM64Subtarget::ClassifyGlobalReference(const GlobalValue *GV, const TargetMachine &TM) const { // Determine whether this is a reference to a definition or a declaration. // Materializable GVs (in JIT lazy compilation mode) do not require an extra // load from stub. bool isDecl = GV->hasAvailableExternallyLinkage(); if (GV->isDeclaration() && !GV->isMaterializable()) isDecl = true; // MachO large model always goes via a GOT, simply to get a single 8-byte // absolute relocation on all global addresses. if (TM.getCodeModel() == CodeModel::Large && isTargetMachO()) return ARM64II::MO_GOT; // The small code mode's direct accesses use ADRP, which cannot necessarily // produce the value 0 (if the code is above 4GB). Therefore they must use the // GOT. if (TM.getCodeModel() == CodeModel::Small && GV->isWeakForLinker() && isDecl) return ARM64II::MO_GOT; // If symbol visibility is hidden, the extra load is not needed if // the symbol is definitely defined in the current translation unit. // The handling of non-hidden symbols in PIC mode is rather target-dependent: // + On MachO, if the symbol is defined in this module the GOT can be // skipped. // + On ELF, the R_AARCH64_COPY relocation means that even symbols actually // defined could end up in unexpected places. Use a GOT. if (TM.getRelocationModel() != Reloc::Static && GV->hasDefaultVisibility()) { if (isTargetMachO()) return (isDecl || GV->isWeakForLinker()) ? ARM64II::MO_GOT : ARM64II::MO_NO_FLAG; else return ARM64II::MO_GOT; } return ARM64II::MO_NO_FLAG; } /// This function returns the name of a function which has an interface /// like the non-standard bzero function, if such a function exists on /// the current subtarget and it is considered prefereable over /// memset with zero passed as the second argument. Otherwise it /// returns null. const char *ARM64Subtarget::getBZeroEntry() const { // At the moment, always prefer bzero. return "bzero"; } void ARM64Subtarget::overrideSchedPolicy(MachineSchedPolicy &Policy, MachineInstr *begin, MachineInstr *end, unsigned NumRegionInstrs) const { // LNT run (at least on Cyclone) showed reasonably significant gains for // bi-directional scheduling. 253.perlbmk. Policy.OnlyTopDown = false; Policy.OnlyBottomUp = false; } <commit_msg>[ARM64] Fix formatting.<commit_after>//===-- ARM64Subtarget.cpp - ARM64 Subtarget Information --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ARM64 specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "ARM64InstrInfo.h" #include "ARM64Subtarget.h" #include "llvm/ADT/SmallVector.h" #include "llvm/CodeGen/MachineScheduler.h" #include "llvm/IR/GlobalValue.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; #define DEBUG_TYPE "arm64-subtarget" #define GET_SUBTARGETINFO_CTOR #define GET_SUBTARGETINFO_TARGET_DESC #include "ARM64GenSubtargetInfo.inc" ARM64Subtarget::ARM64Subtarget(const std::string &TT, const std::string &CPU, const std::string &FS, bool LittleEndian) : ARM64GenSubtargetInfo(TT, CPU, FS), ARMProcFamily(Others), HasFPARMv8(false), HasNEON(false), HasCrypto(false), HasZeroCycleRegMove(false), HasZeroCycleZeroing(false), CPUString(CPU), TargetTriple(TT), IsLittleEndian(LittleEndian) { // Determine default and user-specified characteristics if (CPUString.empty()) CPUString = "generic"; ParseSubtargetFeatures(CPUString, FS); } /// ClassifyGlobalReference - Find the target operand flags that describe /// how a global value should be referenced for the current subtarget. unsigned char ARM64Subtarget::ClassifyGlobalReference(const GlobalValue *GV, const TargetMachine &TM) const { // Determine whether this is a reference to a definition or a declaration. // Materializable GVs (in JIT lazy compilation mode) do not require an extra // load from stub. bool isDecl = GV->hasAvailableExternallyLinkage(); if (GV->isDeclaration() && !GV->isMaterializable()) isDecl = true; // MachO large model always goes via a GOT, simply to get a single 8-byte // absolute relocation on all global addresses. if (TM.getCodeModel() == CodeModel::Large && isTargetMachO()) return ARM64II::MO_GOT; // The small code mode's direct accesses use ADRP, which cannot necessarily // produce the value 0 (if the code is above 4GB). Therefore they must use the // GOT. if (TM.getCodeModel() == CodeModel::Small && GV->isWeakForLinker() && isDecl) return ARM64II::MO_GOT; // If symbol visibility is hidden, the extra load is not needed if // the symbol is definitely defined in the current translation unit. // The handling of non-hidden symbols in PIC mode is rather target-dependent: // + On MachO, if the symbol is defined in this module the GOT can be // skipped. // + On ELF, the R_AARCH64_COPY relocation means that even symbols actually // defined could end up in unexpected places. Use a GOT. if (TM.getRelocationModel() != Reloc::Static && GV->hasDefaultVisibility()) { if (isTargetMachO()) return (isDecl || GV->isWeakForLinker()) ? ARM64II::MO_GOT : ARM64II::MO_NO_FLAG; else return ARM64II::MO_GOT; } return ARM64II::MO_NO_FLAG; } /// This function returns the name of a function which has an interface /// like the non-standard bzero function, if such a function exists on /// the current subtarget and it is considered prefereable over /// memset with zero passed as the second argument. Otherwise it /// returns null. const char *ARM64Subtarget::getBZeroEntry() const { // At the moment, always prefer bzero. return "bzero"; } void ARM64Subtarget::overrideSchedPolicy(MachineSchedPolicy &Policy, MachineInstr *begin, MachineInstr *end, unsigned NumRegionInstrs) const { // LNT run (at least on Cyclone) showed reasonably significant gains for // bi-directional scheduling. 253.perlbmk. Policy.OnlyTopDown = false; Policy.OnlyBottomUp = false; } <|endoftext|>
<commit_before><commit_msg>bloedes mergen<commit_after><|endoftext|>
<commit_before>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <fstream> #include <string> #include <vector> #include <exception> // StdAir #include <stdair/stdair_demand_types.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/bom/EventQueue.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/service/Logger.hpp> // Distribution #include <simcrs/SIMCRS_Service.hpp> // TRADEMGEN #include <trademgen/TRADEMGEN_Service.hpp> // Airsched #include <airsched/AIRSCHED_Service.hpp> // Dsim #include <dsim/DSIM_Types.hpp> #include <dsim/command/Simulator.hpp> namespace DSIM { // //////////////////////////////////////////////////////////////////// void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) { try { // DEBUG STDAIR_LOG_DEBUG ("The simulation is starting"); // ///////////////////////////////////////////////////// // Event queue stdair::EventQueue lEventQueue = stdair::EventQueue (); // Browse the list of DemandStreams and Generate the first event for each // DemandStream. ioTRADEMGEN_Service.generateFirstRequests (lEventQueue); // Pop requests, get type, and generate next request of same type while (lEventQueue.isQueueDone() == false) { stdair::EventStruct& lEventStruct = lEventQueue.popEvent (); const stdair::BookingRequestStruct& lPoppedRequest = lEventStruct.getBookingRequest (); // DEBUG STDAIR_LOG_DEBUG ("Poped request: " << lPoppedRequest.describe()); // Play booking request playBookingRequest (ioSIMCRS_Service, lPoppedRequest); // Retrieve the corresponding demand stream const stdair::DemandStreamKeyStr_T& lDemandStreamKey = lEventStruct.getDemandStreamKey (); // generate next request bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service.stillHavingRequestsToBeGenerated(lDemandStreamKey); if (stillHavingRequestsToBeGenerated) { stdair::BookingRequestPtr_T lNextRequest = ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey); assert (lNextRequest != NULL); stdair::EventStruct lNextEventStruct ("Request", lDemandStreamKey, lNextRequest); lEventQueue.addEvent (lNextEventStruct); } lEventQueue.eraseLastUsedEvent (); } // DEBUG STDAIR_LOG_DEBUG ("The simulation has ended"); } catch (const std::exception& lStdError) { STDAIR_LOG_ERROR ("Error: " << lStdError.what()); throw SimulationException(); } } // //////////////////////////////////////////////////////////////////// void Simulator:: playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, const stdair::BookingRequestStruct& iBookingRequest) { // Retrieve a list of travel solutions corresponding the given // booking request. stdair::TravelSolutionList_T lTravelSolutionList = ioSIMCRS_Service.getTravelSolutions (iBookingRequest); if (lTravelSolutionList.empty() == false) { // Get the fare quote for each travel solution. ioSIMCRS_Service.getFare(lTravelSolutionList); // Get the availability for each travel solution. ioSIMCRS_Service.getAvailability (lTravelSolutionList); // Hardcode a travel solution choice. stdair::TravelSolutionList_T::iterator itTS = lTravelSolutionList.begin(); const stdair::TravelSolutionStruct& lChosenTS = *itTS; STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS); // Make a sale. const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize(); ioSIMCRS_Service.sell (lChosenTS, lPartySize); } else { // DEBUG STDAIR_LOG_DEBUG ("No travel solution has been found/chosen."); } } } <commit_msg>[Dev] Fixed the compilation error about SimCRS_Service, for which getFare() has been renamed into getFareQuote().<commit_after>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <fstream> #include <string> #include <vector> #include <exception> // StdAir #include <stdair/stdair_demand_types.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/bom/EventQueue.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/service/Logger.hpp> // Distribution #include <simcrs/SIMCRS_Service.hpp> // TRADEMGEN #include <trademgen/TRADEMGEN_Service.hpp> // Airsched #include <airsched/AIRSCHED_Service.hpp> // Dsim #include <dsim/DSIM_Types.hpp> #include <dsim/command/Simulator.hpp> namespace DSIM { // //////////////////////////////////////////////////////////////////// void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) { try { // DEBUG STDAIR_LOG_DEBUG ("The simulation is starting"); // ///////////////////////////////////////////////////// // Event queue stdair::EventQueue lEventQueue = stdair::EventQueue (); // Browse the list of DemandStreams and Generate the first event for each // DemandStream. ioTRADEMGEN_Service.generateFirstRequests (lEventQueue); // Pop requests, get type, and generate next request of same type while (lEventQueue.isQueueDone() == false) { stdair::EventStruct& lEventStruct = lEventQueue.popEvent (); const stdair::BookingRequestStruct& lPoppedRequest = lEventStruct.getBookingRequest (); // DEBUG STDAIR_LOG_DEBUG ("Poped request: " << lPoppedRequest.describe()); // Play booking request playBookingRequest (ioSIMCRS_Service, lPoppedRequest); // Retrieve the corresponding demand stream const stdair::DemandStreamKeyStr_T& lDemandStreamKey = lEventStruct.getDemandStreamKey (); // generate next request bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service.stillHavingRequestsToBeGenerated(lDemandStreamKey); if (stillHavingRequestsToBeGenerated) { stdair::BookingRequestPtr_T lNextRequest = ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey); assert (lNextRequest != NULL); stdair::EventStruct lNextEventStruct ("Request", lDemandStreamKey, lNextRequest); lEventQueue.addEvent (lNextEventStruct); } lEventQueue.eraseLastUsedEvent (); } // DEBUG STDAIR_LOG_DEBUG ("The simulation has ended"); } catch (const std::exception& lStdError) { STDAIR_LOG_ERROR ("Error: " << lStdError.what()); throw SimulationException(); } } // //////////////////////////////////////////////////////////////////// void Simulator:: playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, const stdair::BookingRequestStruct& iBookingRequest) { // Retrieve a list of travel solutions corresponding the given // booking request. stdair::TravelSolutionList_T lTravelSolutionList = ioSIMCRS_Service.getTravelSolutions (iBookingRequest); if (lTravelSolutionList.empty() == false) { // Get the fare quote for each travel solution. ioSIMCRS_Service.getFareQuote (lTravelSolutionList); // Get the availability for each travel solution. ioSIMCRS_Service.getAvailability (lTravelSolutionList); // Hardcode a travel solution choice. stdair::TravelSolutionList_T::iterator itTS = lTravelSolutionList.begin(); const stdair::TravelSolutionStruct& lChosenTS = *itTS; STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS); // Make a sale. const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize(); ioSIMCRS_Service.sell (lChosenTS, lPartySize); } else { // DEBUG STDAIR_LOG_DEBUG ("No travel solution has been found/chosen."); } } } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __MESOS_AUTHENTICATION_HTTP_AUTHENTICATOR_FACTORY_HPP__ #define __MESOS_AUTHENTICATION_HTTP_AUTHENTICATOR_FACTORY_HPP__ #include <string> #include <mesos/mesos.hpp> #include <process/authenticator.hpp> #include <stout/try.hpp> #include <stout/hashmap.hpp> namespace mesos { namespace http { namespace authentication { class BasicAuthenticatorFactory { public: ~BasicAuthenticatorFactory() {} static Try<process::http::authentication::Authenticator*> create( const Parameters& parameters); static Try<process::http::authentication::Authenticator*> create( const std::string& realm, const Credentials& credentials); static Try<process::http::authentication::Authenticator*> create( const std::string& realm, const hashmap<std::string, std::string>& credentials); protected: BasicAuthenticatorFactory() {} }; } // namespace authentication { } // namespace http { } // namespace mesos { #endif // __MESOS_AUTHENTICATION_HTTP_AUTHENTICATOR_FACTORY_HPP__ <commit_msg>Added Doxygen docs for basic HTTP authenticator.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __MESOS_AUTHENTICATION_HTTP_AUTHENTICATOR_FACTORY_HPP__ #define __MESOS_AUTHENTICATION_HTTP_AUTHENTICATOR_FACTORY_HPP__ #include <string> #include <mesos/mesos.hpp> #include <process/authenticator.hpp> #include <stout/try.hpp> #include <stout/hashmap.hpp> namespace mesos { namespace http { namespace authentication { class BasicAuthenticatorFactory { public: ~BasicAuthenticatorFactory() {} /** * Creates a basic HTTP authenticator from module parameters. Two keys may be * specified in the parameters: `authentication_realm` (required) and * `credentials` (optional). Credentials must be provided as a string which * represents a JSON array, similar to the format of the `--credentials` * command-line flag. * * Example parameters as JSON: * { * "parameters": [ * { * "key": "authentication_realm", * "value": "tatooine" * }, * { * "key": "credentials", * "value": "[ * { * \"principal\": \"luke\", * \"secret\": \"skywalker\" * } * ]" * } * ] * } * * @param parameters The input parameters. This object may contain two keys: * `authentication_realm` (required) and `credentials` (optional). * @return A `Try` containing a new authenticator if successful, or an * `Error` if unsuccessful. */ static Try<process::http::authentication::Authenticator*> create( const Parameters& parameters); /** * Creates a basic HTTP authenticator for the specified realm, initialized * with the provided credentials. * * @param realm The authentication realm associated with this authenticator. * @param credentials The credentials that this authenticator will use to * evaluate authentication requests. * @return A `Try` containing a new authenticator if successful, or an * `Error` if unsuccessful. */ static Try<process::http::authentication::Authenticator*> create( const std::string& realm, const Credentials& credentials); /** * Creates a basic HTTP authenticator for the specified realm, initialized * with the provided credentials. * * @param realm The authentication realm associated with this authenticator. * @param credentials The credentials that this authenticator will use to * evaluate authentication requests. * @return A `Try` containing a new authenticator if successful, or an * `Error` if unsuccessful. */ static Try<process::http::authentication::Authenticator*> create( const std::string& realm, const hashmap<std::string, std::string>& credentials); protected: BasicAuthenticatorFactory() {} }; } // namespace authentication { } // namespace http { } // namespace mesos { #endif // __MESOS_AUTHENTICATION_HTTP_AUTHENTICATOR_FACTORY_HPP__ <|endoftext|>
<commit_before>// // Copyright (c) 2012 Kim Walisch, <[email protected]>. // All rights reserved. // // This file is part of primesieve. // Homepage: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. /// @file main.cpp /// @brief Command-line version of primesieve, multi-threaded (OpenMP). /// @see http://primesieve.googlecode.com /// primesieve is a highly optimized implementation of the sieve of /// Eratosthenes that generates prime numbers and prime k-tuplets (twin /// primes, prime triplets, ...) up to 2^64 maximum. #include "../expr/ExpressionParser.h" #include "../soe/ParallelPrimeSieve.h" // defined in test.cpp void test(); #include <stdint.h> #include <exception> #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <iomanip> #include <algorithm> namespace { // start and stop number for sieving std::vector<uint64_t> number; int32_t threads = -1; int32_t flags = 0; int32_t sieveSize = -1; int32_t preSieve = -1; bool quietMode = false; bool printParser = false; const std::string primes[7] = { "Prime numbers", "Twin primes", "Prime triplets", "Prime quadruplets", "Prime quintuplets", "Prime sextuplets", "Prime septuplets" }; void help() { int maxThreads = ParallelPrimeSieve::getMaxThreads(); std::cout << "Usage: primesieve START STOP [OPTION]..." << std::endl << "Use the segmented sieve of Eratosthenes to generate the prime numbers and/or" << std::endl << "prime k-tuplets in the interval [START, STOP] < 2^64" << std::endl << std::endl << "Options:" << std::endl << std::endl << " -c<N+> Count prime numbers and/or prime k-tuplets, 1 <= N <= 7" << std::endl << " e.g. -c1 count prime numbers (DEFAULT)" << std::endl << " -c23 count twin primes and prime triplets" << std::endl << " -o<OFFSET> Sieve the interval [START, START+OFFSET]" << std::endl << " -p<N> Print prime numbers or prime k-tuplets, 1 <= N <= 7" << std::endl << " e.g. -p1 print prime numbers" << std::endl << " -p5 print prime quintuplets" << std::endl << " -q Quiet mode, print less output" << std::endl << " -r<PRE-SIEVE> Pre-sieve multiples of small primes <= PRE-SIEVE to speed up" << std::endl << " the sieve of Eratosthenes, 13 <= PRE-SIEVE <= 23" << std::endl << " -s<SIZE> Set the sieve size in kilobytes, 1 <= SIZE <= 4096" << std::endl << " Set SIZE to your CPU's L1/L2 cache size for best performance" << std::endl << " -t<THREADS> Set the number of threads for sieving, 1 <= THREADS <= " << maxThreads << std::endl << " Primes are not generated in order if THREADS >= 2" << std::endl << " -test Run various sieving tests and exit" << std::endl << " -v Print version and license information and exit" << std::endl << std::endl << "Examples:" << std::endl << std::endl << "Print the prime numbers up to 1000:" << std::endl << "> primesieve 2 1000 -p1" << std::endl << std::endl << "Count the twin primes and prime triplets in the interval [1E10, 1E10+2^32]:" << std::endl << "> primesieve 1E10 -o2**32 -c23" << std::endl; std::exit(1); } void version() { std::cout << "primesieve 3.7, <http://primesieve.googlecode.com>" << std::endl << "Copyright (C) 2012 Kim Walisch" << std::endl << "This software is licensed under the New BSD License. See the LICENSE file" << std::endl << "for more information." << std::endl; std::exit(1); } int getWidth(const ParallelPrimeSieve& pps) { int size = 0; for (int i = 0; i < 7; i++) { if (pps.isFlag(COUNT_PRIMES << i)) size = std::max(size, (int) primes[i].size()); } return size; } bool isDigits(const std::string &str) { const std::string digits("0123456789"); if (str.size() == 0) return false; return str.find_first_not_of(digits) == std::string::npos; } /// Process the command-line options. /// @see help(void) /// void processOptions(int argc, char* argv[]) { if (argc < 2 || argc > 20) help(); std::string arg; ExpressionParser<uint64_t> parser64; ExpressionParser<> parser; uint64_t tmp = 0; // process START and STOP number for (int i = 1; i < std::min(3, argc); i++) { try { number.push_back(parser64.eval(argv[i])); if (!isDigits(argv[i])) printParser = true; } catch (parser_error&) { } } // process options for (int i = (int) number.size() + 1; i < argc; i++) { if (*argv[i] != '-' && *argv[i] != '/') help(); argv[i]++; switch (*argv[i]++) { case 'c': tmp = parser.eval(argv[i]); do { if (tmp % 10 < 1 || tmp % 10 > 7) help(); flags |= ParallelPrimeSieve::COUNT_PRIMES << (tmp % 10 - 1); tmp /= 10; } while (tmp > 0); break; case 'o': if (number.size() == 0) help(); tmp = number[0] + parser64.eval(argv[i]); number.push_back(tmp); break; case 'p': tmp = parser.eval(argv[i]); if (tmp < 1 || tmp > 7) help(); flags |= ParallelPrimeSieve::PRINT_PRIMES << (tmp - 1); quietMode = true; break; case 'q': quietMode = true; break; case 'r': preSieve = parser.eval(argv[i]); break; case 's': sieveSize = parser.eval(argv[i]); break; case 't': arg = argv[i]; if (arg.compare("est") == 0) test(); threads = parser.eval(argv[i]); break; case 'v': version(); default : help(); } } if (number.size() != 2) help(); } } // end namespace int main(int argc, char* argv[]) { try { processOptions(argc, argv); } catch (parser_error&) { help(); } std::cout << std::left; if (!quietMode && printParser) { std::cout << std::setw(10) << "START" << " = " << number[0] << std::endl; std::cout << std::setw(10) << "STOP" << " = " << number[1] << std::endl; } try { ParallelPrimeSieve pps; pps.setStart(number[0]); pps.setStop (number[1]); if (flags != 0) pps.setFlags(flags); if (sieveSize != -1) pps.setSieveSize(sieveSize); if (preSieve != -1) pps.setPreSieveLimit(preSieve); if (threads != -1) pps.setNumThreads(threads); // set default settings if (!pps.isPrint() && !pps.isCount()) pps.addFlags(pps.COUNT_PRIMES); if (!pps.isPrint() && !quietMode) pps.addFlags(pps.PRINT_STATUS); if (!quietMode) { if (preSieve != -1) std::cout << std::setw(10) << "Pre-sieve" << " = " << pps.getPreSieveLimit() << std::endl; std::cout << std::setw(10) << "Sieve size" << " = " << pps.getSieveSize() << " kilobytes" << std::endl; std::cout << std::setw(10) << "Threads" << " = " << pps.getNumThreads() << std::endl; } // start sieving primes pps.sieve(); if (pps.isFlag(pps.PRINT_STATUS)) std::cout << std::endl; if (pps.isPrint() && pps.isCount()) std::cout << std::endl; int width = getWidth(pps); for (int32_t i = 0; i < 7; i++) { if (pps.isFlag(pps.COUNT_PRIMES << i)) std::cout << std::setw(width) << primes[i] << " : " << pps.getCounts(i) << std::endl; } if (!pps.isPrint()) { std::cout << std::setw(width) << "Time elapsed" << " : " << pps.getSeconds() << " sec" << std::endl; } if (!quietMode && pps.getNumThreads() >= 64) { std::cout << "\nHint: the -q (Quiet mode) option significantly reduces the thread" << std::endl << "synchronization overhead when using >= 64 threads." << std::endl; } } catch (std::exception& e) { std::cerr << "Error: " << e.what() << std::endl << "Try `primesieve -help' for more information." << std::endl; return 1; } return 0; } <commit_msg>improved code readability<commit_after>// // Copyright (c) 2012 Kim Walisch, <[email protected]>. // All rights reserved. // // This file is part of primesieve. // Homepage: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. /// @file main.cpp /// @brief Command-line version of primesieve, multi-threaded (OpenMP). /// @see http://primesieve.googlecode.com /// primesieve is a highly optimized implementation of the sieve of /// Eratosthenes that generates prime numbers and prime k-tuplets (twin /// primes, prime triplets, ...) up to 2^64 maximum. #include "../expr/ExpressionParser.h" #include "../soe/ParallelPrimeSieve.h" // defined in test.cpp void test(); #include <stdint.h> #include <exception> #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <iomanip> #include <algorithm> namespace { // start and stop number for sieving std::vector<uint64_t> number; int32_t threads = -1; int32_t flags = 0; int32_t sieveSize = -1; int32_t preSieve = -1; bool quietMode = false; bool printParserResult = false; const std::string primes[7] = { "Prime numbers", "Twin primes", "Prime triplets", "Prime quadruplets", "Prime quintuplets", "Prime sextuplets", "Prime septuplets" }; void help() { int maxThreads = ParallelPrimeSieve::getMaxThreads(); std::cout << "Usage: primesieve START STOP [OPTION]..." << std::endl << "Use the segmented sieve of Eratosthenes to generate the prime numbers and/or" << std::endl << "prime k-tuplets in the interval [START, STOP] < 2^64" << std::endl << std::endl << "Options:" << std::endl << std::endl << " -c<N+> Count prime numbers and/or prime k-tuplets, 1 <= N <= 7" << std::endl << " e.g. -c1 count prime numbers (DEFAULT)" << std::endl << " -c23 count twin primes and prime triplets" << std::endl << " -o<OFFSET> Sieve the interval [START, START+OFFSET]" << std::endl << " -p<N> Print prime numbers or prime k-tuplets, 1 <= N <= 7" << std::endl << " e.g. -p1 print prime numbers" << std::endl << " -p5 print prime quintuplets" << std::endl << " -q Quiet mode, print less output" << std::endl << " -r<PRE-SIEVE> Pre-sieve multiples of small primes <= PRE-SIEVE to speed up" << std::endl << " the sieve of Eratosthenes, 13 <= PRE-SIEVE <= 23" << std::endl << " -s<SIZE> Set the sieve size in kilobytes, 1 <= SIZE <= 4096" << std::endl << " Set SIZE to your CPU's L1/L2 cache size for best performance" << std::endl << " -t<THREADS> Set the number of threads for sieving, 1 <= THREADS <= " << maxThreads << std::endl << " Primes are not generated in order if THREADS >= 2" << std::endl << " -test Run various sieving tests and exit" << std::endl << " -v Print version and license information and exit" << std::endl << std::endl << "Examples:" << std::endl << std::endl << "Print the prime numbers up to 1000:" << std::endl << "> primesieve 2 1000 -p1" << std::endl << std::endl << "Count the twin primes and prime triplets in the interval [1E10, 1E10+2^32]:" << std::endl << "> primesieve 1E10 -o2**32 -c23" << std::endl; std::exit(1); } void version() { std::cout << "primesieve 3.7, <http://primesieve.googlecode.com>" << std::endl << "Copyright (C) 2012 Kim Walisch" << std::endl << "This software is licensed under the New BSD License. See the LICENSE file" << std::endl << "for more information." << std::endl; std::exit(1); } int getWidth(const ParallelPrimeSieve& pps) { int size = 0; for (int i = 0; i < 7; i++) { if (pps.isFlag(COUNT_PRIMES << i)) size = std::max(size, (int) primes[i].size()); } return size; } bool isDigits(const std::string &str) { const std::string digits("0123456789"); if (str.size() == 0) return false; return str.find_first_not_of(digits) == std::string::npos; } /// Process the command-line options. /// @see help(void) /// void processOptions(int argc, char* argv[]) { if (argc < 2 || argc > 20) help(); std::string arg; ExpressionParser<uint64_t> parser64; ExpressionParser<> parser; uint64_t tmp = 0; // process START and STOP number for (int i = 1; i < std::min(3, argc); i++) { try { number.push_back(parser64.eval(argv[i])); if (!isDigits(argv[i])) printParserResult = true; } catch (parser_error&) { } } // process options for (int i = (int) number.size() + 1; i < argc; i++) { if (*argv[i] != '-' && *argv[i] != '/') help(); argv[i]++; switch (*argv[i]++) { case 'c': tmp = parser.eval(argv[i]); do { if (tmp % 10 < 1 || tmp % 10 > 7) help(); flags |= ParallelPrimeSieve::COUNT_PRIMES << (tmp % 10 - 1); tmp /= 10; } while (tmp > 0); break; case 'o': if (number.size() == 0) help(); tmp = number[0] + parser64.eval(argv[i]); number.push_back(tmp); break; case 'p': tmp = parser.eval(argv[i]); if (tmp < 1 || tmp > 7) help(); flags |= ParallelPrimeSieve::PRINT_PRIMES << (tmp - 1); quietMode = true; break; case 'q': quietMode = true; break; case 'r': preSieve = parser.eval(argv[i]); break; case 's': sieveSize = parser.eval(argv[i]); break; case 't': arg = argv[i]; if (arg.compare("est") == 0) test(); threads = parser.eval(argv[i]); break; case 'v': version(); default : help(); } } if (number.size() != 2) help(); } } // end namespace int main(int argc, char* argv[]) { try { processOptions(argc, argv); } catch (parser_error&) { help(); } std::cout << std::left; if (!quietMode && printParserResult) { std::cout << std::setw(10) << "START" << " = " << number[0] << std::endl; std::cout << std::setw(10) << "STOP" << " = " << number[1] << std::endl; } try { ParallelPrimeSieve pps; pps.setStart(number[0]); pps.setStop (number[1]); if (flags != 0) pps.setFlags(flags); if (sieveSize != -1) pps.setSieveSize(sieveSize); if (preSieve != -1) pps.setPreSieveLimit(preSieve); if (threads != -1) pps.setNumThreads(threads); // set default settings if (!pps.isPrint() && !pps.isCount()) pps.addFlags(pps.COUNT_PRIMES); if (!pps.isPrint() && !quietMode) pps.addFlags(pps.PRINT_STATUS); if (!quietMode) { if (preSieve != -1) std::cout << std::setw(10) << "Pre-sieve" << " = " << pps.getPreSieveLimit() << std::endl; std::cout << std::setw(10) << "Sieve size" << " = " << pps.getSieveSize() << " kilobytes" << std::endl; std::cout << std::setw(10) << "Threads" << " = " << pps.getNumThreads() << std::endl; } // start sieving primes pps.sieve(); if (pps.isFlag(pps.PRINT_STATUS)) std::cout << std::endl; if (pps.isPrint() && pps.isCount()) std::cout << std::endl; int width = getWidth(pps); for (int32_t i = 0; i < 7; i++) { if (pps.isFlag(pps.COUNT_PRIMES << i)) std::cout << std::setw(width) << primes[i] << " : " << pps.getCounts(i) << std::endl; } if (!pps.isPrint()) { std::cout << std::setw(width) << "Time elapsed" << " : " << pps.getSeconds() << " sec" << std::endl; } if (!quietMode && pps.getNumThreads() >= 64) { std::cout << "\nHint: the -q (Quiet mode) option significantly reduces the thread" << std::endl << "synchronization overhead when using >= 64 threads." << std::endl; } } catch (std::exception& e) { std::cerr << "Error: " << e.what() << std::endl << "Try `primesieve -help' for more information." << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>// Smooth - C++ framework for writing applications based on Espressif's ESP-IDF. // Copyright (C) 2019 Per Malmberg (https://github.com/PerMalmberg) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <smooth/core/logging/log.h> #include <smooth/core/SystemStatistics.h> #ifdef ESP_PLATFORM #include <freertos/FreeRTOS.h> #include <freertos/task.h> #endif using namespace smooth::core::logging; static const char* tag = "MemStat"; namespace smooth::core { TaskStats::TaskStats(uint32_t stack_size) : stack_size(stack_size) { #ifdef ESP_PLATFORM high_water_mark = uxTaskGetStackHighWaterMark(nullptr); #else high_water_mark = 0; #endif } void SystemStatistics::dump() const noexcept { //auto current_free = esp_get_free_heap_size(); //auto all_time_free_low = esp_get_minimum_free_heap_size(); #ifdef ESP_PLATFORM Log::info(tag, "[INTERNAL]"); dump_mem_stats(MALLOC_CAP_INTERNAL); Log::info(tag, "[SPIRAM]"); dump_mem_stats(MALLOC_CAP_SPIRAM); #endif { // Only need to lock while accessing the shared data synch guard{lock}; Log::info(tag, Format("Name\tStack\tMin free stack")); for (const auto& stat : task_info) { Log::info(tag, Format("{1}\t{2}\t{3}", Str(stat.first), UInt32(stat.second.get_stack_size()), UInt32(stat.second.get_high_water_mark()))); } } } #ifdef ESP_PLATFORM void SystemStatistics::dump_mem_stats(uint32_t caps) const noexcept { Log::info(tag, Format("8-bit F:{1} LB:{2} M:{3} | 32-bit: F:{4} LB:{5} M:{6}", UInt32(heap_caps_get_free_size(caps | MALLOC_CAP_8BIT)), UInt32(heap_caps_get_largest_free_block(caps | MALLOC_CAP_8BIT)), UInt32(heap_caps_get_minimum_free_size(caps | MALLOC_CAP_8BIT)), UInt32(heap_caps_get_free_size(caps | MALLOC_CAP_32BIT)), UInt32(heap_caps_get_largest_free_block(caps | MALLOC_CAP_32BIT)), UInt32(heap_caps_get_minimum_free_size(caps | MALLOC_CAP_32BIT)))); } #endif }<commit_msg>Log also DMA memory.<commit_after>// Smooth - C++ framework for writing applications based on Espressif's ESP-IDF. // Copyright (C) 2019 Per Malmberg (https://github.com/PerMalmberg) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <smooth/core/logging/log.h> #include <smooth/core/SystemStatistics.h> #ifdef ESP_PLATFORM #include <freertos/FreeRTOS.h> #include <freertos/task.h> #endif using namespace smooth::core::logging; static const char* tag = "MemStat"; namespace smooth::core { TaskStats::TaskStats(uint32_t stack_size) : stack_size(stack_size) { #ifdef ESP_PLATFORM high_water_mark = uxTaskGetStackHighWaterMark(nullptr); #else high_water_mark = 0; #endif } void SystemStatistics::dump() const noexcept { //auto current_free = esp_get_free_heap_size(); //auto all_time_free_low = esp_get_minimum_free_heap_size(); #ifdef ESP_PLATFORM Log::info(tag, "[INTERNAL]"); dump_mem_stats(MALLOC_CAP_INTERNAL); Log::info(tag, "[INTERNAL | DMA]"); dump_mem_stats(MALLOC_CAP_INTERNAL|MALLOC_CAP_DMA); Log::info(tag, "[SPIRAM]"); dump_mem_stats(MALLOC_CAP_SPIRAM); #endif { // Only need to lock while accessing the shared data synch guard{lock}; Log::info(tag, Format("Name\tStack\tMin free stack")); for (const auto& stat : task_info) { Log::info(tag, Format("{1}\t{2}\t{3}", Str(stat.first), UInt32(stat.second.get_stack_size()), UInt32(stat.second.get_high_water_mark()))); } } } #ifdef ESP_PLATFORM void SystemStatistics::dump_mem_stats(uint32_t caps) const noexcept { Log::info(tag, Format("8-bit F:{1} LB:{2} M:{3} | 32-bit: F:{4} LB:{5} M:{6}", UInt32(heap_caps_get_free_size(caps | MALLOC_CAP_8BIT)), UInt32(heap_caps_get_largest_free_block(caps | MALLOC_CAP_8BIT)), UInt32(heap_caps_get_minimum_free_size(caps | MALLOC_CAP_8BIT)), UInt32(heap_caps_get_free_size(caps | MALLOC_CAP_32BIT)), UInt32(heap_caps_get_largest_free_block(caps | MALLOC_CAP_32BIT)), UInt32(heap_caps_get_minimum_free_size(caps | MALLOC_CAP_32BIT)))); } #endif }<|endoftext|>
<commit_before>/** * @file Cosa/IOBuffer.cpp * @version 1.0 * * @section License * Copyright (C) 2013, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * @section Description * Ring buffer for IOStreams. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/IOBuffer.hh" int IOBuffer::putchar(char c) { uint8_t next = (m_head + 1) & BUFFER_MASK; if (next == m_tail) return (-1); m_buffer[next] = c; m_head = next; return (c & 0xff); } int IOBuffer::getchar() { if (is_empty()) return (-1); uint8_t next = (m_tail + 1) & BUFFER_MASK; int c = m_buffer[m_tail]; m_tail = next; return (c & 0xff); } int IOBuffer::flush() { m_tail = 0; m_head = 0; } <commit_msg>Improving IOBuffer. Adding is_full() and inlining some functions.<commit_after>/** * @file Cosa/IOBuffer.cpp * @version 1.0 * * @section License * Copyright (C) 2013, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * @section Description * Circlic buffer for IOStreams. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/IOBuffer.hh" int IOBuffer::putchar(char c) { uint8_t next = (m_head + 1) & BUFFER_MASK; if (next == m_tail) return (-1); m_buffer[next] = c; m_head = next; return (c & 0xff); } int IOBuffer::getchar() { if (m_head == m_tail) return (-1); uint8_t next = (m_tail + 1) & BUFFER_MASK; m_tail = next; return (m_buffer[next]); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ocomponentaccess.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: as $ $Date: 2001-06-11 10:14:41 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_HELPER_OCOMPONENTACCESS_HXX_ #define __FRAMEWORK_HELPER_OCOMPONENTACCESS_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAMESSUPPLIER_HPP_ #include <com/sun/star/frame/XFramesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XELEMENTACCESS_HPP_ #include <com/sun/star/container/XElementAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_ #include <com/sun/star/container/XEnumeration.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short implement XEnumerationAccess interface as helper to create many oneway enumeration of components @descr We share mutex and framecontainer with ouer owner and have full access to his child tasks. (Ouer owner can be the Desktop only!) We create oneway enumerations on demand. These "lists" can be used for one time only. Step during the list from first to last element. (The type of created enumerations is OComponentEnumeration.) @implements XInterface XTypeProvider XEnumerationAccess XElementAccess @base ThreadHelpBase OWeakObject @devstatus ready to use *//*-*************************************************************************************************************/ class OComponentAccess : public css::lang::XTypeProvider , public css::container::XEnumerationAccess , // => XElementAccess private ThreadHelpBase , // Must be the first of baseclasses - Is neccessary for right initialization of objects! public ::cppu::OWeakObject { //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: //--------------------------------------------------------------------------------------------------------- // constructor / destructor //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short constructor to initialize this instance @descr A desktop will create an enumeration-access-object. An enumeration is a oneway-list and a snapshot of the components of current tasks under the desktop. But we need a instance to create more then one enumerations at different times! @seealso class Desktop @seealso class OComponentEnumeration @param "xOwner" is a reference to ouer owner and must be the desktop! @return - @onerror Do nothing and reset this object to default with an empty list. *//*-*****************************************************************************************************/ OComponentAccess( const css::uno::Reference< css::frame::XDesktop >& xOwner ); //--------------------------------------------------------------------------------------------------------- // XInterface //--------------------------------------------------------------------------------------------------------- DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER //--------------------------------------------------------------------------------------------------------- // XEnumerationAccess //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short create a new enumeration of components @descr You can call this method to get a new snapshot from all components of all tasks of the desktop as an enumeration. @seealso interface XEnumerationAccess @seealso interface XEnumeration @seealso class Desktop @param - @return If the desktop and some components exist => a valid reference to an enumeration<BR> An NULL-reference, other way. @onerror - *//*-*****************************************************************************************************/ virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL createEnumeration() throw( css::uno::RuntimeException ); //--------------------------------------------------------------------------------------------------------- // XElementAccess //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short get the type of elements in enumeration @descr - @seealso interface XElementAccess @seealso class OComponentEnumeration @param - @return The uno-type XComponent. @onerror - *//*-*****************************************************************************************************/ virtual css::uno::Type SAL_CALL getElementType() throw( css::uno::RuntimeException ); /*-****************************************************************************************************//** @short get state of componentlist of enumeration. @descr - @seealso interface XElementAccess @param - @return sal_True ,if more then 0 elements exist. @return sal_False ,otherwise. @onerror - *//*-*****************************************************************************************************/ virtual sal_Bool SAL_CALL hasElements() throw( css::uno::RuntimeException ); //------------------------------------------------------------------------------------------------------------- // protected methods //------------------------------------------------------------------------------------------------------------- protected: /*-****************************************************************************************************//** @short standard destructor @descr This method destruct an instance of this class and clear some member. Don't use an instance of this class as normal member. Use it dynamicly with a pointer. We hold a weakreference to ouer owner and not to ouer superclass! Thats the reason for a protected dtor. @seealso class Desktop @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual ~OComponentAccess(); //------------------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------------------- private: /*-****************************************************************************************************//** @short recursive method (!) to collect all components of all frames from the subtree of given node @descr This is neccessary to create the enumeration. @seealso method createEnumeration @param "xNode" , root of subtree and start point of search @param "seqComponents", result list of search. We cant use a return value, we search recursive and must collect all informations. @return - @onerror - *//*-*****************************************************************************************************/ void impl_collectAllChildComponents( const css::uno::Reference< css::frame::XFramesSupplier >& xNode , css::uno::Sequence< css::uno::Reference< css::lang::XComponent > >& seqComponents ); /*-****************************************************************************************************//** @short get the component of a frame @descr The component of a frame can be the window, the controller or the model. @seealso method createEnumeration @param "xFrame", frame which contains the component @return A reference to the component of given frame. @onerror A null reference is returned. *//*-*****************************************************************************************************/ css::uno::Reference< css::lang::XComponent > impl_getFrameComponent( const css::uno::Reference< css::frame::XFrame >& xFrame ) const; //------------------------------------------------------------------------------------------------------------- // debug methods // (should be private everyway!) //------------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short debug-method to check incoming parameter of some other mehods of this class @descr The following methods are used to check parameters for other methods of this class. The return value is used directly for an ASSERT(...). @seealso ASSERTs in implementation! @param references to checking variables @return sal_False ,on invalid parameter. @return sal_True ,otherwise @onerror - *//*-*****************************************************************************************************/ #ifdef ENABLE_ASSERTIONS private: static sal_Bool impldbg_checkParameter_OComponentAccessCtor( const css::uno::Reference< css::frame::XDesktop >& xOwner ); #endif // #ifdef ENABLE_ASSERTIONS //------------------------------------------------------------------------------------------------------------- // variables // (should be private everyway!) //------------------------------------------------------------------------------------------------------------- private: css::uno::WeakReference< css::frame::XDesktop > m_xOwner ; /// weak reference to the desktop object! }; // class OComponentAccess } // namespace framework #endif // #ifndef __FRAMEWORK_HELPER_OCOMPONENTACCESS_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.3.584); FILE MERGED 2005/09/05 13:04:48 rt 1.3.584.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ocomponentaccess.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:16:50 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_HELPER_OCOMPONENTACCESS_HXX_ #define __FRAMEWORK_HELPER_OCOMPONENTACCESS_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAMESSUPPLIER_HPP_ #include <com/sun/star/frame/XFramesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XELEMENTACCESS_HPP_ #include <com/sun/star/container/XElementAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_ #include <com/sun/star/container/XEnumeration.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short implement XEnumerationAccess interface as helper to create many oneway enumeration of components @descr We share mutex and framecontainer with ouer owner and have full access to his child tasks. (Ouer owner can be the Desktop only!) We create oneway enumerations on demand. These "lists" can be used for one time only. Step during the list from first to last element. (The type of created enumerations is OComponentEnumeration.) @implements XInterface XTypeProvider XEnumerationAccess XElementAccess @base ThreadHelpBase OWeakObject @devstatus ready to use *//*-*************************************************************************************************************/ class OComponentAccess : public css::lang::XTypeProvider , public css::container::XEnumerationAccess , // => XElementAccess private ThreadHelpBase , // Must be the first of baseclasses - Is neccessary for right initialization of objects! public ::cppu::OWeakObject { //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: //--------------------------------------------------------------------------------------------------------- // constructor / destructor //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short constructor to initialize this instance @descr A desktop will create an enumeration-access-object. An enumeration is a oneway-list and a snapshot of the components of current tasks under the desktop. But we need a instance to create more then one enumerations at different times! @seealso class Desktop @seealso class OComponentEnumeration @param "xOwner" is a reference to ouer owner and must be the desktop! @return - @onerror Do nothing and reset this object to default with an empty list. *//*-*****************************************************************************************************/ OComponentAccess( const css::uno::Reference< css::frame::XDesktop >& xOwner ); //--------------------------------------------------------------------------------------------------------- // XInterface //--------------------------------------------------------------------------------------------------------- DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER //--------------------------------------------------------------------------------------------------------- // XEnumerationAccess //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short create a new enumeration of components @descr You can call this method to get a new snapshot from all components of all tasks of the desktop as an enumeration. @seealso interface XEnumerationAccess @seealso interface XEnumeration @seealso class Desktop @param - @return If the desktop and some components exist => a valid reference to an enumeration<BR> An NULL-reference, other way. @onerror - *//*-*****************************************************************************************************/ virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL createEnumeration() throw( css::uno::RuntimeException ); //--------------------------------------------------------------------------------------------------------- // XElementAccess //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short get the type of elements in enumeration @descr - @seealso interface XElementAccess @seealso class OComponentEnumeration @param - @return The uno-type XComponent. @onerror - *//*-*****************************************************************************************************/ virtual css::uno::Type SAL_CALL getElementType() throw( css::uno::RuntimeException ); /*-****************************************************************************************************//** @short get state of componentlist of enumeration. @descr - @seealso interface XElementAccess @param - @return sal_True ,if more then 0 elements exist. @return sal_False ,otherwise. @onerror - *//*-*****************************************************************************************************/ virtual sal_Bool SAL_CALL hasElements() throw( css::uno::RuntimeException ); //------------------------------------------------------------------------------------------------------------- // protected methods //------------------------------------------------------------------------------------------------------------- protected: /*-****************************************************************************************************//** @short standard destructor @descr This method destruct an instance of this class and clear some member. Don't use an instance of this class as normal member. Use it dynamicly with a pointer. We hold a weakreference to ouer owner and not to ouer superclass! Thats the reason for a protected dtor. @seealso class Desktop @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual ~OComponentAccess(); //------------------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------------------- private: /*-****************************************************************************************************//** @short recursive method (!) to collect all components of all frames from the subtree of given node @descr This is neccessary to create the enumeration. @seealso method createEnumeration @param "xNode" , root of subtree and start point of search @param "seqComponents", result list of search. We cant use a return value, we search recursive and must collect all informations. @return - @onerror - *//*-*****************************************************************************************************/ void impl_collectAllChildComponents( const css::uno::Reference< css::frame::XFramesSupplier >& xNode , css::uno::Sequence< css::uno::Reference< css::lang::XComponent > >& seqComponents ); /*-****************************************************************************************************//** @short get the component of a frame @descr The component of a frame can be the window, the controller or the model. @seealso method createEnumeration @param "xFrame", frame which contains the component @return A reference to the component of given frame. @onerror A null reference is returned. *//*-*****************************************************************************************************/ css::uno::Reference< css::lang::XComponent > impl_getFrameComponent( const css::uno::Reference< css::frame::XFrame >& xFrame ) const; //------------------------------------------------------------------------------------------------------------- // debug methods // (should be private everyway!) //------------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short debug-method to check incoming parameter of some other mehods of this class @descr The following methods are used to check parameters for other methods of this class. The return value is used directly for an ASSERT(...). @seealso ASSERTs in implementation! @param references to checking variables @return sal_False ,on invalid parameter. @return sal_True ,otherwise @onerror - *//*-*****************************************************************************************************/ #ifdef ENABLE_ASSERTIONS private: static sal_Bool impldbg_checkParameter_OComponentAccessCtor( const css::uno::Reference< css::frame::XDesktop >& xOwner ); #endif // #ifdef ENABLE_ASSERTIONS //------------------------------------------------------------------------------------------------------------- // variables // (should be private everyway!) //------------------------------------------------------------------------------------------------------------- private: css::uno::WeakReference< css::frame::XDesktop > m_xOwner ; /// weak reference to the desktop object! }; // class OComponentAccess } // namespace framework #endif // #ifndef __FRAMEWORK_HELPER_OCOMPONENTACCESS_HXX_ <|endoftext|>
<commit_before>#include <memory> #include "DeviceManager.hpp" typedef unsigned char uchar; struct Snapshot { int m_seed; float m_frequency; int m_interp; int m_noiseType; int m_octaves; float m_lacunarity; float m_gain; int m_fractalType; float m_fractalBounding; int m_cellularDistanceFunction; int m_cellularReturnType; float m_perturbAmp; int m_perturb; }; class KernelAdapter { public: //Initialize KernelAdapter(Device& device); ~KernelAdapter(); //Kernels //2D float* GEN_Value2( Snapshot param, // IN : class members size_t size_x, size_t size_y, // | float scale_x, float scale_y, // | IN : Parameters float offset_x, float offset_y // | ); float* GEN_ValueFractal2( Snapshot param, // IN : class members size_t size_x, size_t size_y, // | float scale_x, float scale_y, // | IN : Parameters float offset_x, float offset_y // | ); float* GEN_Perlin2( Snapshot param, // IN : class members size_t size_x, size_t size_y, // | float scale_x, float scale_y, // | IN : Parameters float offset_x, float offset_y // | ); float* GEN_PerlinFractal2( Snapshot param, // IN : class members size_t size_x, size_t size_y, // | float scale_x, float scale_y, // | IN : Parameters float offset_x, float offset_y // | ); float* GEN_Simplex2( Snapshot param, // IN : class members size_t size_x, size_t size_y, // | float scale_x, float scale_y, // | IN : Parameters float offset_x, float offset_y // | ); float* GEN_SimplexFractal2( Snapshot param, // IN : class members size_t size_x, size_t size_y, // | float scale_x, float scale_y, // | IN : Parameters float offset_x, float offset_y // | ); float* GEN_Cellular2( Snapshot param, // IN : class members size_t size_x, size_t size_y, // | float scale_x, float scale_y, // | IN : Parameters float offset_x, float offset_y // | ); float* GEN_WhiteNoise2( Snapshot param, // IN : class members size_t size_x, size_t size_y, // | float scale_x, float scale_y, // | IN : Parameters float offset_x, float offset_y // | ); float* GEN_WhiteNoiseInt2( Snapshot param, // IN : class members size_t size_x, size_t size_y, // | int scale_x, int scale_y, // | IN : Parameters int offset_x, int offset_y // | ); //3D float* GEN_Value3( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, // | float scale_x, float scale_y, float scale_z, // | IN : Parameters float offset_x, float offset_y, float offset_z // | ); float* GEN_ValueFractal3( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, // | float scale_x, float scale_y, float scale_z, // | IN : Parameters float offset_x, float offset_y, float offset_z // | ); float* GEN_Perlin3( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, // | float scale_x, float scale_y, float scale_z, // | IN : Parameters float offset_x, float offset_y, float offset_z // | ); float* GEN_PerlinFractal3( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, // | float scale_x, float scale_y, float scale_z, // | IN : Parameters float offset_x, float offset_y, float offset_z // | ); float* GEN_Simplex3( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, // | float scale_x, float scale_y, float scale_z, // | IN : Parameters float offset_x, float offset_y, float offset_z // | ); float* GEN_SimplexFractal3( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, // | float scale_x, float scale_y, float scale_z, // | IN : Parameters float offset_x, float offset_y, float offset_z // | ); float* GEN_Cellular3( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, // | float scale_x, float scale_y, float scale_z, // | IN : Parameters float offset_x, float offset_y, float offset_z // | ); float* GEN_WhiteNoise3( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, // | float scale_x, float scale_y, float scale_z, // | IN : Parameters float offset_x, float offset_y, float offset_z // | ); float* GEN_WhiteNoiseInt3( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, // | int scale_x, int scale_y, int scale_z, // | IN : Parameters int offset_x, int offset_y, int offset_z // | ); //4D float* GEN_Simplex4( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, size_t size_w, // | float scale_x, float scale_y, float scale_z, float scale_w, // | IN : Parameters float offset_x, float offset_y, float offset_z, float offset_w // | ); float* GEN_WhiteNoise4( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, size_t size_w, // | float scale_x, float scale_y, float scale_z, float scale_w, // | IN : Parameters float offset_x, float offset_y, float offset_z, float offset_w // | ); float* GEN_WhiteNoiseInt4( Snapshot param, // IN : class members size_t size_x, size_t size_y, size_t size_z, size_t size_w, // | int scale_x, int scale_y, int scale_z, int scale_w, // | IN : Parameters int offset_x, int offset_y, int offset_z, int offset_w // | ); //NoiseLookup float* GEN_Lookup_Cellular2( Snapshot* params, size_t size_p, // IN : members of all classes size_t size_x, size_t size_y, // | float scale_x, float scale_y, // | IN : Parameters float offset_x, float offset_y // | ); float* GEN_Lookup_Cellular3( Snapshot* params, size_t size_p, // IN : members of all classes size_t size_x, size_t size_y, size_t size_z, // | float scale_x, float scale_y, float scale_z, // | IN : Parameters float offset_x, float offset_y, float offset_z // | ); private: class impl; std::unique_ptr<impl> pimpl; }; <commit_msg>Delete KernelAdapter.hpp<commit_after><|endoftext|>
<commit_before>/* libs/graphics/ports/SkFontHost_fontconfig.cpp ** ** Copyright 2008, Google Inc. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ // ----------------------------------------------------------------------------- // This file provides implementations of the font resolution members of // SkFontHost by using the fontconfig[1] library. Fontconfig is usually found // on Linux systems and handles configuration, parsing and caching issues // involved with enumerating and matching fonts. // // [1] http://fontconfig.org // ----------------------------------------------------------------------------- #include <map> #include <string> #include <fontconfig/fontconfig.h> #include "SkDescriptor.h" #include "SkFontHost.h" #include "SkMMapStream.h" #include "SkPaint.h" #include "SkStream.h" #include "SkString.h" #include "SkThread.h" #include "SkTSearch.h" // This is an extern from SkFontHost_FreeType SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name); // ----------------------------------------------------------------------------- // The rest of Skia requires that fonts be identified by a unique unsigned id // and that we be able to load them given the id. What we actually get from // fontconfig is the filename of the font so we keep a locked map from // filenames to fileid numbers and back. // // Note that there's also a unique id in the SkTypeface. This is unique over // both filename and style. Thus we encode that id as (fileid << 8) | style. // Although truetype fonts can support multiple faces in a single file, at the // moment Skia doesn't. // ----------------------------------------------------------------------------- static SkMutex global_fc_map_lock; static std::map<std::string, unsigned> global_fc_map; static std::map<unsigned, std::string> global_fc_map_inverted; static unsigned global_fc_map_next_id = 0; // This is the maximum size of the font cache. static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB static unsigned UniqueIdToFileId(unsigned uniqueid) { return uniqueid >> 8; } static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid) { return static_cast<SkTypeface::Style>(uniqueid & 0xff); } static unsigned FileIdAndStyleToUniqueId(unsigned fileid, SkTypeface::Style style) { // TODO(agl/brettw) bug 6291: This assertion fails for unknown reasons // on ChromeFontTest.LoadArial. This should be fixed. //SkASSERT(style & 0xff == style); return (fileid << 8) | static_cast<int>(style); } class FontConfigTypeface : public SkTypeface { public: FontConfigTypeface(Style style, uint32_t id) : SkTypeface(style, id) { } }; // ----------------------------------------------------------------------------- // Find a matching font where @type (one of FC_*) is equal to @value. For a // list of types, see http://fontconfig.org/fontconfig-devel/x19.html#AEN27. // The variable arguments are a list of triples, just like the first three // arguments, and must be NULL terminated. // // For example, FontMatchString(FC_FILE, FcTypeString, // "/usr/share/fonts/myfont.ttf", NULL); // ----------------------------------------------------------------------------- static FcPattern* FontMatch(const char* type, FcType vtype, const void* value, ...) { va_list ap; va_start(ap, value); FcPattern* pattern = FcPatternCreate(); bool family_requested = false; for (;;) { FcValue fcvalue; fcvalue.type = vtype; switch (vtype) { case FcTypeString: fcvalue.u.s = (FcChar8*) value; break; case FcTypeInteger: fcvalue.u.i = (int) value; break; default: SkASSERT(!"FontMatch unhandled type"); } FcPatternAdd(pattern, type, fcvalue, 0); if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0) family_requested = true; type = va_arg(ap, const char *); if (!type) break; // FcType is promoted to int when passed through ... vtype = static_cast<FcType>(va_arg(ap, int)); value = va_arg(ap, const void *); }; va_end(ap); FcConfigSubstitute(0, pattern, FcMatchPattern); FcDefaultSubstitute(pattern); // Font matching: // CSS often specifies a fallback list of families: // font-family: a, b, c, serif; // However, fontconfig will always do its best to find *a* font when asked // for something so we need a way to tell if the match which it has found is // "good enough" for us. Otherwise, we can return NULL which gets piped up // and lets WebKit know to try the next CSS family name. However, fontconfig // configs allow substitutions (mapping "Arial -> Helvetica" etc) and we // wish to support that. // // Thus, if a specific family is requested we set @family_requested. Then we // record two strings: the family name after config processing and the // family name after resolving. If the two are equal, it's a good match. // // So consider the case where a user has mapped Arial to Helvetica in their // config. // requested family: "Arial" // post_config_family: "Helvetica" // post_match_family: "Helvetica" // -> good match // // and for a missing font: // requested family: "Monaco" // post_config_family: "Monaco" // post_match_family: "Times New Roman" // -> BAD match FcChar8* post_config_family; FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family); FcResult result; FcPattern* match = FcFontMatch(0, pattern, &result); if (!match) { FcPatternDestroy(pattern); return NULL; } FcChar8* post_match_family; FcPatternGetString(match, FC_FAMILY, 0, &post_match_family); const bool family_names_match = !family_requested ? true : strcasecmp((char *) post_config_family, (char *) post_match_family) == 0; FcPatternDestroy(pattern); if (!family_names_match) { FcPatternDestroy(match); return NULL; } return match; } // ----------------------------------------------------------------------------- // Check to see if the filename has already been assigned a fileid and, if so, // use it. Otherwise, assign one. Return the resulting fileid. // ----------------------------------------------------------------------------- static unsigned FileIdFromFilename(const char* filename) { SkAutoMutexAcquire ac(global_fc_map_lock); std::map<std::string, unsigned>::const_iterator i = global_fc_map.find(filename); if (i == global_fc_map.end()) { const unsigned fileid = global_fc_map_next_id++; global_fc_map[filename] = fileid; global_fc_map_inverted[fileid] = filename; return fileid; } else { return i->second; } } SkTypeface* SkFontHost::FindTypeface(const SkTypeface* familyFace, const char familyName[], SkTypeface::Style style) { const char* resolved_family_name = NULL; FcPattern* face_match = NULL; if (familyFace) { // Here we use the inverted global id map to find the filename from the // SkTypeface object. Given the filename we can ask fontconfig for the // familyname of the font. SkAutoMutexAcquire ac(global_fc_map_lock); const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID()); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; FcInit(); face_match = FontMatch(FC_FILE, FcTypeString, i->second.c_str(), NULL); if (!face_match) return NULL; FcChar8* family; if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) { FcPatternDestroy(face_match); return NULL; } // At this point, @family is pointing into the @face_match object so we // cannot release it yet. resolved_family_name = reinterpret_cast<char*>(family); } else if (familyName) { resolved_family_name = familyName; } else { return NULL; } { SkAutoMutexAcquire ac(global_fc_map_lock); FcInit(); } // At this point, we have a resolved_family_name from somewhere SkASSERT(resolved_family_name); const int bold = style & SkTypeface::kBold ? FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL; const int italic = style & SkTypeface::kItalic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN; FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, resolved_family_name, FC_WEIGHT, FcTypeInteger, bold, FC_SLANT, FcTypeInteger, italic, NULL); if (face_match) FcPatternDestroy(face_match); if (!match) return NULL; FcChar8* filename; if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) { FcPatternDestroy(match); return NULL; } // Now @filename is pointing into @match const unsigned fileid = FileIdFromFilename(reinterpret_cast<char*>(filename)); const unsigned id = FileIdAndStyleToUniqueId(fileid, style); SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id)); FcPatternDestroy(match); return typeface; } SkTypeface* SkFontHost::ResolveTypeface(uint32_t id) { SkAutoMutexAcquire ac(global_fc_map_lock); const SkTypeface::Style style = UniqueIdToStyle(id); const unsigned fileid = UniqueIdToFileId(id); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; return SkNEW_ARGS(FontConfigTypeface, (style, id)); } SkStream* SkFontHost::OpenStream(uint32_t id) { SkAutoMutexAcquire ac(global_fc_map_lock); const unsigned fileid = UniqueIdToFileId(id); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; return SkNEW_ARGS(SkFILEStream, (i->second.c_str())); } void SkFontHost::CloseStream(uint32_t fontID, SkStream* stream) { } SkTypeface* SkFontHost::CreateTypeface(SkStream* stream) { SkASSERT(!"SkFontHost::CreateTypeface unimplemented"); return NULL; } SkTypeface* SkFontHost::Deserialize(SkStream* stream) { SkASSERT(!"SkFontHost::Deserialize unimplemented"); return NULL; } void SkFontHost::Serialize(const SkTypeface*, SkWStream*) { SkASSERT(!"SkFontHost::Serialize unimplemented"); } SkScalerContext* SkFontHost::CreateFallbackScalerContext (const SkScalerContext::Rec& rec) { FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, "serif", NULL); // This will fail when we have no fonts on the system. SkASSERT(match); FcChar8* filename; if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) { FcPatternDestroy(match); return NULL; } // Now @filename is pointing into @match const unsigned id = FileIdFromFilename(reinterpret_cast<char*>(filename)); FcPatternDestroy(match); SkAutoDescriptor ad(sizeof(rec) + SkDescriptor::ComputeOverhead(1)); SkDescriptor* desc = ad.getDesc(); desc->init(); SkScalerContext::Rec* newRec = (SkScalerContext::Rec*)desc->addEntry(kRec_SkDescriptorTag, sizeof(rec), &rec); newRec->fFontID = id; desc->computeChecksum(); return SkFontHost::CreateScalerContext(desc); } /////////////////////////////////////////////////////////////////////////////// size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar) { if (sizeAllocatedSoFar > kFontCacheMemoryBudget) return sizeAllocatedSoFar - kFontCacheMemoryBudget; else return 0; // nothing to do } <commit_msg>Linux: fix failure to find any fonts<commit_after>/* libs/graphics/ports/SkFontHost_fontconfig.cpp ** ** Copyright 2008, Google Inc. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ // ----------------------------------------------------------------------------- // This file provides implementations of the font resolution members of // SkFontHost by using the fontconfig[1] library. Fontconfig is usually found // on Linux systems and handles configuration, parsing and caching issues // involved with enumerating and matching fonts. // // [1] http://fontconfig.org // ----------------------------------------------------------------------------- #include <map> #include <string> #include <fontconfig/fontconfig.h> #include "SkDescriptor.h" #include "SkFontHost.h" #include "SkMMapStream.h" #include "SkPaint.h" #include "SkStream.h" #include "SkString.h" #include "SkThread.h" #include "SkTSearch.h" // This is an extern from SkFontHost_FreeType SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name); // ----------------------------------------------------------------------------- // The rest of Skia requires that fonts be identified by a unique unsigned id // and that we be able to load them given the id. What we actually get from // fontconfig is the filename of the font so we keep a locked map from // filenames to fileid numbers and back. // // Note that there's also a unique id in the SkTypeface. This is unique over // both filename and style. Thus we encode that id as (fileid << 8) | style. // Although truetype fonts can support multiple faces in a single file, at the // moment Skia doesn't. // ----------------------------------------------------------------------------- static SkMutex global_fc_map_lock; static std::map<std::string, unsigned> global_fc_map; static std::map<unsigned, std::string> global_fc_map_inverted; static unsigned global_fc_map_next_id = 0; // This is the maximum size of the font cache. static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB static unsigned UniqueIdToFileId(unsigned uniqueid) { return uniqueid >> 8; } static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid) { return static_cast<SkTypeface::Style>(uniqueid & 0xff); } static unsigned FileIdAndStyleToUniqueId(unsigned fileid, SkTypeface::Style style) { // TODO(agl/brettw) bug 6291: This assertion fails for unknown reasons // on ChromeFontTest.LoadArial. This should be fixed. //SkASSERT(style & 0xff == style); return (fileid << 8) | static_cast<int>(style); } class FontConfigTypeface : public SkTypeface { public: FontConfigTypeface(Style style, uint32_t id) : SkTypeface(style, id) { } }; // ----------------------------------------------------------------------------- // Find a matching font where @type (one of FC_*) is equal to @value. For a // list of types, see http://fontconfig.org/fontconfig-devel/x19.html#AEN27. // The variable arguments are a list of triples, just like the first three // arguments, and must be NULL terminated. // // For example, FontMatchString(FC_FILE, FcTypeString, // "/usr/share/fonts/myfont.ttf", NULL); // ----------------------------------------------------------------------------- static FcPattern* FontMatch(bool is_fallback, const char* type, FcType vtype, const void* value, ...) { va_list ap; va_start(ap, value); FcPattern* pattern = FcPatternCreate(); bool family_requested = false; for (;;) { FcValue fcvalue; fcvalue.type = vtype; switch (vtype) { case FcTypeString: fcvalue.u.s = (FcChar8*) value; break; case FcTypeInteger: fcvalue.u.i = (int) value; break; default: SkASSERT(!"FontMatch unhandled type"); } FcPatternAdd(pattern, type, fcvalue, 0); if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0) family_requested = true; type = va_arg(ap, const char *); if (!type) break; // FcType is promoted to int when passed through ... vtype = static_cast<FcType>(va_arg(ap, int)); value = va_arg(ap, const void *); }; va_end(ap); FcConfigSubstitute(0, pattern, FcMatchPattern); FcDefaultSubstitute(pattern); // Font matching: // CSS often specifies a fallback list of families: // font-family: a, b, c, serif; // However, fontconfig will always do its best to find *a* font when asked // for something so we need a way to tell if the match which it has found is // "good enough" for us. Otherwise, we can return NULL which gets piped up // and lets WebKit know to try the next CSS family name. However, fontconfig // configs allow substitutions (mapping "Arial -> Helvetica" etc) and we // wish to support that. // // Thus, if a specific family is requested we set @family_requested. Then we // record two strings: the family name after config processing and the // family name after resolving. If the two are equal, it's a good match. // // So consider the case where a user has mapped Arial to Helvetica in their // config. // requested family: "Arial" // post_config_family: "Helvetica" // post_match_family: "Helvetica" // -> good match // // and for a missing font: // requested family: "Monaco" // post_config_family: "Monaco" // post_match_family: "Times New Roman" // -> BAD match FcChar8* post_config_family; FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family); FcResult result; FcPattern* match = FcFontMatch(0, pattern, &result); if (!match) { FcPatternDestroy(pattern); return NULL; } FcChar8* post_match_family; FcPatternGetString(match, FC_FAMILY, 0, &post_match_family); const bool family_names_match = !family_requested ? true : strcasecmp((char *) post_config_family, (char *) post_match_family) == 0; FcPatternDestroy(pattern); if (!family_names_match && !is_fallback) { FcPatternDestroy(match); return NULL; } return match; } // ----------------------------------------------------------------------------- // Check to see if the filename has already been assigned a fileid and, if so, // use it. Otherwise, assign one. Return the resulting fileid. // ----------------------------------------------------------------------------- static unsigned FileIdFromFilename(const char* filename) { SkAutoMutexAcquire ac(global_fc_map_lock); std::map<std::string, unsigned>::const_iterator i = global_fc_map.find(filename); if (i == global_fc_map.end()) { const unsigned fileid = global_fc_map_next_id++; global_fc_map[filename] = fileid; global_fc_map_inverted[fileid] = filename; return fileid; } else { return i->second; } } SkTypeface* SkFontHost::FindTypeface(const SkTypeface* familyFace, const char familyName[], SkTypeface::Style style) { const char* resolved_family_name = NULL; FcPattern* face_match = NULL; if (familyFace) { // Here we use the inverted global id map to find the filename from the // SkTypeface object. Given the filename we can ask fontconfig for the // familyname of the font. SkAutoMutexAcquire ac(global_fc_map_lock); const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID()); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; FcInit(); face_match = FontMatch(false, FC_FILE, FcTypeString, i->second.c_str(), NULL); if (!face_match) return NULL; FcChar8* family; if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) { FcPatternDestroy(face_match); return NULL; } // At this point, @family is pointing into the @face_match object so we // cannot release it yet. resolved_family_name = reinterpret_cast<char*>(family); } else if (familyName) { resolved_family_name = familyName; } else { return NULL; } { SkAutoMutexAcquire ac(global_fc_map_lock); FcInit(); } // At this point, we have a resolved_family_name from somewhere SkASSERT(resolved_family_name); const int bold = style & SkTypeface::kBold ? FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL; const int italic = style & SkTypeface::kItalic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN; FcPattern* match = FontMatch(false, FC_FAMILY, FcTypeString, resolved_family_name, FC_WEIGHT, FcTypeInteger, bold, FC_SLANT, FcTypeInteger, italic, NULL); if (face_match) FcPatternDestroy(face_match); if (!match) return NULL; FcChar8* filename; if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) { FcPatternDestroy(match); return NULL; } // Now @filename is pointing into @match const unsigned fileid = FileIdFromFilename(reinterpret_cast<char*>(filename)); const unsigned id = FileIdAndStyleToUniqueId(fileid, style); SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id)); FcPatternDestroy(match); return typeface; } SkTypeface* SkFontHost::ResolveTypeface(uint32_t id) { SkAutoMutexAcquire ac(global_fc_map_lock); const SkTypeface::Style style = UniqueIdToStyle(id); const unsigned fileid = UniqueIdToFileId(id); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; return SkNEW_ARGS(FontConfigTypeface, (style, id)); } SkStream* SkFontHost::OpenStream(uint32_t id) { SkAutoMutexAcquire ac(global_fc_map_lock); const unsigned fileid = UniqueIdToFileId(id); std::map<unsigned, std::string>::const_iterator i = global_fc_map_inverted.find(fileid); if (i == global_fc_map_inverted.end()) return NULL; return SkNEW_ARGS(SkFILEStream, (i->second.c_str())); } void SkFontHost::CloseStream(uint32_t fontID, SkStream* stream) { } SkTypeface* SkFontHost::CreateTypeface(SkStream* stream) { SkASSERT(!"SkFontHost::CreateTypeface unimplemented"); return NULL; } SkTypeface* SkFontHost::Deserialize(SkStream* stream) { SkASSERT(!"SkFontHost::Deserialize unimplemented"); return NULL; } void SkFontHost::Serialize(const SkTypeface*, SkWStream*) { SkASSERT(!"SkFontHost::Serialize unimplemented"); } SkScalerContext* SkFontHost::CreateFallbackScalerContext (const SkScalerContext::Rec& rec) { FcPattern* match = FontMatch(true, FC_FAMILY, FcTypeString, "serif", NULL); // This will fail when we have no fonts on the system. SkASSERT(match); FcChar8* filename; if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) { FcPatternDestroy(match); return NULL; } // Now @filename is pointing into @match const unsigned id = FileIdFromFilename(reinterpret_cast<char*>(filename)); FcPatternDestroy(match); SkAutoDescriptor ad(sizeof(rec) + SkDescriptor::ComputeOverhead(1)); SkDescriptor* desc = ad.getDesc(); desc->init(); SkScalerContext::Rec* newRec = (SkScalerContext::Rec*)desc->addEntry(kRec_SkDescriptorTag, sizeof(rec), &rec); newRec->fFontID = id; desc->computeChecksum(); return SkFontHost::CreateScalerContext(desc); } /////////////////////////////////////////////////////////////////////////////// size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar) { if (sizeAllocatedSoFar > kFontCacheMemoryBudget) return sizeAllocatedSoFar - kFontCacheMemoryBudget; else return 0; // nothing to do } <|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2016 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : hugh/render/software/test/rasterizer/simple.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // includes, system #include <array> // std::array<> #include <glm/gtx/io.hpp> // glm::operator<< // includes, project #include <hugh/render/software/rasterizer/simple.hpp> #include <hugh/support/io_utils.hpp> #define HUGH_USE_TRACE #undef HUGH_USE_TRACE #include <hugh/support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal } // namespace { #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(test_hugh_render_software_rasterizer_simple_ctor) { using namespace hugh::render::software; { rasterizer::simple const rs; BOOST_CHECK(true); } { using viewport = hugh::scene::object::camera::viewport; rasterizer::simple const rs(viewport(0, 0, 10, 10)); BOOST_CHECK(true); } } BOOST_AUTO_TEST_CASE(test_hugh_render_software_rasterizer_simple_process_line) { using namespace hugh::render::software; using viewport = hugh::scene::object::camera::viewport; viewport const v(0, 0, 4, 3); // adj: 0 //viewport const v(0, 0, 8, 6); // adj: -1 //viewport const v(0, 0, 16, 12); // adj: -3 //viewport const v(0, 0, 24, 18); // adj: -5 //viewport const v(0, 0, 40, 30); // adj: -9 // w*w+h*h needs to be a square number for 'd' to make sense unsigned const d(std::sqrt((v. width * v. width) + (v.height * v.height))); glm::vec3 const o( 0, 0,0); glm::vec3 const x(v.width, 0,0); glm::vec3 const y( 0,v.height,0); glm::vec3 const z( 0, 0,1); std::array<std::pair<line const, unsigned const>, 22> const lines = { { { line(o, x), v. width+1 }, { line( x, o), v. width+1 }, { line(o, -x), 1 }, { line( -x, o), 1 }, { line(x, -x), v. width+1 }, { line( -x, x), v. width+1 }, { line(o, y), v.height+1 }, { line( y, o), v.height+1 }, { line(o, -y), 1 }, { line( -y, o), 1 }, { line(y, -y), v.height+1 }, { line( -y, y), v.height+1 }, { line(o, z), 1 }, { line( z, o), 1 }, { line(o, -z), 1 }, { line( -z, o), 1 }, { line(z, -z), 1 }, { line( -z, z), 1 }, { line(o, x+y), d }, { line(x+y, o), d }, { line(y, x), d }, { line( x, y), d }, } }; rasterizer::simple const rs(v); for (auto const& lp : lines) { using fragment_list = rasterizer::simple::fragment_list_type; fragment_list const fl(rs.process(lp.first)); BOOST_CHECK(lp.second == fl.size()); { std::ostringstream ostr; using hugh::support::ostream::operator<<; ostr << lp.second << "=?=" << fl.size() << ':' << glm::io::width(2) << glm::io::precision(0) << fl; BOOST_TEST_MESSAGE(ostr.str()); } } } BOOST_AUTO_TEST_CASE(test_hugh_render_software_rasterizer_simple_print_on) { using namespace hugh::render::software; using viewport = hugh::scene::object::camera::viewport; rasterizer::simple const rs(viewport(0, 0, 10, 10)); std::ostringstream ostr; ostr << rs; BOOST_CHECK (!ostr.str().empty()); BOOST_TEST_MESSAGE( ostr.str()); } <commit_msg>added: test case for triangle processing<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2016 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : hugh/render/software/test/rasterizer/simple.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // includes, system #include <array> // std::array<> #include <glm/gtx/io.hpp> // glm::operator<< // includes, project #include <hugh/render/software/rasterizer/simple.hpp> #include <hugh/support/io_utils.hpp> #define HUGH_USE_TRACE #undef HUGH_USE_TRACE #include <hugh/support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal } // namespace { #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(test_hugh_render_software_rasterizer_simple_ctor) { using namespace hugh::render::software; using viewport = hugh::scene::object::camera::viewport; { rasterizer::simple const rs; BOOST_CHECK(viewport() == *rs.viewport); } { viewport const vp(0, 0, 10, 10); rasterizer::simple const rs(vp); BOOST_CHECK(vp == *rs.viewport); } } BOOST_AUTO_TEST_CASE(test_hugh_render_software_rasterizer_simple_process_line) { using namespace hugh::render::software; using viewport = hugh::scene::object::camera::viewport; viewport const v(0, 0, 4, 3); // adj: 0 //viewport const v(0, 0, 8, 6); // adj: -1 //viewport const v(0, 0, 16, 12); // adj: -3 //viewport const v(0, 0, 24, 18); // adj: -5 //viewport const v(0, 0, 40, 30); // adj: -9 // w*w+h*h needs to be a square number for 'd' to make sense unsigned const d(std::sqrt((v. width * v. width) + (v.height * v.height))); glm::vec3 const o( 0, 0, 0); glm::vec3 const x(v.width, 0, 0); glm::vec3 const y( 0, v.height, 0); glm::vec3 const z( 0, 0, 1); std::array<std::pair<line const, unsigned const>, 22> const lines = { { { line(o, x), v. width+1 }, { line( x, o), v. width+1 }, { line(o, -x), 1 }, { line( -x, o), 1 }, { line(x, -x), v. width+1 }, { line( -x, x), v. width+1 }, { line(o, y), v.height+1 }, { line( y, o), v.height+1 }, { line(o, -y), 1 }, { line( -y, o), 1 }, { line(y, -y), v.height+1 }, { line( -y, y), v.height+1 }, { line(o, z), 1 }, { line( z, o), 1 }, { line(o, -z), 1 }, { line( -z, o), 1 }, { line(z, -z), 1 }, { line( -z, z), 1 }, { line(o, x+y), d }, { line(x+y, o), d }, { line(y, x), d }, { line( x, y), d }, } }; rasterizer::simple const rs(v); for (auto const& lp : lines) { using fragment_list = rasterizer::simple::fragment_list_type; fragment_list const fl(rs.process(lp.first)); BOOST_CHECK(lp.second == fl.size()); { std::ostringstream ostr; using hugh::support::ostream::operator<<; ostr << lp.second << "=?=" << fl.size() << ':' << glm::io::width(2) << glm::io::precision(0) << fl; BOOST_TEST_MESSAGE(ostr.str()); } } BOOST_TEST_MESSAGE('\n'); } template <typename T> glm::tvec3<T> two(glm::tvec3<T> const& a) { return a * T(2); } BOOST_AUTO_TEST_CASE(test_hugh_render_software_rasterizer_simple_process_triangle) { using namespace hugh::render::software; using viewport = hugh::scene::object::camera::viewport; //viewport const v(0, 0, 4, 3); // adj: +1, -2 viewport const v(0, 0, 8, 6); // adj: +2, -3 //viewport const v(0, 0, 16, 12); // adj: +3 //viewport const v(0, 0, 24, 18); // adj: +4 //viewport const v(0, 0, 40, 30); // adj: +6 unsigned const a((((v.width+1) * (v.height+1)) / 2) + 2); glm::vec3 const o( 0, 0, 0); glm::vec3 const x(v.width, 0, 0); glm::vec3 const y( 0, v.height, 0); glm::vec3 const z( 0, 0, 1); std::array<std::pair<triangle const, unsigned const>, 18> const triangles = { { { triangle(o, x, y), a }, { triangle(o, y, x), 0 }, { triangle(x, y, o), a }, { triangle(y, x, o), 0 }, { triangle(y, o, x), a }, { triangle(x, o, y), 0 }, { triangle(x, x+y, y), a }, { triangle(x, y, x+y), 0 }, { triangle(x+y, y, x), a }, { triangle(y, x+y, x), 0 }, { triangle(y, x, x+y), a }, { triangle(x+y, x, y), 0 }, { triangle(o, two(x), two(y)), (2.f*a)-3 }, { triangle(o, 2.f*y, 2.f*x), 0 }, { triangle(two(x), two(y), o), (2.f*a)-3 }, { triangle(2.f*y, 2.f*x, o), 0 }, { triangle(two(y), o, two(x)), (2.f*a)-3 }, { triangle(2.f*x, o, 2.f*y), 0 }, } }; rasterizer::simple const rs(v); for (auto const& tp : triangles) { using fragment_list = rasterizer::simple::fragment_list_type; fragment_list const fl(rs.process(tp.first)); BOOST_CHECK(tp.second == fl.size()); { std::ostringstream ostr; using hugh::support::ostream::operator<<; ostr << tp.second << "=?=" << fl.size() << ':' << glm::io::width(2) << glm::io::precision(0) << fl; BOOST_TEST_MESSAGE(ostr.str()); } } BOOST_TEST_MESSAGE('\n'); } BOOST_AUTO_TEST_CASE(test_hugh_render_software_rasterizer_simple_print_on) { using namespace hugh::render::software; using viewport = hugh::scene::object::camera::viewport; rasterizer::simple const rs(viewport(0, 0, 10, 10)); std::ostringstream ostr; ostr << rs; BOOST_CHECK (!ostr.str().empty()); BOOST_TEST_MESSAGE( ostr.str()); } <|endoftext|>
<commit_before>/* * SlideQuizRenderer.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SlideQuizRenderer.hpp" #include <iostream> #include <boost/bind.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/replace.hpp> #include <core/SafeConvert.hpp> #include <core/RegexUtils.hpp> using namespace core; namespace session { namespace modules { namespace presentation { namespace { std::string handleClickFunction(const std::string& formId) { return "handle" + formId + "Click"; } std::string asFormInput(const boost::cmatch& match, const std::string& formId, int* pItemIndex) { *pItemIndex = *pItemIndex + 1; boost::format fmt("<li>" "<input type=\"radio\" name=\"%1%\" value=\"%2%\"" " onclick=\"%4%(this);\"/>%3%" "</li>"); std::string input = boost::str(fmt % (formId + "_input") % *pItemIndex % match[1] % handleClickFunction(formId)); return input; } } // anonymous namespace void renderQuiz(int slideIndex, int correctItemIndex, std::string* pHead, std::string* pHTML) { // build form id std::string suffix = safe_convert::numberToString<int>(slideIndex); std::string formId = "quizForm" + suffix; // build validation script boost::format fmtScript( "<script>\n" "function %1%(clickedBtn) {\n" " var answer = parseInt(clickedBtn.value);\n" " var correct = answer == %2%;\n" " document.getElementById('%3%_correct').style.display =" " correct ? \"block\" : \"none\";\n" " document.getElementById('%3%_incorrect').style.display =" " correct ? \"none\" : \"block\";\n" " if (window.parent.recordPresentationQuizAnswer)\n" " window.parent.recordPresentationQuizAnswer(" "%4%, answer, correct);\n " "}\n" "</script>\n\n"); *pHead = boost::str(fmtScript % handleClickFunction(formId) % correctItemIndex % formId % slideIndex); // correct and incorrect divs boost::format fmtFeedback( "<div id=\"%1%_correct\" style=\"display:none\">\n" "Correct!\n" "</div>\n" "<div id=\"%1%_incorrect\" style=\"display:none\">\n" "Incorrect!\n" "</div>\n"); std::string feedbackHTML = boost::str(fmtFeedback % formId); // enclose in form boost::format fmt("<form id=\"%1%\">\n\n<ul>"); boost::algorithm::replace_first(*pHTML, "<ul>", boost::str(fmt % formId)); boost::format suffixFmt("</ul>\n\n%1%\n</form>\n"); boost::algorithm::replace_last(*pHTML, "</ul>", boost::str(suffixFmt % feedbackHTML)); // create input elements int itemIndex = 0; boost::iostreams::regex_filter filter(boost::regex("<li>([^<]+)<\\/li>"), boost::bind(asFormInput, _1, formId, &itemIndex)); // inputs html Error error = regex_utils::filterString(*pHTML, filter, pHTML); if (error) LOG_ERROR(error); } } // namespace presentation } // namespace modules } // namesapce session <commit_msg>more permissive regex for capturing quiz items<commit_after>/* * SlideQuizRenderer.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SlideQuizRenderer.hpp" #include <iostream> #include <boost/bind.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/replace.hpp> #include <core/SafeConvert.hpp> #include <core/RegexUtils.hpp> using namespace core; namespace session { namespace modules { namespace presentation { namespace { std::string handleClickFunction(const std::string& formId) { return "handle" + formId + "Click"; } std::string asFormInput(const boost::cmatch& match, const std::string& formId, int* pItemIndex) { *pItemIndex = *pItemIndex + 1; boost::format fmt("<li>" "<input type=\"radio\" name=\"%1%\" value=\"%2%\"" " onclick=\"%4%(this);\"/>%3%" "</li>"); std::string input = boost::str(fmt % (formId + "_input") % *pItemIndex % match[1] % handleClickFunction(formId)); return input; } } // anonymous namespace void renderQuiz(int slideIndex, int correctItemIndex, std::string* pHead, std::string* pHTML) { // build form id std::string suffix = safe_convert::numberToString<int>(slideIndex); std::string formId = "quizForm" + suffix; // build validation script boost::format fmtScript( "<script>\n" "function %1%(clickedBtn) {\n" " var answer = parseInt(clickedBtn.value);\n" " var correct = answer == %2%;\n" " document.getElementById('%3%_correct').style.display =" " correct ? \"block\" : \"none\";\n" " document.getElementById('%3%_incorrect').style.display =" " correct ? \"none\" : \"block\";\n" " if (window.parent.recordPresentationQuizAnswer)\n" " window.parent.recordPresentationQuizAnswer(" "%4%, answer, correct);\n " "}\n" "</script>\n\n"); *pHead = boost::str(fmtScript % handleClickFunction(formId) % correctItemIndex % formId % slideIndex); // correct and incorrect divs boost::format fmtFeedback( "<div id=\"%1%_correct\" style=\"display:none\">\n" "Correct!\n" "</div>\n" "<div id=\"%1%_incorrect\" style=\"display:none\">\n" "Incorrect!\n" "</div>\n"); std::string feedbackHTML = boost::str(fmtFeedback % formId); // enclose in form boost::format fmt("<form id=\"%1%\">\n\n<ul>"); boost::algorithm::replace_first(*pHTML, "<ul>", boost::str(fmt % formId)); boost::format suffixFmt("</ul>\n\n%1%\n</form>\n"); boost::algorithm::replace_last(*pHTML, "</ul>", boost::str(suffixFmt % feedbackHTML)); // create input elements int itemIndex = 0; boost::iostreams::regex_filter filter(boost::regex("<li>(.+?)<\\/li>"), boost::bind(asFormInput, _1, formId, &itemIndex)); // inputs html Error error = regex_utils::filterString(*pHTML, filter, pHTML); if (error) LOG_ERROR(error); } } // namespace presentation } // namespace modules } // namesapce session <|endoftext|>
<commit_before>//===- MipsSubtarget.cpp - Mips Subtarget Information -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Mips specific subclass of TargetSubtargetInfo. // //===----------------------------------------------------------------------===// #include "MipsSubtarget.h" #include "Mips.h" #include "llvm/Support/TargetRegistry.h" #define GET_SUBTARGETINFO_TARGET_DESC #define GET_SUBTARGETINFO_CTOR #include "MipsGenSubtargetInfo.inc" using namespace llvm; MipsSubtarget::MipsSubtarget(const std::string &TT, const std::string &CPU, const std::string &FS, bool little) : MipsGenSubtargetInfo(TT, CPU, FS), MipsArchVersion(Mips32), MipsABI(O32), IsLittle(little), IsSingleFloat(false), IsFP64bit(false), IsGP64bit(false), HasVFPU(false), IsLinux(true), HasSEInReg(false), HasCondMov(false), HasMulDivAdd(false), HasMinMax(false), HasSwap(false), HasBitCount(false) { std::string CPUName = CPU; if (CPUName.empty()) CPUName = "mips32r1"; // Parse features string. ParseSubtargetFeatures(CPUName, FS); // Initialize scheduling itinerary for the specified CPU. InstrItins = getInstrItineraryForCPU(CPUName); // Set MipsABI if it hasn't been set yet. if (MipsABI == UnknownABI) MipsABI = hasMips64() ? N64 : O32; // Check if Architecture and ABI are compatible. assert(((!hasMips64() && (isABI_O32() || isABI_EABI())) || (hasMips64() && (isABI_N32() || isABI_N64()))) && "Invalid Arch & ABI pair."); // Is the target system Linux ? if (TT.find("linux") == std::string::npos) IsLinux = false; } <commit_msg>MipsArchVersion does not need to be in the initialization list and MipsABI should be initialized to UnknownABI.<commit_after>//===- MipsSubtarget.cpp - Mips Subtarget Information -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Mips specific subclass of TargetSubtargetInfo. // //===----------------------------------------------------------------------===// #include "MipsSubtarget.h" #include "Mips.h" #include "llvm/Support/TargetRegistry.h" #define GET_SUBTARGETINFO_TARGET_DESC #define GET_SUBTARGETINFO_CTOR #include "MipsGenSubtargetInfo.inc" using namespace llvm; MipsSubtarget::MipsSubtarget(const std::string &TT, const std::string &CPU, const std::string &FS, bool little) : MipsGenSubtargetInfo(TT, CPU, FS), MipsABI(UnknownABI), IsLittle(little), IsSingleFloat(false), IsFP64bit(false), IsGP64bit(false), HasVFPU(false), IsLinux(true), HasSEInReg(false), HasCondMov(false), HasMulDivAdd(false), HasMinMax(false), HasSwap(false), HasBitCount(false) { std::string CPUName = CPU; if (CPUName.empty()) CPUName = "mips32r1"; // Parse features string. ParseSubtargetFeatures(CPUName, FS); // Initialize scheduling itinerary for the specified CPU. InstrItins = getInstrItineraryForCPU(CPUName); // Set MipsABI if it hasn't been set yet. if (MipsABI == UnknownABI) MipsABI = hasMips64() ? N64 : O32; // Check if Architecture and ABI are compatible. assert(((!hasMips64() && (isABI_O32() || isABI_EABI())) || (hasMips64() && (isABI_N32() || isABI_N64()))) && "Invalid Arch & ABI pair."); // Is the target system Linux ? if (TT.find("linux") == std::string::npos) IsLinux = false; } <|endoftext|>
<commit_before>/* * Copyright 2007-2022 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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 * FOUNDATION 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 "Client.hxx" #include "translation/Protocol.hxx" #include "io/UniqueFileDescriptor.hxx" #include "system/Error.hxx" #include "util/ByteOrder.hxx" #include "util/ConstBuffer.hxx" #include "util/PrintException.hxx" #include "util/RuntimeError.hxx" #include "util/StringCompare.hxx" #include <inttypes.h> #include <stdlib.h> #include <stdio.h> struct Usage { const char *msg = nullptr; }; static void SimpleCommand(const char *server, ConstBuffer<const char *> args, BengProxy::ControlCommand cmd) { if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(cmd); } static void Nop(const char *server, ConstBuffer<const char *> args) { SimpleCommand(server, args, BengProxy::ControlCommand::NOP); } static constexpr struct { const char *name; TranslationCommand cmd; } tcache_invalidate_strings[] = { { "URI", TranslationCommand::URI }, { "PARAM", TranslationCommand::PARAM }, { "LISTENER_TAG", TranslationCommand::LISTENER_TAG }, { "REMOTE_HOST", TranslationCommand::REMOTE_HOST }, { "HOST", TranslationCommand::HOST }, { "LANGUAGE", TranslationCommand::LANGUAGE }, { "USER_AGENT", TranslationCommand::USER_AGENT }, { "QUERY_STRING", TranslationCommand::QUERY_STRING }, { "SITE", TranslationCommand::SITE }, { "INTERNAL_REDIRECT", TranslationCommand::INTERNAL_REDIRECT }, { "ENOTDIR", TranslationCommand::ENOTDIR_ }, { "USER", TranslationCommand::USER }, }; static std::string ParseTcacheInvalidate(StringView name, const char *value) { for (const auto &i : tcache_invalidate_strings) if (name.Equals(i.name)) return BengControlClient::MakeTcacheInvalidate(i.cmd, value); throw FormatRuntimeError("Unrecognized key: '%.*s'", int(name.size), name.data); } static std::string ParseTcacheInvalidate(const char *s) { const char *eq = strchr(s, '='); if (eq == nullptr) throw FormatRuntimeError("Missing '=': %s", s); if (eq == s) throw FormatRuntimeError("Missing name: %s", s); return ParseTcacheInvalidate({s, eq}, eq + 1); } static void TcacheInvalidate(const char *server, ConstBuffer<const char *> args) { std::string payload; for (const char *s : args) payload += ParseTcacheInvalidate(s); BengControlClient client(server); client.Send(BengProxy::ControlCommand::TCACHE_INVALIDATE, payload); } static void Verbose(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Log level missing"}; const char *s = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; uint8_t log_level = atoi(s); BengControlClient client(server); client.Send(BengProxy::ControlCommand::VERBOSE, {&log_level, sizeof(log_level)}); } static void EnableNode(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Node name missing"}; const StringView name = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::ENABLE_NODE, name); } static void FadeNode(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Node name missing"}; const StringView name = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::FADE_NODE, name); } static void NodeStatus(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Node name missing"}; const StringView name = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.AutoBind(); client.Send(BengProxy::ControlCommand::NODE_STATUS, name); const auto response = client.Receive(); if (response.first != BengProxy::ControlCommand::NODE_STATUS) throw std::runtime_error("Wrong response command"); const auto nul = response.second.find('\0'); if (nul == response.second.npos) throw std::runtime_error("Malformed response payload"); printf("%s\n", response.second.c_str() + nul + 1); } static void PrintStatsAttribute(const char *name, const uint32_t &value) noexcept { if (value != 0) printf("%s %" PRIu32 "\n", name, FromBE32(value)); } static void PrintStatsAttribute(const char *name, const uint64_t &value) noexcept { if (value != 0) printf("%s %" PRIu64 "\n", name, FromBE64(value)); } static void Stats(const char *server, ConstBuffer<const char *> args) { if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.AutoBind(); client.Send(BengProxy::ControlCommand::STATS); const auto response = client.Receive(); if (response.first != BengProxy::ControlCommand::STATS) throw std::runtime_error("Wrong response command"); BengProxy::ControlStats stats; memset(&stats, 0, sizeof(stats)); memcpy(&stats, response.second.data(), std::min(sizeof(stats), response.second.size())); PrintStatsAttribute("incoming_connections", stats.incoming_connections); PrintStatsAttribute("outgoing_connections", stats.outgoing_connections); PrintStatsAttribute("children", stats.children); PrintStatsAttribute("sessions", stats.sessions); PrintStatsAttribute("http_requests", stats.http_requests); PrintStatsAttribute("translation_cache_size", stats.translation_cache_size); PrintStatsAttribute("http_cache_size", stats.http_cache_size); PrintStatsAttribute("filter_cache_size", stats.filter_cache_size); PrintStatsAttribute("translation_cache_brutto_size", stats.translation_cache_brutto_size); PrintStatsAttribute("http_cache_brutto_size", stats.http_cache_brutto_size); PrintStatsAttribute("filter_cache_brutto_size", stats.filter_cache_brutto_size); PrintStatsAttribute("nfs_cache_size", stats.nfs_cache_size); PrintStatsAttribute("nfs_cache_brutto_size", stats.nfs_cache_brutto_size); PrintStatsAttribute("io_buffers_size", stats.io_buffers_size); PrintStatsAttribute("io_buffers_brutto_size", stats.io_buffers_brutto_size); PrintStatsAttribute("http_traffic_received", stats.http_traffic_received); PrintStatsAttribute("http_traffic_sent", stats.http_traffic_sent); } static void FadeChildren(const char *server, ConstBuffer<const char *> args) { StringView tag = nullptr; if (!args.empty()) tag = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::FADE_CHILDREN, tag); } static void FlushFilterCache(const char *server, ConstBuffer<const char *> args) { StringView tag = nullptr; if (!args.empty()) tag = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::FLUSH_FILTER_CACHE, tag); } static void DiscardSession(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Not enough arguments"}; const StringView attach_id = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::DISCARD_SESSION, attach_id); } static void Stopwatch(const char *server, ConstBuffer<const char *> args) { if (!args.empty()) throw Usage{"Too many arguments"}; UniqueFileDescriptor r, w; if (!UniqueFileDescriptor::CreatePipe(r, w)) throw MakeErrno("pipe() failed"); FileDescriptor fds[] = { w }; BengControlClient client(server); client.Send(BengProxy::ControlCommand::STOPWATCH_PIPE, nullptr, fds); w.Close(); while (true) { char buffer[8192]; ssize_t nbytes = r.Read(buffer, sizeof(buffer)); if (nbytes <= 0) break; if (write(STDOUT_FILENO, buffer, nbytes) < 0) break; } } int main(int argc, char **argv) try { ConstBuffer<const char *> args(argv + 1, argc - 1); const char *server = "@bp-control"; while (!args.empty() && args.front()[0] == '-') { const char *option = args.shift(); if (const char *new_server = StringAfterPrefix(option, "--server=")) { server = new_server; } else throw Usage{"Unknown option"}; } if (args.empty()) throw Usage(); const char *const command = args.shift(); if (StringIsEqual(command, "nop")) { Nop(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "tcache-invalidate")) { TcacheInvalidate(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "enable-node")) { EnableNode(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "fade-node")) { FadeNode(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "node-status")) { NodeStatus(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "dump-pools")) { SimpleCommand(server, args, BengProxy::ControlCommand::DUMP_POOLS); return EXIT_SUCCESS; } else if (StringIsEqual(command, "stats")) { Stats(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "verbose")) { Verbose(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "fade-children")) { FadeChildren(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "disable-zeroconf")) { SimpleCommand(server, args, BengProxy::ControlCommand::DISABLE_ZEROCONF); return EXIT_SUCCESS; } else if (StringIsEqual(command, "enable-zeroconf")) { SimpleCommand(server, args, BengProxy::ControlCommand::ENABLE_ZEROCONF); return EXIT_SUCCESS; } else if (StringIsEqual(command, "flush-nfs-cache")) { SimpleCommand(server, args, BengProxy::ControlCommand::FLUSH_NFS_CACHE); return EXIT_SUCCESS; } else if (StringIsEqual(command, "flush-filter-cache")) { FlushFilterCache(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "discard-session")) { DiscardSession(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "stopwatch")) { Stopwatch(server, args); return EXIT_SUCCESS; } else throw Usage{"Unknown command"}; } catch (const Usage &u) { if (u.msg) fprintf(stderr, "%s\n\n", u.msg); fprintf(stderr, "Usage: %s [--server=SERVER[:PORT]] COMMAND ...\n" "\n" "Commands:\n" " nop\n" " tcache-invalidate [KEY=VALUE...]\n" " enable-node NAME:PORT\n" " fade-node NAME:PORT\n" " dump-pools\n" " verbose LEVEL\n" " fade-children [TAG]\n" " disable-zeroconf\n" " enable-zeroconf\n" " flush-nfs-cache\n" " flush-filter-cache [TAG]\n" " discard-session ATTACH_ID\n" " stopwatch\n" "\n" "Names for tcache-invalidate:\n", argv[0]); for (const auto &i : tcache_invalidate_strings) fprintf(stderr, " %s\n", i.name); return EXIT_FAILURE; } catch (...) { PrintException(std::current_exception()); return EXIT_FAILURE; } <commit_msg>control/Main: use std::string_view<commit_after>/* * Copyright 2007-2022 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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 * FOUNDATION 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 "Client.hxx" #include "translation/Protocol.hxx" #include "io/UniqueFileDescriptor.hxx" #include "system/Error.hxx" #include "util/ByteOrder.hxx" #include "util/ConstBuffer.hxx" #include "util/PrintException.hxx" #include "util/RuntimeError.hxx" #include "util/StringCompare.hxx" #include <inttypes.h> #include <stdlib.h> #include <stdio.h> struct Usage { const char *msg = nullptr; }; static void SimpleCommand(const char *server, ConstBuffer<const char *> args, BengProxy::ControlCommand cmd) { if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(cmd); } static void Nop(const char *server, ConstBuffer<const char *> args) { SimpleCommand(server, args, BengProxy::ControlCommand::NOP); } static constexpr struct { const char *name; TranslationCommand cmd; } tcache_invalidate_strings[] = { { "URI", TranslationCommand::URI }, { "PARAM", TranslationCommand::PARAM }, { "LISTENER_TAG", TranslationCommand::LISTENER_TAG }, { "REMOTE_HOST", TranslationCommand::REMOTE_HOST }, { "HOST", TranslationCommand::HOST }, { "LANGUAGE", TranslationCommand::LANGUAGE }, { "USER_AGENT", TranslationCommand::USER_AGENT }, { "QUERY_STRING", TranslationCommand::QUERY_STRING }, { "SITE", TranslationCommand::SITE }, { "INTERNAL_REDIRECT", TranslationCommand::INTERNAL_REDIRECT }, { "ENOTDIR", TranslationCommand::ENOTDIR_ }, { "USER", TranslationCommand::USER }, }; static std::string ParseTcacheInvalidate(std::string_view name, const char *value) { for (const auto &i : tcache_invalidate_strings) if (name == i.name) return BengControlClient::MakeTcacheInvalidate(i.cmd, value); throw FormatRuntimeError("Unrecognized key: '%.*s'", int(name.size()), name.data()); } static std::string ParseTcacheInvalidate(const char *s) { const char *eq = strchr(s, '='); if (eq == nullptr) throw FormatRuntimeError("Missing '=': %s", s); if (eq == s) throw FormatRuntimeError("Missing name: %s", s); return ParseTcacheInvalidate({s, eq}, eq + 1); } static void TcacheInvalidate(const char *server, ConstBuffer<const char *> args) { std::string payload; for (const char *s : args) payload += ParseTcacheInvalidate(s); BengControlClient client(server); client.Send(BengProxy::ControlCommand::TCACHE_INVALIDATE, payload); } static void Verbose(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Log level missing"}; const char *s = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; uint8_t log_level = atoi(s); BengControlClient client(server); client.Send(BengProxy::ControlCommand::VERBOSE, {&log_level, sizeof(log_level)}); } static void EnableNode(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Node name missing"}; const std::string_view name = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::ENABLE_NODE, name); } static void FadeNode(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Node name missing"}; const std::string_view name = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::FADE_NODE, name); } static void NodeStatus(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Node name missing"}; const std::string_view name = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.AutoBind(); client.Send(BengProxy::ControlCommand::NODE_STATUS, name); const auto response = client.Receive(); if (response.first != BengProxy::ControlCommand::NODE_STATUS) throw std::runtime_error("Wrong response command"); const auto nul = response.second.find('\0'); if (nul == response.second.npos) throw std::runtime_error("Malformed response payload"); printf("%s\n", response.second.c_str() + nul + 1); } static void PrintStatsAttribute(const char *name, const uint32_t &value) noexcept { if (value != 0) printf("%s %" PRIu32 "\n", name, FromBE32(value)); } static void PrintStatsAttribute(const char *name, const uint64_t &value) noexcept { if (value != 0) printf("%s %" PRIu64 "\n", name, FromBE64(value)); } static void Stats(const char *server, ConstBuffer<const char *> args) { if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.AutoBind(); client.Send(BengProxy::ControlCommand::STATS); const auto response = client.Receive(); if (response.first != BengProxy::ControlCommand::STATS) throw std::runtime_error("Wrong response command"); BengProxy::ControlStats stats; memset(&stats, 0, sizeof(stats)); memcpy(&stats, response.second.data(), std::min(sizeof(stats), response.second.size())); PrintStatsAttribute("incoming_connections", stats.incoming_connections); PrintStatsAttribute("outgoing_connections", stats.outgoing_connections); PrintStatsAttribute("children", stats.children); PrintStatsAttribute("sessions", stats.sessions); PrintStatsAttribute("http_requests", stats.http_requests); PrintStatsAttribute("translation_cache_size", stats.translation_cache_size); PrintStatsAttribute("http_cache_size", stats.http_cache_size); PrintStatsAttribute("filter_cache_size", stats.filter_cache_size); PrintStatsAttribute("translation_cache_brutto_size", stats.translation_cache_brutto_size); PrintStatsAttribute("http_cache_brutto_size", stats.http_cache_brutto_size); PrintStatsAttribute("filter_cache_brutto_size", stats.filter_cache_brutto_size); PrintStatsAttribute("nfs_cache_size", stats.nfs_cache_size); PrintStatsAttribute("nfs_cache_brutto_size", stats.nfs_cache_brutto_size); PrintStatsAttribute("io_buffers_size", stats.io_buffers_size); PrintStatsAttribute("io_buffers_brutto_size", stats.io_buffers_brutto_size); PrintStatsAttribute("http_traffic_received", stats.http_traffic_received); PrintStatsAttribute("http_traffic_sent", stats.http_traffic_sent); } static void FadeChildren(const char *server, ConstBuffer<const char *> args) { std::string_view tag{}; if (!args.empty()) tag = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::FADE_CHILDREN, tag); } static void FlushFilterCache(const char *server, ConstBuffer<const char *> args) { std::string_view tag{}; if (!args.empty()) tag = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::FLUSH_FILTER_CACHE, tag); } static void DiscardSession(const char *server, ConstBuffer<const char *> args) { if (args.empty()) throw Usage{"Not enough arguments"}; const std::string_view attach_id = args.shift(); if (!args.empty()) throw Usage{"Too many arguments"}; BengControlClient client(server); client.Send(BengProxy::ControlCommand::DISCARD_SESSION, attach_id); } static void Stopwatch(const char *server, ConstBuffer<const char *> args) { if (!args.empty()) throw Usage{"Too many arguments"}; UniqueFileDescriptor r, w; if (!UniqueFileDescriptor::CreatePipe(r, w)) throw MakeErrno("pipe() failed"); FileDescriptor fds[] = { w }; BengControlClient client(server); client.Send(BengProxy::ControlCommand::STOPWATCH_PIPE, nullptr, fds); w.Close(); while (true) { char buffer[8192]; ssize_t nbytes = r.Read(buffer, sizeof(buffer)); if (nbytes <= 0) break; if (write(STDOUT_FILENO, buffer, nbytes) < 0) break; } } int main(int argc, char **argv) try { ConstBuffer<const char *> args(argv + 1, argc - 1); const char *server = "@bp-control"; while (!args.empty() && args.front()[0] == '-') { const char *option = args.shift(); if (const char *new_server = StringAfterPrefix(option, "--server=")) { server = new_server; } else throw Usage{"Unknown option"}; } if (args.empty()) throw Usage(); const char *const command = args.shift(); if (StringIsEqual(command, "nop")) { Nop(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "tcache-invalidate")) { TcacheInvalidate(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "enable-node")) { EnableNode(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "fade-node")) { FadeNode(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "node-status")) { NodeStatus(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "dump-pools")) { SimpleCommand(server, args, BengProxy::ControlCommand::DUMP_POOLS); return EXIT_SUCCESS; } else if (StringIsEqual(command, "stats")) { Stats(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "verbose")) { Verbose(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "fade-children")) { FadeChildren(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "disable-zeroconf")) { SimpleCommand(server, args, BengProxy::ControlCommand::DISABLE_ZEROCONF); return EXIT_SUCCESS; } else if (StringIsEqual(command, "enable-zeroconf")) { SimpleCommand(server, args, BengProxy::ControlCommand::ENABLE_ZEROCONF); return EXIT_SUCCESS; } else if (StringIsEqual(command, "flush-nfs-cache")) { SimpleCommand(server, args, BengProxy::ControlCommand::FLUSH_NFS_CACHE); return EXIT_SUCCESS; } else if (StringIsEqual(command, "flush-filter-cache")) { FlushFilterCache(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "discard-session")) { DiscardSession(server, args); return EXIT_SUCCESS; } else if (StringIsEqual(command, "stopwatch")) { Stopwatch(server, args); return EXIT_SUCCESS; } else throw Usage{"Unknown command"}; } catch (const Usage &u) { if (u.msg) fprintf(stderr, "%s\n\n", u.msg); fprintf(stderr, "Usage: %s [--server=SERVER[:PORT]] COMMAND ...\n" "\n" "Commands:\n" " nop\n" " tcache-invalidate [KEY=VALUE...]\n" " enable-node NAME:PORT\n" " fade-node NAME:PORT\n" " dump-pools\n" " verbose LEVEL\n" " fade-children [TAG]\n" " disable-zeroconf\n" " enable-zeroconf\n" " flush-nfs-cache\n" " flush-filter-cache [TAG]\n" " discard-session ATTACH_ID\n" " stopwatch\n" "\n" "Names for tcache-invalidate:\n", argv[0]); for (const auto &i : tcache_invalidate_strings) fprintf(stderr, " %s\n", i.name); return EXIT_FAILURE; } catch (...) { PrintException(std::current_exception()); return EXIT_FAILURE; } <|endoftext|>
<commit_before><commit_msg>GatewayConnection: mark received message as const<commit_after><|endoftext|>
<commit_before>/********************* Example code for the Adafruit RGB Character LCD Shield and Library This code displays text on the shield, and also reads the buttons on the keypad. When a button is pressed, the backlight changes color. **********************/ // include the library code: //#include <Wire.h> #include <Adafruit_RGBLCDShield/Adafruit_MCP23017.h> #include <Adafruit_RGBLCDShield/Adafruit_RGBLCDShield.h> // The shield uses the I2C SCL and SDA pins. On classic Arduinos // this is Analog 4 and 5 so you can't use those for analogRead() anymore // However, you can connect other I2C sensors to the I2C bus and share // the I2C bus. Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield(); // These #defines make it easy to set the backlight color #define RED 0x1 #define YELLOW 0x3 #define GREEN 0x2 #define TEAL 0x6 #define BLUE 0x4 #define VIOLET 0x5 #define WHITE 0x7 void setup() { // Debugging output Serial.begin(9600); // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. We track how long it takes since // this library has been optimized a bit and we're proud of it :) int time = millis(); lcd.print("Hello, world!"); time = millis() - time; Serial.print("Took "); Serial.print(time); Serial.println(" ms"); lcd.setBacklight(WHITE); } uint8_t i=0; void loop() { // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.setCursor(0, 1); // print the number of seconds since reset: lcd.print(millis()/1000); uint8_t buttons = lcd.readButtons(); if (buttons) { lcd.clear(); lcd.setCursor(0,0); if (buttons & BUTTON_UP) { lcd.print("UP "); lcd.setBacklight(RED); } if (buttons & BUTTON_DOWN) { lcd.print("DOWN "); lcd.setBacklight(YELLOW); } if (buttons & BUTTON_LEFT) { lcd.print("LEFT "); lcd.setBacklight(GREEN); } if (buttons & BUTTON_RIGHT) { lcd.print("RIGHT "); lcd.setBacklight(TEAL); } if (buttons & BUTTON_SELECT) { lcd.print("SELECT "); lcd.setBacklight(VIOLET); } } } <commit_msg>Fixed example code<commit_after>/********************* Example code for the Adafruit RGB Character LCD Shield and Library This code displays text on the shield, and also reads the buttons on the keypad. When a button is pressed, the backlight changes color. **********************/ // include the library code: //#include <Wire.h> #include "Adafruit_RGBLCDShield/Adafruit_MCP23017.h" #include "Adafruit_RGBLCDShield/Adafruit_RGBLCDShield.h" // The shield uses the I2C SCL and SDA pins. On classic Arduinos // this is Analog 4 and 5 so you can't use those for analogRead() anymore // However, you can connect other I2C sensors to the I2C bus and share // the I2C bus. Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield(); // These #defines make it easy to set the backlight color #define RED 0x1 #define YELLOW 0x3 #define GREEN 0x2 #define TEAL 0x6 #define BLUE 0x4 #define VIOLET 0x5 #define WHITE 0x7 void setup() { // Debugging output Serial.begin(9600); // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. We track how long it takes since // this library has been optimized a bit and we're proud of it :) int time = millis(); lcd.print("Hello, world!"); time = millis() - time; Serial.print("Took "); Serial.print(time); Serial.println(" ms"); lcd.setBacklight(WHITE); } uint8_t i=0; void loop() { // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.setCursor(0, 1); // print the number of seconds since reset: lcd.print(millis()/1000); uint8_t buttons = lcd.readButtons(); if (buttons) { lcd.clear(); lcd.setCursor(0,0); if (buttons & BUTTON_UP) { lcd.print("UP "); lcd.setBacklight(RED); } if (buttons & BUTTON_DOWN) { lcd.print("DOWN "); lcd.setBacklight(YELLOW); } if (buttons & BUTTON_LEFT) { lcd.print("LEFT "); lcd.setBacklight(GREEN); } if (buttons & BUTTON_RIGHT) { lcd.print("RIGHT "); lcd.setBacklight(TEAL); } if (buttons & BUTTON_SELECT) { lcd.print("SELECT "); lcd.setBacklight(VIOLET); } } } <|endoftext|>
<commit_before>#ifndef _SNARKFRONT_SHA_512_256_HPP_ #define _SNARKFRONT_SHA_512_256_HPP_ #include <array> #include <cstdint> #include "Alg.hpp" #include "Alg_uint.hpp" #include "AST.hpp" #include "BitwiseOps.hpp" #include "Lazy.hpp" #include "SHA_512.hpp" namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // SHA-512/256 // template <typename H, typename T, typename MSG, typename F> class SHA_512_256 : public SHA_512<T, MSG, F> { public: typedef T WordType; typedef std::array<T, 16> MsgType; typedef std::array<H, 8> DigType; SHA_512_256() : m_setDigest(false) {} // overrides base class SHA-512 const std::array<H, 8>& digest() { if (m_setDigest) { for (std::size_t i = 0; i < 4; ++i) { // high 32 bits m_Hleft256[2*i] = F::xword(F::SHR( this->m_H[i], 32)); // low 32 bits m_Hleft256[2*i + 1] = F::xword(F::SHR( F::SHL( this->m_H[i], 32), 32)); } m_setDigest = false; } return m_Hleft256; } virtual void afterHash() { m_setDigest = true; } protected: // overrides base class SHA-512 void initHashValue() { // set initial hash value (NIST FIPS 180-4 section 5.3.6.2) const std::array<std::uint64_t, 8> a { 0x22312194FC2BF72C, 0x9F555FA3C84C64C2, 0x2393B86B6F53B151, 0x963877195940EABD, 0x96283EE2A88EFFE3, 0xBE5E1E2553863992, 0x2B0199FC2C85B8AA, 0x0EB72DDC81C52CA2 }; for (std::size_t i = 0; i < 8; ++i) { this->m_H[i] = F::constant(a[i]); } } // truncated 256-bit message digest std::array<H, 8> m_Hleft256; bool m_setDigest; }; //////////////////////////////////////////////////////////////////////////////// // typedefs // namespace zk { template <typename FR> using SHA512_256 = SHA_512_256<AST_Var<Alg_uint32<FR>>, AST_Var<Alg_uint64<FR>>, Lazy<AST_Var<Alg_uint64<FR>>, std::uint64_t>, SHA_Functions<AST_Node<Alg_uint64<FR>>, AST_Op<Alg_uint64<FR>>, BitwiseAST<Alg_uint64<FR>, Alg_uint32<FR>>>>; } // namespace zk namespace eval { typedef SHA_512_256<std::uint32_t, std::uint64_t, std::uint64_t, SHA_Functions<std::uint64_t, std::uint64_t, BitwiseINT<std::uint64_t, std::uint32_t>>> SHA512_256; } // namespace eval } // namespace snarkfront #endif <commit_msg>8-bit unsigned int array pre-image<commit_after>#ifndef _SNARKFRONT_SHA_512_256_HPP_ #define _SNARKFRONT_SHA_512_256_HPP_ #include <array> #include <cstdint> #include "Alg.hpp" #include "Alg_uint.hpp" #include "AST.hpp" #include "BitwiseOps.hpp" #include "Lazy.hpp" #include "SHA_512.hpp" namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // SHA-512/256 // template <typename H, typename T, typename MSG, typename U, typename F> class SHA_512_256 : public SHA_512<T, MSG, U, F> { public: typedef T WordType; typedef U ByteType; typedef std::array<T, 16> MsgType; typedef std::array<H, 8> DigType; typedef std::array<U, 16 * 8> PreType; SHA_512_256() : m_setDigest(false) {} // overrides base class SHA-512 const std::array<H, 8>& digest() { if (m_setDigest) { for (std::size_t i = 0; i < 4; ++i) { // high 32 bits m_Hleft256[2*i] = F::xword(F::SHR( this->m_H[i], 32)); // low 32 bits m_Hleft256[2*i + 1] = F::xword(F::SHR( F::SHL( this->m_H[i], 32), 32)); } m_setDigest = false; } return m_Hleft256; } virtual void afterHash() { m_setDigest = true; } protected: // overrides base class SHA-512 void initHashValue() { // set initial hash value (NIST FIPS 180-4 section 5.3.6.2) const std::array<std::uint64_t, 8> a { 0x22312194FC2BF72C, 0x9F555FA3C84C64C2, 0x2393B86B6F53B151, 0x963877195940EABD, 0x96283EE2A88EFFE3, 0xBE5E1E2553863992, 0x2B0199FC2C85B8AA, 0x0EB72DDC81C52CA2 }; for (std::size_t i = 0; i < 8; ++i) { this->m_H[i] = F::constant(a[i]); } } // truncated 256-bit message digest std::array<H, 8> m_Hleft256; bool m_setDigest; }; //////////////////////////////////////////////////////////////////////////////// // typedefs // namespace zk { template <typename FR> using SHA512_256 = SHA_512_256<AST_Var<Alg_uint32<FR>>, AST_Var<Alg_uint64<FR>>, Lazy<AST_Var<Alg_uint64<FR>>, std::uint64_t>, AST_Var<Alg_uint8<FR>>, SHA_Functions<AST_Node<Alg_uint64<FR>>, AST_Op<Alg_uint64<FR>>, BitwiseAST<Alg_uint64<FR>, Alg_uint32<FR>>>>; } // namespace zk namespace eval { typedef SHA_512_256<std::uint32_t, std::uint64_t, std::uint64_t, std::uint8_t, SHA_Functions<std::uint64_t, std::uint64_t, BitwiseINT<std::uint64_t, std::uint32_t>>> SHA512_256; } // namespace eval } // namespace snarkfront #endif <|endoftext|>
<commit_before> // The files containing the tree of of child classes of |Integrator| must be // included in the order of inheritance to avoid circular dependencies. This // class will end up being reincluded as part of the implementation of its // parent. #ifndef PRINCIPIA_INTEGRATORS_INTEGRATORS_HPP_ #include "integrators/integrators.hpp" #else #ifndef PRINCIPIA_INTEGRATORS_EMBEDDED_EXPLICIT_RUNGE_KUTTA_NYSTRÖM_INTEGRATOR_HPP_ // NOLINT(whitespace/line_length) #define PRINCIPIA_INTEGRATORS_EMBEDDED_EXPLICIT_RUNGE_KUTTA_NYSTRÖM_INTEGRATOR_HPP_ // NOLINT(whitespace/line_length) #include <functional> #include <vector> #include "base/not_null.hpp" #include "base/status.hpp" #include "numerics/fixed_arrays.hpp" #include "integrators/methods.hpp" #include "integrators/ordinary_differential_equations.hpp" #include "quantities/named_quantities.hpp" #include "serialization/integrators.pb.h" namespace principia { namespace integrators { namespace internal_embedded_explicit_runge_kutta_nyström_integrator { using base::not_null; using base::Status; using geometry::Instant; using numerics::FixedStrictlyLowerTriangularMatrix; using numerics::FixedVector; using quantities::Time; using quantities::Variation; // This class solves ordinary differential equations of the form q″ = f(q, t) // using an embedded Runge-Kutta-Nyström method. We follow the standard // conventions for the coefficients, i.e., // c for the nodes; // a for the Runge-Kutta matrix; // b̂ for the position weights of the high-order method; // b̂′ for the velocity weights of the high-order method; // b for the position weights of the low-order method; // b′ for the velocity weights of the low-order method. // See Dormand, El-Mikkawy and Prince (1986), // Families of Runge-Kutta-Nyström formulae, for an example. // In the implementation, we follow Dormand, El-Mikkawy and Prince in calling // the results of the right-hand-side evaluations gᵢ. The notations kᵢ or fᵢ // also appear in the litterature. // Since we are interested in physical applications, we call the solution q and // its derivative v, rather than the more common y and y′ found in the // literature on Runge-Kutta-Nyström methods. // The order of the template parameters follow the notation of Dormand and // Prince, whose RKNq(p)sF has higher order q, lower order p, comprises // s stages, and has the first-same-as-last property. template<typename Method, typename Position> class EmbeddedExplicitRungeKuttaNyströmIntegrator : public AdaptiveStepSizeIntegrator< SpecialSecondOrderDifferentialEquation<Position>> { public: using ODE = SpecialSecondOrderDifferentialEquation<Position>; using typename Integrator<ODE>::AppendState; using typename AdaptiveStepSizeIntegrator<ODE>::Parameters; using typename AdaptiveStepSizeIntegrator<ODE>::ToleranceToErrorRatio; static constexpr auto higher_order = Method::higher_order; static constexpr auto lower_order = Method::lower_order; static constexpr auto first_same_as_last = Method::first_same_as_last; EmbeddedExplicitRungeKuttaNyströmIntegrator(); EmbeddedExplicitRungeKuttaNyströmIntegrator( EmbeddedExplicitRungeKuttaNyströmIntegrator const&) = delete; EmbeddedExplicitRungeKuttaNyströmIntegrator( EmbeddedExplicitRungeKuttaNyströmIntegrator&&) = delete; EmbeddedExplicitRungeKuttaNyströmIntegrator& operator=( EmbeddedExplicitRungeKuttaNyströmIntegrator const&) = delete; EmbeddedExplicitRungeKuttaNyströmIntegrator& operator=( EmbeddedExplicitRungeKuttaNyströmIntegrator&&) = delete; class Instance : public AdaptiveStepSizeIntegrator<ODE>::Instance { public: Status Solve(Instant const& t_final) override; EmbeddedExplicitRungeKuttaNyströmIntegrator const& integrator() const override; not_null<std::unique_ptr<typename Integrator<ODE>::Instance>> Clone() const override; void WriteToMessage( not_null<serialization::IntegratorInstance*> message) const override; private: Instance(IntegrationProblem<ODE> const& problem, AppendState const& append_state, ToleranceToErrorRatio const& tolerance_to_error_ratio, Parameters const& adaptive_step_size, EmbeddedExplicitRungeKuttaNyströmIntegrator const& integrator); EmbeddedExplicitRungeKuttaNyströmIntegrator const& integrator_; friend class EmbeddedExplicitRungeKuttaNyströmIntegrator; }; not_null<std::unique_ptr<typename Integrator<ODE>::Instance>> NewInstance( IntegrationProblem<ODE> const& problem, AppendState const& append_state, ToleranceToErrorRatio const& tolerance_to_error_ratio, Parameters const& parameters) const override; void WriteToMessage( not_null<serialization::AdaptiveStepSizeIntegrator*> message) const override; private: not_null<std::unique_ptr<typename Integrator<ODE>::Instance>> ReadFromMessage( serialization::AdaptiveStepSizeIntegratorInstance const& message, IntegrationProblem<ODE> const& problem, AppendState const& append_state, ToleranceToErrorRatio const& tolerance_to_error_ratio, Parameters const& parameters) const override; static constexpr auto stages_ = Method::stages; static constexpr auto c_ = Method::c; static constexpr auto a_ = Method::a; static constexpr auto b_hat_ = Method::b_hat; static constexpr auto b_prime_hat_ = Method::b_prime_hat; static constexpr auto b_ = Method::b; static constexpr auto b_prime_ = Method::b_prime; }; } // namespace internal_embedded_explicit_runge_kutta_nyström_integrator template<typename Method, typename Position> internal_embedded_explicit_runge_kutta_nyström_integrator:: EmbeddedExplicitRungeKuttaNyströmIntegrator<Method, Position> const& EmbeddedExplicitRungeKuttaNyströmIntegrator(); } // namespace integrators } // namespace principia #include "integrators/embedded_explicit_runge_kutta_nyström_integrator_body.hpp" #endif // PRINCIPIA_INTEGRATORS_EMBEDDED_EXPLICIT_RUNGE_KUTTA_NYSTRÖM_INTEGRATOR_HPP_ // NOLINT(whitespace/line_length) #endif // PRINCIPIA_INTEGRATORS_INTEGRATORS_HPP_ <commit_msg>comment<commit_after> // The files containing the tree of of child classes of |Integrator| must be // included in the order of inheritance to avoid circular dependencies. This // class will end up being reincluded as part of the implementation of its // parent. #ifndef PRINCIPIA_INTEGRATORS_INTEGRATORS_HPP_ #include "integrators/integrators.hpp" #else #ifndef PRINCIPIA_INTEGRATORS_EMBEDDED_EXPLICIT_RUNGE_KUTTA_NYSTRÖM_INTEGRATOR_HPP_ // NOLINT(whitespace/line_length) #define PRINCIPIA_INTEGRATORS_EMBEDDED_EXPLICIT_RUNGE_KUTTA_NYSTRÖM_INTEGRATOR_HPP_ // NOLINT(whitespace/line_length) #include <functional> #include <vector> #include "base/not_null.hpp" #include "base/status.hpp" #include "numerics/fixed_arrays.hpp" #include "integrators/methods.hpp" #include "integrators/ordinary_differential_equations.hpp" #include "quantities/named_quantities.hpp" #include "serialization/integrators.pb.h" namespace principia { namespace integrators { namespace internal_embedded_explicit_runge_kutta_nyström_integrator { using base::not_null; using base::Status; using geometry::Instant; using numerics::FixedStrictlyLowerTriangularMatrix; using numerics::FixedVector; using quantities::Time; using quantities::Variation; // This class solves ordinary differential equations of the form q″ = f(q, t) // using an embedded Runge-Kutta-Nyström method. We follow the standard // conventions for the coefficients, i.e., // c for the nodes; // a for the Runge-Kutta matrix; // b̂ for the position weights of the high-order method; // b̂′ for the velocity weights of the high-order method; // b for the position weights of the low-order method; // b′ for the velocity weights of the low-order method. // See Dormand, El-Mikkawy and Prince (1986), // Families of Runge-Kutta-Nyström formulae, for an example. // Note that the velocity weights b′ are sometimes called d instead, e.g., // المكاوى and رحمو‎ (2003), A new optimized non-FSAL embedded // Runge–Kutta–Nystrom algorithm of orders 6 and 4 in six stages, or // Sommeijer (1993), Explicit, high-order Runge-Kutta-Nyström methods for // parallel computers. // In the implementation, we follow Dormand, El-Mikkawy and Prince in calling // the results of the right-hand-side evaluations gᵢ. The notations kᵢ or fᵢ // also appear in the litterature. // Since we are interested in physical applications, we call the solution q and // its derivative v, rather than the more common y and y′ found in the // literature on Runge-Kutta-Nyström methods. // The order of the template parameters follow the notation of Dormand and // Prince, whose RKNq(p)sF has higher order q, lower order p, comprises // s stages, and has the first-same-as-last property. template<typename Method, typename Position> class EmbeddedExplicitRungeKuttaNyströmIntegrator : public AdaptiveStepSizeIntegrator< SpecialSecondOrderDifferentialEquation<Position>> { public: using ODE = SpecialSecondOrderDifferentialEquation<Position>; using typename Integrator<ODE>::AppendState; using typename AdaptiveStepSizeIntegrator<ODE>::Parameters; using typename AdaptiveStepSizeIntegrator<ODE>::ToleranceToErrorRatio; static constexpr auto higher_order = Method::higher_order; static constexpr auto lower_order = Method::lower_order; static constexpr auto first_same_as_last = Method::first_same_as_last; EmbeddedExplicitRungeKuttaNyströmIntegrator(); EmbeddedExplicitRungeKuttaNyströmIntegrator( EmbeddedExplicitRungeKuttaNyströmIntegrator const&) = delete; EmbeddedExplicitRungeKuttaNyströmIntegrator( EmbeddedExplicitRungeKuttaNyströmIntegrator&&) = delete; EmbeddedExplicitRungeKuttaNyströmIntegrator& operator=( EmbeddedExplicitRungeKuttaNyströmIntegrator const&) = delete; EmbeddedExplicitRungeKuttaNyströmIntegrator& operator=( EmbeddedExplicitRungeKuttaNyströmIntegrator&&) = delete; class Instance : public AdaptiveStepSizeIntegrator<ODE>::Instance { public: Status Solve(Instant const& t_final) override; EmbeddedExplicitRungeKuttaNyströmIntegrator const& integrator() const override; not_null<std::unique_ptr<typename Integrator<ODE>::Instance>> Clone() const override; void WriteToMessage( not_null<serialization::IntegratorInstance*> message) const override; private: Instance(IntegrationProblem<ODE> const& problem, AppendState const& append_state, ToleranceToErrorRatio const& tolerance_to_error_ratio, Parameters const& adaptive_step_size, EmbeddedExplicitRungeKuttaNyströmIntegrator const& integrator); EmbeddedExplicitRungeKuttaNyströmIntegrator const& integrator_; friend class EmbeddedExplicitRungeKuttaNyströmIntegrator; }; not_null<std::unique_ptr<typename Integrator<ODE>::Instance>> NewInstance( IntegrationProblem<ODE> const& problem, AppendState const& append_state, ToleranceToErrorRatio const& tolerance_to_error_ratio, Parameters const& parameters) const override; void WriteToMessage( not_null<serialization::AdaptiveStepSizeIntegrator*> message) const override; private: not_null<std::unique_ptr<typename Integrator<ODE>::Instance>> ReadFromMessage( serialization::AdaptiveStepSizeIntegratorInstance const& message, IntegrationProblem<ODE> const& problem, AppendState const& append_state, ToleranceToErrorRatio const& tolerance_to_error_ratio, Parameters const& parameters) const override; static constexpr auto stages_ = Method::stages; static constexpr auto c_ = Method::c; static constexpr auto a_ = Method::a; static constexpr auto b_hat_ = Method::b_hat; static constexpr auto b_prime_hat_ = Method::b_prime_hat; static constexpr auto b_ = Method::b; static constexpr auto b_prime_ = Method::b_prime; }; } // namespace internal_embedded_explicit_runge_kutta_nyström_integrator template<typename Method, typename Position> internal_embedded_explicit_runge_kutta_nyström_integrator:: EmbeddedExplicitRungeKuttaNyströmIntegrator<Method, Position> const& EmbeddedExplicitRungeKuttaNyströmIntegrator(); } // namespace integrators } // namespace principia #include "integrators/embedded_explicit_runge_kutta_nyström_integrator_body.hpp" #endif // PRINCIPIA_INTEGRATORS_EMBEDDED_EXPLICIT_RUNGE_KUTTA_NYSTRÖM_INTEGRATOR_HPP_ // NOLINT(whitespace/line_length) #endif // PRINCIPIA_INTEGRATORS_INTEGRATORS_HPP_ <|endoftext|>
<commit_before>/* * TcpIpAsyncClientSsl.hpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef CORE_HTTP_TCP_IP_ASYNC_CLIENT_SSL_HPP #define CORE_HTTP_TCP_IP_ASYNC_CLIENT_SSL_HPP #ifdef _WIN32 #error TcpIpAsyncClientSsl is not supported on Windows #endif #include <boost/scoped_ptr.hpp> #include <boost/asio/ip/tcp.hpp> #include "BoostAsioSsl.hpp" #include <core/http/AsyncClient.hpp> #include <core/http/TcpIpAsyncConnector.hpp> namespace rstudio { namespace core { namespace http { class TcpIpAsyncClientSsl : public AsyncClient<boost::asio::ssl::stream<boost::asio::ip::tcp::socket> > { public: TcpIpAsyncClientSsl(boost::asio::io_service& ioService, const std::string& address, const std::string& port, bool verify, const std::string& certificateAuthority = std::string(), const boost::posix_time::time_duration& connectionTimeout = boost::posix_time::time_duration(boost::posix_time::pos_infin)) : AsyncClient<boost::asio::ssl::stream<boost::asio::ip::tcp::socket> >(ioService), sslContext_(ioService, boost::asio::ssl::context::sslv23_client), address_(address), port_(port), verify_(verify), certificateAuthority_(certificateAuthority), connectionTimeout_(connectionTimeout) { if (verify_) { sslContext_.set_default_verify_paths(); sslContext_.set_verify_mode(boost::asio::ssl::context::verify_peer); if (!certificateAuthority_.empty()) { boost::asio::const_buffer buff(certificateAuthority_.data(), certificateAuthority_.size()); boost::system::error_code ec; sslContext_.add_certificate_authority(buff, ec); if (ec) LOG_ERROR(Error(ec, ERROR_LOCATION)); } } else { sslContext_.set_verify_mode(boost::asio::ssl::context::verify_none); } // use scoped ptr so we can call the constructor after we've configured // the ssl::context (immediately above) ptrSslStream_.reset(new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(ioService, sslContext_)); } protected: virtual boost::asio::ssl::stream<boost::asio::ip::tcp::socket>& socket() { return *(ptrSslStream_); } virtual void connectAndWriteRequest() { boost::shared_ptr<TcpIpAsyncConnector> pAsyncConnector( new TcpIpAsyncConnector(ioService(), &(ptrSslStream_->next_layer()))); pAsyncConnector->connect( address_, port_, boost::bind(&TcpIpAsyncClientSsl::performHandshake, TcpIpAsyncClientSsl::sharedFromThis()), boost::bind(&TcpIpAsyncClientSsl::handleConnectionError, TcpIpAsyncClientSsl::sharedFromThis(), _1), connectionTimeout_); } private: void performHandshake() { if (verify_) { ptrSslStream_->set_verify_callback( boost::asio::ssl::rfc2818_verification(address_)); } ptrSslStream_->async_handshake( boost::asio::ssl::stream_base::client, boost::bind(&TcpIpAsyncClientSsl::handleHandshake, sharedFromThis(), boost::asio::placeholders::error)); } void handleHandshake(const boost::system::error_code& ec) { try { if (!ec) { // finished handshake, commence with request writeRequest(); } else { handleErrorCode(ec, ERROR_LOCATION); } } CATCH_UNEXPECTED_ASYNC_CLIENT_EXCEPTION } const boost::shared_ptr<TcpIpAsyncClientSsl> sharedFromThis() { boost::shared_ptr<AsyncClient<boost::asio::ssl::stream<boost::asio::ip::tcp::socket> > > ptrShared = shared_from_this(); return boost::static_pointer_cast<TcpIpAsyncClientSsl>(ptrShared); } virtual bool isShutdownError(const boost::system::error_code& ec) { return util::isSslShutdownError(ec); } private: boost::asio::ssl::context sslContext_; boost::scoped_ptr<boost::asio::ssl::stream<boost::asio::ip::tcp::socket> > ptrSslStream_; std::string address_; std::string port_; bool verify_; std::string certificateAuthority_; boost::posix_time::time_duration connectionTimeout_; }; } // namespace http } // namespace core } // namespace rstudio #endif // CORE_HTTP_TCP_IP_ASYNC_CLIENT_SSL_HPP <commit_msg>set the server name indication so we can work with TLS v 1.3<commit_after>/* * TcpIpAsyncClientSsl.hpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef CORE_HTTP_TCP_IP_ASYNC_CLIENT_SSL_HPP #define CORE_HTTP_TCP_IP_ASYNC_CLIENT_SSL_HPP #ifdef _WIN32 #error TcpIpAsyncClientSsl is not supported on Windows #endif #include <boost/scoped_ptr.hpp> #include <boost/asio/ip/tcp.hpp> #include "BoostAsioSsl.hpp" #include <core/http/AsyncClient.hpp> #include <core/http/TcpIpAsyncConnector.hpp> namespace rstudio { namespace core { namespace http { class TcpIpAsyncClientSsl : public AsyncClient<boost::asio::ssl::stream<boost::asio::ip::tcp::socket> > { public: TcpIpAsyncClientSsl(boost::asio::io_service& ioService, std::string address, std::string port, bool verify, const std::string& certificateAuthority = std::string(), const boost::posix_time::time_duration& connectionTimeout = boost::posix_time::time_duration(boost::posix_time::pos_infin), const std::string& hostname = std::string() ) : AsyncClient<boost::asio::ssl::stream<boost::asio::ip::tcp::socket> >(ioService), sslContext_(boost::asio::ssl::context::sslv23_client), address_(std::move(address)), port_(std::move(port)), verify_(verify), certificateAuthority_(certificateAuthority), connectionTimeout_(connectionTimeout) { if (verify_) { sslContext_.set_default_verify_paths(); sslContext_.set_verify_mode(boost::asio::ssl::context::verify_peer); if (!certificateAuthority_.empty()) { boost::asio::const_buffer buff(certificateAuthority_.data(), certificateAuthority_.size()); boost::system::error_code ec; sslContext_.add_certificate_authority(buff, ec); if (ec) LOG_ERROR(Error(ec, ERROR_LOCATION)); } } else { sslContext_.set_verify_mode(boost::asio::ssl::context::verify_none); } // use scoped ptr so we can call the constructor after we've configured // the ssl::context (immediately above) ptrSslStream_.reset(new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(ioService, sslContext_)); // Set the SNI so we still work with TLS v1.3 if (!SSL_set_tlsext_host_name( ptrSslStream_->native_handle(), (hostname.empty() ? address_.c_str() : hostname.c_str()))) { boost::system::error_code ec{ static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() }; LOG_ERROR(Error(ec, ERROR_LOCATION)); } } protected: virtual boost::asio::ssl::stream<boost::asio::ip::tcp::socket>& socket() { return *(ptrSslStream_); } virtual void connectAndWriteRequest() { boost::shared_ptr<TcpIpAsyncConnector> pAsyncConnector( new TcpIpAsyncConnector(ioService(), &(ptrSslStream_->next_layer()))); pAsyncConnector->connect( address_, port_, boost::bind(&TcpIpAsyncClientSsl::performHandshake, TcpIpAsyncClientSsl::sharedFromThis()), boost::bind(&TcpIpAsyncClientSsl::handleConnectionError, TcpIpAsyncClientSsl::sharedFromThis(), _1), connectionTimeout_); } private: void performHandshake() { if (verify_) { ptrSslStream_->set_verify_callback( boost::asio::ssl::rfc2818_verification(address_)); } ptrSslStream_->async_handshake( boost::asio::ssl::stream_base::client, boost::bind(&TcpIpAsyncClientSsl::handleHandshake, sharedFromThis(), boost::asio::placeholders::error)); } void handleHandshake(const boost::system::error_code& ec) { try { if (!ec) { // finished handshake, commence with request writeRequest(); } else { handleErrorCode(ec, ERROR_LOCATION); } } CATCH_UNEXPECTED_ASYNC_CLIENT_EXCEPTION } const boost::shared_ptr<TcpIpAsyncClientSsl> sharedFromThis() { boost::shared_ptr<AsyncClient<boost::asio::ssl::stream<boost::asio::ip::tcp::socket> > > ptrShared = shared_from_this(); return boost::static_pointer_cast<TcpIpAsyncClientSsl>(ptrShared); } virtual bool isShutdownError(const boost::system::error_code& ec) { return util::isSslShutdownError(ec); } private: boost::asio::ssl::context sslContext_; boost::scoped_ptr<boost::asio::ssl::stream<boost::asio::ip::tcp::socket> > ptrSslStream_; std::string address_; std::string port_; bool verify_; std::string certificateAuthority_; boost::posix_time::time_duration connectionTimeout_; }; } // namespace http } // namespace core } // namespace rstudio #endif // CORE_HTTP_TCP_IP_ASYNC_CLIENT_SSL_HPP <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief X11 Platform. *//*--------------------------------------------------------------------*/ #include "tcuX11Platform.hpp" #include "deUniquePtr.hpp" #include "gluPlatform.hpp" #include "vkPlatform.hpp" #include "tcuX11.hpp" #include "tcuFunctionLibrary.hpp" #if defined (DEQP_SUPPORT_GLX) # include "tcuX11GlxPlatform.hpp" #endif #if defined (DEQP_SUPPORT_EGL) # include "tcuX11EglPlatform.hpp" #endif namespace tcu { namespace x11 { class X11GLPlatform : public glu::Platform { public: void registerFactory (de::MovePtr<glu::ContextFactory> factory) { m_contextFactoryRegistry.registerFactory(factory.release()); } }; class VulkanLibrary : public vk::Library { public: VulkanLibrary (void) : m_library ("libvulkan.so") , m_driver (m_library) { } const vk::PlatformInterface& getPlatformInterface (void) const { return m_driver; } private: const tcu::DynamicFunctionLibrary m_library; const vk::PlatformDriver m_driver; }; class X11VulkanPlatform : public vk::Platform { public: vk::Library* createLibrary (void) const { return new VulkanLibrary(); } }; class X11Platform : public tcu::Platform { public: X11Platform (void); bool processEvents (void) { return !m_eventState.getQuitFlag(); } const glu::Platform& getGLPlatform (void) const { return m_glPlatform; } #if defined (DEQP_SUPPORT_EGL) const eglu::Platform& getEGLPlatform (void) const { return m_eglPlatform; } #endif // DEQP_SUPPORT_EGL const vk::Platform& getVulkanPlatform (void) const { return m_vkPlatform; } private: EventState m_eventState; #if defined (DEQP_SUPPORT_EGL) x11::egl::Platform m_eglPlatform; #endif // DEQP_SPPORT_EGL X11GLPlatform m_glPlatform; X11VulkanPlatform m_vkPlatform; }; X11Platform::X11Platform (void) #if defined (DEQP_SUPPORT_EGL) : m_eglPlatform (m_eventState) #endif // DEQP_SUPPORT_EGL { #if defined (DEQP_SUPPORT_GLX) m_glPlatform.registerFactory(glx::createContextFactory(m_eventState)); #endif // DEQP_SUPPORT_GLX #if defined (DEQP_SUPPORT_EGL) m_glPlatform.registerFactory(m_eglPlatform.createContextFactory()); #endif // DEQP_SUPPORT_EGL } } // x11 } // tcu tcu::Platform* createPlatform (void) { return new tcu::x11::X11Platform(); } <commit_msg>Fix Vulkan library name in X11 platform<commit_after>/*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief X11 Platform. *//*--------------------------------------------------------------------*/ #include "tcuX11Platform.hpp" #include "deUniquePtr.hpp" #include "gluPlatform.hpp" #include "vkPlatform.hpp" #include "tcuX11.hpp" #include "tcuFunctionLibrary.hpp" #if defined (DEQP_SUPPORT_GLX) # include "tcuX11GlxPlatform.hpp" #endif #if defined (DEQP_SUPPORT_EGL) # include "tcuX11EglPlatform.hpp" #endif namespace tcu { namespace x11 { class X11GLPlatform : public glu::Platform { public: void registerFactory (de::MovePtr<glu::ContextFactory> factory) { m_contextFactoryRegistry.registerFactory(factory.release()); } }; class VulkanLibrary : public vk::Library { public: VulkanLibrary (void) : m_library ("libvulkan-1.so") , m_driver (m_library) { } const vk::PlatformInterface& getPlatformInterface (void) const { return m_driver; } private: const tcu::DynamicFunctionLibrary m_library; const vk::PlatformDriver m_driver; }; class X11VulkanPlatform : public vk::Platform { public: vk::Library* createLibrary (void) const { return new VulkanLibrary(); } }; class X11Platform : public tcu::Platform { public: X11Platform (void); bool processEvents (void) { return !m_eventState.getQuitFlag(); } const glu::Platform& getGLPlatform (void) const { return m_glPlatform; } #if defined (DEQP_SUPPORT_EGL) const eglu::Platform& getEGLPlatform (void) const { return m_eglPlatform; } #endif // DEQP_SUPPORT_EGL const vk::Platform& getVulkanPlatform (void) const { return m_vkPlatform; } private: EventState m_eventState; #if defined (DEQP_SUPPORT_EGL) x11::egl::Platform m_eglPlatform; #endif // DEQP_SPPORT_EGL X11GLPlatform m_glPlatform; X11VulkanPlatform m_vkPlatform; }; X11Platform::X11Platform (void) #if defined (DEQP_SUPPORT_EGL) : m_eglPlatform (m_eventState) #endif // DEQP_SUPPORT_EGL { #if defined (DEQP_SUPPORT_GLX) m_glPlatform.registerFactory(glx::createContextFactory(m_eventState)); #endif // DEQP_SUPPORT_GLX #if defined (DEQP_SUPPORT_EGL) m_glPlatform.registerFactory(m_eglPlatform.createContextFactory()); #endif // DEQP_SUPPORT_EGL } } // x11 } // tcu tcu::Platform* createPlatform (void) { return new tcu::x11::X11Platform(); } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "RefineSidesetGenerator.h" #include "MooseMeshUtils.h" #include "libmesh/elem.h" #include "libmesh/mesh_refinement.h" #include "CastUniquePointer.h" registerMooseObject("MooseApp", RefineSidesetGenerator); InputParameters RefineSidesetGenerator::validParams() { InputParameters params = MeshGenerator::validParams(); params.addClassDescription("Mesh generator which refines one or more sidesets"); params.addRequiredParam<MeshGeneratorName>("input", "Input mesh to modify"); params.addRequiredParam<std::vector<BoundaryName>>("boundaries", "The list of boundaries to be modified"); params.addRequiredParam<std::vector<int>>( "refinement", "The amount of times to refine each sideset, corresponding to their index in 'boundaries'"); params.addParam<bool>( "enable_neighbor_refinement", true, "Toggles whether neighboring level one elements should be refined or not. Defaults to true"); MultiMooseEnum boundary_side("primary secondary both", "both"); params.addParam<MultiMooseEnum>("boundary_side", boundary_side, "Whether the generator should refine itself(primary), its " "neighbors(secondary), or itself and its neighbors(both)"); return params; } RefineSidesetGenerator::RefineSidesetGenerator(const InputParameters & parameters) : MeshGenerator(parameters), _input(getMesh("input")), _boundaries(getParam<std::vector<BoundaryName>>("boundaries")), _refinement(getParam<std::vector<int>>("refinement")), _enable_neighbor_refinement(getParam<bool>("enable_neighbor_refinement")), _boundary_side(getParam<MultiMooseEnum>("boundary_side")) { } std::unique_ptr<MeshBase> RefineSidesetGenerator::generate() { // Get the list of boundary ids from the boundary names const auto boundary_ids = MooseMeshUtils::getBoundaryIDs( *_input, getParam<std::vector<BoundaryName>>("boundaries"), true); // Check that the boundary ids/names exist in the mesh for (std::size_t i = 0; i < boundary_ids.size(); ++i) if (boundary_ids[i] == Moose::INVALID_BOUNDARY_ID && isParamValid("boundaries")) paramError("boundaries", "The boundary '", getParam<std::vector<BoundaryName>>("boundaries")[i], "' was not found within the mesh"); std::unique_ptr<MeshBase> mesh = std::move(_input); int max = *std::max_element(_refinement.begin(), _refinement.end()); return recursive_refine(boundary_ids, mesh, _refinement, max); } std::unique_ptr<MeshBase> RefineSidesetGenerator::recursive_refine(std::vector<boundary_id_type> boundary_ids, std::unique_ptr<MeshBase> & mesh, std::vector<int> refinement, int max, int ref_step) { // If the refinement step has reached the largest value in the _refinement array, return the mesh, // as we are done. if (ref_step == max) return dynamic_pointer_cast<MeshBase>(mesh); mesh->prepare_for_use(); std::vector<std::tuple<dof_id_type, unsigned short int, boundary_id_type>> sideList = mesh->get_boundary_info().build_active_side_list(); for (std::size_t i = 0; i < boundary_ids.size(); i++) { if (refinement[i] > 0 && refinement[i] > ref_step) { for (std::tuple<dof_id_type, unsigned short int, boundary_id_type> tuple : sideList) { if (std::get<2>(tuple) == boundary_ids[i]) { Elem * elem = mesh->elem_ptr(std::get<0>(tuple)); if (_boundary_side[i] == "primary" || _boundary_side[i] == "both") elem->set_refinement_flag(Elem::REFINE); if (_boundary_side[i] == "secondary" || _boundary_side[i] == "both") { auto neighbor = elem->neighbor_ptr(std::get<1>(tuple)); // when we have multiple domains, domains will only refine the elements that they own // since there can be instances where there is no neighbor, this null_ptr check is // necessary if (neighbor) { if (neighbor->active()) neighbor->set_refinement_flag(Elem::REFINE); else { std::vector<Elem *> family_tree; neighbor->active_family_tree_by_neighbor(family_tree, elem); for (auto child_elem : family_tree) child_elem->set_refinement_flag(Elem::REFINE); } } } } } } } MeshRefinement refinedmesh(*mesh); if (!_enable_neighbor_refinement) refinedmesh.face_level_mismatch_limit() = 0; refinedmesh.refine_elements(); ref_step++; return recursive_refine(boundary_ids, mesh, refinement, max, ref_step); } <commit_msg>Applied clang-formatting patch to RefineSidesetGenerator.C<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "RefineSidesetGenerator.h" #include "MooseMeshUtils.h" #include "libmesh/elem.h" #include "libmesh/mesh_refinement.h" #include "CastUniquePointer.h" registerMooseObject("MooseApp", RefineSidesetGenerator); InputParameters RefineSidesetGenerator::validParams() { InputParameters params = MeshGenerator::validParams(); params.addClassDescription("Mesh generator which refines one or more sidesets"); params.addRequiredParam<MeshGeneratorName>("input", "Input mesh to modify"); params.addRequiredParam<std::vector<BoundaryName>>("boundaries", "The list of boundaries to be modified"); params.addRequiredParam<std::vector<int>>( "refinement", "The amount of times to refine each sideset, corresponding to their index in 'boundaries'"); params.addParam<bool>( "enable_neighbor_refinement", true, "Toggles whether neighboring level one elements should be refined or not. Defaults to true"); MultiMooseEnum boundary_side("primary secondary both", "both"); params.addParam<MultiMooseEnum>("boundary_side", boundary_side, "Whether the generator should refine itself(primary), its " "neighbors(secondary), or itself and its neighbors(both)"); return params; } RefineSidesetGenerator::RefineSidesetGenerator(const InputParameters & parameters) : MeshGenerator(parameters), _input(getMesh("input")), _boundaries(getParam<std::vector<BoundaryName>>("boundaries")), _refinement(getParam<std::vector<int>>("refinement")), _enable_neighbor_refinement(getParam<bool>("enable_neighbor_refinement")), _boundary_side(getParam<MultiMooseEnum>("boundary_side")) { } std::unique_ptr<MeshBase> RefineSidesetGenerator::generate() { // Get the list of boundary ids from the boundary names const auto boundary_ids = MooseMeshUtils::getBoundaryIDs( *_input, getParam<std::vector<BoundaryName>>("boundaries"), true); // Check that the boundary ids/names exist in the mesh for (std::size_t i = 0; i < boundary_ids.size(); ++i) if (boundary_ids[i] == Moose::INVALID_BOUNDARY_ID && isParamValid("boundaries")) paramError("boundaries", "The boundary '", getParam<std::vector<BoundaryName>>("boundaries")[i], "' was not found within the mesh"); std::unique_ptr<MeshBase> mesh = std::move(_input); int max = *std::max_element(_refinement.begin(), _refinement.end()); return recursive_refine(boundary_ids, mesh, _refinement, max); } std::unique_ptr<MeshBase> RefineSidesetGenerator::recursive_refine(std::vector<boundary_id_type> boundary_ids, std::unique_ptr<MeshBase> & mesh, std::vector<int> refinement, int max, int ref_step) { // If the refinement step has reached the largest value in the _refinement array, return the mesh, // as we are done. if (ref_step == max) return dynamic_pointer_cast<MeshBase>(mesh); mesh->prepare_for_use(); std::vector<std::tuple<dof_id_type, unsigned short int, boundary_id_type>> sideList = mesh->get_boundary_info().build_active_side_list(); for (std::size_t i = 0; i < boundary_ids.size(); i++) { if (refinement[i] > 0 && refinement[i] > ref_step) { for (std::tuple<dof_id_type, unsigned short int, boundary_id_type> tuple : sideList) { if (std::get<2>(tuple) == boundary_ids[i]) { Elem * elem = mesh->elem_ptr(std::get<0>(tuple)); if (_boundary_side[i] == "primary" || _boundary_side[i] == "both") elem->set_refinement_flag(Elem::REFINE); if (_boundary_side[i] == "secondary" || _boundary_side[i] == "both") { auto neighbor = elem->neighbor_ptr(std::get<1>(tuple)); // when we have multiple domains, domains will only refine the elements that they own // since there can be instances where there is no neighbor, this null_ptr check is // necessary if (neighbor) { if (neighbor->active()) neighbor->set_refinement_flag(Elem::REFINE); else { std::vector<Elem *> family_tree; neighbor->active_family_tree_by_neighbor(family_tree, elem); for (auto child_elem : family_tree) child_elem->set_refinement_flag(Elem::REFINE); } } } } } } } MeshRefinement refinedmesh(*mesh); if (!_enable_neighbor_refinement) refinedmesh.face_level_mismatch_limit() = 0; refinedmesh.refine_elements(); ref_step++; return recursive_refine(boundary_ids, mesh, refinement, max, ref_step); } <|endoftext|>
<commit_before>/* CatenaStm32L0_ReadAnalog.cpp Mon Feb 18 2019 09:56:32 chwon */ /* Module: CatenaStm32L0_ReadAnalog.cpp Function: CatenaStm32L0::ReadAnalog() Version: V0.14.0 Mon Feb 18 2019 09:56:32 chwon Edit level 2 Copyright notice: This file copyright (C) 2018-2019 by MCCI Corporation 3520 Krums Corners Road Ithaca, NY 14850 An unpublished work. All rights reserved. This file is proprietary information, and may not be disclosed or copied without the prior permission of MCCI Corporation Author: ChaeHee Won, MCCI Corporation December 2018 Revision history: 0.13.0 Tue Dec 18 2018 15:41:52 chwon Module created. 0.14.0 Mon Feb 18 2019 09:56:32 chwon Turn on nad off HSI clock if system clock use MSI clock. */ #ifdef ARDUINO_ARCH_STM32 #include "CatenaStm32L0.h" #include "Catena_Log.h" #include <Arduino.h> using namespace McciCatena; /****************************************************************************\ | | Manifest constants & typedefs. | | This is strictly for private types and constants which will not | be exported. | \****************************************************************************/ constexpr unsigned long ADC_TIMEOUT = 10; constexpr int STM32L0_ADC_CHANNEL_VREFINT = 17; constexpr int STM32L0_ADC_CHANNEL_TEMPSENSOR = 18; static bool AdcCalibrate(void); static bool AdcDisable(void); static bool AdcEnable(void); static bool AdcGetValue(uint32_t *value); static void AdcStart(void); /****************************************************************************\ | | Read-only data. | | If program is to be ROM-able, these must all be tagged read-only | using the ROM storage class; they may be global. | \****************************************************************************/ /****************************************************************************\ | | VARIABLES: | | If program is to be ROM-able, these must be initialized | using the BSS keyword. (This allows for compilers that require | every variable to have an initializer.) Note that only those | variables owned by this module should be declared here, using the BSS | keyword; this allows for linkers that dislike multiple declarations | of objects. | \****************************************************************************/ // because this is defined inside the McciCatena namespace in the header file // we need to explicitly add the namespace tag here. bool McciCatena::CatenaStm32L0_ReadAnalog( uint32_t Channel, uint32_t ReadCount, uint32_t Multiplier, uint32_t *pValue ) { uint32_t vRef; uint32_t vChannel; bool fStatusOk; constexpr uint32_t AdcClockModeAsync = 0; constexpr uint32_t AdcClockModePclk2 = ADC_CFGR2_CKMODE_0; /* the clock we'll use: */ constexpr uint32_t AdcClockMode = AdcClockModeAsync; if (pValue == NULL) return false; *pValue = 0; if (Channel > STM32L0_ADC_CHANNEL_VREFINT) return false; /* make sure that the RCC is generating the low-frequency clock */ __HAL_RCC_ADC1_CLK_ENABLE(); #if CATENA_CFG_SYSCLK < 16 /* Set the Low Frequency Mode */ /* ADC->CCR = ADC_CCR_LFMEN; -- it's not working with MSI clock */ /* ADC requires HSI clock, so enable it now */ LL_RCC_HSI_Enable(); while (LL_RCC_HSI_IsReady() != 1U) { /* Wait for HSI ready */ } #endif fStatusOk = true; if (fStatusOk) { *pValue = 2; // make sure the clock is configured // ADC1->CFGR2 = (ADC1->CFGR2 & ~ADC_CFGR2_CKMODE) | AdcClockMode; fStatusOk = AdcCalibrate(); } // calibration turns off the ADC. Turn it back on. if (fStatusOk) { *pValue = 3; // Set the ADC clock source ADC1->CFGR2 = (ADC1->CFGR2 & ~ADC_CFGR2_CKMODE) | AdcClockMode; ADC1->CR = ADC_CR_ADVREGEN; fStatusOk = AdcEnable(); } if (fStatusOk) { *pValue = 4; ADC1->CFGR1 = ADC_CFGR1_WAIT | ADC_CFGR1_SCANDIR; ADC1->CHSELR = (1u << STM32L0_ADC_CHANNEL_VREFINT) | (1u << Channel); ADC1->SMPR = ADC_SMPR_SMPR; ADC->CCR = ADC_CCR_VREFEN; /* start ADC, which will take 2 readings */ AdcStart(); fStatusOk = AdcGetValue(&vRef); if (fStatusOk) { *pValue = 5; if (Channel != STM32L0_ADC_CHANNEL_VREFINT) fStatusOk = AdcGetValue(&vChannel); else vChannel = vRef; } if (fStatusOk) { *pValue = 6; ADC1->CHSELR = (1u << Channel); for (auto i = 1; i < ReadCount; ++i) { ++*pValue; AdcStart(); fStatusOk = AdcGetValue(&vChannel); if (! fStatusOk) break; } } } AdcDisable(); ADC1->CR &= ~ADC_CR_ADVREGEN; ADC->CCR &= ~ADC_CCR_VREFEN; #if CATENA_CFG_SYSCLK < 16 LL_RCC_HSI_Disable(); #endif __HAL_RCC_ADC1_FORCE_RESET(); __HAL_RCC_ADC1_RELEASE_RESET(); __HAL_RCC_ADC1_CLK_DISABLE(); if (fStatusOk) { uint16_t * pVrefintCal; uint32_t vRefInt_cal; uint32_t vResult; pVrefintCal = (uint16_t *) (0x1FF80078); // add a factor of 4 to vRefInt_cal, we'll take it out below vRefInt_cal = (*pVrefintCal * 3000 + 1) / (4096 / 4); vResult = vChannel * Multiplier; vResult = vResult * vRefInt_cal / vRef; // remove the factor of 4, and round *pValue = (vResult + 2) >> 2; } return fStatusOk; } static bool AdcDisable(void) { uint32_t uTime; if (ADC1->CR & ADC_CR_ADSTART) ADC1->CR |= ADC_CR_ADSTP; uTime = millis(); while (ADC1->CR & ADC_CR_ADSTP) { if ((millis() - uTime) > ADC_TIMEOUT) { gLog.printf( gLog.kError, "?AdcDisable:" " CR=%x\n", ADC1->CR ); return false; } } ADC1->CR |= ADC_CR_ADDIS; uTime = millis(); while (ADC1->CR & ADC_CR_ADEN) { if ((millis() - uTime) > ADC_TIMEOUT) { gLog.printf( gLog.kError, "?AdcDisable:" " CR=%x\n", ADC1->CR ); return false; } } return true; } static bool AdcCalibrate(void) { static uint32_t s_uLastCalibTime = 0; uint32_t uTime; if (ADC1->CR & ADC_CR_ADEN) { ADC1->CR &= ~ADC_CR_ADEN; // if (! AdcDisable()) // return false; } uTime = millis(); if ((uTime - s_uLastCalibTime) < 2000) return true; s_uLastCalibTime = uTime; /* turn on the cal bit */ ADC1->ISR = ADC_ISR_EOCAL; ADC1->CR |= ADC_CR_ADCAL; while (! (ADC1->ISR & ADC_ISR_EOCAL)) { if ((millis() - uTime) > ADC_TIMEOUT) { gLog.printf( gLog.kError, "?AdcCalibrate:" " CCR=%x CR=%x ISR=%x\n", ADC->CCR, ADC1->CR, ADC1->ISR ); return false; } } // uint32_t calData = ADC1->DR; /* turn off eocal */ ADC1->ISR = ADC_ISR_EOCAL; return true; } static bool AdcEnable(void) { uint32_t uTime; if (ADC1->CR & ADC_CR_ADEN) return true; /* clear the done bit */ ADC1->ISR = ADC_ISR_ADRDY; ADC1->CR |= ADC_CR_ADEN; if (ADC1->CFGR1 & ADC_CFGR1_AUTOFF) return true; uTime = millis(); while (!(ADC1->ISR & ADC_ISR_ADRDY)) { if ((millis() - uTime) > ADC_TIMEOUT) { gLog.printf( gLog.kError, "?AdcEnable:" " CR=%x ISR=%x\n", ADC1->CR, ADC1->ISR ); return false; } } return true; } static bool AdcGetValue(uint32_t *value) { uint32_t rAdcIsr; uint32_t uTime; uTime = millis(); while (! ((rAdcIsr = ADC1->ISR) & (ADC_ISR_EOC | ADC_ISR_EOSEQ))) { if ((millis() - uTime) > ADC_TIMEOUT) { *value = 0x0FFFu; gLog.printf( gLog.kError, "?AdcGetValue:" " ISR=%x\n", rAdcIsr ); return false; } } /* rarely, EOSEQ gets set early... so wait if needed */ if (! (rAdcIsr & ADC_ISR_EOC)) { for (unsigned i = 0; i < 256u; ++i) { if ((rAdcIsr = ADC1->ISR) & ADC_ISR_EOC) break; } } if (rAdcIsr & ADC_ISR_EOC) { *value = ADC1->DR; ADC1->ISR = ADC_ISR_EOC; return true; } gLog.printf( gLog.kError, "?AdcGetValue:" " ISR=%x\n", rAdcIsr ); // no more data in this sequence *value = 0x0FFFu; return false; } static void AdcStart(void) { ADC1->ISR = (ADC_ISR_EOC | ADC_ISR_EOSEQ); ADC1->CR |= ADC_CR_ADSTART; } /* Name: CatenaStm32L0::ReadAnalog Function: Read analog value for given channel Definition: uint32_t CatenaStm32L0::ReadAnalog( uint32_t Channel, uint32_t ReadCount, uint32_t Multiplier ); Description: This function reads the analog value for the given channel. Returns: Analog value */ uint32_t CatenaStm32L0::ReadAnalog( uint32_t Channel, uint32_t ReadCount, uint32_t Multiplier ) const { uint32_t vResult; bool fStatusOk; fStatusOk = CatenaStm32L0_ReadAnalog( Channel, ReadCount, Multiplier, &vResult ); if (! fStatusOk) { gLog.printf( gLog.kError, "?CatenaStm32L0::ReadAnalog(%u):" " CatenaStm32L0_ReadAnalog() failed (%u)\n", Channel, vResult ); vResult = 0x0FFFu; } return vResult; } #endif // ARDUINO_ARCH_STM32 /**** end of CatenaStm32L0_ReadAnalog.cpp ****/ <commit_msg>Add ADC_CALIBRATE_TIME constexpr and comment out debug message.<commit_after>/* CatenaStm32L0_ReadAnalog.cpp Mon Feb 18 2019 09:56:32 chwon */ /* Module: CatenaStm32L0_ReadAnalog.cpp Function: CatenaStm32L0::ReadAnalog() Version: V0.14.0 Mon Feb 18 2019 09:56:32 chwon Edit level 2 Copyright notice: This file copyright (C) 2018-2019 by MCCI Corporation 3520 Krums Corners Road Ithaca, NY 14850 An unpublished work. All rights reserved. This file is proprietary information, and may not be disclosed or copied without the prior permission of MCCI Corporation Author: ChaeHee Won, MCCI Corporation December 2018 Revision history: 0.13.0 Tue Dec 18 2018 15:41:52 chwon Module created. 0.14.0 Mon Feb 18 2019 09:56:32 chwon Turn on and off HSI clock if system clock use MSI clock. */ #ifdef ARDUINO_ARCH_STM32 #include "CatenaStm32L0.h" #include "Catena_Log.h" #include <Arduino.h> using namespace McciCatena; /****************************************************************************\ | | Manifest constants & typedefs. | | This is strictly for private types and constants which will not | be exported. | \****************************************************************************/ constexpr unsigned long ADC_TIMEOUT = 10; constexpr unsigned long ADC_CALIBRATE_TIME = 2000; constexpr int STM32L0_ADC_CHANNEL_VREFINT = 17; constexpr int STM32L0_ADC_CHANNEL_TEMPSENSOR = 18; static bool AdcCalibrate(void); static bool AdcDisable(void); static bool AdcEnable(void); static bool AdcGetValue(uint32_t *value); static void AdcStart(void); /****************************************************************************\ | | Read-only data. | | If program is to be ROM-able, these must all be tagged read-only | using the ROM storage class; they may be global. | \****************************************************************************/ /****************************************************************************\ | | VARIABLES: | | If program is to be ROM-able, these must be initialized | using the BSS keyword. (This allows for compilers that require | every variable to have an initializer.) Note that only those | variables owned by this module should be declared here, using the BSS | keyword; this allows for linkers that dislike multiple declarations | of objects. | \****************************************************************************/ // because this is defined inside the McciCatena namespace in the header file // we need to explicitly add the namespace tag here. bool McciCatena::CatenaStm32L0_ReadAnalog( uint32_t Channel, uint32_t ReadCount, uint32_t Multiplier, uint32_t *pValue ) { uint32_t vRef; uint32_t vChannel; bool fStatusOk; constexpr uint32_t AdcClockModeAsync = 0; constexpr uint32_t AdcClockModePclk2 = ADC_CFGR2_CKMODE_0; /* the clock we'll use: */ constexpr uint32_t AdcClockMode = AdcClockModeAsync; if (pValue == NULL) return false; *pValue = 0; if (Channel > STM32L0_ADC_CHANNEL_VREFINT) return false; /* make sure that the RCC is generating the low-frequency clock */ __HAL_RCC_ADC1_CLK_ENABLE(); #if CATENA_CFG_SYSCLK < 16 /* Set the Low Frequency Mode */ /* ADC->CCR = ADC_CCR_LFMEN; -- it's not working with MSI clock */ /* ADC requires HSI clock, so enable it now */ LL_RCC_HSI_Enable(); while (LL_RCC_HSI_IsReady() != 1U) { /* Wait for HSI ready */ } #endif fStatusOk = true; if (fStatusOk) { *pValue = 2; // make sure the clock is configured // ADC1->CFGR2 = (ADC1->CFGR2 & ~ADC_CFGR2_CKMODE) | AdcClockMode; fStatusOk = AdcCalibrate(); } // calibration turns off the ADC. Turn it back on. if (fStatusOk) { *pValue = 3; // Set the ADC clock source ADC1->CFGR2 = (ADC1->CFGR2 & ~ADC_CFGR2_CKMODE) | AdcClockMode; ADC1->CR = ADC_CR_ADVREGEN; fStatusOk = AdcEnable(); } if (fStatusOk) { *pValue = 4; ADC1->CFGR1 = ADC_CFGR1_WAIT | ADC_CFGR1_SCANDIR; ADC1->CHSELR = (1u << STM32L0_ADC_CHANNEL_VREFINT) | (1u << Channel); ADC1->SMPR = ADC_SMPR_SMPR; ADC->CCR = ADC_CCR_VREFEN; /* start ADC, which will take 2 readings */ AdcStart(); fStatusOk = AdcGetValue(&vRef); if (fStatusOk) { *pValue = 5; if (Channel != STM32L0_ADC_CHANNEL_VREFINT) fStatusOk = AdcGetValue(&vChannel); else vChannel = vRef; } if (fStatusOk) { *pValue = 6; ADC1->CHSELR = (1u << Channel); for (auto i = 1; i < ReadCount; ++i) { ++*pValue; AdcStart(); fStatusOk = AdcGetValue(&vChannel); if (! fStatusOk) break; } } } AdcDisable(); ADC1->CR &= ~ADC_CR_ADVREGEN; ADC->CCR &= ~ADC_CCR_VREFEN; #if CATENA_CFG_SYSCLK < 16 LL_RCC_HSI_Disable(); #endif __HAL_RCC_ADC1_FORCE_RESET(); __HAL_RCC_ADC1_RELEASE_RESET(); __HAL_RCC_ADC1_CLK_DISABLE(); if (fStatusOk) { uint16_t * pVrefintCal; uint32_t vRefInt_cal; uint32_t vResult; pVrefintCal = (uint16_t *) (0x1FF80078); // add a factor of 4 to vRefInt_cal, we'll take it out below vRefInt_cal = (*pVrefintCal * 3000 + 1) / (4096 / 4); vResult = vChannel * Multiplier; vResult = vResult * vRefInt_cal / vRef; // remove the factor of 4, and round *pValue = (vResult + 2) >> 2; } return fStatusOk; } static bool AdcDisable(void) { uint32_t uTime; if (ADC1->CR & ADC_CR_ADSTART) ADC1->CR |= ADC_CR_ADSTP; uTime = millis(); while (ADC1->CR & ADC_CR_ADSTP) { if ((millis() - uTime) > ADC_TIMEOUT) { // gLog.printf( // gLog.kError, // "?AdcDisable:" // " CR=%x\n", // ADC1->CR // ); return false; } } ADC1->CR |= ADC_CR_ADDIS; uTime = millis(); while (ADC1->CR & ADC_CR_ADEN) { if ((millis() - uTime) > ADC_TIMEOUT) { // gLog.printf( // gLog.kError, // "?AdcDisable:" // " CR=%x\n", // ADC1->CR // ); return false; } } return true; } static bool AdcCalibrate(void) { static uint32_t s_uLastCalibTime = 0; uint32_t uTime; if (ADC1->CR & ADC_CR_ADEN) { ADC1->CR &= ~ADC_CR_ADEN; // if (! AdcDisable()) // return false; } uTime = millis(); if ((uTime - s_uLastCalibTime) < ADC_CALIBRATE_TIME) return true; s_uLastCalibTime = uTime; /* turn on the cal bit */ ADC1->ISR = ADC_ISR_EOCAL; ADC1->CR |= ADC_CR_ADCAL; while (! (ADC1->ISR & ADC_ISR_EOCAL)) { if ((millis() - uTime) > ADC_TIMEOUT) { // gLog.printf( // gLog.kError, // "?AdcCalibrate:" // " CCR=%x CR=%x ISR=%x\n", // ADC->CCR, // ADC1->CR, // ADC1->ISR // ); return false; } } // uint32_t calData = ADC1->DR; /* turn off eocal */ ADC1->ISR = ADC_ISR_EOCAL; return true; } static bool AdcEnable(void) { uint32_t uTime; if (ADC1->CR & ADC_CR_ADEN) return true; /* clear the done bit */ ADC1->ISR = ADC_ISR_ADRDY; ADC1->CR |= ADC_CR_ADEN; if (ADC1->CFGR1 & ADC_CFGR1_AUTOFF) return true; uTime = millis(); while (!(ADC1->ISR & ADC_ISR_ADRDY)) { if ((millis() - uTime) > ADC_TIMEOUT) { // gLog.printf( // gLog.kError, // "?AdcEnable:" // " CR=%x ISR=%x\n", // ADC1->CR, // ADC1->ISR // ); return false; } } return true; } static bool AdcGetValue(uint32_t *value) { uint32_t rAdcIsr; uint32_t uTime; uTime = millis(); while (! ((rAdcIsr = ADC1->ISR) & (ADC_ISR_EOC | ADC_ISR_EOSEQ))) { if ((millis() - uTime) > ADC_TIMEOUT) { *value = 0x0FFFu; // gLog.printf( // gLog.kError, // "?AdcGetValue:" // " ISR=%x\n", // rAdcIsr // ); return false; } } /* rarely, EOSEQ gets set early... so wait if needed */ if (! (rAdcIsr & ADC_ISR_EOC)) { for (unsigned i = 0; i < 256u; ++i) { if ((rAdcIsr = ADC1->ISR) & ADC_ISR_EOC) break; } } if (rAdcIsr & ADC_ISR_EOC) { *value = ADC1->DR; ADC1->ISR = ADC_ISR_EOC; return true; } // gLog.printf( // gLog.kError, // "?AdcGetValue:" // " ISR=%x\n", // rAdcIsr // ); // no more data in this sequence *value = 0x0FFFu; return false; } static void AdcStart(void) { ADC1->ISR = (ADC_ISR_EOC | ADC_ISR_EOSEQ); ADC1->CR |= ADC_CR_ADSTART; } /* Name: CatenaStm32L0::ReadAnalog Function: Read analog value for given channel Definition: uint32_t CatenaStm32L0::ReadAnalog( uint32_t Channel, uint32_t ReadCount, uint32_t Multiplier ); Description: This function reads the analog value for the given channel. Returns: Analog value */ uint32_t CatenaStm32L0::ReadAnalog( uint32_t Channel, uint32_t ReadCount, uint32_t Multiplier ) const { uint32_t vResult; bool fStatusOk; fStatusOk = CatenaStm32L0_ReadAnalog( Channel, ReadCount, Multiplier, &vResult ); if (! fStatusOk) { gLog.printf( gLog.kError, "?CatenaStm32L0::ReadAnalog(%u):" " CatenaStm32L0_ReadAnalog() failed (%u)\n", Channel, vResult ); vResult = 0x0FFFu; } return vResult; } #endif // ARDUINO_ARCH_STM32 /**** end of CatenaStm32L0_ReadAnalog.cpp ****/ <|endoftext|>
<commit_before>/** @file logging.cpp @brief Syslog utility <p> Copyright (C) 2009-2010 Nokia Corporation @author Ustun Ergenoglu <[email protected]> This file is part of Sensord. Sensord 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. Sensord 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 Sensord. If not, see <http://www.gnu.org/licenses/>. </p> */ #include "logging.h" #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <QDateTime> #include <QFile> #include <iostream> #include <signal.h> #include <sensormanager.h> #ifdef SENSORD_USE_SYSLOG #include <syslog.h> #endif SensordLogLevel SensordLogger::outputLevel = SensordLogWarning; SensordLogger::SensordLogger (const char *module, const char* func, const char *file, int line, SensordLogLevel level) : QTextStream(), moduleName(module), currentLevel(level) { #ifdef SENSORD_USE_SYSLOG openlog(NULL, LOG_PERROR, LOG_DAEMON); #endif printLog = ((level >= SensordLogTest) && (level < SensordLogN)) && (level >= outputLevel); signal(SIGUSR1, signalHandler); signal(SIGUSR2, signalFlush); setString(&data); if (printLog) { //add level switch (level) { case SensordLogTest: *this << QString("*TEST*").toLocal8Bit().data(); break; case SensordLogDebug: *this << QString("*DEBUG*").toLocal8Bit().data(); break; case SensordLogWarning: *this << QString("*WARNING*").toLocal8Bit().data(); break; case SensordLogCritical: *this << QString("*CRITICAL*").toLocal8Bit().data(); break; case SensordLogN: default: break; } //add time stamp *this << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss").toLocal8Bit().data(); #ifndef SENSORD_USE_SYSLOG //add module name *this << QString("[" + QString(module) + "]").toLocal8Bit().data(); #endif //File, line and function *this << QString("[" + QString(file) + ":" + QString::number(line) + ":" + QString(func) + "]").toLocal8Bit().data(); } } SensordLogger::~SensordLogger() { if (printLog) { #ifdef SENSORD_USE_SYSLOG int logPriority; switch (currentLevel) { case SensordLogN: default: case SensordLogTest: logPriority = LOG_DEBUG; break; case SensordLogDebug: logPriority = LOG_INFO; break; case SensordLogWarning: logPriority = LOG_WARNING; break; case SensordLogCritical: logPriority = LOG_CRIT; break; } syslog(logPriority, data.toLocal8Bit().data()); closelog(); #else fcntl(STDERR_FILENO, F_SETFL, O_WRONLY); QTextStream::operator<<('\n'); QTextStream(stderr) << data; #endif } setDevice(NULL); } void SensordLogger::setOutputLevel(SensordLogLevel level) { outputLevel = level; } SensordLogLevel SensordLogger::getOutputLevel() { return outputLevel; } void SensordLogger::signalHandler(int param) { Q_UNUSED(param); outputLevel = static_cast<SensordLogLevel> ((static_cast<int>(outputLevel) + 1) % SensordLogN); std::cerr << "Signal Handled \n"; std::cerr << "New debugging level: " << outputLevel << "\n"; //std::cerr << "Debugging output " << (printDebug?"enabled":"disabled") << "\n"; } void SensordLogger::signalFlush(int param) { Q_UNUSED(param); QStringList output; output.append("Flushing sensord state\n"); output.append(QString(" Logging level: %1\n").arg(outputLevel)); SensorManager& sm = SensorManager::instance(); output.append(" Adaptors:\n"); foreach (QString key, sm.deviceAdaptorInstanceMap_.keys()) { DeviceAdaptorInstanceEntry& entry = sm.deviceAdaptorInstanceMap_[key]; output.append(QString(" %1 [%2 listener(s)]\n").arg(entry.type_).arg(entry.cnt_)); } output.append(" Chains:\n"); foreach (QString key, sm.chainInstanceMap_.keys()) { ChainInstanceEntry& entry = sm.chainInstanceMap_[key]; output.append(QString(" %1 [%2 listener(s)]. %3\n").arg(entry.type_).arg(entry.cnt_).arg(entry.chain_->running()?"Running":"Stopped")); } output.append(" Logical sensors:\n"); foreach (QString key, sm.sensorInstanceMap_.keys()) { SensorInstanceEntry& entry = sm.sensorInstanceMap_[key]; bool control = true; if (entry.controllingSession_ <= 0) { control = false; } output.append(QString(" %1 [%2 %3 listen session(s)]. %4\n").arg(entry.type_).arg(control? "Control +":"No control,").arg(entry.listenSessions_.size()).arg(entry.sensor_->running()?"Running":"Stopped")); } foreach (QString line, output) { #ifdef SENSORD_USE_SYSLOG openlog(NULL, LOG_PERROR, LOG_DAEMON); syslog(LOG_DEBUG, line.toLocal8Bit().data()); closelog(); #else fcntl(STDERR_FILENO, F_SETFL, O_WRONLY); QTextStream(stderr) << line; #endif } } <commit_msg>Fixed a bug in syslog logging.<commit_after>/** @file logging.cpp @brief Syslog utility <p> Copyright (C) 2009-2010 Nokia Corporation @author Ustun Ergenoglu <[email protected]> This file is part of Sensord. Sensord 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. Sensord 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 Sensord. If not, see <http://www.gnu.org/licenses/>. </p> */ #include "logging.h" #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <QDateTime> #include <QFile> #include <iostream> #include <signal.h> #include <sensormanager.h> #ifdef SENSORD_USE_SYSLOG #include <syslog.h> #endif SensordLogLevel SensordLogger::outputLevel = SensordLogWarning; SensordLogger::SensordLogger (const char *module, const char* func, const char *file, int line, SensordLogLevel level) : QTextStream(), moduleName(module), currentLevel(level) { #ifdef SENSORD_USE_SYSLOG openlog(NULL, LOG_PERROR, LOG_DAEMON); #endif printLog = ((level >= SensordLogTest) && (level < SensordLogN)) && (level >= outputLevel); signal(SIGUSR1, signalHandler); signal(SIGUSR2, signalFlush); setString(&data); if (printLog) { //add level switch (level) { case SensordLogTest: *this << QString("*TEST*").toLocal8Bit().data(); break; case SensordLogDebug: *this << QString("*DEBUG*").toLocal8Bit().data(); break; case SensordLogWarning: *this << QString("*WARNING*").toLocal8Bit().data(); break; case SensordLogCritical: *this << QString("*CRITICAL*").toLocal8Bit().data(); break; case SensordLogN: default: break; } //add time stamp *this << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss").toLocal8Bit().data(); #ifndef SENSORD_USE_SYSLOG //add module name *this << QString("[" + QString(module) + "]").toLocal8Bit().data(); #endif //File, line and function *this << QString("[" + QString(file) + ":" + QString::number(line) + ":" + QString(func) + "]").toLocal8Bit().data(); } } SensordLogger::~SensordLogger() { if (printLog) { #ifdef SENSORD_USE_SYSLOG int logPriority; switch (currentLevel) { case SensordLogN: default: case SensordLogTest: logPriority = LOG_DEBUG; break; case SensordLogDebug: logPriority = LOG_INFO; break; case SensordLogWarning: logPriority = LOG_WARNING; break; case SensordLogCritical: logPriority = LOG_CRIT; break; } syslog(logPriority, "%s", data.toLocal8Bit().data()); closelog(); #else fcntl(STDERR_FILENO, F_SETFL, O_WRONLY); QTextStream::operator<<('\n'); QTextStream(stderr) << data; #endif } setDevice(NULL); } void SensordLogger::setOutputLevel(SensordLogLevel level) { outputLevel = level; } SensordLogLevel SensordLogger::getOutputLevel() { return outputLevel; } void SensordLogger::signalHandler(int param) { Q_UNUSED(param); outputLevel = static_cast<SensordLogLevel> ((static_cast<int>(outputLevel) + 1) % SensordLogN); std::cerr << "Signal Handled \n"; std::cerr << "New debugging level: " << outputLevel << "\n"; //std::cerr << "Debugging output " << (printDebug?"enabled":"disabled") << "\n"; } void SensordLogger::signalFlush(int param) { Q_UNUSED(param); QStringList output; output.append("Flushing sensord state\n"); output.append(QString(" Logging level: %1\n").arg(outputLevel)); SensorManager& sm = SensorManager::instance(); output.append(" Adaptors:\n"); foreach (QString key, sm.deviceAdaptorInstanceMap_.keys()) { DeviceAdaptorInstanceEntry& entry = sm.deviceAdaptorInstanceMap_[key]; output.append(QString(" %1 [%2 listener(s)]\n").arg(entry.type_).arg(entry.cnt_)); } output.append(" Chains:\n"); foreach (QString key, sm.chainInstanceMap_.keys()) { ChainInstanceEntry& entry = sm.chainInstanceMap_[key]; output.append(QString(" %1 [%2 listener(s)]. %3\n").arg(entry.type_).arg(entry.cnt_).arg(entry.chain_->running()?"Running":"Stopped")); } output.append(" Logical sensors:\n"); foreach (QString key, sm.sensorInstanceMap_.keys()) { SensorInstanceEntry& entry = sm.sensorInstanceMap_[key]; bool control = true; if (entry.controllingSession_ <= 0) { control = false; } output.append(QString(" %1 [%2 %3 listen session(s)]. %4\n").arg(entry.type_).arg(control? "Control +":"No control,").arg(entry.listenSessions_.size()).arg(entry.sensor_->running()?"Running":"Stopped")); } foreach (QString line, output) { #ifdef SENSORD_USE_SYSLOG openlog(NULL, LOG_PERROR, LOG_DAEMON); syslog(LOG_DEBUG, "%s", line.toLocal8Bit().data()); closelog(); #else fcntl(STDERR_FILENO, F_SETFL, O_WRONLY); QTextStream(stderr) << line; #endif } } <|endoftext|>
<commit_before>#include <cthun-client/connector/client_metadata.hpp> #include <cthun-client/connector/errors.hpp> #define LEATHERMAN_LOGGING_NAMESPACE CTHUN_CLIENT_LOGGING_PREFIX".client_metadata" #include <leatherman/logging/logging.hpp> #include <openssl/x509v3.h> #include <openssl/ssl.h> #include <stdio.h> // std::fopen namespace CthunClient { // Get rid of OSX 10.7 and greater deprecation warnings. #if defined(__APPLE__) && defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif static const std::string CTHUN_URI_SCHEME { "cth://" }; std::string getCommonNameFromCert(const std::string& client_crt_path) { LOG_INFO("Retrieving the client identity from %1%", client_crt_path); std::unique_ptr<std::FILE, int(*)(std::FILE*)> fp { std::fopen(client_crt_path.data(), "r"), std::fclose }; if (fp == nullptr) { throw connection_config_error { "certificate file '" + client_crt_path + "' does not exist" }; } std::unique_ptr<X509, void(*)(X509*)> cert { PEM_read_X509(fp.get(), NULL, NULL, NULL), X509_free }; if (cert == nullptr) { throw connection_config_error { "certificate file '" + client_crt_path + "' is invalid" }; } X509_NAME* subj = X509_get_subject_name(cert.get()); X509_NAME_ENTRY* name_entry = X509_NAME_get_entry(subj, 0); if (name_entry == nullptr) { throw connection_config_error { "failed to retrieve the client name " "from " + client_crt_path }; } ASN1_STRING* asn1_name = X509_NAME_ENTRY_get_data(name_entry); unsigned char* name_ptr = ASN1_STRING_data(asn1_name); int name_size = ASN1_STRING_length(asn1_name); return std::string { name_ptr, name_ptr + name_size }; } #if defined(__APPLE__) && defined(__clang__) #pragma clang diagnostic pop #endif ClientMetadata::ClientMetadata(const std::string& _client_type, const std::string& _ca, const std::string& _crt, const std::string& _key) : ca { _ca }, crt { _crt }, key { _key }, client_type { _client_type }, common_name { getCommonNameFromCert(crt) }, uri { CTHUN_URI_SCHEME + common_name + "/" + client_type } { LOG_INFO("Retrieved common name from %1% and determined client URI: %2%", _crt, uri); } } // namespace CthunClient <commit_msg>(CTH-213) Update logging and error messages of ClientMetadata<commit_after>#include <cthun-client/connector/client_metadata.hpp> #include <cthun-client/connector/errors.hpp> #define LEATHERMAN_LOGGING_NAMESPACE CTHUN_CLIENT_LOGGING_PREFIX".client_metadata" #include <leatherman/logging/logging.hpp> #include <openssl/x509v3.h> #include <openssl/ssl.h> #include <stdio.h> // std::fopen namespace CthunClient { // Get rid of OSX 10.7 and greater deprecation warnings. #if defined(__APPLE__) && defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif static const std::string CTHUN_URI_SCHEME { "cth://" }; std::string getCommonNameFromCert(const std::string& client_crt_path) { LOG_INFO("Retrieving the common name from certificate %1%", client_crt_path); std::unique_ptr<std::FILE, int(*)(std::FILE*)> fp { std::fopen(client_crt_path.data(), "r"), std::fclose }; if (fp == nullptr) { throw connection_config_error { "certificate file '" + client_crt_path + "' does not exist" }; } std::unique_ptr<X509, void(*)(X509*)> cert { PEM_read_X509(fp.get(), NULL, NULL, NULL), X509_free }; if (cert == nullptr) { throw connection_config_error { "certificate file '" + client_crt_path + "' is invalid" }; } X509_NAME* subj = X509_get_subject_name(cert.get()); X509_NAME_ENTRY* name_entry = X509_NAME_get_entry(subj, 0); if (name_entry == nullptr) { throw connection_config_error { "failed to retrieve the client common " "name from " + client_crt_path }; } ASN1_STRING* asn1_name = X509_NAME_ENTRY_get_data(name_entry); unsigned char* name_ptr = ASN1_STRING_data(asn1_name); int name_size = ASN1_STRING_length(asn1_name); return std::string { name_ptr, name_ptr + name_size }; } #if defined(__APPLE__) && defined(__clang__) #pragma clang diagnostic pop #endif ClientMetadata::ClientMetadata(const std::string& _client_type, const std::string& _ca, const std::string& _crt, const std::string& _key) : ca { _ca }, crt { _crt }, key { _key }, client_type { _client_type }, common_name { getCommonNameFromCert(crt) }, uri { CTHUN_URI_SCHEME + common_name + "/" + client_type } { LOG_INFO("Retrieved common name from the certificate and determined " "the client URI: %1%", uri); } } // namespace CthunClient <|endoftext|>
<commit_before>/* * NotebookDocQueue.cpp * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "NotebookDocQueue.hpp" #include <boost/foreach.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; #define kDocQueueId "doc_id" #define kDocQueueJobDesc "job_desc" #define kDocQueuePixelWidth "pixel_width" #define kDocQueueCharWidth "pixel_width" #define kDocQueueUnits "units" #define kDocQueueMaxUnits "max_units" #define kDocQueueCommitMode "commit_mode" #define kDocQueueCompletedUnits "completed_units" namespace rstudio { namespace session { namespace modules { namespace rmarkdown { namespace notebook { NotebookDocQueue::NotebookDocQueue(const std::string& docId, const std::string& jobDesc, CommitMode commitMode, int pixelWidth, int charWidth, int maxUnits) : docId_(docId), jobDesc_(jobDesc), commitMode_(commitMode), pixelWidth_(pixelWidth), charWidth_(charWidth), maxUnits_(maxUnits) { } boost::shared_ptr<NotebookQueueUnit> NotebookDocQueue::firstUnit() { if (queue_.empty()) return boost::shared_ptr<NotebookQueueUnit>(); return *queue_.begin(); } json::Object NotebookDocQueue::toJson() const { // serialize all the queue units json::Array units; BOOST_FOREACH(const boost::shared_ptr<NotebookQueueUnit> unit, queue_) { units.push_back(unit->toJson()); } // form JSON object for client json::Object queue; queue[kDocQueueId] = docId_; queue[kDocQueueJobDesc] = jobDesc_; queue[kDocQueueCommitMode] = commitMode_; queue[kDocQueuePixelWidth] = pixelWidth_; queue[kDocQueueCharWidth] = charWidth_; queue[kDocQueueUnits] = units; queue[kDocQueueMaxUnits] = maxUnits_; queue[kDocQueueCompletedUnits] = json::Array(); return queue; } core::Error NotebookDocQueue::fromJson(const core::json::Object& source, boost::shared_ptr<NotebookDocQueue>* pQueue) { // extract contained unit for manipulation json::Array units; int commitMode = 0, pixelWidth = 0, charWidth = 0, maxUnits = 0; std::string docId, jobDesc; Error error = json::readObject(source, kDocQueueId, &docId, kDocQueueJobDesc, &jobDesc, kDocQueueCommitMode, &commitMode, kDocQueuePixelWidth, &pixelWidth, kDocQueueCharWidth, &charWidth, kDocQueueUnits, &units, kDocQueueMaxUnits, &maxUnits); if (error) return error; *pQueue = boost::make_shared<NotebookDocQueue>(docId, jobDesc, static_cast<CommitMode>(commitMode), pixelWidth, charWidth, maxUnits); BOOST_FOREACH(const json::Value val, units) { // ignore non-objects if (val.type() != json::ObjectType) continue; boost::shared_ptr<NotebookQueueUnit> pUnit = boost::make_shared<NotebookQueueUnit>(); Error error = NotebookQueueUnit::fromJson(val.get_obj(), &pUnit); if (error) LOG_ERROR(error); else (*pQueue)->queue_.push_back(pUnit); } return Success(); } bool chunkIdEquals(const boost::shared_ptr<NotebookQueueUnit> unit, const std::string &chunkId) { return unit->chunkId() == chunkId; } Error NotebookDocQueue::update(const boost::shared_ptr<NotebookQueueUnit> unit, QueueOperation op, const std::string& before) { std::list<boost::shared_ptr<NotebookQueueUnit> >::iterator it; switch(op) { case QueueAdd: // find insertion position it = std::find_if(queue_.begin(), queue_.end(), boost::bind(chunkIdEquals, _1, before)); queue_.insert(it, unit); maxUnits_ = std::max(maxUnits_, static_cast<int>(queue_.size())); break; case QueueUpdate: it = std::find_if(queue_.begin(), queue_.end(), boost::bind(chunkIdEquals, _1, unit->chunkId())); if (it == queue_.end()) { // no matching chunk ID in queue break; } (*it)->updateFrom(*unit); break; case QueueDelete: queue_.remove_if(boost::bind(chunkIdEquals, _1, unit->chunkId())); break; } return Success(); } std::string NotebookDocQueue::docId() const { return docId_; } int NotebookDocQueue::pixelWidth() const { return pixelWidth_; } int NotebookDocQueue::charWidth() const { return charWidth_; } bool NotebookDocQueue::complete() const { return queue_.empty(); } CommitMode NotebookDocQueue::commitMode() const { return commitMode_; } } // namespace notebook } // namespace rmarkdown } // namespace modules } // namespace session } // namespace rstudio <commit_msg>fix pixel/char width confusion in doc queue<commit_after>/* * NotebookDocQueue.cpp * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "NotebookDocQueue.hpp" #include <boost/foreach.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; #define kDocQueueId "doc_id" #define kDocQueueJobDesc "job_desc" #define kDocQueuePixelWidth "pixel_width" #define kDocQueueCharWidth "char_width" #define kDocQueueUnits "units" #define kDocQueueMaxUnits "max_units" #define kDocQueueCommitMode "commit_mode" #define kDocQueueCompletedUnits "completed_units" namespace rstudio { namespace session { namespace modules { namespace rmarkdown { namespace notebook { NotebookDocQueue::NotebookDocQueue(const std::string& docId, const std::string& jobDesc, CommitMode commitMode, int pixelWidth, int charWidth, int maxUnits) : docId_(docId), jobDesc_(jobDesc), commitMode_(commitMode), pixelWidth_(pixelWidth), charWidth_(charWidth), maxUnits_(maxUnits) { } boost::shared_ptr<NotebookQueueUnit> NotebookDocQueue::firstUnit() { if (queue_.empty()) return boost::shared_ptr<NotebookQueueUnit>(); return *queue_.begin(); } json::Object NotebookDocQueue::toJson() const { // serialize all the queue units json::Array units; BOOST_FOREACH(const boost::shared_ptr<NotebookQueueUnit> unit, queue_) { units.push_back(unit->toJson()); } // form JSON object for client json::Object queue; queue[kDocQueueId] = docId_; queue[kDocQueueJobDesc] = jobDesc_; queue[kDocQueueCommitMode] = commitMode_; queue[kDocQueuePixelWidth] = pixelWidth_; queue[kDocQueueCharWidth] = charWidth_; queue[kDocQueueUnits] = units; queue[kDocQueueMaxUnits] = maxUnits_; queue[kDocQueueCompletedUnits] = json::Array(); return queue; } core::Error NotebookDocQueue::fromJson(const core::json::Object& source, boost::shared_ptr<NotebookDocQueue>* pQueue) { // extract contained unit for manipulation json::Array units; int commitMode = 0, pixelWidth = 0, charWidth = 0, maxUnits = 0; std::string docId, jobDesc; Error error = json::readObject(source, kDocQueueId, &docId, kDocQueueJobDesc, &jobDesc, kDocQueueCommitMode, &commitMode, kDocQueuePixelWidth, &pixelWidth, kDocQueueCharWidth, &charWidth, kDocQueueUnits, &units, kDocQueueMaxUnits, &maxUnits); if (error) return error; *pQueue = boost::make_shared<NotebookDocQueue>(docId, jobDesc, static_cast<CommitMode>(commitMode), pixelWidth, charWidth, maxUnits); BOOST_FOREACH(const json::Value val, units) { // ignore non-objects if (val.type() != json::ObjectType) continue; boost::shared_ptr<NotebookQueueUnit> pUnit = boost::make_shared<NotebookQueueUnit>(); Error error = NotebookQueueUnit::fromJson(val.get_obj(), &pUnit); if (error) LOG_ERROR(error); else (*pQueue)->queue_.push_back(pUnit); } return Success(); } bool chunkIdEquals(const boost::shared_ptr<NotebookQueueUnit> unit, const std::string &chunkId) { return unit->chunkId() == chunkId; } Error NotebookDocQueue::update(const boost::shared_ptr<NotebookQueueUnit> unit, QueueOperation op, const std::string& before) { std::list<boost::shared_ptr<NotebookQueueUnit> >::iterator it; switch(op) { case QueueAdd: // find insertion position it = std::find_if(queue_.begin(), queue_.end(), boost::bind(chunkIdEquals, _1, before)); queue_.insert(it, unit); maxUnits_ = std::max(maxUnits_, static_cast<int>(queue_.size())); break; case QueueUpdate: it = std::find_if(queue_.begin(), queue_.end(), boost::bind(chunkIdEquals, _1, unit->chunkId())); if (it == queue_.end()) { // no matching chunk ID in queue break; } (*it)->updateFrom(*unit); break; case QueueDelete: queue_.remove_if(boost::bind(chunkIdEquals, _1, unit->chunkId())); break; } return Success(); } std::string NotebookDocQueue::docId() const { return docId_; } int NotebookDocQueue::pixelWidth() const { return pixelWidth_; } int NotebookDocQueue::charWidth() const { return charWidth_; } bool NotebookDocQueue::complete() const { return queue_.empty(); } CommitMode NotebookDocQueue::commitMode() const { return commitMode_; } } // namespace notebook } // namespace rmarkdown } // namespace modules } // namespace session } // namespace rstudio <|endoftext|>
<commit_before>/* * Copyright (C) 2008 The Android Open Source Project * * 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 "signal_catcher.h" #include <fcntl.h> #include <pthread.h> #include <signal.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include "base/unix_file/fd_file.h" #include "class_linker.h" #include "gc/heap.h" #include "os.h" #include "runtime.h" #include "scoped_thread_state_change.h" #include "signal_set.h" #include "thread.h" #include "thread_list.h" #include "utils.h" namespace art { static void DumpCmdLine(std::ostream& os) { #if defined(__linux__) // Show the original command line, and the current command line too if it's changed. // On Android, /proc/self/cmdline will have been rewritten to something like "system_server". std::string current_cmd_line; if (ReadFileToString("/proc/self/cmdline", &current_cmd_line)) { current_cmd_line.resize(current_cmd_line.size() - 1); // Lose the trailing '\0'. std::replace(current_cmd_line.begin(), current_cmd_line.end(), '\0', ' '); os << "Cmdline: " << current_cmd_line; const char* stashed_cmd_line = GetCmdLine(); if (stashed_cmd_line != NULL && current_cmd_line != stashed_cmd_line) { os << "Original command line: " << stashed_cmd_line; } } os << "\n"; #else os << "Cmdline: " << GetCmdLine() << "\n"; #endif } SignalCatcher::SignalCatcher(const std::string& stack_trace_file) : stack_trace_file_(stack_trace_file), lock_("SignalCatcher lock"), cond_("SignalCatcher::cond_", lock_), thread_(NULL) { SetHaltFlag(false); // Create a raw pthread; its start routine will attach to the runtime. CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Run, this), "signal catcher thread"); Thread* self = Thread::Current(); MutexLock mu(self, lock_); while (thread_ == NULL) { cond_.Wait(self); } } SignalCatcher::~SignalCatcher() { // Since we know the thread is just sitting around waiting for signals // to arrive, send it one. SetHaltFlag(true); CHECK_PTHREAD_CALL(pthread_kill, (pthread_, SIGQUIT), "signal catcher shutdown"); CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "signal catcher shutdown"); } void SignalCatcher::SetHaltFlag(bool new_value) { MutexLock mu(Thread::Current(), lock_); halt_ = new_value; } bool SignalCatcher::ShouldHalt() { MutexLock mu(Thread::Current(), lock_); return halt_; } void SignalCatcher::Output(const std::string& s) { if (stack_trace_file_.empty()) { LOG(INFO) << s; return; } ScopedThreadStateChange tsc(Thread::Current(), kWaitingForSignalCatcherOutput); int fd = open(stack_trace_file_.c_str(), O_APPEND | O_CREAT | O_WRONLY, 0666); if (fd == -1) { PLOG(ERROR) << "Unable to open stack trace file '" << stack_trace_file_ << "'"; return; } UniquePtr<File> file(new File(fd, stack_trace_file_)); if (!file->WriteFully(s.data(), s.size())) { PLOG(ERROR) << "Failed to write stack traces to '" << stack_trace_file_ << "'"; } else { LOG(INFO) << "Wrote stack traces to '" << stack_trace_file_ << "'"; } } void SignalCatcher::HandleSigQuit() { Runtime* runtime = Runtime::Current(); ThreadList* thread_list = runtime->GetThreadList(); // Grab exclusively the mutator lock, set state to Runnable without checking for a pending // suspend request as we're going to suspend soon anyway. We set the state to Runnable to avoid // giving away the mutator lock. thread_list->SuspendAll(); Thread* self = Thread::Current(); Locks::mutator_lock_->AssertExclusiveHeld(self); const char* old_cause = self->StartAssertNoThreadSuspension("Handling SIGQUIT"); ThreadState old_state = self->SetStateUnsafe(kRunnable); std::ostringstream os; os << "\n" << "----- pid " << getpid() << " at " << GetIsoDate() << " -----\n"; DumpCmdLine(os); os << "Build type: " << (kIsDebugBuild ? "debug" : "optimized") << "\n"; runtime->DumpForSigQuit(os); if (false) { std::string maps; if (ReadFileToString("/proc/self/maps", &maps)) { os << "/proc/self/maps:\n" << maps; } } os << "----- end " << getpid() << " -----\n"; CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable); if (self->ReadFlag(kCheckpointRequest)) { self->RunCheckpointFunction(); } self->EndAssertNoThreadSuspension(old_cause); thread_list->ResumeAll(); Output(os.str()); } void SignalCatcher::HandleSigUsr1() { LOG(INFO) << "SIGUSR1 forcing GC (no HPROF)"; Runtime::Current()->GetHeap()->CollectGarbage(false); } int SignalCatcher::WaitForSignal(Thread* self, SignalSet& signals) { ScopedThreadStateChange tsc(self, kWaitingInMainSignalCatcherLoop); // Signals for sigwait() must be blocked but not ignored. We // block signals like SIGQUIT for all threads, so the condition // is met. When the signal hits, we wake up, without any signal // handlers being invoked. int signal_number = signals.Wait(); if (!ShouldHalt()) { // Let the user know we got the signal, just in case the system's too screwed for us to // actually do what they want us to do... LOG(INFO) << *self << ": reacting to signal " << signal_number; // If anyone's holding locks (which might prevent us from getting back into state Runnable), say so... Runtime::Current()->DumpLockHolders(LOG(INFO)); } return signal_number; } void* SignalCatcher::Run(void* arg) { SignalCatcher* signal_catcher = reinterpret_cast<SignalCatcher*>(arg); CHECK(signal_catcher != NULL); Runtime* runtime = Runtime::Current(); CHECK(runtime->AttachCurrentThread("Signal Catcher", true, runtime->GetSystemThreadGroup(), !runtime->IsCompiler())); Thread* self = Thread::Current(); DCHECK_NE(self->GetState(), kRunnable); { MutexLock mu(self, signal_catcher->lock_); signal_catcher->thread_ = self; signal_catcher->cond_.Broadcast(self); } // Set up mask with signals we want to handle. SignalSet signals; signals.Add(SIGQUIT); signals.Add(SIGUSR1); while (true) { int signal_number = signal_catcher->WaitForSignal(self, signals); if (signal_catcher->ShouldHalt()) { runtime->DetachCurrentThread(); return NULL; } switch (signal_number) { case SIGQUIT: signal_catcher->HandleSigQuit(); break; case SIGUSR1: signal_catcher->HandleSigUsr1(); break; default: LOG(ERROR) << "Unexpected signal %d" << signal_number; break; } } } } // namespace art <commit_msg>am dd13413c: Merge "Run checkpoints after resuming threads in signal catcher SIGQUIT."<commit_after>/* * Copyright (C) 2008 The Android Open Source Project * * 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 "signal_catcher.h" #include <fcntl.h> #include <pthread.h> #include <signal.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include "base/unix_file/fd_file.h" #include "class_linker.h" #include "gc/heap.h" #include "os.h" #include "runtime.h" #include "scoped_thread_state_change.h" #include "signal_set.h" #include "thread.h" #include "thread_list.h" #include "utils.h" namespace art { static void DumpCmdLine(std::ostream& os) { #if defined(__linux__) // Show the original command line, and the current command line too if it's changed. // On Android, /proc/self/cmdline will have been rewritten to something like "system_server". std::string current_cmd_line; if (ReadFileToString("/proc/self/cmdline", &current_cmd_line)) { current_cmd_line.resize(current_cmd_line.size() - 1); // Lose the trailing '\0'. std::replace(current_cmd_line.begin(), current_cmd_line.end(), '\0', ' '); os << "Cmdline: " << current_cmd_line; const char* stashed_cmd_line = GetCmdLine(); if (stashed_cmd_line != NULL && current_cmd_line != stashed_cmd_line) { os << "Original command line: " << stashed_cmd_line; } } os << "\n"; #else os << "Cmdline: " << GetCmdLine() << "\n"; #endif } SignalCatcher::SignalCatcher(const std::string& stack_trace_file) : stack_trace_file_(stack_trace_file), lock_("SignalCatcher lock"), cond_("SignalCatcher::cond_", lock_), thread_(NULL) { SetHaltFlag(false); // Create a raw pthread; its start routine will attach to the runtime. CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Run, this), "signal catcher thread"); Thread* self = Thread::Current(); MutexLock mu(self, lock_); while (thread_ == NULL) { cond_.Wait(self); } } SignalCatcher::~SignalCatcher() { // Since we know the thread is just sitting around waiting for signals // to arrive, send it one. SetHaltFlag(true); CHECK_PTHREAD_CALL(pthread_kill, (pthread_, SIGQUIT), "signal catcher shutdown"); CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "signal catcher shutdown"); } void SignalCatcher::SetHaltFlag(bool new_value) { MutexLock mu(Thread::Current(), lock_); halt_ = new_value; } bool SignalCatcher::ShouldHalt() { MutexLock mu(Thread::Current(), lock_); return halt_; } void SignalCatcher::Output(const std::string& s) { if (stack_trace_file_.empty()) { LOG(INFO) << s; return; } ScopedThreadStateChange tsc(Thread::Current(), kWaitingForSignalCatcherOutput); int fd = open(stack_trace_file_.c_str(), O_APPEND | O_CREAT | O_WRONLY, 0666); if (fd == -1) { PLOG(ERROR) << "Unable to open stack trace file '" << stack_trace_file_ << "'"; return; } UniquePtr<File> file(new File(fd, stack_trace_file_)); if (!file->WriteFully(s.data(), s.size())) { PLOG(ERROR) << "Failed to write stack traces to '" << stack_trace_file_ << "'"; } else { LOG(INFO) << "Wrote stack traces to '" << stack_trace_file_ << "'"; } } void SignalCatcher::HandleSigQuit() { Runtime* runtime = Runtime::Current(); ThreadList* thread_list = runtime->GetThreadList(); // Grab exclusively the mutator lock, set state to Runnable without checking for a pending // suspend request as we're going to suspend soon anyway. We set the state to Runnable to avoid // giving away the mutator lock. thread_list->SuspendAll(); Thread* self = Thread::Current(); Locks::mutator_lock_->AssertExclusiveHeld(self); const char* old_cause = self->StartAssertNoThreadSuspension("Handling SIGQUIT"); ThreadState old_state = self->SetStateUnsafe(kRunnable); std::ostringstream os; os << "\n" << "----- pid " << getpid() << " at " << GetIsoDate() << " -----\n"; DumpCmdLine(os); os << "Build type: " << (kIsDebugBuild ? "debug" : "optimized") << "\n"; runtime->DumpForSigQuit(os); if (false) { std::string maps; if (ReadFileToString("/proc/self/maps", &maps)) { os << "/proc/self/maps:\n" << maps; } } os << "----- end " << getpid() << " -----\n"; CHECK_EQ(self->SetStateUnsafe(old_state), kRunnable); self->EndAssertNoThreadSuspension(old_cause); thread_list->ResumeAll(); // Run the checkpoints after resuming the threads to prevent deadlocks if the checkpoint function // acquires the mutator lock. if (self->ReadFlag(kCheckpointRequest)) { self->RunCheckpointFunction(); } Output(os.str()); } void SignalCatcher::HandleSigUsr1() { LOG(INFO) << "SIGUSR1 forcing GC (no HPROF)"; Runtime::Current()->GetHeap()->CollectGarbage(false); } int SignalCatcher::WaitForSignal(Thread* self, SignalSet& signals) { ScopedThreadStateChange tsc(self, kWaitingInMainSignalCatcherLoop); // Signals for sigwait() must be blocked but not ignored. We // block signals like SIGQUIT for all threads, so the condition // is met. When the signal hits, we wake up, without any signal // handlers being invoked. int signal_number = signals.Wait(); if (!ShouldHalt()) { // Let the user know we got the signal, just in case the system's too screwed for us to // actually do what they want us to do... LOG(INFO) << *self << ": reacting to signal " << signal_number; // If anyone's holding locks (which might prevent us from getting back into state Runnable), say so... Runtime::Current()->DumpLockHolders(LOG(INFO)); } return signal_number; } void* SignalCatcher::Run(void* arg) { SignalCatcher* signal_catcher = reinterpret_cast<SignalCatcher*>(arg); CHECK(signal_catcher != NULL); Runtime* runtime = Runtime::Current(); CHECK(runtime->AttachCurrentThread("Signal Catcher", true, runtime->GetSystemThreadGroup(), !runtime->IsCompiler())); Thread* self = Thread::Current(); DCHECK_NE(self->GetState(), kRunnable); { MutexLock mu(self, signal_catcher->lock_); signal_catcher->thread_ = self; signal_catcher->cond_.Broadcast(self); } // Set up mask with signals we want to handle. SignalSet signals; signals.Add(SIGQUIT); signals.Add(SIGUSR1); while (true) { int signal_number = signal_catcher->WaitForSignal(self, signals); if (signal_catcher->ShouldHalt()) { runtime->DetachCurrentThread(); return NULL; } switch (signal_number) { case SIGQUIT: signal_catcher->HandleSigQuit(); break; case SIGUSR1: signal_catcher->HandleSigUsr1(); break; default: LOG(ERROR) << "Unexpected signal %d" << signal_number; break; } } } } // namespace art <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "DT2Transient.h" #include "Problem.h" //libMesh includes #include "implicit_system.h" #include "nonlinear_implicit_system.h" #include "nonlinear_solver.h" #include "transient_system.h" #include "numeric_vector.h" // C++ Includes #include <iomanip> template<> InputParameters validParams<DT2Transient>() { InputParameters params = validParams<Transient>(); params.addRequiredParam<Real>("e_tol","Target error tolerance."); params.addRequiredParam<Real>("e_max","Maximum acceptable error."); params.addParam<Real>("max_increase", 1.0e9, "Maximum ratio that the time step can increase."); return params; } DT2Transient::DT2Transient(const std::string & name, InputParameters parameters) : Transient(name, parameters), _u_diff(NULL), _u1(NULL), _u2(NULL), _u_saved(NULL), _u_older_saved(NULL), _aux1(NULL), _aux_saved(NULL), _aux_older_saved(NULL), _e_tol(getParam<Real>("e_tol")), _e_max(getParam<Real>("e_max")), _max_increase(getParam<Real>("max_increase")) { } DT2Transient::~DT2Transient() { } void DT2Transient::preExecute() { TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys(); _u1 = &nl_sys.add_vector("u1", true, GHOSTED); _u2 = &nl_sys.add_vector("u2", false, GHOSTED); _u_diff = &nl_sys.add_vector("u_diff", false, GHOSTED); _u_saved = &nl_sys.add_vector("u_saved", false, GHOSTED); _u_older_saved = &nl_sys.add_vector("u_older_saved", false, GHOSTED); TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys(); _aux1 = &aux_sys.add_vector("aux1", true, GHOSTED); _aux_saved = &aux_sys.add_vector("aux_saved", false, GHOSTED); _aux_older_saved = &aux_sys.add_vector("aux_older_saved", false, GHOSTED); Transient::preExecute(); } void DT2Transient::preSolve() { /*NonlinearSystem & nl =*/ _problem.getNonlinearSystem(); // returned reference is not used for anything? TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys(); TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys(); // save solution vectors *_u_saved = *nl_sys.current_local_solution; *_u_older_saved = *nl_sys.older_local_solution; *_aux_saved = *aux_sys.solution; *_aux_older_saved = *aux_sys.older_local_solution; _u_saved->close(); _u_older_saved->close(); _aux_saved->close(); _aux_older_saved->close(); // save dt _dt_full = _dt; } void DT2Transient::postSolve() { /*NonlinearSystem & nl =*/ _problem.getNonlinearSystem(); // returned reference is not used for anything? TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys(); TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys(); if (_converged) { // save the solution (for time step with dt) *_u1 = *nl_sys.current_local_solution; _u1->close(); *_aux1 = *aux_sys.current_local_solution; _aux1->close(); // take two steps with dt/2 std::cout << "Taking two dt/2 time steps" << std::endl; // go back in time *nl_sys.current_local_solution = *_u_saved; *aux_sys.current_local_solution = *_aux_saved; nl_sys.current_local_solution->close(); aux_sys.current_local_solution->close(); _time -= _dt_full; _problem.computePostprocessors(); // cut the time step in half _dt = _dt_full / 2; // 1. step _problem.onTimestepBegin(); _time += _dt; std::cout << " - 1. step" << std::endl; Moose::setSolverDefaults(_problem); nl_sys.solve(); _converged = nl_sys.nonlinear_solver->converged; if (!_converged) return; nl_sys.update(); _problem.copyOldSolutions(); _problem.computePostprocessors(); // 2. step _problem.onTimestepBegin(); _time += _dt; std::cout << " - 2. step" << std::endl; Moose::setSolverDefaults(_problem); nl_sys.solve(); _converged = nl_sys.nonlinear_solver->converged; if (!_converged) return; nl_sys.update(); *_u2 = *nl_sys.current_local_solution; _u2->close(); // compute error *_u_diff = *_u2; *_u_diff -= *_u1; _u_diff->close(); _error = (_u_diff->l2_norm() / std::max(_u1->l2_norm(), _u2->l2_norm())) / _dt_full; _dt = _dt_full; Transient::postSolve(); } } bool DT2Transient::lastSolveConverged() { if (!_converged) return false; if (_error < _e_max) return true; else { std::cout << "DT2Transient: Marking last solve not converged since |U2-U1|/max(|U2|,|U1|) >= e_max." << std::endl; return false; } } Real DT2Transient::computeDT() { if(_t_step < 2) return Transient::computeDT(); TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys(); TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys(); if(lastSolveConverged()) { Real new_dt = _dt_full * std::pow(_e_tol / _error, 1.0 / _problem.getNonlinearSystem().getTimeSteppingOrder()); if (new_dt/_dt_full > _max_increase) _dt = _dt_full*_max_increase; else _dt = new_dt; *nl_sys.current_local_solution= *_u1; *nl_sys.old_local_solution = *_u1; *nl_sys.older_local_solution = *_u_saved; *aux_sys.current_local_solution = *_aux1; *aux_sys.old_local_solution = *_aux1; *aux_sys.older_local_solution = *_aux_saved; nl_sys.current_local_solution->close(); nl_sys.old_local_solution->close(); nl_sys.older_local_solution->close(); aux_sys.current_local_solution->close(); aux_sys.old_local_solution->close(); aux_sys.older_local_solution->close(); } else { // reject the step _time -= _dt; // recover initial state *nl_sys.current_local_solution = *_u_saved; *nl_sys.old_local_solution = *_u_saved; *nl_sys.older_local_solution = *_u_older_saved; *aux_sys.current_local_solution = *_aux_saved; *aux_sys.old_local_solution = *_aux_saved; *aux_sys.older_local_solution = *_aux_older_saved; nl_sys.solution->close(); nl_sys.old_local_solution->close(); nl_sys.older_local_solution->close(); aux_sys.solution->close(); aux_sys.old_local_solution->close(); aux_sys.older_local_solution->close(); } return Transient::computeDT(); } <commit_msg>Fixing a bug in DT2Transient (closes #802) (author: Yaqi Wang)<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "DT2Transient.h" #include "Problem.h" //libMesh includes #include "implicit_system.h" #include "nonlinear_implicit_system.h" #include "nonlinear_solver.h" #include "transient_system.h" #include "numeric_vector.h" // C++ Includes #include <iomanip> template<> InputParameters validParams<DT2Transient>() { InputParameters params = validParams<Transient>(); params.addRequiredParam<Real>("e_tol","Target error tolerance."); params.addRequiredParam<Real>("e_max","Maximum acceptable error."); params.addParam<Real>("max_increase", 1.0e9, "Maximum ratio that the time step can increase."); return params; } DT2Transient::DT2Transient(const std::string & name, InputParameters parameters) : Transient(name, parameters), _u_diff(NULL), _u1(NULL), _u2(NULL), _u_saved(NULL), _u_older_saved(NULL), _aux1(NULL), _aux_saved(NULL), _aux_older_saved(NULL), _e_tol(getParam<Real>("e_tol")), _e_max(getParam<Real>("e_max")), _max_increase(getParam<Real>("max_increase")) { } DT2Transient::~DT2Transient() { } void DT2Transient::preExecute() { TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys(); _u1 = &nl_sys.add_vector("u1", true, GHOSTED); _u2 = &nl_sys.add_vector("u2", false, GHOSTED); _u_diff = &nl_sys.add_vector("u_diff", false, GHOSTED); _u_saved = &nl_sys.add_vector("u_saved", false, GHOSTED); _u_older_saved = &nl_sys.add_vector("u_older_saved", false, GHOSTED); TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys(); _aux1 = &aux_sys.add_vector("aux1", true, GHOSTED); _aux_saved = &aux_sys.add_vector("aux_saved", false, GHOSTED); _aux_older_saved = &aux_sys.add_vector("aux_older_saved", false, GHOSTED); Transient::preExecute(); } void DT2Transient::preSolve() { /*NonlinearSystem & nl =*/ _problem.getNonlinearSystem(); // returned reference is not used for anything? TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys(); TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys(); // save solution vectors *_u_saved = *nl_sys.current_local_solution; *_u_older_saved = *nl_sys.older_local_solution; *_aux_saved = *aux_sys.current_local_solution; *_aux_older_saved = *aux_sys.older_local_solution; _u_saved->close(); _u_older_saved->close(); _aux_saved->close(); _aux_older_saved->close(); // save dt _dt_full = _dt; } void DT2Transient::postSolve() { /*NonlinearSystem & nl =*/ _problem.getNonlinearSystem(); // returned reference is not used for anything? TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys(); TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys(); if (_converged) { // save the solution (for time step with dt) *_u1 = *nl_sys.current_local_solution; _u1->close(); *_aux1 = *aux_sys.current_local_solution; _aux1->close(); // take two steps with dt/2 std::cout << "Taking two dt/2 time steps" << std::endl; // go back in time *nl_sys.current_local_solution = *_u_saved; *aux_sys.current_local_solution = *_aux_saved; nl_sys.current_local_solution->close(); aux_sys.current_local_solution->close(); _time -= _dt_full; _problem.computePostprocessors(); // cut the time step in half _dt = _dt_full / 2; // 1. step _problem.onTimestepBegin(); _time += _dt; std::cout << " - 1. step" << std::endl; Moose::setSolverDefaults(_problem); nl_sys.solve(); _converged = nl_sys.nonlinear_solver->converged; if (!_converged) return; nl_sys.update(); _problem.copyOldSolutions(); _problem.computePostprocessors(); // 2. step _problem.onTimestepBegin(); _time += _dt; std::cout << " - 2. step" << std::endl; Moose::setSolverDefaults(_problem); nl_sys.solve(); _converged = nl_sys.nonlinear_solver->converged; if (!_converged) return; nl_sys.update(); *_u2 = *nl_sys.current_local_solution; _u2->close(); // compute error *_u_diff = *_u2; *_u_diff -= *_u1; _u_diff->close(); _error = (_u_diff->l2_norm() / std::max(_u1->l2_norm(), _u2->l2_norm())) / _dt_full; _dt = _dt_full; Transient::postSolve(); } } bool DT2Transient::lastSolveConverged() { if (!_converged) return false; if (_error < _e_max) return true; else { std::cout << "DT2Transient: Marking last solve not converged since |U2-U1|/max(|U2|,|U1|) = " << _error << " >= e_max." << std::endl; return false; } } Real DT2Transient::computeDT() { if(_t_step < 2) return Transient::computeDT(); TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys(); TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys(); if(lastSolveConverged()) { Real new_dt = _dt_full * std::pow(_e_tol / _error, 1.0 / _problem.getNonlinearSystem().getTimeSteppingOrder()); if (new_dt/_dt_full > _max_increase) _dt = _dt_full*_max_increase; else _dt = new_dt; *nl_sys.current_local_solution= *_u1; *nl_sys.old_local_solution = *_u1; *nl_sys.older_local_solution = *_u_saved; *aux_sys.current_local_solution = *_aux1; *aux_sys.old_local_solution = *_aux1; *aux_sys.older_local_solution = *_aux_saved; nl_sys.current_local_solution->close(); nl_sys.old_local_solution->close(); nl_sys.older_local_solution->close(); aux_sys.current_local_solution->close(); aux_sys.old_local_solution->close(); aux_sys.older_local_solution->close(); } else { // reject the step _time -= _dt; // recover initial state *nl_sys.current_local_solution = *_u_saved; *nl_sys.old_local_solution = *_u_saved; *nl_sys.older_local_solution = *_u_older_saved; *aux_sys.current_local_solution = *_aux_saved; *aux_sys.old_local_solution = *_aux_saved; *aux_sys.older_local_solution = *_aux_older_saved; nl_sys.solution->close(); nl_sys.old_local_solution->close(); nl_sys.older_local_solution->close(); aux_sys.solution->close(); aux_sys.old_local_solution->close(); aux_sys.older_local_solution->close(); } return Transient::computeDT(); } <|endoftext|>
<commit_before><commit_msg>Ironingy typo<commit_after><|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "cxcoretest.h" using namespace cv; class CV_RandTest : public CvTest { public: CV_RandTest(); protected: void run(int); bool check_pdf(const Mat& hist, double scale, int dist_type, double& refval, double& realval); }; CV_RandTest::CV_RandTest(): CvTest( "rand", "cvRandArr, cvRNG" ) { support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; } static double chi2_p95(int n) { static float chi2_tab95[] = { 3.841f, 5.991f, 7.815f, 9.488f, 11.07f, 12.59f, 14.07f, 15.51f, 16.92f, 18.31f, 19.68f, 21.03f, 21.03f, 22.36f, 23.69f, 25.00f, 26.30f, 27.59f, 28.87f, 30.14f, 31.41f, 32.67f, 33.92f, 35.17f, 36.42f, 37.65f, 38.89f, 40.11f, 41.34f, 42.56f, 43.77f }; static const double xp = 1.64; CV_Assert(n >= 1); if( n <= 30 ) return chi2_tab95[n-1]; return n + sqrt((double)2*n)*xp + 0.6666666666666*(xp*xp - 1); } bool CV_RandTest::check_pdf(const Mat& hist, double scale, int dist_type, double& refval, double& realval) { Mat hist0(hist.size(), CV_32F); const int* H = (const int*)hist.data; float* H0 = ((float*)hist0.data); int i, hsz = hist.cols; double sum = 0; for( i = 0; i < hsz; i++ ) sum += H[i]; CV_Assert( fabs(1./sum - scale) < FLT_EPSILON ); if( dist_type == CV_RAND_UNI ) { float scale0 = (float)(1./hsz); for( i = 0; i < hsz; i++ ) H0[i] = scale0; } else { double sum = 0, r = (hsz-1.)/2; double alpha = 2*sqrt(2.)/r, beta = -alpha*r; for( i = 0; i < hsz; i++ ) { double x = i*alpha + beta; H0[i] = (float)exp(-x*x); sum += H0[i]; } sum = 1./sum; for( i = 0; i < hsz; i++ ) H0[i] = (float)(H0[i]*sum); } double chi2 = 0; for( i = 0; i < hsz; i++ ) { double a = H0[i]; double b = H[i]*scale; if( a > DBL_EPSILON ) chi2 += (a - b)*(a - b)/(a + b); } realval = chi2; double chi2_pval = chi2_p95(hsz - 1 - (dist_type == CV_RAND_NORMAL ? 2 : 0)); refval = chi2_pval*0.01; return realval <= refval; } void CV_RandTest::run( int ) { static int _ranges[][2] = {{ 0, 256 }, { -128, 128 }, { 0, 65536 }, { -32768, 32768 }, { -1000000, 1000000 }, { -1000, 1000 }, { -1000, 1000 }}; const int MAX_SDIM = 10; const int N = 1200000; const int maxSlice = 1000; const int MAX_HIST_SIZE = 1000; int progress = 0; CvRNG* rng = ts->get_rng(); RNG tested_rng = theRNG(); test_case_count = 200; for( int idx = 0; idx < test_case_count; idx++ ) { progress = update_progress( progress, idx, test_case_count, 0 ); ts->update_context( this, idx, false ); int depth = cvTsRandInt(rng) % (CV_64F+1); int c, cn = (cvTsRandInt(rng) % 4) + 1; int type = CV_MAKETYPE(depth, cn); int dist_type = cvTsRandInt(rng) % (CV_RAND_NORMAL+1); int i, k, SZ = N/cn; Scalar A, B; bool do_sphere_test = dist_type == CV_RAND_UNI; Mat arr[2], hist[4]; int W[] = {0,0,0,0}; arr[0].create(1, SZ, type); arr[1].create(1, SZ, type); bool fast_algo = dist_type == CV_RAND_UNI && depth < CV_32F; for( c = 0; c < cn; c++ ) { int a, b, hsz; if( dist_type == CV_RAND_UNI ) { a = (int)(cvTsRandInt(rng) % (_ranges[depth][1] - _ranges[depth][0])) + _ranges[depth][0]; do { b = (int)(cvTsRandInt(rng) % (_ranges[depth][1] - _ranges[depth][0])) + _ranges[depth][0]; } while( abs(a-b) <= 1 ); if( a > b ) std::swap(a, b); unsigned r = (unsigned)(b - a); fast_algo = fast_algo && r <= 256 && (r & (r-1)) == 0; hsz = min((unsigned)(b - a), (unsigned)MAX_HIST_SIZE); do_sphere_test = do_sphere_test && b - a >= 100; } else { int vrange = _ranges[depth][1] - _ranges[depth][0]; int meanrange = vrange/16; int mindiv = MAX(vrange/20, 5); int maxdiv = MIN(vrange/8, 10000); a = cvTsRandInt(rng) % meanrange - meanrange/2 + (_ranges[depth][0] + _ranges[depth][1])/2; b = cvTsRandInt(rng) % (maxdiv - mindiv) + mindiv; hsz = min((unsigned)b*9, (unsigned)MAX_HIST_SIZE); } A[c] = a; B[c] = b; hist[c].create(1, hsz, CV_32S); } cv::RNG saved_rng = tested_rng; int maxk = fast_algo ? 0 : 1; for( k = 0; k <= maxk; k++ ) { tested_rng = saved_rng; int sz = 0, dsz = 0, slice; for( slice = 0; slice < maxSlice; slice++, sz += dsz ) { dsz = slice+1 < maxSlice ? cvTsRandInt(rng) % (SZ - sz + 1) : SZ - sz; Mat aslice = arr[k].colRange(sz, sz + dsz); tested_rng.fill(aslice, dist_type, A, B); } } if( maxk >= 1 && norm(arr[0], arr[1], NORM_INF) != 0 ) { ts->printf( CvTS::LOG, "RNG output depends on the array lengths (some generated numbers get lost?)" ); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } for( c = 0; c < cn; c++ ) { const uchar* data = arr[0].data; int* H = hist[c].ptr<int>(); int HSZ = hist[c].cols; double minVal = dist_type == CV_RAND_UNI ? A[c] : A[c] - B[c]*4; double maxVal = dist_type == CV_RAND_UNI ? B[c] : A[c] + B[c]*4; double scale = HSZ/(maxVal - minVal); double delta = -minVal*scale; hist[c] = Scalar::all(0); for( i = c; i < SZ*cn; i += cn ) { double val = depth == CV_8U ? ((const uchar*)data)[i] : depth == CV_8S ? ((const schar*)data)[i] : depth == CV_16U ? ((const ushort*)data)[i] : depth == CV_16S ? ((const short*)data)[i] : depth == CV_32S ? ((const int*)data)[i] : depth == CV_32F ? ((const float*)data)[i] : ((const double*)data)[i]; int ival = cvFloor(val*scale + delta); if( (unsigned)ival < (unsigned)HSZ ) { H[ival]++; W[c]++; } else if( dist_type == CV_RAND_UNI ) { if( (minVal <= val && val < maxVal) || (depth >= CV_32F && val == maxVal) ) { H[ival < 0 ? 0 : HSZ-1]++; W[c]++; } else { putchar('^'); } } } if( dist_type == CV_RAND_UNI && W[c] != SZ ) { ts->printf( CvTS::LOG, "Uniform RNG gave values out of the range [%g,%g) on channel %d/%d\n", A[c], B[c], c, cn); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } if( dist_type == CV_RAND_NORMAL && W[c] < SZ*.90) { ts->printf( CvTS::LOG, "Normal RNG gave too many values out of the range (%g+4*%g,%g+4*%g) on channel %d/%d\n", A[c], B[c], A[c], B[c], c, cn); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } double refval = 0, realval = 0; if( !check_pdf(hist[c], 1./W[c], dist_type, refval, realval) ) { ts->printf( CvTS::LOG, "RNG failed Chi-square test " "(got %g vs probable maximum %g) on channel %d/%d\n", realval, refval, c, cn); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } } // Monte-Carlo test. Compute volume of SDIM-dimensional sphere // inscribed in [-1,1]^SDIM cube. if( do_sphere_test ) { int SDIM = cvTsRandInt(rng) % (MAX_SDIM-1) + 2; int N0 = (SZ*cn/SDIM), N = 0; double r2 = 0; const uchar* data = arr[0].data; double scale[4], delta[4]; for( c = 0; c < cn; c++ ) { scale[c] = 2./(B[c] - A[c]); delta[c] = -A[c]*scale[c] - 1; } for( i = k = c = 0; i <= SZ*cn - SDIM; i++, k++, c++ ) { double val = depth == CV_8U ? ((const uchar*)data)[i] : depth == CV_8S ? ((const schar*)data)[i] : depth == CV_16U ? ((const ushort*)data)[i] : depth == CV_16S ? ((const short*)data)[i] : depth == CV_32S ? ((const int*)data)[i] : depth == CV_32F ? ((const float*)data)[i] : ((const double*)data)[i]; c &= c < cn ? -1 : 0; val = val*scale[c] + delta[c]; r2 += val*val; if( k == SDIM-1 ) { N += r2 <= 1; r2 = 0; k = -1; } } double V = ((double)N/N0)*(1 << SDIM); // the theoretically computed volume int sdim = SDIM % 2; double V0 = sdim + 1; for( sdim += 2; sdim <= SDIM; sdim += 2 ) V0 *= 2*CV_PI/sdim; if( fabs(V - V0) > 0.2*fabs(V0) ) { ts->printf( CvTS::LOG, "RNG failed %d-dim sphere volume test (got %g instead of %g)\n", SDIM, V, V0); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } } } } CV_RandTest rand_test; <commit_msg>Commented out rand test due to failure on win32<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "cxcoretest.h" using namespace cv; class CV_RandTest : public CvTest { public: CV_RandTest(); protected: void run(int); bool check_pdf(const Mat& hist, double scale, int dist_type, double& refval, double& realval); }; CV_RandTest::CV_RandTest(): CvTest( "rand", "cvRandArr, cvRNG" ) { support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; } static double chi2_p95(int n) { static float chi2_tab95[] = { 3.841f, 5.991f, 7.815f, 9.488f, 11.07f, 12.59f, 14.07f, 15.51f, 16.92f, 18.31f, 19.68f, 21.03f, 21.03f, 22.36f, 23.69f, 25.00f, 26.30f, 27.59f, 28.87f, 30.14f, 31.41f, 32.67f, 33.92f, 35.17f, 36.42f, 37.65f, 38.89f, 40.11f, 41.34f, 42.56f, 43.77f }; static const double xp = 1.64; CV_Assert(n >= 1); if( n <= 30 ) return chi2_tab95[n-1]; return n + sqrt((double)2*n)*xp + 0.6666666666666*(xp*xp - 1); } bool CV_RandTest::check_pdf(const Mat& hist, double scale, int dist_type, double& refval, double& realval) { Mat hist0(hist.size(), CV_32F); const int* H = (const int*)hist.data; float* H0 = ((float*)hist0.data); int i, hsz = hist.cols; double sum = 0; for( i = 0; i < hsz; i++ ) sum += H[i]; CV_Assert( fabs(1./sum - scale) < FLT_EPSILON ); if( dist_type == CV_RAND_UNI ) { float scale0 = (float)(1./hsz); for( i = 0; i < hsz; i++ ) H0[i] = scale0; } else { double sum = 0, r = (hsz-1.)/2; double alpha = 2*sqrt(2.)/r, beta = -alpha*r; for( i = 0; i < hsz; i++ ) { double x = i*alpha + beta; H0[i] = (float)exp(-x*x); sum += H0[i]; } sum = 1./sum; for( i = 0; i < hsz; i++ ) H0[i] = (float)(H0[i]*sum); } double chi2 = 0; for( i = 0; i < hsz; i++ ) { double a = H0[i]; double b = H[i]*scale; if( a > DBL_EPSILON ) chi2 += (a - b)*(a - b)/(a + b); } realval = chi2; double chi2_pval = chi2_p95(hsz - 1 - (dist_type == CV_RAND_NORMAL ? 2 : 0)); refval = chi2_pval*0.01; return realval <= refval; } void CV_RandTest::run( int ) { static int _ranges[][2] = {{ 0, 256 }, { -128, 128 }, { 0, 65536 }, { -32768, 32768 }, { -1000000, 1000000 }, { -1000, 1000 }, { -1000, 1000 }}; const int MAX_SDIM = 10; const int N = 1200000; const int maxSlice = 1000; const int MAX_HIST_SIZE = 1000; int progress = 0; CvRNG* rng = ts->get_rng(); RNG tested_rng = theRNG(); test_case_count = 200; for( int idx = 0; idx < test_case_count; idx++ ) { progress = update_progress( progress, idx, test_case_count, 0 ); ts->update_context( this, idx, false ); int depth = cvTsRandInt(rng) % (CV_64F+1); int c, cn = (cvTsRandInt(rng) % 4) + 1; int type = CV_MAKETYPE(depth, cn); int dist_type = cvTsRandInt(rng) % (CV_RAND_NORMAL+1); int i, k, SZ = N/cn; Scalar A, B; bool do_sphere_test = dist_type == CV_RAND_UNI; Mat arr[2], hist[4]; int W[] = {0,0,0,0}; arr[0].create(1, SZ, type); arr[1].create(1, SZ, type); bool fast_algo = dist_type == CV_RAND_UNI && depth < CV_32F; for( c = 0; c < cn; c++ ) { int a, b, hsz; if( dist_type == CV_RAND_UNI ) { a = (int)(cvTsRandInt(rng) % (_ranges[depth][1] - _ranges[depth][0])) + _ranges[depth][0]; do { b = (int)(cvTsRandInt(rng) % (_ranges[depth][1] - _ranges[depth][0])) + _ranges[depth][0]; } while( abs(a-b) <= 1 ); if( a > b ) std::swap(a, b); unsigned r = (unsigned)(b - a); fast_algo = fast_algo && r <= 256 && (r & (r-1)) == 0; hsz = min((unsigned)(b - a), (unsigned)MAX_HIST_SIZE); do_sphere_test = do_sphere_test && b - a >= 100; } else { int vrange = _ranges[depth][1] - _ranges[depth][0]; int meanrange = vrange/16; int mindiv = MAX(vrange/20, 5); int maxdiv = MIN(vrange/8, 10000); a = cvTsRandInt(rng) % meanrange - meanrange/2 + (_ranges[depth][0] + _ranges[depth][1])/2; b = cvTsRandInt(rng) % (maxdiv - mindiv) + mindiv; hsz = min((unsigned)b*9, (unsigned)MAX_HIST_SIZE); } A[c] = a; B[c] = b; hist[c].create(1, hsz, CV_32S); } cv::RNG saved_rng = tested_rng; int maxk = fast_algo ? 0 : 1; for( k = 0; k <= maxk; k++ ) { tested_rng = saved_rng; int sz = 0, dsz = 0, slice; for( slice = 0; slice < maxSlice; slice++, sz += dsz ) { dsz = slice+1 < maxSlice ? cvTsRandInt(rng) % (SZ - sz + 1) : SZ - sz; Mat aslice = arr[k].colRange(sz, sz + dsz); tested_rng.fill(aslice, dist_type, A, B); } } if( maxk >= 1 && norm(arr[0], arr[1], NORM_INF) != 0 ) { ts->printf( CvTS::LOG, "RNG output depends on the array lengths (some generated numbers get lost?)" ); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } for( c = 0; c < cn; c++ ) { const uchar* data = arr[0].data; int* H = hist[c].ptr<int>(); int HSZ = hist[c].cols; double minVal = dist_type == CV_RAND_UNI ? A[c] : A[c] - B[c]*4; double maxVal = dist_type == CV_RAND_UNI ? B[c] : A[c] + B[c]*4; double scale = HSZ/(maxVal - minVal); double delta = -minVal*scale; hist[c] = Scalar::all(0); for( i = c; i < SZ*cn; i += cn ) { double val = depth == CV_8U ? ((const uchar*)data)[i] : depth == CV_8S ? ((const schar*)data)[i] : depth == CV_16U ? ((const ushort*)data)[i] : depth == CV_16S ? ((const short*)data)[i] : depth == CV_32S ? ((const int*)data)[i] : depth == CV_32F ? ((const float*)data)[i] : ((const double*)data)[i]; int ival = cvFloor(val*scale + delta); if( (unsigned)ival < (unsigned)HSZ ) { H[ival]++; W[c]++; } else if( dist_type == CV_RAND_UNI ) { if( (minVal <= val && val < maxVal) || (depth >= CV_32F && val == maxVal) ) { H[ival < 0 ? 0 : HSZ-1]++; W[c]++; } else { putchar('^'); } } } if( dist_type == CV_RAND_UNI && W[c] != SZ ) { ts->printf( CvTS::LOG, "Uniform RNG gave values out of the range [%g,%g) on channel %d/%d\n", A[c], B[c], c, cn); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } if( dist_type == CV_RAND_NORMAL && W[c] < SZ*.90) { ts->printf( CvTS::LOG, "Normal RNG gave too many values out of the range (%g+4*%g,%g+4*%g) on channel %d/%d\n", A[c], B[c], A[c], B[c], c, cn); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } double refval = 0, realval = 0; if( !check_pdf(hist[c], 1./W[c], dist_type, refval, realval) ) { ts->printf( CvTS::LOG, "RNG failed Chi-square test " "(got %g vs probable maximum %g) on channel %d/%d\n", realval, refval, c, cn); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } } // Monte-Carlo test. Compute volume of SDIM-dimensional sphere // inscribed in [-1,1]^SDIM cube. if( do_sphere_test ) { int SDIM = cvTsRandInt(rng) % (MAX_SDIM-1) + 2; int N0 = (SZ*cn/SDIM), N = 0; double r2 = 0; const uchar* data = arr[0].data; double scale[4], delta[4]; for( c = 0; c < cn; c++ ) { scale[c] = 2./(B[c] - A[c]); delta[c] = -A[c]*scale[c] - 1; } for( i = k = c = 0; i <= SZ*cn - SDIM; i++, k++, c++ ) { double val = depth == CV_8U ? ((const uchar*)data)[i] : depth == CV_8S ? ((const schar*)data)[i] : depth == CV_16U ? ((const ushort*)data)[i] : depth == CV_16S ? ((const short*)data)[i] : depth == CV_32S ? ((const int*)data)[i] : depth == CV_32F ? ((const float*)data)[i] : ((const double*)data)[i]; c &= c < cn ? -1 : 0; val = val*scale[c] + delta[c]; r2 += val*val; if( k == SDIM-1 ) { N += r2 <= 1; r2 = 0; k = -1; } } double V = ((double)N/N0)*(1 << SDIM); // the theoretically computed volume int sdim = SDIM % 2; double V0 = sdim + 1; for( sdim += 2; sdim <= SDIM; sdim += 2 ) V0 *= 2*CV_PI/sdim; if( fabs(V - V0) > 0.2*fabs(V0) ) { ts->printf( CvTS::LOG, "RNG failed %d-dim sphere volume test (got %g instead of %g)\n", SDIM, V, V0); ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); return; } } } } //CV_RandTest rand_test; <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/initfiles/p9_npu_scom.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_npu_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr auto literal_2 = 2; constexpr auto literal_3 = 3; constexpr auto literal_1 = 1; constexpr auto literal_0 = 0; constexpr auto literal_0x0 = 0x0; constexpr auto literal_0x1111111111111111 = 0x1111111111111111; constexpr auto literal_0x0000000000000000 = 0x0000000000000000; fapi2::ReturnCode p9_npu_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1) { fapi2::ReturnCode l_rc = 0; do { fapi2::buffer<uint64_t> l_scom_buffer; fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_Type l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE; l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE, TGT0, l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE); if (l_rc) { FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE)"); break; } { l_rc = fapi2::getScom( TGT0, 0x5011000ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011000ull)"); break; } { l_scom_buffer.insert<uint64_t> (((((l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_0] == literal_2) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_1] == literal_2)) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_2] == literal_2)) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_3] == literal_2)), 38, 1, 63 ); } l_rc = fapi2::putScom(TGT0, 0x5011000ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011000ull)"); break; } } fapi2::ATTR_PROC_EPS_READ_CYCLES_Type l_TGT1_ATTR_PROC_EPS_READ_CYCLES; l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_READ_CYCLES, TGT1, l_TGT1_ATTR_PROC_EPS_READ_CYCLES); if (l_rc) { FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_EPS_READ_CYCLES)"); break; } fapi2::ATTR_PROC_EPS_WRITE_CYCLES_Type l_TGT1_ATTR_PROC_EPS_WRITE_CYCLES; l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_WRITE_CYCLES, TGT1, l_TGT1_ATTR_PROC_EPS_WRITE_CYCLES); if (l_rc) { FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_EPS_WRITE_CYCLES)"); break; } { l_rc = fapi2::getScom( TGT0, 0x5011002ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011002ull)"); break; } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_READ_CYCLES[literal_0], 28, 12, 52 ); } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_READ_CYCLES[literal_1], 40, 12, 52 ); } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_READ_CYCLES[literal_2], 52, 12, 52 ); } { l_scom_buffer.insert<uint64_t> (literal_0x0, 0, 4, 60 ); } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_WRITE_CYCLES[literal_0], 4, 12, 52 ); } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_WRITE_CYCLES[literal_1], 16, 12, 52 ); } l_rc = fapi2::putScom(TGT0, 0x5011002ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011002ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011008ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011008ull)"); break; } { l_scom_buffer.insert<uint64_t> (((((l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_0] == literal_2) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_1] == literal_2)) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_2] == literal_2)) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_3] == literal_2)), 51, 1, 63 ); } l_rc = fapi2::putScom(TGT0, 0x5011008ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011008ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011403ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011403ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x1111111111111111, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011403ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011403ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011406ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011406ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011406ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011406ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011407ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011407ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011407ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011407ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011446ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011446ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011446ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011446ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011447ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011447ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011447ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011447ull)"); break; } } } while (0); return l_rc; } <commit_msg>initCompiler: display correct buffer inserts<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/initfiles/p9_npu_scom.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_npu_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr auto literal_2 = 2; constexpr auto literal_3 = 3; constexpr auto literal_1 = 1; constexpr auto literal_0 = 0; constexpr auto literal_0x0 = 0x0; constexpr auto literal_0x1111111111111111 = 0x1111111111111111; constexpr auto literal_0x0000000000000000 = 0x0000000000000000; fapi2::ReturnCode p9_npu_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1) { fapi2::ReturnCode l_rc = 0; do { fapi2::buffer<uint64_t> l_scom_buffer; fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_Type l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE; l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE, TGT0, l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE); if (l_rc) { FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE)"); break; } { l_rc = fapi2::getScom( TGT0, 0x5011000ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011000ull)"); break; } { l_scom_buffer.insert<uint64_t> (((((l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_0] == literal_2) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_1] == literal_2)) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_2] == literal_2)) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_3] == literal_2)), 38, 1, 63 ); } l_rc = fapi2::putScom(TGT0, 0x5011000ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011000ull)"); break; } } fapi2::ATTR_PROC_EPS_READ_CYCLES_Type l_TGT1_ATTR_PROC_EPS_READ_CYCLES; l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_READ_CYCLES, TGT1, l_TGT1_ATTR_PROC_EPS_READ_CYCLES); if (l_rc) { FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_EPS_READ_CYCLES)"); break; } fapi2::ATTR_PROC_EPS_WRITE_CYCLES_Type l_TGT1_ATTR_PROC_EPS_WRITE_CYCLES; l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_WRITE_CYCLES, TGT1, l_TGT1_ATTR_PROC_EPS_WRITE_CYCLES); if (l_rc) { FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_EPS_WRITE_CYCLES)"); break; } { l_rc = fapi2::getScom( TGT0, 0x5011002ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011002ull)"); break; } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_READ_CYCLES[literal_0], 28, 12, 52 ); } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_READ_CYCLES[literal_1], 40, 12, 52 ); } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_READ_CYCLES[literal_2], 52, 12, 52 ); } { l_scom_buffer.insert<uint64_t> (literal_0x0, 0, 4, 60 ); } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_WRITE_CYCLES[literal_0], 4, 12, 52 ); } { l_scom_buffer.insert<uint64_t> (l_TGT1_ATTR_PROC_EPS_WRITE_CYCLES[literal_1], 16, 12, 52 ); } l_rc = fapi2::putScom(TGT0, 0x5011002ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011002ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011008ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011008ull)"); break; } { l_scom_buffer.insert<uint64_t> (((((l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_0] == literal_2) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_1] == literal_2)) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_2] == literal_2)) || (l_TGT0_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE[literal_3] == literal_2)), 51, 1, 63 ); } l_rc = fapi2::putScom(TGT0, 0x5011008ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011008ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011403ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011403ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x1111111111111111, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011403ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011403ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011406ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011406ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011406ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011406ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011407ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011407ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011407ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011407ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011446ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011446ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011446ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011446ull)"); break; } } { l_rc = fapi2::getScom( TGT0, 0x5011447ull, l_scom_buffer ); if (l_rc) { FAPI_ERR("ERROR executing: getScom (0x5011447ull)"); break; } { l_scom_buffer.insert<uint64_t> (literal_0x0000000000000000, 0, 64, 0 ); } l_rc = fapi2::putScom(TGT0, 0x5011447ull, l_scom_buffer); if (l_rc) { FAPI_ERR("ERROR executing: putScom (0x5011447ull)"); break; } } } while (0); return l_rc; } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX64M SDC サンプル @n ・P07(176) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/cmt_io.hpp" #include "common/sci_io.hpp" #include "common/fifo.hpp" #include "common/format.hpp" #include "common/command.hpp" #include "common/rspi_io.hpp" #include "common/spi_io.hpp" #include "common/sdc_io.hpp" #include "RX64M/sdhi_io.hpp" #include "common/string_utils.hpp" // #define SDHI namespace { device::cmt_io<device::CMT0> cmt_; typedef utils::fifo<uint16_t, 256> buffer; device::sci_io<device::SCI1, buffer, buffer> sci_; utils::rtc_io rtc_; // typedef device::rspi_io<device::RSPI> RSPI; // RSPI rspi_; #ifdef SDHI typedef fatfs::sdhi_io<device::SDHI, true> SDC; #else // Soft SDC 用 SPI 定義(SPI) typedef device::PORT<device::PORTC, device::bitpos::B3> MISO; typedef device::PORT<device::PORT7, device::bitpos::B6> MOSI; typedef device::PORT<device::PORT7, device::bitpos::B7> SPCK; typedef device::spi_io<MISO, MOSI, SPCK, device::soft_spi_mode::CK10> SPI; SPI spi_; typedef device::PORT<device::PORTC, device::bitpos::B2> sdc_select; ///< カード選択信号 typedef device::PORT<device::PORT8, device::bitpos::B2> sdc_power; ///< カード電源制御 typedef device::PORT<device::PORT8, device::bitpos::B1> sdc_detect; ///< カード検出 typedef utils::sdc_io<SPI, sdc_select, sdc_power, sdc_detect> SDC; #endif SDC sdc_(spi_, 20000000); utils::command<256> cmd_; // utils::SDRAM_128M_32W sdram_; } extern "C" { void sci_putch(char ch) { sci_.putch(ch); } void sci_puts(const char* str) { sci_.puts(str); } char sci_getch(void) { return sci_.getch(); } uint16_t sci_length() { return sci_.recv_length(); } DSTATUS disk_initialize(BYTE drv) { return sdc_.at_mmc().disk_initialize(drv); } DSTATUS disk_status(BYTE drv) { return sdc_.at_mmc().disk_status(drv); } DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) { return sdc_.at_mmc().disk_read(drv, buff, sector, count); } DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) { return sdc_.at_mmc().disk_write(drv, buff, sector, count); } DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) { return sdc_.at_mmc().disk_ioctl(drv, ctrl, buff); } DWORD get_fattime(void) { time_t t = 0; rtc_.get_time(t); return utils::str::get_fattime(t); } void utf8_to_sjis(const char* src, char* dst) { utils::str::utf8_to_sjis(src, dst); } time_t get_time_() { time_t t = 0; if(!rtc_.get_time(t)) { utils::format("Stall RTC read\n"); } return t; } void disp_time_(time_t t) { struct tm *m = localtime(&t); utils::format("%s %s %d %02d:%02d:%02d %4d\n") % get_wday(m->tm_wday) % get_mon(m->tm_mon) % static_cast<uint32_t>(m->tm_mday) % static_cast<uint32_t>(m->tm_hour) % static_cast<uint32_t>(m->tm_min) % static_cast<uint32_t>(m->tm_sec) % static_cast<uint32_t>(m->tm_year + 1900); } const char* get_dec_(const char* p, char tmch, int& value) { int v = 0; char ch; while((ch = *p) != 0) { ++p; if(ch == tmch) { break; } else if(ch >= '0' && ch <= '9') { v *= 10; v += ch - '0'; } else { return nullptr; } } value = v; return p; } void set_time_date_() { time_t t = get_time_(); if(t == 0) return; struct tm *m = localtime(&t); bool err = false; if(cmd_.get_words() == 3) { char buff[12]; if(cmd_.get_word(1, sizeof(buff), buff)) { const char* p = buff; int vs[3]; uint8_t i; for(i = 0; i < 3; ++i) { p = get_dec_(p, '/', vs[i]); if(p == nullptr) { break; } } if(p != nullptr && p[0] == 0 && i == 3) { if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900; if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1; if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2]; } else { err = true; } } if(cmd_.get_word(2, sizeof(buff), buff)) { const char* p = buff; int vs[3]; uint8_t i; for(i = 0; i < 3; ++i) { p = get_dec_(p, ':', vs[i]); if(p == nullptr) { break; } } if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) { if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0]; if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1]; if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2]; else m->tm_sec = 0; } else { err = true; } } } if(err) { sci_puts("Can't analize Time/Date input.\n"); return; } time_t tt = mktime(m); if(!rtc_.set_time(tt)) { sci_puts("Stall RTC write...\n"); } } bool check_mount_() { auto f = sdc_.get_mount(); if(!f) { utils::format("SD card not mount.\n"); } return f; } } int main(int argc, char** argv); int main(int argc, char** argv) { device::system_io<12000000>::setup_system_clock(); // SDRAM 初期化 128M/32bits bus // sdram_(); { // タイマー設定(60Hz) uint8_t cmt_irq_level = 4; cmt_.start(60, cmt_irq_level); } { // SCI 設定 // uint8_t sci_level = 2; uint8_t sci_level = 0; sci_.start(115200, sci_level); } { // RTC 設定 rtc_.start(); } { // SD カード・クラスの初期化 sdc_.start(); } utils::format("RX64M SDC sample\n"); device::PORT0::PDR.B7 = 1; // output cmd_.set_prompt("# "); uint32_t cnt = 0; char buff[16]; while(1) { cmt_.sync(); sdc_.service(); // コマンド入力と、コマンド解析 if(cmd_.service()) { uint8_t cmdn = cmd_.get_words(); if(cmdn >= 1) { bool f = false; if(cmd_.cmp_word(0, "dir")) { // dir [xxx] if(check_mount_()) { if(cmdn >= 2) { char tmp[128]; cmd_.get_word(1, sizeof(tmp), tmp); sdc_.dir(tmp); } else { sdc_.dir(""); } } f = true; } else if(cmd_.cmp_word(0, "cd")) { // cd [xxx] if(check_mount_()) { if(cmdn >= 2) { char tmp[128]; cmd_.get_word(1, sizeof(tmp), tmp); sdc_.cd(tmp); } else { sdc_.cd("/"); } } f = true; } else if(cmd_.cmp_word(0, "pwd")) { // pwd utils::format("%s\n") % sdc_.get_current(); f = true; } else if(cmd_.cmp_word(0, "date")) { if(cmdn == 1) { time_t t = get_time_(); if(t != 0) { disp_time_(t); } } else { set_time_date_(); } f = true; } else if(cmd_.cmp_word(0, "help") || cmd_.cmp_word(0, "?")) { utils::format("date\n"); utils::format("date yyyy/mm/dd hh:mm[:ss]\n"); utils::format("dir [name]\n"); utils::format("cd [directory-name]\n"); utils::format("pwd\n"); f = true; } if(!f) { char tmp[128]; if(cmd_.get_word(0, sizeof(tmp), tmp)) { utils::format("Command error: '%s'\n") % tmp; } } } } ++cnt; if(cnt >= 30) { cnt = 0; } device::PORT0::PODR.B7 = (cnt < 10) ? 0 : 1; } } <commit_msg>update SDC manage<commit_after>//=====================================================================// /*! @file @brief RX64M SDC サンプル @n ・P07(176) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/cmt_io.hpp" #include "common/sci_io.hpp" #include "common/fifo.hpp" #include "common/format.hpp" #include "common/command.hpp" #include "common/rspi_io.hpp" #include "common/spi_io.hpp" #include "common/spi_io2.hpp" #include "common/sdc_man.hpp" #include "RX64M/sdhi_io.hpp" #include "common/string_utils.hpp" #define SDHI_IF namespace { typedef device::cmt_io<device::CMT0> CMT; CMT cmt_; typedef utils::fifo<uint16_t, 256> BUFFER; typedef device::sci_io<device::SCI1, BUFFER, BUFFER> SCI; SCI sci_; utils::rtc_io rtc_; typedef device::PORT<device::PORT8, device::bitpos::B2> SDC_POWER; ///< カード電源制御 #ifdef SDHI_IF // カード電源制御は使わない場合、「device::NULL_PORT」を指定する。 // typedef fatfs::sdhi_io<device::SDHI, SDC_POWER> SDHI; ///< ハードウェアー定義 typedef fatfs::sdhi_io<device::SDHI, device::NULL_PORT> SDHI; ///< ハードウェアー定義 SDHI sdh_; #else // Soft SDC 用 SPI 定義(SPI) typedef device::PORT<device::PORTC, device::bitpos::B3> MISO; typedef device::PORT<device::PORT7, device::bitpos::B6> MOSI; typedef device::PORT<device::PORT7, device::bitpos::B7> SPCK; typedef device::spi_io2<MISO, MOSI, SPCK> SPI; ///< Soft SPI 定義 // typedef device::rspi_io<device::RSPI> RSPI; ///< Hard SPI 定義 // RSPI rspi_; SPI spi_; typedef device::PORT<device::PORTC, device::bitpos::B2> SDC_SELECT; ///< カード選択信号 typedef device::PORT<device::PORT8, device::bitpos::B1> SDC_DETECT; ///< カード検出 typedef fatfs::mmc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> MMC; ///< ハードウェアー定義 MMC sdh_(spi_, 20000000); #endif typedef utils::sdc_man SDC; SDC sdc_; utils::command<256> cmd_; // utils::SDRAM_128M_32W sdram_; uint8_t v_ = 91; uint8_t m_ = 123; uint8_t rand_() { v_ += v_ << 2; ++v_; uint8_t n = 0; if(m_ & 0x02) n = 1; if(m_ & 0x40) n ^= 1; m_ += m_; if(n == 0) ++m_; return v_ ^ m_; } //-----------------------------------------------------------------// /*! @brief ファイル作成テスト @param[in] fname ファイル名 @param[in] size 作成サイズ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool create_test_file_(const char* fname, uint32_t size) { uint8_t buff[512]; FIL fp; for(uint16_t i = 0; i < sizeof(buff); ++i) { buff[i] = rand_(); } auto st = cmt_.get_counter(); if(!sdc_.open(&fp, fname, FA_WRITE | FA_CREATE_ALWAYS)) { utils::format("Can't create file: '%s'\n") % fname; return false; } auto ed = cmt_.get_counter(); uint32_t topen = ed - st; st = ed; auto rs = size; while(rs > 0) { UINT sz = sizeof(buff); if(sz > rs) sz = rs; UINT bw; f_write(&fp, buff, sz, &bw); rs -= bw; } ed = cmt_.get_counter(); uint32_t twrite = ed - st; st = ed; f_close(&fp); ed = cmt_.get_counter(); uint32_t tclose = ed - st; utils::format("Open: %d [ms]\n") % (topen * 10); auto pbyte = size * 100 / twrite; utils::format("Write: %d Bytes/Sec\n") % pbyte; utils::format("Write: %d KBytes/Sec\n") % (pbyte / 1024); utils::format("Close: %d [ms]\n") % (tclose * 10); return true; } } extern "C" { void sci_putch(char ch) { sci_.putch(ch); } void sci_puts(const char* str) { sci_.puts(str); } char sci_getch(void) { return sci_.getch(); } uint16_t sci_length() { return sci_.recv_length(); } DSTATUS disk_initialize(BYTE drv) { return sdh_.disk_initialize(drv); } DSTATUS disk_status(BYTE drv) { return sdh_.disk_status(drv); } DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) { return sdh_.disk_read(drv, buff, sector, count); } DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) { return sdh_.disk_write(drv, buff, sector, count); } DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) { return sdh_.disk_ioctl(drv, ctrl, buff); } DWORD get_fattime(void) { time_t t = 0; rtc_.get_time(t); return utils::str::get_fattime(t); } void utf8_to_sjis(const char* src, char* dst) { utils::str::utf8_to_sjis(src, dst); } time_t get_time_() { time_t t = 0; if(!rtc_.get_time(t)) { utils::format("Stall RTC read\n"); } return t; } void disp_time_(time_t t) { struct tm *m = localtime(&t); utils::format("%s %s %d %02d:%02d:%02d %4d\n") % get_wday(m->tm_wday) % get_mon(m->tm_mon) % static_cast<uint32_t>(m->tm_mday) % static_cast<uint32_t>(m->tm_hour) % static_cast<uint32_t>(m->tm_min) % static_cast<uint32_t>(m->tm_sec) % static_cast<uint32_t>(m->tm_year + 1900); } const char* get_dec_(const char* p, char tmch, int& value) { int v = 0; char ch; while((ch = *p) != 0) { ++p; if(ch == tmch) { break; } else if(ch >= '0' && ch <= '9') { v *= 10; v += ch - '0'; } else { return nullptr; } } value = v; return p; } void set_time_date_() { time_t t = get_time_(); if(t == 0) return; struct tm *m = localtime(&t); bool err = false; if(cmd_.get_words() == 3) { char buff[12]; if(cmd_.get_word(1, sizeof(buff), buff)) { const char* p = buff; int vs[3]; uint8_t i; for(i = 0; i < 3; ++i) { p = get_dec_(p, '/', vs[i]); if(p == nullptr) { break; } } if(p != nullptr && p[0] == 0 && i == 3) { if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900; if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1; if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2]; } else { err = true; } } if(cmd_.get_word(2, sizeof(buff), buff)) { const char* p = buff; int vs[3]; uint8_t i; for(i = 0; i < 3; ++i) { p = get_dec_(p, ':', vs[i]); if(p == nullptr) { break; } } if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) { if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0]; if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1]; if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2]; else m->tm_sec = 0; } else { err = true; } } } if(err) { sci_puts("Can't analize Time/Date input.\n"); return; } time_t tt = mktime(m); if(!rtc_.set_time(tt)) { sci_puts("Stall RTC write...\n"); } } bool check_mount_() { auto f = sdc_.get_mount(); if(!f) { utils::format("SD card not mount.\n"); } return f; } } int main(int argc, char** argv); int main(int argc, char** argv) { SDC_POWER::DIR = 1; SDC_POWER::P = 0; device::system_io<12000000>::setup_system_clock(); // SDRAM 初期化 128M/32bits bus // sdram_(); { // タイマー設定(100Hz) uint8_t cmt_irq_level = 4; cmt_.start(100, cmt_irq_level); } { // SCI 設定 // uint8_t sci_level = 2; uint8_t sci_level = 0; sci_.start(115200, sci_level); } { // RTC 設定 rtc_.start(); } #ifdef SDHI_IF utils::format("RX64M SDHI SD-Card sample\n"); #else utils::format("RX64M Soft SPI SD-Card sample\n"); #endif { // SD カード・クラスの初期化 sdh_.start(); sdc_.start(); } device::PORT0::PDR.B7 = 1; // output cmd_.set_prompt("# "); uint32_t cnt = 0; char buff[16]; while(1) { cmt_.sync(); sdc_.service(sdh_.service()); // コマンド入力と、コマンド解析 if(cmd_.service()) { uint8_t cmdn = cmd_.get_words(); if(cmdn >= 1) { bool f = false; if(cmd_.cmp_word(0, "dir")) { // dir [xxx] if(check_mount_()) { if(cmdn >= 2) { char tmp[128]; cmd_.get_word(1, sizeof(tmp), tmp); sdc_.dir(tmp); } else { sdc_.dir(""); } } f = true; } else if(cmd_.cmp_word(0, "cd")) { // cd [xxx] if(check_mount_()) { if(cmdn >= 2) { char tmp[128]; cmd_.get_word(1, sizeof(tmp), tmp); sdc_.cd(tmp); } else { sdc_.cd("/"); } } f = true; } else if(cmd_.cmp_word(0, "pwd")) { // pwd utils::format("%s\n") % sdc_.get_current(); f = true; } else if(cmd_.cmp_word(0, "date")) { if(cmdn == 1) { time_t t = get_time_(); if(t != 0) { disp_time_(t); } } else { set_time_date_(); } f = true; } else if(cmd_.cmp_word(0, "test")) { create_test_file_("write_test.bin", 1024 * 1024); f = true; } else if(cmd_.cmp_word(0, "help") || cmd_.cmp_word(0, "?")) { utils::format("date\n"); utils::format("date yyyy/mm/dd hh:mm[:ss]\n"); utils::format("dir [name]\n"); utils::format("cd [directory-name]\n"); utils::format("pwd\n"); utils::format("test test speed for write file\n"); f = true; } if(!f) { char tmp[128]; if(cmd_.get_word(0, sizeof(tmp), tmp)) { utils::format("Command error: '%s'\n") % tmp; } } } } ++cnt; if(cnt >= 50) { cnt = 0; } device::PORT0::PODR.B7 = (cnt < 15) ? 0 : 1; } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/path_decider/path_decider.h" #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; namespace { const double kTimeSampleInterval = 0.1; } PathDecider::PathDecider() : Task("PathDecider") {} apollo::common::Status PathDecider::Execute( Frame *, ReferenceLineInfo *reference_line_info) { reference_line_ = &reference_line_info->reference_line(); speed_data_ = &reference_line_info->speed_data(); return Process(reference_line_info->path_data(), reference_line_info->path_decision()); } Status PathDecider::Process(const PathData &path_data, PathDecision *const path_decision) { CHECK_NOTNULL(path_decision); if (!MakeObjectDecision(path_data, path_decision)) { AERROR << "Failed to make decision based on tunnel"; return Status(ErrorCode::PLANNING_ERROR, "dp_road_graph decision "); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); if (!MakeStaticObstacleDecision(path_data, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } bool PathDecider::MakeStaticObstacleDecision( const PathData &path_data, PathDecision *const path_decision) { if (!FLAGS_enable_nudge_decision) { return true; } DCHECK_NOTNULL(path_decision); std::vector<common::SLPoint> adc_sl_points; std::vector<common::math::Box2d> adc_bounding_box; const auto &vehicle_param = common::VehicleConfigHelper::instance()->GetConfig().vehicle_param(); const double adc_length = vehicle_param.length(); const double adc_width = vehicle_param.length(); const double adc_max_edge_to_center_dist = std::hypot(std::max(vehicle_param.front_edge_to_center(), vehicle_param.back_edge_to_center()), std::max(vehicle_param.left_edge_to_center(), vehicle_param.right_edge_to_center())); for (const common::PathPoint &path_point : path_data.discretized_path().path_points()) { adc_bounding_box.emplace_back( common::math::Vec2d{path_point.x(), path_point.y()}, path_point.theta(), adc_length, adc_width); common::SLPoint adc_sl; if (!reference_line_->XYToSL({path_point.x(), path_point.y()}, &adc_sl)) { AERROR << "get_point_in_Frenet_frame error for ego vehicle " << path_point.x() << " " << path_point.y(); return false; } else { adc_sl_points.push_back(std::move(adc_sl)); } } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (!obstacle->IsStatic()) { continue; } // IGNORE by default ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = path_obstacle->perception_sl_boundary(); bool has_stop = false; for (std::size_t j = 0; j < adc_sl_points.size(); ++j) { const auto &adc_sl = adc_sl_points[j]; if (adc_sl.s() + adc_max_edge_to_center_dist + FLAGS_static_decision_ignore_s_range < sl_boundary.start_s() || adc_sl.s() - adc_max_edge_to_center_dist - FLAGS_static_decision_ignore_s_range > sl_boundary.end_s()) { // ignore: no overlap in s direction continue; } if (adc_sl.l() + adc_max_edge_to_center_dist + FLAGS_static_decision_nudge_l_buffer < sl_boundary.start_l() || adc_sl.l() - adc_max_edge_to_center_dist - FLAGS_static_decision_nudge_l_buffer > sl_boundary.end_l()) { // ignore: no overlap in l direction continue; } // check STOP/NUDGE double left_width; double right_width; if (!reference_line_->get_lane_width(adc_sl.s(), &left_width, &right_width)) { left_width = right_width = FLAGS_default_reference_line_width / 2; } double driving_width; bool left_nudgable = false; bool right_nudgable = false; if (sl_boundary.start_l() >= 0) { // obstacle on the left, check RIGHT_NUDGE driving_width = sl_boundary.start_l() - FLAGS_static_decision_nudge_l_buffer + right_width; right_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else if (sl_boundary.end_l() <= 0) { // obstacle on the right, check LEFT_NUDGE driving_width = std::fabs(sl_boundary.end_l()) - FLAGS_static_decision_nudge_l_buffer + left_width; left_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else { // obstacle across the central line, decide RIGHT_NUDGE/LEFT_NUDGE double driving_width_left = left_width - sl_boundary.end_l() - FLAGS_static_decision_nudge_l_buffer; double driving_width_right = right_width - std::fabs(sl_boundary.start_l()) - FLAGS_static_decision_nudge_l_buffer; if (std::max(driving_width_right, driving_width_left) >= FLAGS_min_driving_width) { // nudgable left_nudgable = driving_width_left > driving_width_right ? true : false; right_nudgable = !left_nudgable; } } if (!left_nudgable && !right_nudgable) { // STOP: and break ObjectDecisionType stop_decision; ObjectStop *object_stop_ptr = stop_decision.mutable_stop(); object_stop_ptr->set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE); const auto &vehicle_param = common::VehicleConfigHelper::instance() ->GetConfig() .vehicle_param(); constexpr double kStopBuffer = 1.0e-6; auto stop_ref_s = std::fmax(adc_sl_points[0].s() + vehicle_param.front_edge_to_center() + kStopBuffer, sl_boundary.start_s() - FLAGS_stop_distance_obstacle); object_stop_ptr->set_distance_s(stop_ref_s - sl_boundary.start_s()); auto stop_ref_point = reference_line_->get_reference_point(stop_ref_s); object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x()); object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y()); object_stop_ptr->set_stop_heading(stop_ref_point.heading()); path_decision->AddLongitudinalDecision("DpRoadGraph", obstacle->Id(), stop_decision); has_stop = true; break; } else { // NUDGE: and continue to check potential STOP along the ref line if (!object_decision.has_nudge()) { ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); if (left_nudgable) { // LEFT_NUDGE object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l(FLAGS_nudge_distance_obstacle); } else { // RIGHT_NUDGE object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l(-FLAGS_nudge_distance_obstacle); } } } } if (!has_stop) { path_decision->AddLateralDecision("DpRoadGraph", obstacle->Id(), object_decision); } } return true; } bool PathDecider::MakeDynamicObstcleDecision( const PathData &path_data, PathDecision *const path_decision) { // Compute dynamic obstacle decision const double interval = kTimeSampleInterval; const double total_time = std::min(speed_data_->TotalTime(), FLAGS_prediction_total_time); std::size_t evaluate_time_slots = static_cast<std::size_t>(std::floor(total_time / interval)); // list of Box2d for adc given speed profile std::vector<common::math::Box2d> adc_by_time; if (!ComputeBoundingBoxesForAdc(path_data.frenet_frame_path(), evaluate_time_slots, &adc_by_time)) { AERROR << "fill adc_by_time error"; return false; } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (obstacle->IsStatic()) { continue; } double timestamp = 0.0; for (std::size_t k = 0; k < evaluate_time_slots; ++k, timestamp += interval) { // TODO(all) make nudge decision for dynamic obstacles. // const auto obstacle_by_time = // obstacle->GetBoundingBox(obstacle->GetPointAtTime(timestamp)); } } return true; } bool PathDecider::ComputeBoundingBoxesForAdc( const FrenetFramePath &frenet_frame_path, const std::size_t evaluate_time_slots, std::vector<common::math::Box2d> *adc_boxes) { CHECK(adc_boxes != nullptr); const auto &vehicle_config = common::VehicleConfigHelper::instance()->GetConfig(); double adc_length = vehicle_config.vehicle_param().length(); double adc_width = vehicle_config.vehicle_param().length(); double time_stamp = 0.0; const double interval = kTimeSampleInterval; for (std::size_t i = 0; i < evaluate_time_slots; ++i, time_stamp += interval) { common::SpeedPoint speed_point; if (!speed_data_->EvaluateByTime(time_stamp, &speed_point)) { AINFO << "get_speed_point_with_time for time_stamp[" << time_stamp << "]"; return false; } const common::FrenetFramePoint &interpolated_frenet_point = frenet_frame_path.EvaluateByS(speed_point.s()); double s = interpolated_frenet_point.s(); double l = interpolated_frenet_point.l(); double dl = interpolated_frenet_point.dl(); common::math::Vec2d adc_position_cartesian; common::SLPoint sl_point; sl_point.set_s(s); sl_point.set_l(l); reference_line_->SLToXY(sl_point, &adc_position_cartesian); ReferencePoint reference_point = reference_line_->get_reference_point(s); double one_minus_kappa_r_d = 1 - reference_point.kappa() * l; double delta_theta = std::atan2(dl, one_minus_kappa_r_d); double theta = ::apollo::common::math::NormalizeAngle( delta_theta + reference_point.heading()); adc_boxes->emplace_back(adc_position_cartesian, theta, adc_length, adc_width); } return true; } } // namespace planning } // namespace apollo <commit_msg>planning: add gflag to guard NUDGE decision<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/path_decider/path_decider.h" #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; namespace { const double kTimeSampleInterval = 0.1; } PathDecider::PathDecider() : Task("PathDecider") {} apollo::common::Status PathDecider::Execute( Frame *, ReferenceLineInfo *reference_line_info) { reference_line_ = &reference_line_info->reference_line(); speed_data_ = &reference_line_info->speed_data(); return Process(reference_line_info->path_data(), reference_line_info->path_decision()); } Status PathDecider::Process(const PathData &path_data, PathDecision *const path_decision) { CHECK_NOTNULL(path_decision); if (!MakeObjectDecision(path_data, path_decision)) { AERROR << "Failed to make decision based on tunnel"; return Status(ErrorCode::PLANNING_ERROR, "dp_road_graph decision "); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); if (!MakeStaticObstacleDecision(path_data, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } bool PathDecider::MakeStaticObstacleDecision( const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); std::vector<common::SLPoint> adc_sl_points; std::vector<common::math::Box2d> adc_bounding_box; const auto &vehicle_param = common::VehicleConfigHelper::instance()->GetConfig().vehicle_param(); const double adc_length = vehicle_param.length(); const double adc_width = vehicle_param.length(); const double adc_max_edge_to_center_dist = std::hypot(std::max(vehicle_param.front_edge_to_center(), vehicle_param.back_edge_to_center()), std::max(vehicle_param.left_edge_to_center(), vehicle_param.right_edge_to_center())); for (const common::PathPoint &path_point : path_data.discretized_path().path_points()) { adc_bounding_box.emplace_back( common::math::Vec2d{path_point.x(), path_point.y()}, path_point.theta(), adc_length, adc_width); common::SLPoint adc_sl; if (!reference_line_->XYToSL({path_point.x(), path_point.y()}, &adc_sl)) { AERROR << "get_point_in_Frenet_frame error for ego vehicle " << path_point.x() << " " << path_point.y(); return false; } else { adc_sl_points.push_back(std::move(adc_sl)); } } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (!obstacle->IsStatic()) { continue; } // IGNORE by default ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = path_obstacle->perception_sl_boundary(); bool has_stop = false; for (std::size_t j = 0; j < adc_sl_points.size(); ++j) { const auto &adc_sl = adc_sl_points[j]; if (adc_sl.s() + adc_max_edge_to_center_dist + FLAGS_static_decision_ignore_s_range < sl_boundary.start_s() || adc_sl.s() - adc_max_edge_to_center_dist - FLAGS_static_decision_ignore_s_range > sl_boundary.end_s()) { // ignore: no overlap in s direction continue; } if (adc_sl.l() + adc_max_edge_to_center_dist + FLAGS_static_decision_nudge_l_buffer < sl_boundary.start_l() || adc_sl.l() - adc_max_edge_to_center_dist - FLAGS_static_decision_nudge_l_buffer > sl_boundary.end_l()) { // ignore: no overlap in l direction continue; } // check STOP/NUDGE double left_width; double right_width; if (!reference_line_->get_lane_width(adc_sl.s(), &left_width, &right_width)) { left_width = right_width = FLAGS_default_reference_line_width / 2; } double driving_width; bool left_nudgable = false; bool right_nudgable = false; if (sl_boundary.start_l() >= 0) { // obstacle on the left, check RIGHT_NUDGE driving_width = sl_boundary.start_l() - FLAGS_static_decision_nudge_l_buffer + right_width; right_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else if (sl_boundary.end_l() <= 0) { // obstacle on the right, check LEFT_NUDGE driving_width = std::fabs(sl_boundary.end_l()) - FLAGS_static_decision_nudge_l_buffer + left_width; left_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else { // obstacle across the central line, decide RIGHT_NUDGE/LEFT_NUDGE double driving_width_left = left_width - sl_boundary.end_l() - FLAGS_static_decision_nudge_l_buffer; double driving_width_right = right_width - std::fabs(sl_boundary.start_l()) - FLAGS_static_decision_nudge_l_buffer; if (std::max(driving_width_right, driving_width_left) >= FLAGS_min_driving_width) { // nudgable left_nudgable = driving_width_left > driving_width_right ? true : false; right_nudgable = !left_nudgable; } } if (!left_nudgable && !right_nudgable) { // STOP: and break ObjectStop *object_stop_ptr = object_decision.mutable_stop(); object_stop_ptr->set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE); const auto &vehicle_param = common::VehicleConfigHelper::instance() ->GetConfig() .vehicle_param(); constexpr double kStopBuffer = 1.0e-6; auto stop_ref_s = std::fmax(adc_sl_points[0].s() + vehicle_param.front_edge_to_center() + kStopBuffer, sl_boundary.start_s() - FLAGS_stop_distance_obstacle); object_stop_ptr->set_distance_s(stop_ref_s - sl_boundary.start_s()); auto stop_ref_point = reference_line_->get_reference_point(stop_ref_s); object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x()); object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y()); object_stop_ptr->set_stop_heading(stop_ref_point.heading()); has_stop = true; break; } else { // NUDGE: and continue to check potential STOP along the ref line if (!FLAGS_enable_nudge_decision) { continue; } if (!object_decision.has_nudge()) { ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); if (left_nudgable) { // LEFT_NUDGE object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l(FLAGS_nudge_distance_obstacle); } else { // RIGHT_NUDGE object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l(-FLAGS_nudge_distance_obstacle); } } } } if (has_stop) { // STOP path_decision->AddLongitudinalDecision("PathDecider", obstacle->Id(), object_decision); } else { // NUDGE / IGNORE path_decision->AddLateralDecision("PathDecider", obstacle->Id(), object_decision); } } return true; } bool PathDecider::MakeDynamicObstcleDecision( const PathData &path_data, PathDecision *const path_decision) { // Compute dynamic obstacle decision const double interval = kTimeSampleInterval; const double total_time = std::min(speed_data_->TotalTime(), FLAGS_prediction_total_time); std::size_t evaluate_time_slots = static_cast<std::size_t>(std::floor(total_time / interval)); // list of Box2d for adc given speed profile std::vector<common::math::Box2d> adc_by_time; if (!ComputeBoundingBoxesForAdc(path_data.frenet_frame_path(), evaluate_time_slots, &adc_by_time)) { AERROR << "fill adc_by_time error"; return false; } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (obstacle->IsStatic()) { continue; } double timestamp = 0.0; for (std::size_t k = 0; k < evaluate_time_slots; ++k, timestamp += interval) { // TODO(all) make nudge decision for dynamic obstacles. // const auto obstacle_by_time = // obstacle->GetBoundingBox(obstacle->GetPointAtTime(timestamp)); } } return true; } bool PathDecider::ComputeBoundingBoxesForAdc( const FrenetFramePath &frenet_frame_path, const std::size_t evaluate_time_slots, std::vector<common::math::Box2d> *adc_boxes) { CHECK(adc_boxes != nullptr); const auto &vehicle_config = common::VehicleConfigHelper::instance()->GetConfig(); double adc_length = vehicle_config.vehicle_param().length(); double adc_width = vehicle_config.vehicle_param().length(); double time_stamp = 0.0; const double interval = kTimeSampleInterval; for (std::size_t i = 0; i < evaluate_time_slots; ++i, time_stamp += interval) { common::SpeedPoint speed_point; if (!speed_data_->EvaluateByTime(time_stamp, &speed_point)) { AINFO << "get_speed_point_with_time for time_stamp[" << time_stamp << "]"; return false; } const common::FrenetFramePoint &interpolated_frenet_point = frenet_frame_path.EvaluateByS(speed_point.s()); double s = interpolated_frenet_point.s(); double l = interpolated_frenet_point.l(); double dl = interpolated_frenet_point.dl(); common::math::Vec2d adc_position_cartesian; common::SLPoint sl_point; sl_point.set_s(s); sl_point.set_l(l); reference_line_->SLToXY(sl_point, &adc_position_cartesian); ReferencePoint reference_point = reference_line_->get_reference_point(s); double one_minus_kappa_r_d = 1 - reference_point.kappa() * l; double delta_theta = std::atan2(dl, one_minus_kappa_r_d); double theta = ::apollo::common::math::NormalizeAngle( delta_theta + reference_point.heading()); adc_boxes->emplace_back(adc_position_cartesian, theta, adc_length, adc_width); } return true; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_throttle_sync.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// ---------------------------------------------------------------------------- /// @file p9_throttle_sync.H /// /// @brief p9_throttle_sync HWP /// /// The purpose of this procedure is to triggers sync command from a 'master' /// MC to other MCs that have attached memory in a processor. /// /// ---------------------------------------------------------------------------- /// *HWP HWP Owner : Joe McGill <[email protected]> /// *HWP FW Owner : Thi Tran <[email protected]> /// *HWP Team : Nest /// *HWP Level : 2 /// *HWP Consumed by : HB /// ---------------------------------------------------------------------------- #ifndef _P9_THROTTLE_SYNC_H_ #define _P9_THROTTLE_SYNC_H_ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <fapi2.H> #include <p9_nest_common_mc_def.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> // Function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_throttle_sync_FP_t)( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&); //------------------------------------------------------------------------------ // Function prototypes //------------------------------------------------------------------------------ /// /// @brief p9_throttle_sync procedure /// /// The purpose of this procedure is to triggers sync command from a 'master' /// MC to other MCs that have attached memory in a processor. /// /// @param[in] i_target Reference to TARGET_TYPE_PROC_CHIP target /// /// @return FAPI2_RC_SUCCESS if success, else error code. /// extern "C" { fapi2::ReturnCode p9_throttle_sync( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); } // extern "C" #endif // _P9_THROTTLE_SYNC_H_ <commit_msg>L3 update -- p9_throttle_sync<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_throttle_sync.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// ---------------------------------------------------------------------------- /// @file p9_throttle_sync.H /// /// @brief p9_throttle_sync HWP /// /// The purpose of this procedure is to triggers sync command from a 'master' /// MC to other MCs that have attached memory in a processor. /// /// ---------------------------------------------------------------------------- /// *HWP HWP Owner : Joe McGill <[email protected]> /// *HWP FW Owner : Thi Tran <[email protected]> /// *HWP Team : Nest /// *HWP Level : 3 /// *HWP Consumed by : HB /// ---------------------------------------------------------------------------- #ifndef _P9_THROTTLE_SYNC_H_ #define _P9_THROTTLE_SYNC_H_ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <fapi2.H> #include <p9_nest_common_mc_def.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> // Function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_throttle_sync_FP_t)( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&); //------------------------------------------------------------------------------ // Function prototypes //------------------------------------------------------------------------------ /// /// @brief p9_throttle_sync procedure /// /// The purpose of this procedure is to triggers sync command from a 'master' /// MC to other MCs that have attached memory in a processor. /// /// @param[in] i_target Reference to TARGET_TYPE_PROC_CHIP target /// /// @return FAPI2_RC_SUCCESS if success, else error code. /// extern "C" { fapi2::ReturnCode p9_throttle_sync( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); } // extern "C" #endif // _P9_THROTTLE_SYNC_H_ <|endoftext|>
<commit_before>//===---- MemLocationDumper.cpp - Dump all memory locations in program ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This pass dumps all the memory locations accessed in the function, as well // as their expansions. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-memlocation-dumper" #include "swift/SILPasses/Passes.h" #include "swift/SIL/MemLocation.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILValue.h" #include "swift/SILAnalysis/Analysis.h" #include "swift/SILPasses/Transforms.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Top Level Driver //===----------------------------------------------------------------------===// namespace { enum class MLKind : unsigned { OnlyExpansion=0, OnlyReduction=1, All=2, }; } // end anonymous namespace static llvm::cl::opt<MLKind> DebugMemLocationKinds("ml", llvm::cl::desc("MemLocation Kinds:"), llvm::cl::init(MLKind::All), llvm::cl::values(clEnumValN(MLKind::OnlyExpansion, "only-expansion", "only-expansion"), clEnumValN(MLKind::OnlyReduction, "only-reduction", "only-reduction"), clEnumValN(MLKind::All, "all", "all"), clEnumValEnd)); namespace { /// Dumps the alias relations between all instructions of a function. class MemLocationDumper : public SILFunctionTransform { void testExpansion(SILFunction &Fn) { MemLocationList Locs; for (auto &BB : Fn) { for (auto &II : BB) { MemLocation L; if (auto *LI = dyn_cast<LoadInst>(&II)) { L.initialize(LI->getOperand()); if (!L.isValid()) continue; MemLocation::expand(L, &Fn.getModule(), Locs); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { L.initialize(SI->getDest()); if (!L.isValid()) continue; MemLocation::expand(L, &Fn.getModule(), Locs); } } unsigned Counter = 0; for (auto &Loc : Locs) { llvm::outs() << "#" << Counter++ << Loc; } Locs.clear(); } llvm::outs() << "\n"; } void run() override { SILFunction &Fn = *getFunction(); llvm::outs() << "@" << Fn.getName() << "\n"; if (DebugMemLocationKinds == MLKind::OnlyExpansion) { testExpansion(Fn); return; } } StringRef getName() override { return "Mem Location Dumper"; } }; } // end anonymous namespace SILTransform *swift::createMemLocationDumper() { return new MemLocationDumper(); } <commit_msg>Removed a stale comment and renamed a function. NFC<commit_after>//===---- MemLocationDumper.cpp - Dump all memory locations in program ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This pass dumps all the memory locations accessed in the function, as well // as their expansions. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-memlocation-dumper" #include "swift/SILPasses/Passes.h" #include "swift/SIL/MemLocation.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILValue.h" #include "swift/SILAnalysis/Analysis.h" #include "swift/SILPasses/Transforms.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Top Level Driver //===----------------------------------------------------------------------===// namespace { enum class MLKind : unsigned { OnlyExpansion=0, OnlyReduction=1, All=2, }; } // end anonymous namespace static llvm::cl::opt<MLKind> DebugMemLocationKinds("ml", llvm::cl::desc("MemLocation Kinds:"), llvm::cl::init(MLKind::All), llvm::cl::values(clEnumValN(MLKind::OnlyExpansion, "only-expansion", "only-expansion"), clEnumValN(MLKind::OnlyReduction, "only-reduction", "only-reduction"), clEnumValN(MLKind::All, "all", "all"), clEnumValEnd)); namespace { class MemLocationDumper : public SILFunctionTransform { /// Dumps the expansions of memory locations accessed in the function. void dumpExpansion(SILFunction &Fn) { MemLocationList Locs; for (auto &BB : Fn) { for (auto &II : BB) { MemLocation L; if (auto *LI = dyn_cast<LoadInst>(&II)) { L.initialize(LI->getOperand()); if (!L.isValid()) continue; MemLocation::expand(L, &Fn.getModule(), Locs); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { L.initialize(SI->getDest()); if (!L.isValid()) continue; MemLocation::expand(L, &Fn.getModule(), Locs); } } unsigned Counter = 0; for (auto &Loc : Locs) { llvm::outs() << "#" << Counter++ << Loc; } Locs.clear(); } llvm::outs() << "\n"; } void run() override { SILFunction &Fn = *getFunction(); llvm::outs() << "@" << Fn.getName() << "\n"; if (DebugMemLocationKinds == MLKind::OnlyExpansion) { dumpExpansion(Fn); return; } } StringRef getName() override { return "Mem Location Dumper"; } }; } // end anonymous namespace SILTransform *swift::createMemLocationDumper() { return new MemLocationDumper(); } <|endoftext|>
<commit_before>#ifndef BUILDING_NODE_EXTENSION #define BUILDING_NODE_EXTENSION #endif #include <node.h> #include "WebRtcConnection.h" using namespace v8; WebRtcConnection::WebRtcConnection() {}; WebRtcConnection::~WebRtcConnection() {}; void WebRtcConnection::Init(Handle<Object> target) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("WebRtcConnection")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype tpl->PrototypeTemplate()->Set(String::NewSymbol("close"), FunctionTemplate::New(close)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("init"), FunctionTemplate::New(init)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("setRemoteSdp"), FunctionTemplate::New(setRemoteSdp)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("getLocalSdp"), FunctionTemplate::New(getLocalSdp)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("setAudioReceiver"), FunctionTemplate::New(setAudioReceiver)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("setVideoReceiver"), FunctionTemplate::New(setVideoReceiver)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("getCurrentState"), FunctionTemplate::New(getCurrentState)->GetFunction()); Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction()); target->Set(String::NewSymbol("WebRtcConnection"), constructor); } Handle<Value> WebRtcConnection::New(const Arguments& args) { HandleScope scope; if (args.Length()<4){ ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return args.This(); } // webrtcconnection(bool audioEnabled, bool videoEnabled, const std::string &stunServer, int stunPort, int minPort, int maxPort); bool a = (args[0]->ToBoolean())->BooleanValue(); bool v = (args[1]->ToBoolean())->BooleanValue(); String::Utf8Value param(args[2]->ToString()); std::string stunServer = std::string(*param); int stunPort = args[3]->IntegerValue(); int minPort = args[4]->IntegerValue(); int maxPort = args[5]->IntegerValue(); bool a = (args[0]->ToBoolean())->BooleanValue(); bool v = (args[1]->ToBoolean())->BooleanValue(); WebRtcConnection* obj = new WebRtcConnection(); obj->me = new erizo::WebRtcConnection(a, v, stunServer,stunPort,minPort,maxPort); obj->Wrap(args.This()); return args.This(); } Handle<Value> WebRtcConnection::close(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; delete me; return scope.Close(Null()); } Handle<Value> WebRtcConnection::init(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; bool r = me->init(); return scope.Close(Boolean::New(r)); } Handle<Value> WebRtcConnection::setRemoteSdp(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; String::Utf8Value param(args[0]->ToString()); std::string sdp = std::string(*param); bool r = me->setRemoteSdp(sdp); return scope.Close(Boolean::New(r)); } Handle<Value> WebRtcConnection::getLocalSdp(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; std::string sdp = me->getLocalSdp(); return scope.Close(String::NewSymbol(sdp.c_str())); } Handle<Value> WebRtcConnection::setAudioReceiver(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; MediaSink* param = ObjectWrap::Unwrap<MediaSink>(args[0]->ToObject()); erizo::MediaSink *mr = param->msink; me-> setAudioSink(mr); return scope.Close(Null()); } Handle<Value> WebRtcConnection::setVideoReceiver(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; MediaSink* param = ObjectWrap::Unwrap<MediaSink>(args[0]->ToObject()); erizo::MediaSink *mr = param->msink; me-> setVideoSink(mr); return scope.Close(Null()); } Handle<Value> WebRtcConnection::getCurrentState(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; int state = me->getCurrentState(); return scope.Close(Number::New(state)); } <commit_msg>Remove dublication<commit_after>#ifndef BUILDING_NODE_EXTENSION #define BUILDING_NODE_EXTENSION #endif #include <node.h> #include "WebRtcConnection.h" using namespace v8; WebRtcConnection::WebRtcConnection() {}; WebRtcConnection::~WebRtcConnection() {}; void WebRtcConnection::Init(Handle<Object> target) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("WebRtcConnection")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype tpl->PrototypeTemplate()->Set(String::NewSymbol("close"), FunctionTemplate::New(close)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("init"), FunctionTemplate::New(init)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("setRemoteSdp"), FunctionTemplate::New(setRemoteSdp)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("getLocalSdp"), FunctionTemplate::New(getLocalSdp)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("setAudioReceiver"), FunctionTemplate::New(setAudioReceiver)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("setVideoReceiver"), FunctionTemplate::New(setVideoReceiver)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("getCurrentState"), FunctionTemplate::New(getCurrentState)->GetFunction()); Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction()); target->Set(String::NewSymbol("WebRtcConnection"), constructor); } Handle<Value> WebRtcConnection::New(const Arguments& args) { HandleScope scope; if (args.Length()<4){ ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return args.This(); } // webrtcconnection(bool audioEnabled, bool videoEnabled, const std::string &stunServer, int stunPort, int minPort, int maxPort); bool a = (args[0]->ToBoolean())->BooleanValue(); bool v = (args[1]->ToBoolean())->BooleanValue(); String::Utf8Value param(args[2]->ToString()); std::string stunServer = std::string(*param); int stunPort = args[3]->IntegerValue(); int minPort = args[4]->IntegerValue(); int maxPort = args[5]->IntegerValue(); WebRtcConnection* obj = new WebRtcConnection(); obj->me = new erizo::WebRtcConnection(a, v, stunServer,stunPort,minPort,maxPort); obj->Wrap(args.This()); return args.This(); } Handle<Value> WebRtcConnection::close(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; delete me; return scope.Close(Null()); } Handle<Value> WebRtcConnection::init(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; bool r = me->init(); return scope.Close(Boolean::New(r)); } Handle<Value> WebRtcConnection::setRemoteSdp(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; String::Utf8Value param(args[0]->ToString()); std::string sdp = std::string(*param); bool r = me->setRemoteSdp(sdp); return scope.Close(Boolean::New(r)); } Handle<Value> WebRtcConnection::getLocalSdp(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; std::string sdp = me->getLocalSdp(); return scope.Close(String::NewSymbol(sdp.c_str())); } Handle<Value> WebRtcConnection::setAudioReceiver(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; MediaSink* param = ObjectWrap::Unwrap<MediaSink>(args[0]->ToObject()); erizo::MediaSink *mr = param->msink; me-> setAudioSink(mr); return scope.Close(Null()); } Handle<Value> WebRtcConnection::setVideoReceiver(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; MediaSink* param = ObjectWrap::Unwrap<MediaSink>(args[0]->ToObject()); erizo::MediaSink *mr = param->msink; me-> setVideoSink(mr); return scope.Close(Null()); } Handle<Value> WebRtcConnection::getCurrentState(const Arguments& args) { HandleScope scope; WebRtcConnection* obj = ObjectWrap::Unwrap<WebRtcConnection>(args.This()); erizo::WebRtcConnection *me = obj->me; int state = me->getCurrentState(); return scope.Close(Number::New(state)); } <|endoftext|>
<commit_before><commit_msg>Hotfix error for physical robot PID complete<commit_after><|endoftext|>
<commit_before>// Known bugs: // * Volume on a logarithmic scale // * _buffer must be made thread-safe #include "MPDMessageHandler.h" #include "common.h" #include "StringUtil.h" #include "PlaybackCommandHandler.h" #include "PlaylistCommandHandler.h" #include "GeneralCommandHandler.h" #include "DataRequestHandler.h" #include "Timer.h" #include <algorithm> #include <functional> #include <fstream> #include <string> #include <unordered_map> namespace foo_mpdsrv { MPDMessageHandler::MPDMessageHandler(MPDMessageHandler&& right) : _sender(std::move(right._sender)), _actions(std::move(right._actions)), _activeHandleCommandRoutine(&MPDMessageHandler::HandleCommandOnly) { TRACK_CALL_TEXT("MPDMessageHandler::MPDMessageHandler(&&)"); } MPDMessageHandler::MPDMessageHandler(SOCKET connection) : _sender(connection) { TRACK_CALL_TEXT("MPDMessageHandler::MPDMessageHandler(socket)"); _actions.insert(std::make_pair("ping", &HandlePing)); _actions.insert(std::make_pair("pause", &HandlePause)); _actions.insert(std::make_pair("play", &HandlePlay)); _actions.insert(std::make_pair("playid", &HandlePlayId)); _actions.insert(std::make_pair("stop", &HandleStop)); _actions.insert(std::make_pair("next", &HandleNext)); _actions.insert(std::make_pair("previous", &HandlePrevious)); _actions.insert(std::make_pair("playlistinfo", &HandlePlaylistinfo)); _actions.insert(std::make_pair("listplaylistinfo", &HandleListplaylistinfo)); _actions.insert(std::make_pair("lsinfo", &HandleLsinfo)); _actions.insert(std::make_pair("currentsong", &HandleCurrentsong)); _actions.insert(std::make_pair("plchanges", &HandlePlchanges)); _actions.insert(std::make_pair("status", &HandleStatus)); _actions.insert(std::make_pair("stats", &HandleStats)); _actions.insert(std::make_pair("outputs", &HandleOutputs)); _actions.insert(std::make_pair("close", &HandleClose)); _actions.insert(std::make_pair("volume", &HandleVolume)); _actions.insert(std::make_pair("setvol", &HandleVolume)); } MPDMessageHandler::~MPDMessageHandler() { TRACK_CALL_TEXT("MPDMessageHandler::~MPDMessageHandler()"); #ifdef FOO_MPDSRV_THREADED ExitThread(); WaitTillThreadDone(); #endif } void MPDMessageHandler::PushBuffer(const char* buf, size_t numBytes) { TRACK_CALL_TEXT("MPDMessageHandler::PushBuffer()"); _buffer.insert(_buffer.end(), buf, buf + numBytes); #ifdef FOO_MPDSRV_THREADED Wake(); #else HandleBuffer(); #endif } void MPDMessageHandler::HandleBuffer() { TRACK_CALL_TEXT("MPDMessageHandler::HandleBuffer()"); char newLineChars[] = { '\n', '\r' }; BufferType::iterator begin = _buffer.begin(); BufferType::iterator end = _buffer.end(); BufferType::iterator newLine; while((newLine = std::find_first_of(begin, end, newLineChars, newLineChars + sizeof(newLineChars))) != end) { std::string nextCommand(begin, newLine); Trim(nextCommand); begin = newLine + 1; if(!nextCommand.empty()) { Logger(Logger::DBG) << "I: " << nextCommand; (this->*_activeHandleCommandRoutine)(nextCommand); } } _buffer.erase(_buffer.begin(), begin); } template<typename T> void MPDMessageHandler::ExecuteCommandQueue(T commandLoop) { TRACK_CALL_TEXT("MPDMessageHandler::ExecuteCommandQueue()"); size_t i = 0; try { for(i = 0; i < _commandQueue.size(); ++i) commandLoop(_commandQueue[i]); } catch(const CommandException& e) { _sender.SendError(i, _commandQueue[i], e); } _commandQueue.clear(); } void MPDMessageHandler::HandleCommandListActive(const std::string& cmd) { if(!StrStartsWithLC(cmd, "command_list_end")) _commandQueue.push_back(cmd); else { ExecuteCommandQueue([this](const std::string& cmd) { ExecuteCommand(cmd); }); _sender.SendOk(); _activeHandleCommandRoutine = &MPDMessageHandler::HandleCommandOnly; } } void MPDMessageHandler::HandleCommandListOkActive(const std::string& cmd) { if(!StrStartsWithLC(cmd, "command_list_end")) _commandQueue.push_back(cmd); else { ExecuteCommandQueue([this](const std::string& cmd) { ExecuteCommand(cmd); _sender.SendListOk(); }); _activeHandleCommandRoutine = &MPDMessageHandler::HandleCommandOnly; } } void MPDMessageHandler::HandleCommandOnly(const std::string& cmd) { if(StrStartsWithLC(cmd, "command_list_begin")) { _activeHandleCommandRoutine = &MPDMessageHandler::HandleCommandListActive; } else if(StrStartsWithLC(cmd, "command_list_ok_begin")) { _activeHandleCommandRoutine = &MPDMessageHandler::HandleCommandListOkActive; } else { try { ExecuteCommand(cmd); _sender.SendOk(); } catch(const CommandException& e) { _sender.SendError(0, cmd, e); } } } bool MPDMessageHandler::WakeProc(abort_callback &abort) { TRACK_CALL_TEXT("MPDMessageHandler::WakeProc()"); Logger(Logger::FINEST) << "==>MPDMessageHandler got pushed buffer"; try { HandleBuffer(); } catch(const std::exception& e) { Logger(Logger::SEVERE) << "Caught exception: " << e; } return true; } void MPDMessageHandler::ExecuteCommand(std::string message) { TRACK_CALL_TEXT("MPDMessageHandler::ExecuteCommand()"); Timer time; std::vector<std::string> cmd = SplitCommand(message); std::transform(cmd[0].begin(), cmd[0].end(), cmd[0].begin(), tolower); auto action = _actions.find(cmd[0]); if(action != _actions.end()) action->second(_sender, cmd); else { Logger(Logger::DBG) << "Command not found: " << message; } time.LogDifference("Command " + cmd[0]); } std::vector<std::string> MPDMessageHandler::SplitCommand(const std::string& cmd) { assert(!cmd.empty()); TRACK_CALL_TEXT("MPDMessageHandler::SplitCommand()"); std::vector<std::string> ret; std::string::const_iterator start = cmd.begin(); std::string::const_iterator end = cmd.end(); while(start != end) { std::string::const_iterator argEnd; if(*start == '"') { argEnd = std::find(start + 1, end, '"'); ret.push_back(std::string(start, argEnd)); argEnd += 1; } else { argEnd = std::find_if(start + 1, end, &CharIsSpace); ret.push_back(std::string(start, argEnd)); } start = std::find_if_not(argEnd, end, &CharIsSpace); } return ret; } /*void MPDMessageHandler::SendAllFileinfo(std::vector<std::string>& args) { if(args.size() < 2) args.push_back("/"); pfc::string8 path = args[1].c_str(); NormalizePath(path); static_api_ptr_t<library_manager> lib; pfc::list_t<metadb_handle_ptr> out; lib->get_all_items(out); SortByFolder tmp; out.sort(tmp); FilterListByPath(out, path); t_size length = out.get_count(); for(t_size i = 0; i < length; ++i) _sender.SendSongMetadata(out[i]); }*/ }<commit_msg>Fixed argument out of range when no closing " was given<commit_after>// Known bugs: // * Volume on a logarithmic scale // * _buffer must be made thread-safe #include "MPDMessageHandler.h" #include "common.h" #include "StringUtil.h" #include "PlaybackCommandHandler.h" #include "PlaylistCommandHandler.h" #include "GeneralCommandHandler.h" #include "DataRequestHandler.h" #include "Timer.h" #include <algorithm> #include <functional> #include <fstream> #include <string> #include <unordered_map> namespace foo_mpdsrv { MPDMessageHandler::MPDMessageHandler(MPDMessageHandler&& right) : _sender(std::move(right._sender)), _actions(std::move(right._actions)), _activeHandleCommandRoutine(&MPDMessageHandler::HandleCommandOnly) { TRACK_CALL_TEXT("MPDMessageHandler::MPDMessageHandler(&&)"); } MPDMessageHandler::MPDMessageHandler(SOCKET connection) : _sender(connection) { TRACK_CALL_TEXT("MPDMessageHandler::MPDMessageHandler(socket)"); _actions.insert(std::make_pair("ping", &HandlePing)); _actions.insert(std::make_pair("pause", &HandlePause)); _actions.insert(std::make_pair("play", &HandlePlay)); _actions.insert(std::make_pair("playid", &HandlePlayId)); _actions.insert(std::make_pair("stop", &HandleStop)); _actions.insert(std::make_pair("next", &HandleNext)); _actions.insert(std::make_pair("previous", &HandlePrevious)); _actions.insert(std::make_pair("playlistinfo", &HandlePlaylistinfo)); _actions.insert(std::make_pair("listplaylistinfo", &HandleListplaylistinfo)); _actions.insert(std::make_pair("lsinfo", &HandleLsinfo)); _actions.insert(std::make_pair("currentsong", &HandleCurrentsong)); _actions.insert(std::make_pair("plchanges", &HandlePlchanges)); _actions.insert(std::make_pair("status", &HandleStatus)); _actions.insert(std::make_pair("stats", &HandleStats)); _actions.insert(std::make_pair("outputs", &HandleOutputs)); _actions.insert(std::make_pair("close", &HandleClose)); _actions.insert(std::make_pair("volume", &HandleVolume)); _actions.insert(std::make_pair("setvol", &HandleVolume)); } MPDMessageHandler::~MPDMessageHandler() { TRACK_CALL_TEXT("MPDMessageHandler::~MPDMessageHandler()"); #ifdef FOO_MPDSRV_THREADED ExitThread(); WaitTillThreadDone(); #endif } void MPDMessageHandler::PushBuffer(const char* buf, size_t numBytes) { TRACK_CALL_TEXT("MPDMessageHandler::PushBuffer()"); _buffer.insert(_buffer.end(), buf, buf + numBytes); #ifdef FOO_MPDSRV_THREADED Wake(); #else HandleBuffer(); #endif } void MPDMessageHandler::HandleBuffer() { TRACK_CALL_TEXT("MPDMessageHandler::HandleBuffer()"); char newLineChars[] = { '\n', '\r' }; BufferType::iterator begin = _buffer.begin(); BufferType::iterator end = _buffer.end(); BufferType::iterator newLine; while((newLine = std::find_first_of(begin, end, newLineChars, newLineChars + sizeof(newLineChars))) != end) { std::string nextCommand(begin, newLine); Trim(nextCommand); begin = newLine + 1; if(!nextCommand.empty()) { Logger(Logger::DBG) << "I: " << nextCommand; (this->*_activeHandleCommandRoutine)(nextCommand); } } _buffer.erase(_buffer.begin(), begin); } template<typename T> void MPDMessageHandler::ExecuteCommandQueue(T commandLoop) { TRACK_CALL_TEXT("MPDMessageHandler::ExecuteCommandQueue()"); size_t i = 0; try { for(i = 0; i < _commandQueue.size(); ++i) commandLoop(_commandQueue[i]); } catch(const CommandException& e) { _sender.SendError(i, _commandQueue[i], e); } _commandQueue.clear(); } void MPDMessageHandler::HandleCommandListActive(const std::string& cmd) { if(!StrStartsWithLC(cmd, "command_list_end")) _commandQueue.push_back(cmd); else { ExecuteCommandQueue([this](const std::string& cmd) { ExecuteCommand(cmd); }); _sender.SendOk(); _activeHandleCommandRoutine = &MPDMessageHandler::HandleCommandOnly; } } void MPDMessageHandler::HandleCommandListOkActive(const std::string& cmd) { if(!StrStartsWithLC(cmd, "command_list_end")) _commandQueue.push_back(cmd); else { ExecuteCommandQueue([this](const std::string& cmd) { ExecuteCommand(cmd); _sender.SendListOk(); }); _activeHandleCommandRoutine = &MPDMessageHandler::HandleCommandOnly; } } void MPDMessageHandler::HandleCommandOnly(const std::string& cmd) { if(StrStartsWithLC(cmd, "command_list_begin")) { _activeHandleCommandRoutine = &MPDMessageHandler::HandleCommandListActive; } else if(StrStartsWithLC(cmd, "command_list_ok_begin")) { _activeHandleCommandRoutine = &MPDMessageHandler::HandleCommandListOkActive; } else { try { ExecuteCommand(cmd); _sender.SendOk(); } catch(const CommandException& e) { _sender.SendError(0, cmd, e); } } } bool MPDMessageHandler::WakeProc(abort_callback &abort) { TRACK_CALL_TEXT("MPDMessageHandler::WakeProc()"); Logger(Logger::FINEST) << "==>MPDMessageHandler got pushed buffer"; try { HandleBuffer(); } catch(const std::exception& e) { Logger(Logger::SEVERE) << "Caught exception: " << e; } return true; } void MPDMessageHandler::ExecuteCommand(std::string message) { TRACK_CALL_TEXT("MPDMessageHandler::ExecuteCommand()"); Timer time; std::vector<std::string> cmd = SplitCommand(message); std::transform(cmd[0].begin(), cmd[0].end(), cmd[0].begin(), tolower); auto action = _actions.find(cmd[0]); if(action != _actions.end()) action->second(_sender, cmd); else { Logger(Logger::DBG) << "Command not found: " << message; } time.LogDifference("Command " + cmd[0]); } std::vector<std::string> MPDMessageHandler::SplitCommand(const std::string& cmd) { assert(!cmd.empty()); TRACK_CALL_TEXT("MPDMessageHandler::SplitCommand()"); std::vector<std::string> ret; std::string::const_iterator start = cmd.begin(); std::string::const_iterator end = cmd.end(); while(start != end) { std::string::const_iterator argEnd; if(*start == '"') argEnd = std::find(start + 1, end, '"'); else argEnd = std::find_if(start + 1, end, &CharIsSpace); ret.push_back(std::string(start, argEnd)); if(argEnd != cmd.end()) argEnd += 1; start = std::find_if_not(argEnd, end, &CharIsSpace); } return ret; } /*void MPDMessageHandler::SendAllFileinfo(std::vector<std::string>& args) { if(args.size() < 2) args.push_back("/"); pfc::string8 path = args[1].c_str(); NormalizePath(path); static_api_ptr_t<library_manager> lib; pfc::list_t<metadb_handle_ptr> out; lib->get_all_items(out); SortByFolder tmp; out.sort(tmp); FilterListByPath(out, path); t_size length = out.get_count(); for(t_size i = 0; i < length; ++i) _sender.SendSongMetadata(out[i]); }*/ }<|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <string> #include "compression.h" #include "download.h" #include "logging.h" #include "signature.h" #include "statistics.h" #include "swissknife.h" #include "swissknife_pull.h" #include "util/posix.h" #include "uuid.h" using namespace std; // NOLINT const char *kVersion = VERSION; namespace swissknife { download::DownloadManager *g_download_manager; signature::SignatureManager *g_signature_manager; perf::Statistics *g_statistics; void Usage() { LogCvmfs(kLogCvmfs, kLogStderr, "Version: %s\n\n" "Usage:\n" "cvmfs_preload -u <Stratum 0 URL>\n" " -r <alien cache directory>\n" " [-d <path to dirtab file>]\n" " [-k <public key>]\n" " [-m <fully qualified repository name>]\n" " [-n <num of parallel download threads>]\n" " [-x <directory for temporary files>]\n\n", kVersion); } } // namespace swissknife const char gCernPublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAukBusmYyFW8KJxVMmeCj\n" "N7vcU1mERMpDhPTa5PgFROSViiwbUsbtpP9CvfxB/KU1gggdbtWOTZVTQqA3b+p8\n" "g5Vve3/rdnN5ZEquxeEfIG6iEZta9Zei5mZMeuK+DPdyjtvN1wP0982ppbZzKRBu\n" "BbzR4YdrwwWXXNZH65zZuUISDJB4my4XRoVclrN5aGVz4PjmIZFlOJ+ytKsMlegW\n" "SNDwZO9z/YtBFil/Ca8FJhRPFMKdvxK+ezgq+OQWAerVNX7fArMC+4Ya5pF3ASr6\n" "3mlvIsBpejCUBygV4N2pxIcPJu/ZDaikmVvdPTNOTZlIFMf4zIP/YHegQSJmOyVp\n" "HQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char gCernIt1PublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo8uKvscgW7FNxzb65Uhm\n" "yr8jPJiyrl2kVzb/hhgdfN14C0tCbfFoE6ciuZFg+9ytLeiL9pzM96gSC+atIFl4\n" "7wTgtAFO1W4PtDQBwA/IG2bnwvNrzk19ob0JYhjZlS9tYKeh7TKCub55+vMwcEbP\n" "urzo3WSNCzJngiGMh1vM5iSlGLpCdSGzdwxLGwc1VjRM7q3KAd7M7TJCynKqXZPX\n" "R2xiD6I/p4xv39AnwphCFSmDh0MWE1WeeNHIiiveikvvN+l8d/ZNASIDhKNCsz6o\n" "aFDsGXvjGy7dg43YzjSSYSFGUnONtl5Fe6y4bQZj1LEPbeInW334MAbMwYF4LKma\n" "yQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char gCernIt4PublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzlAraXimfJP5ie0KtDAE\n" "rNUU5d9bzst+kqfhnb0U0OUtmCIbsueaDlbMmTdRSHMr+T0jI8i9CZxJwtxDqll+\n" "UuB3Li2hYBhk0tYTy29JJYvofVULvrw1kMSLKyTWnV30/MHjYxhLHoZWfdepTjVg\n" "lM0rP58K10wR3Z/AaaikOcy4z6P/MHs9ES1jdZqEBQEmmzKw5nf7pfU2QuVWJrKP\n" "wZ9XeYDzipVbMc1zaLEK0slE+bm2ge/Myvuj/rpYKT+6qzbasQg62abGFuOrjgKI\n" "X4/BVnilkhUfH6ssRKw4yehlKG1M5KJje2+y+iVvLbfoaw3g1Sjrf4p3Gq+ul7AC\n" "PwIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char gCernIt5PublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqFzLLZAg2xmHJLbbq0+N\n" "eYtjRDghUK5mYhARndnC3skFVowDTiqJVc9dIDX5zuxQ9HyC0iKM1HbvN64IH/Uf\n" "qoXLyZLiXbFwpg6BtEJxwhijdZCiCC5PC//Bb7zSFIVZvWjndujr6ejaY6kx3+jI\n" "sU1HSJ66pqorj+D1fbZCziLcWbS1GzceZ7aTYYPUdGZF1CgjBK5uKrEAoBsPgjWo\n" "+YOEkjskY7swfhUzkCe0YyMyAaS0gsWgYrY2ebrpauFFqKxveKWjDVBTGcwDhiBX\n" "60inUgD6CJXhUpvGHfU8V7Bv6l7dmyzhq/Bk2kRC92TIvxfaHRmS7nuknUY0hW6t\n" "2QIDAQAB\n" "-----END PUBLIC KEY-----\n"; static char CheckParameters(const string &params, swissknife::ArgumentList *args) { for (unsigned i = 0; i < params.length(); ++i) { char param = params[i]; if (args->find(param) == args->end()) { return param; } } return '\0'; } static bool HasDirtabChanged(const string &dirtab_src, const string &dirtab_dst) { bool retval; shash::Any hash_src(shash::kMd5); shash::Any hash_dst(shash::kMd5); retval = shash::HashFile(dirtab_src, &hash_src); if (!retval) return true; retval = shash::HashFile(dirtab_dst, &hash_dst); if (!retval) return true; return hash_src != hash_dst; } int main(int argc, char *argv[]) { int retval; // load some default arguments swissknife::ArgumentList args; string default_num_threads = "4"; args['n'] = &default_num_threads; string option_string = "u:r:k:m:x:d:n:vh"; int c; while ((c = getopt(argc, argv, option_string.c_str())) != -1) { if ((c == 'v') || (c == 'h')) { swissknife::Usage(); return 0; } args[c] = new string(optarg); } // check all mandatory parameters are included string necessary_params = "ur"; char result; if ((result = CheckParameters(necessary_params, &args)) != '\0') { printf("Argument not included but necessary: -%c\n\n", result); swissknife::Usage(); return 2; } if (args.find('m') == args.end()) { string fqrn = GetFileName(*args['u']); LogCvmfs(kLogCvmfs, kLogStdout, "CernVM-FS: guessing fqrn from URL: %s", fqrn.c_str()); args['m'] = new string(fqrn); } if (args.find('x') == args.end()) args['x'] = new string(*args['r'] + "/txn"); const string cache_directory = *args['r']; const string fqrn = *args['m']; const string dirtab = (args.find('d') == args.end()) ? "/dev/null" : *args['d']; const string dirtab_in_cache = cache_directory + "/dirtab." + fqrn; // Default network parameters: 5 seconds timeout, 2 retries args['t'] = new string("5"); args['a'] = new string("2"); // first create the alien cache string *alien_cache_dir = args['r']; retval = MkdirDeep(*alien_cache_dir, 0770); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create %s", alien_cache_dir->c_str()); return 1; } retval = MakeCacheDirectories(*alien_cache_dir, 0770); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create cache skeleton"); return 1; } // if there is no specified public key file we dump the cern.ch public key in // the temporary directory string cern_pk_base_path = *args['x']; string cern_pk_path = cern_pk_base_path + "/cern.ch.pub"; string cern_pk_it1_path = cern_pk_base_path + "/cern-it1.cern.ch.pub"; string cern_pk_it4_path = cern_pk_base_path + "/cern-it4.cern.ch.pub"; string cern_pk_it5_path = cern_pk_base_path + "/cern-it5.cern.ch.pub"; bool keys_created = false; if (args.find('k') == args.end()) { keys_created = true; assert(CopyMem2Path(reinterpret_cast<const unsigned char*>(gCernPublicKey), sizeof(gCernPublicKey), cern_pk_path)); assert(CopyMem2Path( reinterpret_cast<const unsigned char*>(gCernIt1PublicKey), sizeof(gCernIt1PublicKey), cern_pk_it1_path)); assert(CopyMem2Path( reinterpret_cast<const unsigned char*>(gCernIt4PublicKey), sizeof(gCernIt4PublicKey), cern_pk_it4_path)); assert(CopyMem2Path( reinterpret_cast<const unsigned char*>(gCernIt5PublicKey), sizeof(gCernIt5PublicKey), cern_pk_it5_path)); char path_separator = ':'; args['k'] = new string(cern_pk_path + path_separator + cern_pk_it1_path + path_separator + cern_pk_it4_path + path_separator + cern_pk_it5_path); } // now launch swissknife_pull swissknife::g_download_manager = new download::DownloadManager(); swissknife::g_signature_manager = new signature::SignatureManager(); swissknife::g_statistics = new perf::Statistics(); // load the command if (HasDirtabChanged(dirtab, dirtab_in_cache)) { LogCvmfs(kLogCvmfs, kLogStdout, "CernVM-FS: new dirtab, forced run"); args['z'] = NULL; // look into existing catalogs, too } args['c'] = NULL; retval = swissknife::CommandPull().Main(args); // Copy dirtab file if (retval == 0) { CopyPath2Path(dirtab, dirtab_in_cache); } // Create cache uuid if not present cvmfs::Uuid *uuid = cvmfs::Uuid::Create(cache_directory + "/uuid"); if (uuid == NULL) { LogCvmfs(kLogCvmfs, kLogStderr, "Warning: failed to create %s/uuid", cache_directory.c_str()); } delete uuid; if (keys_created) { unlink(cern_pk_path.c_str()); unlink(cern_pk_it1_path.c_str()); unlink(cern_pk_it4_path.c_str()); unlink(cern_pk_it5_path.c_str()); } return retval; } <commit_msg>Fix compilation of preload.cc<commit_after>/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <string> #include "compression.h" #include "download.h" #include "logging.h" #include "signature.h" #include "statistics.h" #include "swissknife.h" #include "swissknife_pull.h" #include "util/posix.h" #include "uuid.h" using namespace std; // NOLINT const char *kVersion = VERSION; namespace swissknife { download::DownloadManager *g_download_manager; signature::SignatureManager *g_signature_manager; perf::Statistics *g_statistics; void Usage() { LogCvmfs(kLogCvmfs, kLogStderr, "Version: %s\n\n" "Usage:\n" "cvmfs_preload -u <Stratum 0 URL>\n" " -r <alien cache directory>\n" " [-d <path to dirtab file>]\n" " [-k <public key>]\n" " [-m <fully qualified repository name>]\n" " [-n <num of parallel download threads>]\n" " [-x <directory for temporary files>]\n\n", kVersion); } } // namespace swissknife const char gCernPublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAukBusmYyFW8KJxVMmeCj\n" "N7vcU1mERMpDhPTa5PgFROSViiwbUsbtpP9CvfxB/KU1gggdbtWOTZVTQqA3b+p8\n" "g5Vve3/rdnN5ZEquxeEfIG6iEZta9Zei5mZMeuK+DPdyjtvN1wP0982ppbZzKRBu\n" "BbzR4YdrwwWXXNZH65zZuUISDJB4my4XRoVclrN5aGVz4PjmIZFlOJ+ytKsMlegW\n" "SNDwZO9z/YtBFil/Ca8FJhRPFMKdvxK+ezgq+OQWAerVNX7fArMC+4Ya5pF3ASr6\n" "3mlvIsBpejCUBygV4N2pxIcPJu/ZDaikmVvdPTNOTZlIFMf4zIP/YHegQSJmOyVp\n" "HQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char gCernIt1PublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo8uKvscgW7FNxzb65Uhm\n" "yr8jPJiyrl2kVzb/hhgdfN14C0tCbfFoE6ciuZFg+9ytLeiL9pzM96gSC+atIFl4\n" "7wTgtAFO1W4PtDQBwA/IG2bnwvNrzk19ob0JYhjZlS9tYKeh7TKCub55+vMwcEbP\n" "urzo3WSNCzJngiGMh1vM5iSlGLpCdSGzdwxLGwc1VjRM7q3KAd7M7TJCynKqXZPX\n" "R2xiD6I/p4xv39AnwphCFSmDh0MWE1WeeNHIiiveikvvN+l8d/ZNASIDhKNCsz6o\n" "aFDsGXvjGy7dg43YzjSSYSFGUnONtl5Fe6y4bQZj1LEPbeInW334MAbMwYF4LKma\n" "yQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char gCernIt4PublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzlAraXimfJP5ie0KtDAE\n" "rNUU5d9bzst+kqfhnb0U0OUtmCIbsueaDlbMmTdRSHMr+T0jI8i9CZxJwtxDqll+\n" "UuB3Li2hYBhk0tYTy29JJYvofVULvrw1kMSLKyTWnV30/MHjYxhLHoZWfdepTjVg\n" "lM0rP58K10wR3Z/AaaikOcy4z6P/MHs9ES1jdZqEBQEmmzKw5nf7pfU2QuVWJrKP\n" "wZ9XeYDzipVbMc1zaLEK0slE+bm2ge/Myvuj/rpYKT+6qzbasQg62abGFuOrjgKI\n" "X4/BVnilkhUfH6ssRKw4yehlKG1M5KJje2+y+iVvLbfoaw3g1Sjrf4p3Gq+ul7AC\n" "PwIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char gCernIt5PublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqFzLLZAg2xmHJLbbq0+N\n" "eYtjRDghUK5mYhARndnC3skFVowDTiqJVc9dIDX5zuxQ9HyC0iKM1HbvN64IH/Uf\n" "qoXLyZLiXbFwpg6BtEJxwhijdZCiCC5PC//Bb7zSFIVZvWjndujr6ejaY6kx3+jI\n" "sU1HSJ66pqorj+D1fbZCziLcWbS1GzceZ7aTYYPUdGZF1CgjBK5uKrEAoBsPgjWo\n" "+YOEkjskY7swfhUzkCe0YyMyAaS0gsWgYrY2ebrpauFFqKxveKWjDVBTGcwDhiBX\n" "60inUgD6CJXhUpvGHfU8V7Bv6l7dmyzhq/Bk2kRC92TIvxfaHRmS7nuknUY0hW6t\n" "2QIDAQAB\n" "-----END PUBLIC KEY-----\n"; static char CheckParameters(const string &params, swissknife::ArgumentList *args) { for (unsigned i = 0; i < params.length(); ++i) { char param = params[i]; if (args->find(param) == args->end()) { return param; } } return '\0'; } static bool HasDirtabChanged(const string &dirtab_src, const string &dirtab_dst) { bool retval; shash::Any hash_src(shash::kMd5); shash::Any hash_dst(shash::kMd5); retval = shash::HashFile(dirtab_src, &hash_src); if (!retval) return true; retval = shash::HashFile(dirtab_dst, &hash_dst); if (!retval) return true; return hash_src != hash_dst; } int main(int argc, char *argv[]) { int retval; // load some default arguments swissknife::ArgumentList args; args['n'].Reset(new string("4")); string option_string = "u:r:k:m:x:d:n:vh"; int c; while ((c = getopt(argc, argv, option_string.c_str())) != -1) { if ((c == 'v') || (c == 'h')) { swissknife::Usage(); return 0; } args[c].Reset(new string(optarg)); } // check all mandatory parameters are included string necessary_params = "ur"; char result; if ((result = CheckParameters(necessary_params, &args)) != '\0') { printf("Argument not included but necessary: -%c\n\n", result); swissknife::Usage(); return 2; } if (args.find('m') == args.end()) { string fqrn = GetFileName(*args['u']); LogCvmfs(kLogCvmfs, kLogStdout, "CernVM-FS: guessing fqrn from URL: %s", fqrn.c_str()); args['m'].Reset(new string(fqrn)); } if (args.find('x') == args.end()) args['x'].Reset(new string(*args['r'] + "/txn")); const string cache_directory = *args['r']; const string fqrn = *args['m']; const string dirtab = (args.find('d') == args.end()) ? "/dev/null" : *args['d']; const string dirtab_in_cache = cache_directory + "/dirtab." + fqrn; // Default network parameters: 5 seconds timeout, 2 retries args['t'].Reset(new string("5")); args['a'].Reset(new string("2")); // first create the alien cache const string& alien_cache_dir = *(args['r']); retval = MkdirDeep(alien_cache_dir, 0770); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create %s", alien_cache_dir.c_str()); return 1; } retval = MakeCacheDirectories(alien_cache_dir, 0770); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create cache skeleton"); return 1; } // if there is no specified public key file we dump the cern.ch public key in // the temporary directory string cern_pk_base_path = *args['x']; string cern_pk_path = cern_pk_base_path + "/cern.ch.pub"; string cern_pk_it1_path = cern_pk_base_path + "/cern-it1.cern.ch.pub"; string cern_pk_it4_path = cern_pk_base_path + "/cern-it4.cern.ch.pub"; string cern_pk_it5_path = cern_pk_base_path + "/cern-it5.cern.ch.pub"; bool keys_created = false; if (args.find('k') == args.end()) { keys_created = true; assert(CopyMem2Path(reinterpret_cast<const unsigned char*>(gCernPublicKey), sizeof(gCernPublicKey), cern_pk_path)); assert(CopyMem2Path( reinterpret_cast<const unsigned char*>(gCernIt1PublicKey), sizeof(gCernIt1PublicKey), cern_pk_it1_path)); assert(CopyMem2Path( reinterpret_cast<const unsigned char*>(gCernIt4PublicKey), sizeof(gCernIt4PublicKey), cern_pk_it4_path)); assert(CopyMem2Path( reinterpret_cast<const unsigned char*>(gCernIt5PublicKey), sizeof(gCernIt5PublicKey), cern_pk_it5_path)); char path_separator = ':'; args['k'].Reset(new string(cern_pk_path + path_separator + cern_pk_it1_path + path_separator + cern_pk_it4_path + path_separator + cern_pk_it5_path)); } // now launch swissknife_pull swissknife::g_download_manager = new download::DownloadManager(); swissknife::g_signature_manager = new signature::SignatureManager(); swissknife::g_statistics = new perf::Statistics(); // load the command if (HasDirtabChanged(dirtab, dirtab_in_cache)) { LogCvmfs(kLogCvmfs, kLogStdout, "CernVM-FS: new dirtab, forced run"); args['z'].Reset(); // look into existing catalogs, too } args['c'].Reset(); retval = swissknife::CommandPull().Main(args); // Copy dirtab file if (retval == 0) { CopyPath2Path(dirtab, dirtab_in_cache); } // Create cache uuid if not present cvmfs::Uuid *uuid = cvmfs::Uuid::Create(cache_directory + "/uuid"); if (uuid == NULL) { LogCvmfs(kLogCvmfs, kLogStderr, "Warning: failed to create %s/uuid", cache_directory.c_str()); } delete uuid; if (keys_created) { unlink(cern_pk_path.c_str()); unlink(cern_pk_it1_path.c_str()); unlink(cern_pk_it4_path.c_str()); unlink(cern_pk_it5_path.c_str()); } return retval; } <|endoftext|>
<commit_before>// Copyright (C) 2009 - 2010 Mathias Froehlich - [email protected] // // 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 General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef RTIObjectInstance_hxx #define RTIObjectInstance_hxx #include <list> #include <map> #include <string> #include <vector> #include "simgear/debug/logstream.hxx" #include "simgear/structure/SGReferenced.hxx" #include "simgear/structure/SGWeakPtr.hxx" #include "simgear/timing/timestamp.hxx" #include "RTIData.hxx" #include "RTIObjectClass.hxx" #include "HLADataElement.hxx" class SGTimeStamp; namespace simgear { class RTIObjectClass; class HLAObjectInstance; class RTIObjectInstance : public SGReferenced { public: RTIObjectInstance(HLAObjectInstance* hlaObjectInstance); virtual ~RTIObjectInstance(); virtual const RTIObjectClass* getObjectClass() const = 0; virtual std::string getName() const = 0; unsigned getNumAttributes() const; unsigned getAttributeIndex(const std::string& name) const; std::string getAttributeName(unsigned index) const; virtual void deleteObjectInstance(const RTIData& tag) = 0; virtual void deleteObjectInstance(const SGTimeStamp& timeStamp, const RTIData& tag) = 0; virtual void localDeleteObjectInstance() = 0; virtual void requestObjectAttributeValueUpdate() = 0; virtual void updateAttributeValues(const RTIData& tag) = 0; virtual void updateAttributeValues(const SGTimeStamp& timeStamp, const RTIData& tag) = 0; void removeInstance(const RTIData& tag); // Call this if you want to roll up the queued timestamed updates // and reflect that into the attached data elements. void reflectQueuedAttributeValues(const SGTimeStamp& timeStamp) { // replay all updates up to the given timestamp UpdateListMap::iterator last = _updateListMap.upper_bound(timeStamp); for (UpdateListMap::iterator i = _updateListMap.begin(); i != last; ++i) { for (UpdateList::iterator j = i->second.begin(); j != i->second.end(); ++j) { // FIXME have a variant that takes the timestamp? reflectAttributeValues(j->_indexDataPairList, j->_tag); } putUpdateToPool(i->second); } } void reflectAttributeValues(const RTIIndexDataPairList& dataPairList, const RTIData& tag); void reflectAttributeValues(const RTIIndexDataPairList& dataPairList, const SGTimeStamp& timeStamp, const RTIData& tag); void reflectAttributeValue(unsigned i, const RTIData& data) { if (_attributeData.size() <= i) return; HLADataElement* dataElement = _attributeData[i]._dataElement.get(); if (!dataElement) return; HLADecodeStream stream(data); dataElement->decode(stream); } const HLADataType* getAttributeDataType(unsigned i) const { return getObjectClass()->getAttributeDataType(i); } HLAUpdateType getAttributeUpdateType(unsigned i) const { return getObjectClass()->getAttributeUpdateType(i); } bool getAttributeSubscribed(unsigned i) const { return getObjectClass()->getAttributeSubscribed(i); } bool getAttributePublished(unsigned i) const { return getObjectClass()->getAttributePublished(i); } HLADataElement* getDataElement(unsigned i) { if (_attributeData.size() <= i) return 0; return _attributeData[i]._dataElement.get(); } const HLADataElement* getDataElement(unsigned i) const { if (_attributeData.size() <= i) return 0; return _attributeData[i]._dataElement.get(); } void setDataElement(unsigned i, HLADataElement* dataElement) { if (_attributeData.size() <= i) return; _attributeData[i]._dataElement = dataElement; } void updateAttributesFromClass(bool owned) { // FIXME: rethink that!!! unsigned numAttributes = getNumAttributes(); unsigned i = 0; for (; i < _attributeData.size(); ++i) { if (getAttributePublished(i)) { } else { _attributeData[i].setUpdateEnabled(false); _attributeData[i].setOwned(false); } } _attributeData.resize(numAttributes); for (; i < numAttributes; ++i) { if (getAttributePublished(i)) { _attributeData[i].setUpdateEnabled(true); _attributeData[i].setOwned(owned); } else { _attributeData[i].setUpdateEnabled(false); _attributeData[i].setOwned(false); } } } void setAttributeForceUpdate(unsigned i) { if (_attributeData.size() <= i) return; _attributeData[i].setForceUpdate(true); } void setAttributeInScope(unsigned i, bool inScope) { if (_attributeData.size() <= i) return; _attributeData[i].setInScope(inScope); } void setAttributeUpdateEnabled(unsigned i, bool enabled) { if (_attributeData.size() <= i) return; _attributeData[i].setUpdateEnabled(enabled); } void setAttributeUpdated(unsigned i) { if (_attributeData.size() <= i) return; _attributeData[i].setForceUpdate(false); } bool getAttributeEffectiveUpdateEnabled(unsigned i) { if (_attributeData.size() <= i) return false; if (!getAttributePublished(i)) return false; if (!_attributeData[i]._updateEnabled) return false; if (!_attributeData[i]._inScope) return false; if (_attributeData[i]._forceUpdate) return true; switch (getAttributeUpdateType(i)) { case HLAPeriodicUpdate: return true; case HLAConditionalUpdate: return true; // FIXME case HLAStaticUpdate: return false; default: return false; } } void setRequestAttributeUpdate(bool request) { for (unsigned i = 0; i < getNumAttributes(); ++i) { if (getAttributeUpdateType(i) == HLAPeriodicUpdate) continue; setRequestAttributeUpdate(i, request); } } void setRequestAttributeUpdate(unsigned i, bool request) { if (_attributeData.size() <= i) return; _attributeData[i].setRequestUpdate(request); if (request) { if (!_pendingAttributeUpdateRequest) { _pendingAttributeUpdateRequest = true; } } } bool getRequestAttributeUpdate(unsigned i) const { if (_attributeData.size() <= i) return false; return _attributeData[i]._requestUpdate; } void flushPendingRequests() { if (_pendingAttributeUpdateRequest) { requestObjectAttributeValueUpdate(); _pendingAttributeUpdateRequest = false; } } protected: // The backward reference to the user visible object SGWeakPtr<HLAObjectInstance> _hlaObjectInstance; // Is true if we should emit a requestattr bool _pendingAttributeUpdateRequest; // Contains a full update as it came in from the RTI struct Update { RTIIndexDataPairList _indexDataPairList; RTIData _tag; }; // A bunch of updates for the same timestamp typedef std::list<Update> UpdateList; // The timestamp sorted list of updates typedef std::map<SGTimeStamp, UpdateList> UpdateListMap; // The timestamped updates sorted by timestamp UpdateListMap _updateListMap; // The pool of unused updates so that we do not need to malloc/free each time UpdateList _updateList; void getUpdateFromPool(UpdateList& updateList) { if (_updateList.empty()) updateList.push_back(Update()); else updateList.splice(updateList.end(), _updateList, _updateList.begin()); } void putUpdateToPool(UpdateList& updateList) { for (UpdateList::iterator i = updateList.begin(); i != updateList.end(); ++i) putDataToPool(i->_indexDataPairList); _updateList.splice(_updateList.end(), updateList); } // Appends the updates in the list to the given timestamps updates void scheduleUpdates(const SGTimeStamp& timeStamp, UpdateList& updateList) { UpdateListMap::iterator i = _updateListMap.find(timeStamp); if (i == _updateListMap.end()) i = _updateListMap.insert(UpdateListMap::value_type(timeStamp, UpdateList())).first; i->second.splice(i->second.end(), updateList); } // This adds raw storage for attribute index i to the end of the dataPairList. void getDataFromPool(unsigned i, RTIIndexDataPairList& dataPairList) { if (_attributeData.size() <= i) { SG_LOG(SG_NETWORK, SG_WARN, "RTI: Invalid object attribute index!"); return; } // Nothing left in the pool - so allocate something if (_attributeData[i]._indexDataPairList.empty()) { dataPairList.push_back(RTIIndexDataPairList::value_type()); dataPairList.back().first = i; return; } // Take one from the pool dataPairList.splice(dataPairList.end(), _attributeData[i]._indexDataPairList, _attributeData[i]._indexDataPairList.begin()); } void putDataToPool(RTIIndexDataPairList& dataPairList) { while (!dataPairList.empty()) { // Put back into the pool unsigned i = dataPairList.front().first; if (_attributeData.size() <= i) { // should not happen!!! SG_LOG(SG_NETWORK, SG_WARN, "RTI: Invalid object attribute index!"); dataPairList.pop_front(); } else { _attributeData[i]._indexDataPairList.splice(_attributeData[i]._indexDataPairList.begin(), dataPairList, dataPairList.begin()); } } } struct AttributeData { AttributeData() : _owned(false), _inScope(true), _updateEnabled(true), _forceUpdate(false), _requestUpdate(false) { } // The hla level data element with tha actual local program // accessible data. SGSharedPtr<HLADataElement> _dataElement; // SGSharedPtr<HLADataElement::TimeStamp> _timeStamp; // Pool of already allocated raw data used for reflection of updates RTIIndexDataPairList _indexDataPairList; void setOwned(bool owned) { _owned = owned; } void setInScope(bool inScope) { _inScope = inScope; } void setUpdateEnabled(bool updateEnabled) { _updateEnabled = updateEnabled; } void setForceUpdate(bool forceUpdate) { _forceUpdate = forceUpdate; } void setRequestUpdate(bool requestUpdate) { _requestUpdate = requestUpdate; } bool _owned; bool _inScope; bool _updateEnabled; bool _forceUpdate; bool _requestUpdate; }; std::vector<AttributeData> _attributeData; friend class HLAObjectInstance; }; } #endif <commit_msg>hla: Initially request update for subscribed unowned attributes.<commit_after>// Copyright (C) 2009 - 2010 Mathias Froehlich - [email protected] // // 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 General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef RTIObjectInstance_hxx #define RTIObjectInstance_hxx #include <list> #include <map> #include <string> #include <vector> #include "simgear/debug/logstream.hxx" #include "simgear/structure/SGReferenced.hxx" #include "simgear/structure/SGWeakPtr.hxx" #include "simgear/timing/timestamp.hxx" #include "RTIData.hxx" #include "RTIObjectClass.hxx" #include "HLADataElement.hxx" class SGTimeStamp; namespace simgear { class RTIObjectClass; class HLAObjectInstance; class RTIObjectInstance : public SGReferenced { public: RTIObjectInstance(HLAObjectInstance* hlaObjectInstance); virtual ~RTIObjectInstance(); virtual const RTIObjectClass* getObjectClass() const = 0; virtual std::string getName() const = 0; unsigned getNumAttributes() const; unsigned getAttributeIndex(const std::string& name) const; std::string getAttributeName(unsigned index) const; virtual void deleteObjectInstance(const RTIData& tag) = 0; virtual void deleteObjectInstance(const SGTimeStamp& timeStamp, const RTIData& tag) = 0; virtual void localDeleteObjectInstance() = 0; virtual void requestObjectAttributeValueUpdate() = 0; virtual void updateAttributeValues(const RTIData& tag) = 0; virtual void updateAttributeValues(const SGTimeStamp& timeStamp, const RTIData& tag) = 0; void removeInstance(const RTIData& tag); // Call this if you want to roll up the queued timestamed updates // and reflect that into the attached data elements. void reflectQueuedAttributeValues(const SGTimeStamp& timeStamp) { // replay all updates up to the given timestamp UpdateListMap::iterator last = _updateListMap.upper_bound(timeStamp); for (UpdateListMap::iterator i = _updateListMap.begin(); i != last; ++i) { for (UpdateList::iterator j = i->second.begin(); j != i->second.end(); ++j) { // FIXME have a variant that takes the timestamp? reflectAttributeValues(j->_indexDataPairList, j->_tag); } putUpdateToPool(i->second); } } void reflectAttributeValues(const RTIIndexDataPairList& dataPairList, const RTIData& tag); void reflectAttributeValues(const RTIIndexDataPairList& dataPairList, const SGTimeStamp& timeStamp, const RTIData& tag); void reflectAttributeValue(unsigned i, const RTIData& data) { if (_attributeData.size() <= i) return; HLADataElement* dataElement = _attributeData[i]._dataElement.get(); if (!dataElement) return; HLADecodeStream stream(data); dataElement->decode(stream); } const HLADataType* getAttributeDataType(unsigned i) const { return getObjectClass()->getAttributeDataType(i); } HLAUpdateType getAttributeUpdateType(unsigned i) const { return getObjectClass()->getAttributeUpdateType(i); } bool getAttributeSubscribed(unsigned i) const { return getObjectClass()->getAttributeSubscribed(i); } bool getAttributePublished(unsigned i) const { return getObjectClass()->getAttributePublished(i); } HLADataElement* getDataElement(unsigned i) { if (_attributeData.size() <= i) return 0; return _attributeData[i]._dataElement.get(); } const HLADataElement* getDataElement(unsigned i) const { if (_attributeData.size() <= i) return 0; return _attributeData[i]._dataElement.get(); } void setDataElement(unsigned i, HLADataElement* dataElement) { if (_attributeData.size() <= i) return; _attributeData[i]._dataElement = dataElement; } void updateAttributesFromClass(bool owned) { // FIXME: rethink that!!! unsigned numAttributes = getNumAttributes(); unsigned i = 0; for (; i < _attributeData.size(); ++i) { if (getAttributePublished(i)) { } else { _attributeData[i].setUpdateEnabled(false); _attributeData[i].setOwned(false); if (getAttributeSubscribed(i)) _attributeData[i].setRequestUpdate(true); } } _attributeData.resize(numAttributes); for (; i < numAttributes; ++i) { if (getAttributePublished(i)) { _attributeData[i].setUpdateEnabled(true); _attributeData[i].setOwned(owned); if (!owned && getAttributeSubscribed(i)) _attributeData[i].setRequestUpdate(true); } else { _attributeData[i].setUpdateEnabled(false); _attributeData[i].setOwned(false); if (getAttributeSubscribed(i)) _attributeData[i].setRequestUpdate(true); } } } void setAttributeForceUpdate(unsigned i) { if (_attributeData.size() <= i) return; _attributeData[i].setForceUpdate(true); } void setAttributeInScope(unsigned i, bool inScope) { if (_attributeData.size() <= i) return; _attributeData[i].setInScope(inScope); } void setAttributeUpdateEnabled(unsigned i, bool enabled) { if (_attributeData.size() <= i) return; _attributeData[i].setUpdateEnabled(enabled); } void setAttributeUpdated(unsigned i) { if (_attributeData.size() <= i) return; _attributeData[i].setForceUpdate(false); } bool getAttributeEffectiveUpdateEnabled(unsigned i) { if (_attributeData.size() <= i) return false; if (!getAttributePublished(i)) return false; if (!_attributeData[i]._updateEnabled) return false; if (!_attributeData[i]._inScope) return false; if (_attributeData[i]._forceUpdate) return true; switch (getAttributeUpdateType(i)) { case HLAPeriodicUpdate: return true; case HLAConditionalUpdate: return true; // FIXME case HLAStaticUpdate: return false; default: return false; } } void setRequestAttributeUpdate(bool request) { for (unsigned i = 0; i < getNumAttributes(); ++i) { if (getAttributeUpdateType(i) == HLAPeriodicUpdate) continue; setRequestAttributeUpdate(i, request); } } void setRequestAttributeUpdate(unsigned i, bool request) { if (_attributeData.size() <= i) return; _attributeData[i].setRequestUpdate(request); if (request) { if (!_pendingAttributeUpdateRequest) { _pendingAttributeUpdateRequest = true; } } } bool getRequestAttributeUpdate(unsigned i) const { if (_attributeData.size() <= i) return false; return _attributeData[i]._requestUpdate; } void flushPendingRequests() { if (_pendingAttributeUpdateRequest) { requestObjectAttributeValueUpdate(); _pendingAttributeUpdateRequest = false; } } protected: // The backward reference to the user visible object SGWeakPtr<HLAObjectInstance> _hlaObjectInstance; // Is true if we should emit a requestattr bool _pendingAttributeUpdateRequest; // Contains a full update as it came in from the RTI struct Update { RTIIndexDataPairList _indexDataPairList; RTIData _tag; }; // A bunch of updates for the same timestamp typedef std::list<Update> UpdateList; // The timestamp sorted list of updates typedef std::map<SGTimeStamp, UpdateList> UpdateListMap; // The timestamped updates sorted by timestamp UpdateListMap _updateListMap; // The pool of unused updates so that we do not need to malloc/free each time UpdateList _updateList; void getUpdateFromPool(UpdateList& updateList) { if (_updateList.empty()) updateList.push_back(Update()); else updateList.splice(updateList.end(), _updateList, _updateList.begin()); } void putUpdateToPool(UpdateList& updateList) { for (UpdateList::iterator i = updateList.begin(); i != updateList.end(); ++i) putDataToPool(i->_indexDataPairList); _updateList.splice(_updateList.end(), updateList); } // Appends the updates in the list to the given timestamps updates void scheduleUpdates(const SGTimeStamp& timeStamp, UpdateList& updateList) { UpdateListMap::iterator i = _updateListMap.find(timeStamp); if (i == _updateListMap.end()) i = _updateListMap.insert(UpdateListMap::value_type(timeStamp, UpdateList())).first; i->second.splice(i->second.end(), updateList); } // This adds raw storage for attribute index i to the end of the dataPairList. void getDataFromPool(unsigned i, RTIIndexDataPairList& dataPairList) { if (_attributeData.size() <= i) { SG_LOG(SG_NETWORK, SG_WARN, "RTI: Invalid object attribute index!"); return; } // Nothing left in the pool - so allocate something if (_attributeData[i]._indexDataPairList.empty()) { dataPairList.push_back(RTIIndexDataPairList::value_type()); dataPairList.back().first = i; return; } // Take one from the pool dataPairList.splice(dataPairList.end(), _attributeData[i]._indexDataPairList, _attributeData[i]._indexDataPairList.begin()); } void putDataToPool(RTIIndexDataPairList& dataPairList) { while (!dataPairList.empty()) { // Put back into the pool unsigned i = dataPairList.front().first; if (_attributeData.size() <= i) { // should not happen!!! SG_LOG(SG_NETWORK, SG_WARN, "RTI: Invalid object attribute index!"); dataPairList.pop_front(); } else { _attributeData[i]._indexDataPairList.splice(_attributeData[i]._indexDataPairList.begin(), dataPairList, dataPairList.begin()); } } } struct AttributeData { AttributeData() : _owned(false), _inScope(true), _updateEnabled(true), _forceUpdate(false), _requestUpdate(false) { } // The hla level data element with tha actual local program // accessible data. SGSharedPtr<HLADataElement> _dataElement; // SGSharedPtr<HLADataElement::TimeStamp> _timeStamp; // Pool of already allocated raw data used for reflection of updates RTIIndexDataPairList _indexDataPairList; void setOwned(bool owned) { _owned = owned; } void setInScope(bool inScope) { _inScope = inScope; } void setUpdateEnabled(bool updateEnabled) { _updateEnabled = updateEnabled; } void setForceUpdate(bool forceUpdate) { _forceUpdate = forceUpdate; } void setRequestUpdate(bool requestUpdate) { _requestUpdate = requestUpdate; } bool _owned; bool _inScope; bool _updateEnabled; bool _forceUpdate; bool _requestUpdate; }; std::vector<AttributeData> _attributeData; friend class HLAObjectInstance; }; } #endif <|endoftext|>
<commit_before>// Test that gcc-toolchain option is working correctly // // RUN: %clangxx -no-canonical-prefixes %s -### -o %t 2>&1 \ // RUN: -target i386-unknown-linux \ // RUN: -gcc-toolchain %S/Inputs/ubuntu_11.04_multiarch_tree/usr \ // RUN: | FileCheck %s // CHECK: "-internal-isystem" // CHECK: "[[TOOLCHAIN:[^"]+]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5" // CHECK: "-internal-isystem" // CHECK: "[[TOOLCHAIN]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/i686-linux-gnu" // CHECK: "-internal-isystem" // CHECK: "[[TOOLCHAIN]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/backward" // CHECK: "-internal-isystem" // CHECK: "/usr/local/include" // CHECK: "-internal-isystem" // CHECK: lib/clang/3.1/include" // CHECK: "-internal-externc-isystem" // CHECK: "/include" // CHECK: "-internal-externc-isystem" // CHECK: "/usr/include" // CHECK: "{{[^"]*}}ld{{(.exe)?}}" // CHECK: "{{[^"]*}}/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/crtbegin.o" // CHECK: "-L{{[^"]*}}/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5" // CHECK: "-L{{[^"]*}}/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../.." <commit_msg>Clean up, add some documentation, and make this test return to checking the linker toolchainness a bit more thoroughly. It used to work this way, but hit buildbot issues. Hopefully subsequent fixes have addressed those problems, but I'll be watching the bots.<commit_after>// Test that gcc-toolchain option is working correctly // // RUN: %clangxx -no-canonical-prefixes %s -### -o %t 2>&1 \ // RUN: -target i386-unknown-linux \ // RUN: -gcc-toolchain %S/Inputs/ubuntu_11.04_multiarch_tree/usr \ // RUN: | FileCheck %s // // Test for header search toolchain detection. // CHECK: "-internal-isystem" // CHECK: "[[TOOLCHAIN:[^"]+]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5" // CHECK: "-internal-isystem" // CHECK: "[[TOOLCHAIN]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/i686-linux-gnu" // CHECK: "-internal-isystem" // CHECK: "[[TOOLCHAIN]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/backward" // CHECK: "-internal-isystem" "/usr/local/include" // // Test for linker toolchain detection. Note that we use a separate variable // because the '/'s may be different in the linker invocation than in the // header search. // CHECK: "{{[^"]*}}ld{{(.exe)?}}" // CHECK: "[[TOOLCHAIN2:[^"]*]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/crtbegin.o" // CHECK: "-L[[TOOLCHAIN2]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5" // CHECK: "-L[[TOOLCHAIN2]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../.." <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "basebmp/scanlineformats.hxx" #include "basebmp/color.hxx" #include "basegfx/range/b2drectangle.hxx" #include "basegfx/range/b2irange.hxx" #include "basegfx/vector/b2ivector.hxx" #include "basegfx/polygon/b2dpolygon.hxx" #include "basegfx/polygon/b2dpolygontools.hxx" #include "vcl/svapp.hxx" #include "quartz/salgdi.h" #include "quartz/utils.h" #include "osx/salframe.h" #include "osx/saldata.hxx" void AquaSalGraphics::SetWindowGraphics( AquaSalFrame* pFrame ) { mpFrame = pFrame; mbWindow = true; mbPrinter = false; mbVirDev = false; } void AquaSalGraphics::SetPrinterGraphics( CGContextRef xContext, long nDPIX, long nDPIY ) { mbWindow = false; mbPrinter = true; mbVirDev = false; mrContext = xContext; mnRealDPIX = nDPIX; mnRealDPIY = nDPIY; // a previously set clip path is now invalid if( mxClipPath ) { CGPathRelease( mxClipPath ); mxClipPath = NULL; } if( mrContext ) { CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace ); CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace ); CGContextSaveGState( mrContext ); SetState(); } } void AquaSalGraphics::InvalidateContext() { UnsetState(); mrContext = 0; } void AquaSalGraphics::UnsetState() { if( mrContext ) { CG_TRACE( "CGContextRestoreGState(" << mrContext << ")" ); CGContextRestoreGState( mrContext ); mrContext = 0; } if( mxClipPath ) { CG_TRACE( "CGPathRelease(" << mxClipPath << ")" ); CGPathRelease( mxClipPath ); mxClipPath = NULL; } } bool AquaSalGraphics::CheckContext() { if( mbWindow && mpFrame && mpFrame->getNSWindow() ) { const unsigned int nWidth = mpFrame->maGeometry.nWidth; const unsigned int nHeight = mpFrame->maGeometry.nHeight; CGContextRef rReleaseContext = 0; CGLayerRef rReleaseLayer = NULL; // check if a new drawing context is needed (e.g. after a resize) if( (unsigned(mnWidth) != nWidth) || (unsigned(mnHeight) != nHeight) ) { mnWidth = nWidth; mnHeight = nHeight; // prepare to release the corresponding resources rReleaseContext = mrContext; rReleaseLayer = mxLayer; mrContext = NULL; mxLayer = NULL; } if( !mrContext ) { const CGSize aLayerSize = { static_cast<CGFloat>(nWidth), static_cast<CGFloat>(nHeight) }; NSGraphicsContext* pNSGContext = [NSGraphicsContext graphicsContextWithWindow: mpFrame->getNSWindow()]; CGContextRef xCGContext = reinterpret_cast<CGContextRef>([pNSGContext graphicsPort]); mxLayer = CGLayerCreateWithContext( xCGContext, aLayerSize, NULL ); CG_TRACE( "CGLayerCreateWithContext(" << xCGContext << "," << aLayerSize << ",NULL) = " << mxLayer ); if( mxLayer ) { mrContext = CGLayerGetContext( mxLayer ); CG_TRACE( "CGLayerGetContext(" << mxLayer << ") = " << mrContext ); } if( mrContext ) { // copy original layer to resized layer if( rReleaseLayer ) { CG_TRACE( "CGContextDrawLayerAtPoint(" << mrContext << "," << CGPointZero << "," << rReleaseLayer << ")" ); CGContextDrawLayerAtPoint( mrContext, CGPointZero, rReleaseLayer ); } CGContextTranslateCTM( mrContext, 0, nHeight ); CGContextScaleCTM( mrContext, 1.0, -1.0 ); CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace ); CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace ); CG_TRACE( "CGContextSaveGState(" << mrContext << ") " << ++mnContextStackDepth ); CGContextSaveGState( mrContext ); SetState(); // re-enable XOR emulation for the new context if( mpXorEmulation ) mpXorEmulation->SetTarget( mnWidth, mnHeight, mnBitmapDepth, mrContext, mxLayer ); } } if( rReleaseLayer ) { CG_TRACE( "CGLayerRelease(" << rReleaseLayer << ")" ); CGLayerRelease( rReleaseLayer ); } else if( rReleaseContext ) { CG_TRACE( "CGContextRelease(" << rReleaseContext << ")" ); CGContextRelease( rReleaseContext ); } } DBG_ASSERT( mrContext || mbPrinter, "<<<WARNING>>> AquaSalGraphics::CheckContext() FAILED!!!!\n" ); return (mrContext != NULL); } CGContextRef AquaSalGraphics::GetContext() { if(!mrContext) { CheckContext(); } return mrContext; } void AquaSalGraphics::RefreshRect(float lX, float lY, float lWidth, float lHeight) { if( ! mbWindow ) // view only on Window graphics return; if( mpFrame ) { // update a little more around the designated rectangle // this helps with antialiased rendering const Rectangle aVclRect(Point(static_cast<long int>(lX-1), static_cast<long int>(lY-1) ), Size( static_cast<long int>(lWidth+2), static_cast<long int>(lHeight+2) ) ); mpFrame->maInvalidRect.Union( aVclRect ); } } void AquaSalGraphics::UpdateWindow( NSRect& ) { if( !mpFrame ) return; NSGraphicsContext* pContext = [NSGraphicsContext currentContext]; if( (mxLayer != NULL) && (pContext != NULL) ) { CGContextRef rCGContext = reinterpret_cast<CGContextRef>([pContext graphicsPort]); CG_TRACE( "[[NSGraphicsContext currentContext] graphicsPort] = " << rCGContext ); CGMutablePathRef rClip = mpFrame->getClipPath(); if( rClip ) { CGContextSaveGState( rCGContext ); CG_TRACE( "CGContextBeginPath(" << rCGContext << ")" ); CGContextBeginPath( rCGContext ); CG_TRACE( "CGContextAddPath(" << rCGContext << "," << rClip << ")" ); CGContextAddPath( rCGContext, rClip ); CG_TRACE( "CGContextClip(" << rCGContext << ")" ); CGContextClip( rCGContext ); } ApplyXorContext(); CG_TRACE( "CGContextDrawLayerAtPoint(" << rCGContext << "," << CGPointZero << "," << mxLayer << ")" ); CGContextDrawLayerAtPoint( rCGContext, CGPointZero, mxLayer ); if( rClip ) // cleanup clipping CGContextRestoreGState( rCGContext ); } else DBG_ASSERT( mpFrame->mbInitShow, "UpdateWindow called on uneligible graphics" ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>#i125020# fix rounding error in AquaSalGraphics::RefreshRect()<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "basebmp/scanlineformats.hxx" #include "basebmp/color.hxx" #include "basegfx/range/b2drectangle.hxx" #include "basegfx/range/b2irange.hxx" #include "basegfx/vector/b2ivector.hxx" #include "basegfx/polygon/b2dpolygon.hxx" #include "basegfx/polygon/b2dpolygontools.hxx" #include "vcl/svapp.hxx" #include "quartz/salgdi.h" #include "quartz/utils.h" #include "osx/salframe.h" #include "osx/saldata.hxx" void AquaSalGraphics::SetWindowGraphics( AquaSalFrame* pFrame ) { mpFrame = pFrame; mbWindow = true; mbPrinter = false; mbVirDev = false; } void AquaSalGraphics::SetPrinterGraphics( CGContextRef xContext, long nDPIX, long nDPIY ) { mbWindow = false; mbPrinter = true; mbVirDev = false; mrContext = xContext; mnRealDPIX = nDPIX; mnRealDPIY = nDPIY; // a previously set clip path is now invalid if( mxClipPath ) { CGPathRelease( mxClipPath ); mxClipPath = NULL; } if( mrContext ) { CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace ); CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace ); CGContextSaveGState( mrContext ); SetState(); } } void AquaSalGraphics::InvalidateContext() { UnsetState(); mrContext = 0; } void AquaSalGraphics::UnsetState() { if( mrContext ) { CG_TRACE( "CGContextRestoreGState(" << mrContext << ")" ); CGContextRestoreGState( mrContext ); mrContext = 0; } if( mxClipPath ) { CG_TRACE( "CGPathRelease(" << mxClipPath << ")" ); CGPathRelease( mxClipPath ); mxClipPath = NULL; } } bool AquaSalGraphics::CheckContext() { if( mbWindow && mpFrame && mpFrame->getNSWindow() ) { const unsigned int nWidth = mpFrame->maGeometry.nWidth; const unsigned int nHeight = mpFrame->maGeometry.nHeight; CGContextRef rReleaseContext = 0; CGLayerRef rReleaseLayer = NULL; // check if a new drawing context is needed (e.g. after a resize) if( (unsigned(mnWidth) != nWidth) || (unsigned(mnHeight) != nHeight) ) { mnWidth = nWidth; mnHeight = nHeight; // prepare to release the corresponding resources rReleaseContext = mrContext; rReleaseLayer = mxLayer; mrContext = NULL; mxLayer = NULL; } if( !mrContext ) { const CGSize aLayerSize = { static_cast<CGFloat>(nWidth), static_cast<CGFloat>(nHeight) }; NSGraphicsContext* pNSGContext = [NSGraphicsContext graphicsContextWithWindow: mpFrame->getNSWindow()]; CGContextRef xCGContext = reinterpret_cast<CGContextRef>([pNSGContext graphicsPort]); mxLayer = CGLayerCreateWithContext( xCGContext, aLayerSize, NULL ); CG_TRACE( "CGLayerCreateWithContext(" << xCGContext << "," << aLayerSize << ",NULL) = " << mxLayer ); if( mxLayer ) { mrContext = CGLayerGetContext( mxLayer ); CG_TRACE( "CGLayerGetContext(" << mxLayer << ") = " << mrContext ); } if( mrContext ) { // copy original layer to resized layer if( rReleaseLayer ) { CG_TRACE( "CGContextDrawLayerAtPoint(" << mrContext << "," << CGPointZero << "," << rReleaseLayer << ")" ); CGContextDrawLayerAtPoint( mrContext, CGPointZero, rReleaseLayer ); } CGContextTranslateCTM( mrContext, 0, nHeight ); CGContextScaleCTM( mrContext, 1.0, -1.0 ); CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace ); CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace ); CG_TRACE( "CGContextSaveGState(" << mrContext << ") " << ++mnContextStackDepth ); CGContextSaveGState( mrContext ); SetState(); // re-enable XOR emulation for the new context if( mpXorEmulation ) mpXorEmulation->SetTarget( mnWidth, mnHeight, mnBitmapDepth, mrContext, mxLayer ); } } if( rReleaseLayer ) { CG_TRACE( "CGLayerRelease(" << rReleaseLayer << ")" ); CGLayerRelease( rReleaseLayer ); } else if( rReleaseContext ) { CG_TRACE( "CGContextRelease(" << rReleaseContext << ")" ); CGContextRelease( rReleaseContext ); } } DBG_ASSERT( mrContext || mbPrinter, "<<<WARNING>>> AquaSalGraphics::CheckContext() FAILED!!!!\n" ); return (mrContext != NULL); } CGContextRef AquaSalGraphics::GetContext() { if(!mrContext) { CheckContext(); } return mrContext; } void AquaSalGraphics::RefreshRect(float lX, float lY, float lWidth, float lHeight) { if( ! mbWindow ) // view only on Window graphics return; if( mpFrame ) { // update a little more around the designated rectangle // this helps with antialiased rendering const Rectangle aVclRect(Point(static_cast<long int>(lX-1), static_cast<long int>(lY-1) ), Size( static_cast<long int>(lWidth+3), static_cast<long int>(lHeight+3) ) ); mpFrame->maInvalidRect.Union( aVclRect ); } } void AquaSalGraphics::UpdateWindow( NSRect& ) { if( !mpFrame ) return; NSGraphicsContext* pContext = [NSGraphicsContext currentContext]; if( (mxLayer != NULL) && (pContext != NULL) ) { CGContextRef rCGContext = reinterpret_cast<CGContextRef>([pContext graphicsPort]); CG_TRACE( "[[NSGraphicsContext currentContext] graphicsPort] = " << rCGContext ); CGMutablePathRef rClip = mpFrame->getClipPath(); if( rClip ) { CGContextSaveGState( rCGContext ); CG_TRACE( "CGContextBeginPath(" << rCGContext << ")" ); CGContextBeginPath( rCGContext ); CG_TRACE( "CGContextAddPath(" << rCGContext << "," << rClip << ")" ); CGContextAddPath( rCGContext, rClip ); CG_TRACE( "CGContextClip(" << rCGContext << ")" ); CGContextClip( rCGContext ); } ApplyXorContext(); CG_TRACE( "CGContextDrawLayerAtPoint(" << rCGContext << "," << CGPointZero << "," << mxLayer << ")" ); CGContextDrawLayerAtPoint( rCGContext, CGPointZero, mxLayer ); if( rClip ) // cleanup clipping CGContextRestoreGState( rCGContext ); } else DBG_ASSERT( mpFrame->mbInitShow, "UpdateWindow called on uneligible graphics" ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/path_decider/path_decider.h" #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; namespace { const double kTimeSampleInterval = 0.1; } PathDecider::PathDecider() : Task("PathDecider") {} apollo::common::Status PathDecider::Execute( Frame *, ReferenceLineInfo *reference_line_info) { reference_line_ = &reference_line_info->reference_line(); speed_data_ = &reference_line_info->speed_data(); return Process(reference_line_info->path_data(), reference_line_info->path_decision()); } Status PathDecider::Process(const PathData &path_data, PathDecision *const path_decision) { CHECK_NOTNULL(path_decision); if (!MakeObjectDecision(path_data, path_decision)) { AERROR << "Failed to make decision based on tunnel"; return Status(ErrorCode::PLANNING_ERROR, "dp_road_graph decision "); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); if (!MakeStaticObstacleDecision(path_data, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } bool PathDecider::MakeStaticObstacleDecision( const PathData &path_data, PathDecision *const path_decision) { if (!FLAGS_enable_nudge_decision) { return true; } DCHECK_NOTNULL(path_decision); std::vector<common::SLPoint> adc_sl_points; std::vector<common::math::Box2d> adc_bounding_box; const auto &vehicle_param = common::VehicleConfigHelper::instance()->GetConfig().vehicle_param(); const double adc_length = vehicle_param.length(); const double adc_width = vehicle_param.length(); const double adc_max_edge_to_center_dist = std::hypot(std::max(vehicle_param.front_edge_to_center(), vehicle_param.back_edge_to_center()), std::max(vehicle_param.left_edge_to_center(), vehicle_param.right_edge_to_center())); for (const common::PathPoint &path_point : path_data.discretized_path().path_points()) { adc_bounding_box.emplace_back( common::math::Vec2d{path_point.x(), path_point.y()}, path_point.theta(), adc_length, adc_width); common::SLPoint adc_sl; if (!reference_line_->XYToSL({path_point.x(), path_point.y()}, &adc_sl)) { AERROR << "get_point_in_Frenet_frame error for ego vehicle " << path_point.x() << " " << path_point.y(); return false; } else { adc_sl_points.push_back(std::move(adc_sl)); } } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (!obstacle->IsStatic()) { continue; } // IGNORE by default ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = path_obstacle->perception_sl_boundary(); bool has_stop = false; for (std::size_t j = 0; j < adc_sl_points.size(); ++j) { const auto &adc_sl = adc_sl_points[j]; if (adc_sl.s() + adc_max_edge_to_center_dist + FLAGS_static_decision_ignore_s_range < sl_boundary.start_s() || adc_sl.s() - adc_max_edge_to_center_dist - FLAGS_static_decision_ignore_s_range > sl_boundary.end_s()) { // ignore: no overlap in s direction continue; } if (adc_sl.l() + adc_max_edge_to_center_dist + FLAGS_static_decision_nudge_l_buffer < sl_boundary.start_l() || adc_sl.l() - adc_max_edge_to_center_dist - FLAGS_static_decision_nudge_l_buffer > sl_boundary.end_l()) { // ignore: no overlap in l direction continue; } // check STOP/NUDGE double left_width; double right_width; if (!reference_line_->get_lane_width(adc_sl.s(), &left_width, &right_width)) { left_width = right_width = FLAGS_default_reference_line_width / 2; } double driving_width; bool left_nudgable = false; bool right_nudgable = false; if (sl_boundary.start_l() >= 0) { // obstacle on the left, check RIGHT_NUDGE driving_width = sl_boundary.start_l() - FLAGS_static_decision_nudge_l_buffer + right_width; right_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else if (sl_boundary.end_l() <= 0) { // obstacle on the right, check LEFT_NUDGE driving_width = std::fabs(sl_boundary.end_l()) - FLAGS_static_decision_nudge_l_buffer + left_width; left_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else { // obstacle across the central line, decide RIGHT_NUDGE/LEFT_NUDGE double driving_width_left = left_width - sl_boundary.end_l() - FLAGS_static_decision_nudge_l_buffer; double driving_width_right = right_width - std::fabs(sl_boundary.start_l()) - FLAGS_static_decision_nudge_l_buffer; if (std::max(driving_width_right, driving_width_left) >= FLAGS_min_driving_width) { // nudgable left_nudgable = driving_width_left > driving_width_right ? true : false; right_nudgable = !left_nudgable; } } if (!left_nudgable && !right_nudgable) { // STOP: and break ObjectDecisionType stop_decision; ObjectStop *object_stop_ptr = stop_decision.mutable_stop(); object_stop_ptr->set_distance_s(-FLAGS_stop_distance_obstacle); object_stop_ptr->set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE); auto stop_ref_s = sl_boundary.start_s() - FLAGS_stop_distance_obstacle; auto stop_ref_point = reference_line_->get_reference_point(stop_ref_s); object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x()); object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y()); object_stop_ptr->set_stop_heading(stop_ref_point.heading()); path_decision->AddLongitudinalDecision("DpRoadGraph", obstacle->Id(), stop_decision); has_stop = true; break; } else { // NUDGE: and continue to check potential STOP along the ref line if (!object_decision.has_nudge()) { ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); if (left_nudgable) { // LEFT_NUDGE object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l(FLAGS_nudge_distance_obstacle); } else { // RIGHT_NUDGE object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l(-FLAGS_nudge_distance_obstacle); } } } } if (!has_stop) { path_decision->AddLateralDecision("DpRoadGraph", obstacle->Id(), object_decision); } } return true; } bool PathDecider::MakeDynamicObstcleDecision( const PathData &path_data, PathDecision *const path_decision) { // Compute dynamic obstacle decision const double interval = kTimeSampleInterval; const double total_time = std::min(speed_data_->TotalTime(), FLAGS_prediction_total_time); std::size_t evaluate_time_slots = static_cast<std::size_t>(std::floor(total_time / interval)); // list of Box2d for adc given speed profile std::vector<common::math::Box2d> adc_by_time; if (!ComputeBoundingBoxesForAdc(path_data.frenet_frame_path(), evaluate_time_slots, &adc_by_time)) { AERROR << "fill adc_by_time error"; return false; } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (obstacle->IsStatic()) { continue; } double timestamp = 0.0; for (std::size_t k = 0; k < evaluate_time_slots; ++k, timestamp += interval) { // TODO(all) make nudge decision for dynamic obstacles. // const auto obstacle_by_time = // obstacle->GetBoundingBox(obstacle->GetPointAtTime(timestamp)); } } return true; } bool PathDecider::ComputeBoundingBoxesForAdc( const FrenetFramePath &frenet_frame_path, const std::size_t evaluate_time_slots, std::vector<common::math::Box2d> *adc_boxes) { CHECK(adc_boxes != nullptr); const auto &vehicle_config = common::VehicleConfigHelper::instance()->GetConfig(); double adc_length = vehicle_config.vehicle_param().length(); double adc_width = vehicle_config.vehicle_param().length(); double time_stamp = 0.0; const double interval = kTimeSampleInterval; for (std::size_t i = 0; i < evaluate_time_slots; ++i, time_stamp += interval) { common::SpeedPoint speed_point; if (!speed_data_->EvaluateByTime(time_stamp, &speed_point)) { AINFO << "get_speed_point_with_time for time_stamp[" << time_stamp << "]"; return false; } const common::FrenetFramePoint &interpolated_frenet_point = frenet_frame_path.EvaluateByS(speed_point.s()); double s = interpolated_frenet_point.s(); double l = interpolated_frenet_point.l(); double dl = interpolated_frenet_point.dl(); common::math::Vec2d adc_position_cartesian; common::SLPoint sl_point; sl_point.set_s(s); sl_point.set_l(l); reference_line_->SLToXY(sl_point, &adc_position_cartesian); ReferencePoint reference_point = reference_line_->get_reference_point(s); double one_minus_kappa_r_d = 1 - reference_point.kappa() * l; double delta_theta = std::atan2(dl, one_minus_kappa_r_d); double theta = ::apollo::common::math::NormalizeAngle( delta_theta + reference_point.heading()); adc_boxes->emplace_back(adc_position_cartesian, theta, adc_length, adc_width); } return true; } } // namespace planning } // namespace apollo <commit_msg>Planning: fixed stop decision s position bug. Use adc front s if the stop s is behind it.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/path_decider/path_decider.h" #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; namespace { const double kTimeSampleInterval = 0.1; } PathDecider::PathDecider() : Task("PathDecider") {} apollo::common::Status PathDecider::Execute( Frame *, ReferenceLineInfo *reference_line_info) { reference_line_ = &reference_line_info->reference_line(); speed_data_ = &reference_line_info->speed_data(); return Process(reference_line_info->path_data(), reference_line_info->path_decision()); } Status PathDecider::Process(const PathData &path_data, PathDecision *const path_decision) { CHECK_NOTNULL(path_decision); if (!MakeObjectDecision(path_data, path_decision)) { AERROR << "Failed to make decision based on tunnel"; return Status(ErrorCode::PLANNING_ERROR, "dp_road_graph decision "); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); if (!MakeStaticObstacleDecision(path_data, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } bool PathDecider::MakeStaticObstacleDecision( const PathData &path_data, PathDecision *const path_decision) { if (!FLAGS_enable_nudge_decision) { return true; } DCHECK_NOTNULL(path_decision); std::vector<common::SLPoint> adc_sl_points; std::vector<common::math::Box2d> adc_bounding_box; const auto &vehicle_param = common::VehicleConfigHelper::instance()->GetConfig().vehicle_param(); const double adc_length = vehicle_param.length(); const double adc_width = vehicle_param.length(); const double adc_max_edge_to_center_dist = std::hypot(std::max(vehicle_param.front_edge_to_center(), vehicle_param.back_edge_to_center()), std::max(vehicle_param.left_edge_to_center(), vehicle_param.right_edge_to_center())); for (const common::PathPoint &path_point : path_data.discretized_path().path_points()) { adc_bounding_box.emplace_back( common::math::Vec2d{path_point.x(), path_point.y()}, path_point.theta(), adc_length, adc_width); common::SLPoint adc_sl; if (!reference_line_->XYToSL({path_point.x(), path_point.y()}, &adc_sl)) { AERROR << "get_point_in_Frenet_frame error for ego vehicle " << path_point.x() << " " << path_point.y(); return false; } else { adc_sl_points.push_back(std::move(adc_sl)); } } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (!obstacle->IsStatic()) { continue; } // IGNORE by default ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = path_obstacle->perception_sl_boundary(); bool has_stop = false; for (std::size_t j = 0; j < adc_sl_points.size(); ++j) { const auto &adc_sl = adc_sl_points[j]; if (adc_sl.s() + adc_max_edge_to_center_dist + FLAGS_static_decision_ignore_s_range < sl_boundary.start_s() || adc_sl.s() - adc_max_edge_to_center_dist - FLAGS_static_decision_ignore_s_range > sl_boundary.end_s()) { // ignore: no overlap in s direction continue; } if (adc_sl.l() + adc_max_edge_to_center_dist + FLAGS_static_decision_nudge_l_buffer < sl_boundary.start_l() || adc_sl.l() - adc_max_edge_to_center_dist - FLAGS_static_decision_nudge_l_buffer > sl_boundary.end_l()) { // ignore: no overlap in l direction continue; } // check STOP/NUDGE double left_width; double right_width; if (!reference_line_->get_lane_width(adc_sl.s(), &left_width, &right_width)) { left_width = right_width = FLAGS_default_reference_line_width / 2; } double driving_width; bool left_nudgable = false; bool right_nudgable = false; if (sl_boundary.start_l() >= 0) { // obstacle on the left, check RIGHT_NUDGE driving_width = sl_boundary.start_l() - FLAGS_static_decision_nudge_l_buffer + right_width; right_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else if (sl_boundary.end_l() <= 0) { // obstacle on the right, check LEFT_NUDGE driving_width = std::fabs(sl_boundary.end_l()) - FLAGS_static_decision_nudge_l_buffer + left_width; left_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else { // obstacle across the central line, decide RIGHT_NUDGE/LEFT_NUDGE double driving_width_left = left_width - sl_boundary.end_l() - FLAGS_static_decision_nudge_l_buffer; double driving_width_right = right_width - std::fabs(sl_boundary.start_l()) - FLAGS_static_decision_nudge_l_buffer; if (std::max(driving_width_right, driving_width_left) >= FLAGS_min_driving_width) { // nudgable left_nudgable = driving_width_left > driving_width_right ? true : false; right_nudgable = !left_nudgable; } } if (!left_nudgable && !right_nudgable) { // STOP: and break ObjectDecisionType stop_decision; ObjectStop *object_stop_ptr = stop_decision.mutable_stop(); object_stop_ptr->set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE); const auto &vehicle_param = common::VehicleConfigHelper::instance() ->GetConfig() .vehicle_param(); constexpr double kStopBuffer = 1.0e-6; auto stop_ref_s = std::fmax(adc_sl_points[0].s() + vehicle_param.front_edge_to_center() + kStopBuffer, sl_boundary.start_s() - FLAGS_stop_distance_obstacle); object_stop_ptr->set_distance_s(stop_ref_s - sl_boundary.start_s()); auto stop_ref_point = reference_line_->get_reference_point(stop_ref_s); object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x()); object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y()); object_stop_ptr->set_stop_heading(stop_ref_point.heading()); path_decision->AddLongitudinalDecision("DpRoadGraph", obstacle->Id(), stop_decision); has_stop = true; break; } else { // NUDGE: and continue to check potential STOP along the ref line if (!object_decision.has_nudge()) { ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); if (left_nudgable) { // LEFT_NUDGE object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l(FLAGS_nudge_distance_obstacle); } else { // RIGHT_NUDGE object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l(-FLAGS_nudge_distance_obstacle); } } } } if (!has_stop) { path_decision->AddLateralDecision("DpRoadGraph", obstacle->Id(), object_decision); } } return true; } bool PathDecider::MakeDynamicObstcleDecision( const PathData &path_data, PathDecision *const path_decision) { // Compute dynamic obstacle decision const double interval = kTimeSampleInterval; const double total_time = std::min(speed_data_->TotalTime(), FLAGS_prediction_total_time); std::size_t evaluate_time_slots = static_cast<std::size_t>(std::floor(total_time / interval)); // list of Box2d for adc given speed profile std::vector<common::math::Box2d> adc_by_time; if (!ComputeBoundingBoxesForAdc(path_data.frenet_frame_path(), evaluate_time_slots, &adc_by_time)) { AERROR << "fill adc_by_time error"; return false; } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (obstacle->IsStatic()) { continue; } double timestamp = 0.0; for (std::size_t k = 0; k < evaluate_time_slots; ++k, timestamp += interval) { // TODO(all) make nudge decision for dynamic obstacles. // const auto obstacle_by_time = // obstacle->GetBoundingBox(obstacle->GetPointAtTime(timestamp)); } } return true; } bool PathDecider::ComputeBoundingBoxesForAdc( const FrenetFramePath &frenet_frame_path, const std::size_t evaluate_time_slots, std::vector<common::math::Box2d> *adc_boxes) { CHECK(adc_boxes != nullptr); const auto &vehicle_config = common::VehicleConfigHelper::instance()->GetConfig(); double adc_length = vehicle_config.vehicle_param().length(); double adc_width = vehicle_config.vehicle_param().length(); double time_stamp = 0.0; const double interval = kTimeSampleInterval; for (std::size_t i = 0; i < evaluate_time_slots; ++i, time_stamp += interval) { common::SpeedPoint speed_point; if (!speed_data_->EvaluateByTime(time_stamp, &speed_point)) { AINFO << "get_speed_point_with_time for time_stamp[" << time_stamp << "]"; return false; } const common::FrenetFramePoint &interpolated_frenet_point = frenet_frame_path.EvaluateByS(speed_point.s()); double s = interpolated_frenet_point.s(); double l = interpolated_frenet_point.l(); double dl = interpolated_frenet_point.dl(); common::math::Vec2d adc_position_cartesian; common::SLPoint sl_point; sl_point.set_s(s); sl_point.set_l(l); reference_line_->SLToXY(sl_point, &adc_position_cartesian); ReferencePoint reference_point = reference_line_->get_reference_point(s); double one_minus_kappa_r_d = 1 - reference_point.kappa() * l; double delta_theta = std::atan2(dl, one_minus_kappa_r_d); double theta = ::apollo::common::math::NormalizeAngle( delta_theta + reference_point.heading()); adc_boxes->emplace_back(adc_position_cartesian, theta, adc_length, adc_width); } return true; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: outdev5.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2003-12-01 13:22:04 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #define _SV_OUTDEV_CXX #include <tools/ref.hxx> #ifndef _SV_SVSYS_HXX #include <svsys.h> #endif #ifndef _SV_SALGDI_HXX #include <salgdi.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _POLY_HXX #include <tools/poly.hxx> #endif #ifndef _SV_METAACT_HXX #include <metaact.hxx> #endif #ifndef _SV_GDIMTF_HXX #include <gdimtf.hxx> #endif #ifndef _SV_OUTDATA_HXX #include <outdata.hxx> #endif #ifndef _SV_OUTDEV_H #include <outdev.h> #endif #ifndef _SV_OUTDEV_HXX #include <outdev.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <virdev.hxx> #endif // ======================================================================= DBG_NAMEEX( OutputDevice ); // ======================================================================= void OutputDevice::DrawRect( const Rectangle& rRect, ULONG nHorzRound, ULONG nVertRound ) { DBG_TRACE( "OutputDevice::DrawRoundRect()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaRoundRectAction( rRect, nHorzRound, nVertRound ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; const Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; nHorzRound = ImplLogicWidthToDevicePixel( nHorzRound ); nVertRound = ImplLogicHeightToDevicePixel( nVertRound ); // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); if ( mbInitFillColor ) ImplInitFillColor(); if ( !nHorzRound && !nVertRound ) mpGraphics->DrawRect( aRect.Left(), aRect.Top(), aRect.GetWidth(), aRect.GetHeight(), this ); else { const Polygon aRoundRectPoly( aRect, nHorzRound, nVertRound ); if ( aRoundRectPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*) aRoundRectPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aRoundRectPoly.GetSize(), pPtAry, this ); else mpGraphics->DrawPolygon( aRoundRectPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawRect( rRect, nHorzRound, nVertRound ); } // ----------------------------------------------------------------------- void OutputDevice::DrawEllipse( const Rectangle& rRect ) { DBG_TRACE( "OutputDevice::DrawEllipse()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaEllipseAction( rRect ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); Polygon aRectPoly( aRect.Center(), aRect.GetWidth() >> 1, aRect.GetHeight() >> 1 ); if ( aRectPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aRectPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aRectPoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aRectPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawEllipse( rRect ); } // ----------------------------------------------------------------------- void OutputDevice::DrawArc( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawArc()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaArcAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || !mbLineColor || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aArcPoly( aRect, aStart, aEnd, POLY_ARC ); if ( aArcPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aArcPoly.GetConstPointAry(); mpGraphics->DrawPolyLine( aArcPoly.GetSize(), pPtAry, this ); } if( mpAlphaVDev ) mpAlphaVDev->DrawArc( rRect, rStartPt, rEndPt ); } // ----------------------------------------------------------------------- void OutputDevice::DrawPie( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawPie()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaPieAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aPiePoly( aRect, aStart, aEnd, POLY_PIE ); if ( aPiePoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aPiePoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aPiePoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aPiePoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawPie( rRect, rStartPt, rEndPt ); } // ----------------------------------------------------------------------- void OutputDevice::DrawChord( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawChord()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaChordAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aChordPoly( aRect, aStart, aEnd, POLY_CHORD ); if ( aChordPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aChordPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aChordPoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aChordPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawChord( rRect, rStartPt, rEndPt ); } <commit_msg>INTEGRATION: CWS vclcleanup02 (1.5.4); FILE MERGED 2003/12/17 16:04:55 mt 1.5.4.2: #i23061# header cleanup, remove #ifdef ???_CXX and #define ???_CXX, also removed .impl files and fixed soke windows compiler warnings 2003/12/10 15:59:30 mt 1.5.4.1: #i23061# VCL cleanup, removed headers, methods and types...<commit_after>/************************************************************************* * * $RCSfile: outdev5.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2004-01-06 13:51:01 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <tools/ref.hxx> #ifndef _SV_SVSYS_HXX #include <svsys.h> #endif #ifndef _SV_SALGDI_HXX #include <salgdi.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _TL_POLY_HXX #include <tools/poly.hxx> #endif #ifndef _SV_METAACT_HXX #include <metaact.hxx> #endif #ifndef _SV_GDIMTF_HXX #include <gdimtf.hxx> #endif #ifndef _SV_OUTDATA_HXX #include <outdata.hxx> #endif #ifndef _SV_OUTDEV_H #include <outdev.h> #endif #ifndef _SV_OUTDEV_HXX #include <outdev.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <virdev.hxx> #endif // ======================================================================= DBG_NAMEEX( OutputDevice ); // ======================================================================= void OutputDevice::DrawRect( const Rectangle& rRect, ULONG nHorzRound, ULONG nVertRound ) { DBG_TRACE( "OutputDevice::DrawRoundRect()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaRoundRectAction( rRect, nHorzRound, nVertRound ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; const Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; nHorzRound = ImplLogicWidthToDevicePixel( nHorzRound ); nVertRound = ImplLogicHeightToDevicePixel( nVertRound ); // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); if ( mbInitFillColor ) ImplInitFillColor(); if ( !nHorzRound && !nVertRound ) mpGraphics->DrawRect( aRect.Left(), aRect.Top(), aRect.GetWidth(), aRect.GetHeight(), this ); else { const Polygon aRoundRectPoly( aRect, nHorzRound, nVertRound ); if ( aRoundRectPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*) aRoundRectPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aRoundRectPoly.GetSize(), pPtAry, this ); else mpGraphics->DrawPolygon( aRoundRectPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawRect( rRect, nHorzRound, nVertRound ); } // ----------------------------------------------------------------------- void OutputDevice::DrawEllipse( const Rectangle& rRect ) { DBG_TRACE( "OutputDevice::DrawEllipse()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaEllipseAction( rRect ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); Polygon aRectPoly( aRect.Center(), aRect.GetWidth() >> 1, aRect.GetHeight() >> 1 ); if ( aRectPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aRectPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aRectPoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aRectPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawEllipse( rRect ); } // ----------------------------------------------------------------------- void OutputDevice::DrawArc( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawArc()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaArcAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || !mbLineColor || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aArcPoly( aRect, aStart, aEnd, POLY_ARC ); if ( aArcPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aArcPoly.GetConstPointAry(); mpGraphics->DrawPolyLine( aArcPoly.GetSize(), pPtAry, this ); } if( mpAlphaVDev ) mpAlphaVDev->DrawArc( rRect, rStartPt, rEndPt ); } // ----------------------------------------------------------------------- void OutputDevice::DrawPie( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawPie()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaPieAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aPiePoly( aRect, aStart, aEnd, POLY_PIE ); if ( aPiePoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aPiePoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aPiePoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aPiePoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawPie( rRect, rStartPt, rEndPt ); } // ----------------------------------------------------------------------- void OutputDevice::DrawChord( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawChord()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaChordAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aChordPoly( aRect, aStart, aEnd, POLY_CHORD ); if ( aChordPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aChordPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aChordPoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aChordPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawChord( rRect, rStartPt, rEndPt ); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: file_stat.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-09-08 16:15:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TYPES_H #include <sys/types.h> #endif #ifndef _LIMITS_H #include <limits.h> #endif #ifndef _UNISTD_H #include <unistd.h> #endif #ifndef _OSL_FILE_H_ #include <osl/file.h> #endif #ifndef _ERRNO_H #include <errno.h> #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif #ifndef _OSL_UUNXAPI_H_ #include "uunxapi.hxx" #endif #ifndef _OSL_FILE_PATH_HELPER_HXX_ #include "file_path_helper.hxx" #endif #ifndef _FILE_ERROR_TRANSL_H_ #include "file_error_transl.h" #endif namespace /* private */ { inline void set_file_type(const struct stat& file_stat, oslFileStatus* pStat) { /* links to directories state also to be a directory */ if (S_ISLNK(file_stat.st_mode)) pStat->eType = osl_File_Type_Link; else if (S_ISDIR(file_stat.st_mode)) pStat->eType = osl_File_Type_Directory; else if (S_ISREG(file_stat.st_mode)) pStat->eType = osl_File_Type_Regular; else if (S_ISFIFO(file_stat.st_mode)) pStat->eType = osl_File_Type_Fifo; else if (S_ISSOCK(file_stat.st_mode)) pStat->eType = osl_File_Type_Socket; else if (S_ISCHR(file_stat.st_mode) || S_ISBLK(file_stat.st_mode)) pStat->eType = osl_File_Type_Special; else pStat->eType = osl_File_Type_Unknown; pStat->uValidFields |= osl_FileStatus_Mask_Type; } inline void set_file_access_mask(const struct stat& file_stat, oslFileStatus* pStat) { // user permissions if (S_IRUSR & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OwnRead; if (S_IWUSR & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OwnWrite; if (S_IXUSR & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OwnExe; // group permissions if (S_IRGRP & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_GrpRead; if (S_IWGRP & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_GrpWrite; if (S_IXGRP & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_GrpExe; // others permissions if (S_IROTH & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OthRead; if (S_IWOTH & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OthWrite; if (S_IXOTH & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OthExe; pStat->uValidFields |= osl_FileStatus_Mask_Attributes; } inline void set_file_access_rights(const struct stat& file_stat, int S_IR, int S_IW, int S_IX, oslFileStatus* pStat) { /* we cannot really map osl_File_Attribute_ReadOnly to the Unix access rights, it's a Windows only flag that's why the following hack. We set osl_FileStatus_Mask_Attributes but if there is no read access for a file we clear the flag again to signal to the caller that there are no file attributes to read because that's better than to give them incorrect one. */ pStat->uValidFields |= osl_FileStatus_Mask_Attributes; if (0 == (S_IR & file_stat.st_mode)) pStat->uValidFields &= ~osl_FileStatus_Mask_Attributes; if (0 == (S_IW & file_stat.st_mode)) pStat->uAttributes |= osl_File_Attribute_ReadOnly; if (S_IX & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_Executable; } /* a process may belong to up to NGROUPS_MAX groups, so when checking group access rights, we have to check all belonging groups */ inline bool is_in_process_grouplist(const gid_t file_group) { // check primary process group if (getgid() == file_group) return true; // check supplementary process groups gid_t grplist[NGROUPS_MAX]; int grp_number = getgroups(NGROUPS_MAX, grplist); for (int i = 0; i < grp_number; i++) { if (grplist[i] == file_group) return true; } return false; } /* Currently we are determining the file access right based on the real user ID not the effective user ID! We don't use access(...) because access follows links which may cause performance problems see #97133. */ inline void set_file_access_rights(const struct stat& file_stat, oslFileStatus* pStat) { if (getuid() == file_stat.st_uid) { set_file_access_rights(file_stat, S_IRUSR, S_IWUSR, S_IXUSR, pStat); } else if (is_in_process_grouplist(file_stat.st_gid)) { set_file_access_rights(file_stat, S_IRGRP, S_IWGRP, S_IXGRP, pStat); } else { set_file_access_rights(file_stat, S_IROTH, S_IWOTH, S_IXOTH, pStat); } } inline void set_file_hidden_status(const rtl::OUString& file_path, oslFileStatus* pStat) { pStat->uAttributes = osl::systemPathIsHiddenFileOrDirectoryEntry(file_path) ? osl_File_Attribute_Hidden : 0; pStat->uValidFields |= osl_FileStatus_Mask_Attributes; } /* the set_file_access_rights must be called after set_file_hidden_status(...) and set_file_access_mask(...) because of the hack in set_file_access_rights(...) */ inline void set_file_attributes( const rtl::OUString& file_path, const struct stat& file_stat, const sal_uInt32 uFieldMask, oslFileStatus* pStat) { set_file_hidden_status(file_path, pStat); set_file_access_mask(file_stat, pStat); // we set the file access rights only on demand // because it's potentially expensive if (uFieldMask & osl_FileStatus_Mask_Attributes) set_file_access_rights(file_stat, pStat); } inline void set_file_access_time(const struct stat& file_stat, oslFileStatus* pStat) { pStat->aAccessTime.Seconds = file_stat.st_atime; pStat->aAccessTime.Nanosec = 0; pStat->uValidFields |= osl_FileStatus_Mask_AccessTime; } inline void set_file_modify_time(const struct stat& file_stat, oslFileStatus* pStat) { pStat->aModifyTime.Seconds = file_stat.st_mtime; pStat->aModifyTime.Nanosec = 0; pStat->uValidFields |= osl_FileStatus_Mask_ModifyTime; } inline void set_file_size(const struct stat& file_stat, oslFileStatus* pStat) { if (S_ISREG(file_stat.st_mode)) { pStat->uFileSize = file_stat.st_size; pStat->uValidFields |= osl_FileStatus_Mask_FileSize; } } /* we only need to call stat or lstat if one of the following flags is set */ inline bool is_stat_call_necessary(sal_uInt32 field_mask) { return ((field_mask & osl_FileStatus_Mask_Type) || (field_mask & osl_FileStatus_Mask_Attributes) || (field_mask & osl_FileStatus_Mask_CreationTime) || (field_mask & osl_FileStatus_Mask_AccessTime) || (field_mask & osl_FileStatus_Mask_ModifyTime) || (field_mask & osl_FileStatus_Mask_FileSize) || (field_mask & osl_FileStatus_Mask_LinkTargetURL) || (field_mask & osl_FileStatus_Mask_Validate)); } inline oslFileError set_link_target_url(const rtl::OUString& file_path, oslFileStatus* pStat) { rtl::OUString link_target; if (!osl::realpath(file_path, link_target)) return oslTranslateFileError(OSL_FET_ERROR, errno); oslFileError osl_error = osl_getFileURLFromSystemPath(link_target.pData, &pStat->ustrLinkTargetURL); if (osl_error != osl_File_E_None) return osl_error; pStat->uValidFields |= osl_FileStatus_Mask_LinkTargetURL; return osl_File_E_None; } inline oslFileError setup_osl_getFileStatus(oslDirectoryItem Item, oslFileStatus* pStat, rtl::OUString& file_path) { if ((NULL == Item) || (NULL == pStat)) return osl_File_E_INVAL; file_path = rtl::OUString(reinterpret_cast<rtl_uString*>(Item)); OSL_ASSERT(file_path.getLength() > 0); if (file_path.getLength() <= 0) return osl_File_E_INVAL; pStat->uValidFields = 0; return osl_File_E_None; } } // end namespace private /**************************************************************************** * osl_getFileStatus ****************************************************************************/ oslFileError SAL_CALL osl_getFileStatus(oslDirectoryItem Item, oslFileStatus* pStat, sal_uInt32 uFieldMask) { rtl::OUString file_path; oslFileError osl_error = setup_osl_getFileStatus(Item, pStat, file_path); if (osl_File_E_None != osl_error) return osl_error; #if defined(__GNUC__) && (__GNUC__ < 3) struct ::stat file_stat; #else struct stat file_stat; #endif if (is_stat_call_necessary(uFieldMask) && (0 != osl::lstat(file_path, file_stat))) return oslTranslateFileError(OSL_FET_ERROR, errno); if (is_stat_call_necessary(uFieldMask)) { // we set all these attributes because it's cheap set_file_type(file_stat, pStat); set_file_access_time(file_stat, pStat); set_file_modify_time(file_stat, pStat); set_file_size(file_stat, pStat); set_file_attributes(file_path, file_stat, uFieldMask, pStat); // file exists semantic of osl_FileStatus_Mask_Validate if ((uFieldMask & osl_FileStatus_Mask_LinkTargetURL) && S_ISLNK(file_stat.st_mode)) { osl_error = set_link_target_url(file_path, pStat); if (osl_error != osl_File_E_None) return osl_error; } } if (uFieldMask & osl_FileStatus_Mask_FileURL) { if ((osl_error = osl_getFileURLFromSystemPath(file_path.pData, &pStat->ustrFileURL)) != osl_File_E_None) return osl_error; pStat->uValidFields |= osl_FileStatus_Mask_FileURL; } if (uFieldMask & osl_FileStatus_Mask_FileName) { osl_systemPathGetFileNameOrLastDirectoryPart(file_path.pData, &pStat->ustrFileName); pStat->uValidFields |= osl_FileStatus_Mask_FileName; } return osl_File_E_None; } <commit_msg>INTEGRATION: CWS hrobeta2 (1.4.64); FILE MERGED 2005/03/03 13:48:40 tra 1.4.64.1: #i42914# attribute osl_FileStatus_Mask_Attributes will not be removed anymore if user has no read rights for a file<commit_after>/************************************************************************* * * $RCSfile: file_stat.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2005-05-02 13:20:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TYPES_H #include <sys/types.h> #endif #ifndef _LIMITS_H #include <limits.h> #endif #ifndef _UNISTD_H #include <unistd.h> #endif #ifndef _OSL_FILE_H_ #include <osl/file.h> #endif #ifndef _ERRNO_H #include <errno.h> #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif #ifndef _OSL_UUNXAPI_H_ #include "uunxapi.hxx" #endif #ifndef _OSL_FILE_PATH_HELPER_HXX_ #include "file_path_helper.hxx" #endif #ifndef _FILE_ERROR_TRANSL_H_ #include "file_error_transl.h" #endif namespace /* private */ { inline void set_file_type(const struct stat& file_stat, oslFileStatus* pStat) { /* links to directories state also to be a directory */ if (S_ISLNK(file_stat.st_mode)) pStat->eType = osl_File_Type_Link; else if (S_ISDIR(file_stat.st_mode)) pStat->eType = osl_File_Type_Directory; else if (S_ISREG(file_stat.st_mode)) pStat->eType = osl_File_Type_Regular; else if (S_ISFIFO(file_stat.st_mode)) pStat->eType = osl_File_Type_Fifo; else if (S_ISSOCK(file_stat.st_mode)) pStat->eType = osl_File_Type_Socket; else if (S_ISCHR(file_stat.st_mode) || S_ISBLK(file_stat.st_mode)) pStat->eType = osl_File_Type_Special; else pStat->eType = osl_File_Type_Unknown; pStat->uValidFields |= osl_FileStatus_Mask_Type; } inline void set_file_access_mask(const struct stat& file_stat, oslFileStatus* pStat) { // user permissions if (S_IRUSR & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OwnRead; if (S_IWUSR & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OwnWrite; if (S_IXUSR & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OwnExe; // group permissions if (S_IRGRP & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_GrpRead; if (S_IWGRP & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_GrpWrite; if (S_IXGRP & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_GrpExe; // others permissions if (S_IROTH & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OthRead; if (S_IWOTH & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OthWrite; if (S_IXOTH & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_OthExe; pStat->uValidFields |= osl_FileStatus_Mask_Attributes; } inline void set_file_access_rights(const struct stat& file_stat, int S_IR, int S_IW, int S_IX, oslFileStatus* pStat) { /* we cannot really map osl_File_Attribute_ReadOnly to the Unix access rights, it's a Windows only flag that's why the following hack. We set osl_FileStatus_Mask_Attributes but if there is no read access for a file we clear the flag again to signal to the caller that there are no file attributes to read because that's better than to give them incorrect one. */ pStat->uValidFields |= osl_FileStatus_Mask_Attributes; if ((0 == (S_IW & file_stat.st_mode)) && (S_IR & file_stat.st_mode)) pStat->uAttributes |= osl_File_Attribute_ReadOnly; if (S_IX & file_stat.st_mode) pStat->uAttributes |= osl_File_Attribute_Executable; } /* a process may belong to up to NGROUPS_MAX groups, so when checking group access rights, we have to check all belonging groups */ inline bool is_in_process_grouplist(const gid_t file_group) { // check primary process group if (getgid() == file_group) return true; // check supplementary process groups gid_t grplist[NGROUPS_MAX]; int grp_number = getgroups(NGROUPS_MAX, grplist); for (int i = 0; i < grp_number; i++) { if (grplist[i] == file_group) return true; } return false; } /* Currently we are determining the file access right based on the real user ID not the effective user ID! We don't use access(...) because access follows links which may cause performance problems see #97133. */ inline void set_file_access_rights(const struct stat& file_stat, oslFileStatus* pStat) { if (getuid() == file_stat.st_uid) { set_file_access_rights(file_stat, S_IRUSR, S_IWUSR, S_IXUSR, pStat); } else if (is_in_process_grouplist(file_stat.st_gid)) { set_file_access_rights(file_stat, S_IRGRP, S_IWGRP, S_IXGRP, pStat); } else { set_file_access_rights(file_stat, S_IROTH, S_IWOTH, S_IXOTH, pStat); } } inline void set_file_hidden_status(const rtl::OUString& file_path, oslFileStatus* pStat) { pStat->uAttributes = osl::systemPathIsHiddenFileOrDirectoryEntry(file_path) ? osl_File_Attribute_Hidden : 0; pStat->uValidFields |= osl_FileStatus_Mask_Attributes; } /* the set_file_access_rights must be called after set_file_hidden_status(...) and set_file_access_mask(...) because of the hack in set_file_access_rights(...) */ inline void set_file_attributes( const rtl::OUString& file_path, const struct stat& file_stat, const sal_uInt32 uFieldMask, oslFileStatus* pStat) { set_file_hidden_status(file_path, pStat); set_file_access_mask(file_stat, pStat); // we set the file access rights only on demand // because it's potentially expensive if (uFieldMask & osl_FileStatus_Mask_Attributes) set_file_access_rights(file_stat, pStat); } inline void set_file_access_time(const struct stat& file_stat, oslFileStatus* pStat) { pStat->aAccessTime.Seconds = file_stat.st_atime; pStat->aAccessTime.Nanosec = 0; pStat->uValidFields |= osl_FileStatus_Mask_AccessTime; } inline void set_file_modify_time(const struct stat& file_stat, oslFileStatus* pStat) { pStat->aModifyTime.Seconds = file_stat.st_mtime; pStat->aModifyTime.Nanosec = 0; pStat->uValidFields |= osl_FileStatus_Mask_ModifyTime; } inline void set_file_size(const struct stat& file_stat, oslFileStatus* pStat) { if (S_ISREG(file_stat.st_mode)) { pStat->uFileSize = file_stat.st_size; pStat->uValidFields |= osl_FileStatus_Mask_FileSize; } } /* we only need to call stat or lstat if one of the following flags is set */ inline bool is_stat_call_necessary(sal_uInt32 field_mask) { return ((field_mask & osl_FileStatus_Mask_Type) || (field_mask & osl_FileStatus_Mask_Attributes) || (field_mask & osl_FileStatus_Mask_CreationTime) || (field_mask & osl_FileStatus_Mask_AccessTime) || (field_mask & osl_FileStatus_Mask_ModifyTime) || (field_mask & osl_FileStatus_Mask_FileSize) || (field_mask & osl_FileStatus_Mask_LinkTargetURL) || (field_mask & osl_FileStatus_Mask_Validate)); } inline oslFileError set_link_target_url(const rtl::OUString& file_path, oslFileStatus* pStat) { rtl::OUString link_target; if (!osl::realpath(file_path, link_target)) return oslTranslateFileError(OSL_FET_ERROR, errno); oslFileError osl_error = osl_getFileURLFromSystemPath(link_target.pData, &pStat->ustrLinkTargetURL); if (osl_error != osl_File_E_None) return osl_error; pStat->uValidFields |= osl_FileStatus_Mask_LinkTargetURL; return osl_File_E_None; } inline oslFileError setup_osl_getFileStatus(oslDirectoryItem Item, oslFileStatus* pStat, rtl::OUString& file_path) { if ((NULL == Item) || (NULL == pStat)) return osl_File_E_INVAL; file_path = rtl::OUString(reinterpret_cast<rtl_uString*>(Item)); OSL_ASSERT(file_path.getLength() > 0); if (file_path.getLength() <= 0) return osl_File_E_INVAL; pStat->uValidFields = 0; return osl_File_E_None; } } // end namespace private /**************************************************************************** * osl_getFileStatus ****************************************************************************/ oslFileError SAL_CALL osl_getFileStatus(oslDirectoryItem Item, oslFileStatus* pStat, sal_uInt32 uFieldMask) { rtl::OUString file_path; oslFileError osl_error = setup_osl_getFileStatus(Item, pStat, file_path); if (osl_File_E_None != osl_error) return osl_error; #if defined(__GNUC__) && (__GNUC__ < 3) struct ::stat file_stat; #else struct stat file_stat; #endif if (is_stat_call_necessary(uFieldMask) && (0 != osl::lstat(file_path, file_stat))) return oslTranslateFileError(OSL_FET_ERROR, errno); if (is_stat_call_necessary(uFieldMask)) { // we set all these attributes because it's cheap set_file_type(file_stat, pStat); set_file_access_time(file_stat, pStat); set_file_modify_time(file_stat, pStat); set_file_size(file_stat, pStat); set_file_attributes(file_path, file_stat, uFieldMask, pStat); // file exists semantic of osl_FileStatus_Mask_Validate if ((uFieldMask & osl_FileStatus_Mask_LinkTargetURL) && S_ISLNK(file_stat.st_mode)) { osl_error = set_link_target_url(file_path, pStat); if (osl_error != osl_File_E_None) return osl_error; } } if (uFieldMask & osl_FileStatus_Mask_FileURL) { if ((osl_error = osl_getFileURLFromSystemPath(file_path.pData, &pStat->ustrFileURL)) != osl_File_E_None) return osl_error; pStat->uValidFields |= osl_FileStatus_Mask_FileURL; } if (uFieldMask & osl_FileStatus_Mask_FileName) { osl_systemPathGetFileNameOrLastDirectoryPart(file_path.pData, &pStat->ustrFileName); pStat->uValidFields |= osl_FileStatus_Mask_FileName; } return osl_File_E_None; } <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ /* Coverage_Tree implements a permutation coverage. Coverage reaches * 1.0 when all permutations of any n subsequent actions have been * executed. n is given as a parameter. */ #ifndef __coverage_tree_hh__ #define __coverage_tree_hh__ #include "coverage.hh" #include <map> #include <list> class Coverage_Tree: public Coverage { public: Coverage_Tree(Log& l, std::string params); virtual void push(); virtual void pop(); virtual bool execute(int action); virtual float getCoverage(); virtual int fitness(int* actions,int n, float* fitness); void set_max_depth(std::string&s); virtual void set_model(Model* _model); protected: void precalc(); int max_depth; /* The data structure root_node is the root of the tree where each node represents an executed action, and contains a map of actions executed after it. exec points to nodes that need to be updated on next execute(). Example how data structure evolves when two actions are executed with depth == 3: 0. Initial state: exec = {0 -> root_node} root_node .action = 0 .nodes = {} 1. Add action 42: exec = {0 -> root_node, 1 -> node_1} root_node .action = 0 .nodes = {42 -> node_1} node_1 .action = 42 .nodes = {} 2. Add action 53: exec = {0 -> root_node, 1 -> node_2, 2 -> node_1} root_node .action = 0 .nodes = {42 -> node_1, 53 -> node_2} node_1 .action = 42 .nodes = {53 -> node_3} node_2 .action = 53 .nodes = {} node_3 .action = 53 .nodes = {} */ struct node; struct node { int action; std::map<int,struct node*> nodes; }; int push_depth; std::list<std::list<std::pair<struct node*, int> > > push_restore; struct node root_node; long node_count; long max_count; std::map<int,struct node*> exec; void print_tree(struct node* node,int depth); }; #endif <commit_msg>push/pop exec structure also<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ /* Coverage_Tree implements a permutation coverage. Coverage reaches * 1.0 when all permutations of any n subsequent actions have been * executed. n is given as a parameter. */ #ifndef __coverage_tree_hh__ #define __coverage_tree_hh__ #include "coverage.hh" #include <map> #include <list> class Coverage_Tree: public Coverage { public: Coverage_Tree(Log& l, std::string params); virtual void push(); virtual void pop(); virtual bool execute(int action); virtual float getCoverage(); virtual int fitness(int* actions,int n, float* fitness); void set_max_depth(std::string&s); virtual void set_model(Model* _model); protected: void precalc(); int max_depth; /* The data structure root_node is the root of the tree where each node represents an executed action, and contains a map of actions executed after it. exec points to nodes that need to be updated on next execute(). Example how data structure evolves when two actions are executed with depth == 3: 0. Initial state: exec = {0 -> root_node} root_node .action = 0 .nodes = {} 1. Add action 42: exec = {0 -> root_node, 1 -> node_1} root_node .action = 0 .nodes = {42 -> node_1} node_1 .action = 42 .nodes = {} 2. Add action 53: exec = {0 -> root_node, 1 -> node_2, 2 -> node_1} root_node .action = 0 .nodes = {42 -> node_1, 53 -> node_2} node_1 .action = 42 .nodes = {53 -> node_3} node_2 .action = 53 .nodes = {} node_3 .action = 53 .nodes = {} */ struct node; struct node { int action; std::map<int,struct node*> nodes; }; int push_depth; std::list<std::list<std::pair<struct node*, int> > > push_restore; std::list<std::map<int,struct node*> > exec_restore; struct node root_node; long node_count; long max_count; std::map<int,struct node*> exec; void print_tree(struct node* node,int depth); }; #endif <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_ABSTRACT_CHANNEL_HPP #define CAF_ABSTRACT_CHANNEL_HPP #include <atomic> #include "caf/fwd.hpp" #include "caf/node_id.hpp" #include "caf/message_id.hpp" #include "caf/ref_counted.hpp" namespace caf { /** * Interface for all message receivers. * This interface describes an * entity that can receive messages and is implemented by {@link actor} * and {@link group}. */ class abstract_channel : public ref_counted { public: friend class abstract_actor; friend class abstract_group; virtual ~abstract_channel(); /** * Enqueues a new message to the channel. */ virtual void enqueue(const actor_addr& sender, message_id mid, message content, execution_unit* host) = 0; /** * Enqueues a new message wrapped in a `mailbox_element` to the channel. * This variant is used by actors whenever it is possible to allocate * mailbox element and message on the same memory block and is thus * more efficient. Non-actors use the default implementation which simply * calls the pure virtual version. */ virtual void enqueue(mailbox_element_ptr what, execution_unit* host); /** * Returns the ID of the node this actor is running on. */ inline node_id node() const { return m_node; } /** * Returns true if {@link node_ptr} returns */ bool is_remote() const; static constexpr int is_abstract_actor_flag = 0x100000; static constexpr int is_abstract_group_flag = 0x200000; inline bool is_abstract_actor() const { return flags() & static_cast<int>(is_abstract_actor_flag); } inline bool is_abstract_group() const { return flags() & static_cast<int>(is_abstract_group_flag); } protected: // note: *both* operations use relaxed memory order, this is because // only the actor itself is granted write access while all access // from other actors or threads is always read-only; further, only // flags that are considered constant after an actor has launched are // read by others, i.e., there is no acquire/release semantic between // setting and reading flags inline int flags() const { return m_flags.load(std::memory_order_relaxed); } inline void flags(int new_value) { m_flags.store(new_value, std::memory_order_relaxed); } private: // can only be called from abstract_actor and abstract_group abstract_channel(int init_flags); abstract_channel(int init_flags, node_id nid); /* * Accumulates several state and type flags. Subtypes may use only the * first 20 bits, i.e., the bitmask 0xFFF00000 is reserved for * channel-related flags. */ std::atomic<int> m_flags; // identifies the node of this channel node_id m_node; }; /** * A smart pointer to an abstract channel. * @relates abstract_channel_ptr */ using abstract_channel_ptr = intrusive_ptr<abstract_channel>; } // namespace caf #endif // CAF_ABSTRACT_CHANNEL_HPP <commit_msg>Fix static cast in `abstract_channel`<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_ABSTRACT_CHANNEL_HPP #define CAF_ABSTRACT_CHANNEL_HPP #include <atomic> #include "caf/fwd.hpp" #include "caf/node_id.hpp" #include "caf/message_id.hpp" #include "caf/ref_counted.hpp" namespace caf { /** * Interface for all message receivers. * This interface describes an * entity that can receive messages and is implemented by {@link actor} * and {@link group}. */ class abstract_channel : public ref_counted { public: friend class abstract_actor; friend class abstract_group; virtual ~abstract_channel(); /** * Enqueues a new message to the channel. */ virtual void enqueue(const actor_addr& sender, message_id mid, message content, execution_unit* host) = 0; /** * Enqueues a new message wrapped in a `mailbox_element` to the channel. * This variant is used by actors whenever it is possible to allocate * mailbox element and message on the same memory block and is thus * more efficient. Non-actors use the default implementation which simply * calls the pure virtual version. */ virtual void enqueue(mailbox_element_ptr what, execution_unit* host); /** * Returns the ID of the node this actor is running on. */ inline node_id node() const { return m_node; } /** * Returns true if {@link node_ptr} returns */ bool is_remote() const; static constexpr int is_abstract_actor_flag = 0x100000; static constexpr int is_abstract_group_flag = 0x200000; inline bool is_abstract_actor() const { return static_cast<bool>(flags() & is_abstract_actor_flag); } inline bool is_abstract_group() const { return static_cast<bool>(flags() & is_abstract_group_flag); } protected: // note: *both* operations use relaxed memory order, this is because // only the actor itself is granted write access while all access // from other actors or threads is always read-only; further, only // flags that are considered constant after an actor has launched are // read by others, i.e., there is no acquire/release semantic between // setting and reading flags inline int flags() const { return m_flags.load(std::memory_order_relaxed); } inline void flags(int new_value) { m_flags.store(new_value, std::memory_order_relaxed); } private: // can only be called from abstract_actor and abstract_group abstract_channel(int init_flags); abstract_channel(int init_flags, node_id nid); /* * Accumulates several state and type flags. Subtypes may use only the * first 20 bits, i.e., the bitmask 0xFFF00000 is reserved for * channel-related flags. */ std::atomic<int> m_flags; // identifies the node of this channel node_id m_node; }; /** * A smart pointer to an abstract channel. * @relates abstract_channel_ptr */ using abstract_channel_ptr = intrusive_ptr<abstract_channel>; } // namespace caf #endif // CAF_ABSTRACT_CHANNEL_HPP <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/utils/imageProcs/p9_scan_compression.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __P9_SCAN_COMPRESSION_H__ #define __P9_SCAN_COMPRESSION_H__ /// This header declares and documents the entry points defined in /// p9_scan_compression.C. Some constants are also required by the scan /// decompression HOMER assembly procedures. #ifndef __ASSEMBLER__ #include <stdint.h> /// Compressed Scan Chain Data Structure Format /// /// The compressed scan ring data structure must be 8-byte aligned in /// memory. The container data structure consists of a header /// followed by an arbitrary number of 8 byte doublewords containing the /// compressed scan data. Images are always stored and processed in /// big-endian byte order. The header format is common across all /// decompression algorithms. /// /// ATTENTION: /// The RS4v2 CompressedScanData had a 4 byte magic value with 0x34 ("4") /// within its third byte, which is at the same byte position as iv_version /// now. Users of CompressedScanData which use the magic value to detect /// a ring data structure won't be able to distingish old and new /// CompressedScanData for iv_version being 0x34. In the very unlikely case /// that we would have that many versions of ComprossedScanData, it is /// strongly suggested to simply skip 0x34 as version number. /// /// Bytes - Content /// /// 0:1 - A 16-bit "magic number" that identifies and validates the /// compression algorithm used to compress the data ("RS"). /// /// 2 - An 8-bit version number (3 for the time being). /// /// 3 - An 8-bit type field distinguishing different scan data types /// (0 for non-CMSK, 1 for CMSK). /// /// 4:5 - The 16-bit size of the compressed scan data with /// this header in \e bytes. This is not the exact length of actual scan data /// in bits, but the number of bytes used by the RS4 encoding to store those /// compressed scan bits. /// /// 6:7 - The 16-bit ring ID uniquely identifying the ring. /// /// 8:11 - scan scom register value typedef struct { uint16_t iv_magic; uint8_t iv_version; uint8_t iv_type; uint16_t iv_size; uint16_t iv_ringId; uint32_t iv_scanAddr; } CompressedScanData; /// Endian-translate a CompressedScanData structure /// /// \param o_data A pointer to a CompressedScanData structure to receive the /// endian-translated form of \a i_data. /// /// \param i_data A pointer to the original CompressedScanData structure. /// /// This API performs an endian-converting copy of a CompressedScanData /// structure. This copy is guaranteed to be done in such a way that \a i_data /// and \a o_data may be the same pointer for in-place conversion. Due to the /// symmetry of reverse, translating a structure twice is always guaranteed to /// return the origial structure to its original byte order. void compressed_scan_data_translate(CompressedScanData* o_data, CompressedScanData* i_data); /// Compress a scan string using the RS4 compression algorithm /// /// \param[in,out] io_rs4 This is a pointer to a memory area which must be /// large enough to hold the worst-case result of compressing \a i_data_str /// and \a i_care_str (see below). Note that the CompressedScanData is /// always created in big-endian format, however the caller can use /// compresed_scan_data_translate() to create a copy of the header in /// host format. /// /// \param[in] i_size The size of the buffer pointed to by \a io_rs4. /// /// \param[in] i_data_str The string to compress. Scan data to compress is /// left-justified in this input string. /// /// \param[in] i_care_str The care mask that identifies which bits in the /// i_data_str that need to be scanned (written). String is left-justified. /// /// \param[in] i_length The length of the input string in \e bits. It is /// assumed the \a i_string contains at least (\a i_length + 7) / 8 bytes. /// /// \param[in] i_scanAddr The 32-bit scan address. /// /// \param[in] i_ringId The ring ID that uniquely identifies the ring name of /// a repair ring. (See p9_ring_id.h for more info.) /// /// This API is required for integration with PHYP which does not support /// malloc(). Applications in environments supporting malloc() can use /// rs4_compress() instead. /// /// We always require the worst-case amount of memory including the header and /// any rounding required to guarantee that the data size is a multiple of 8 /// bytes. The final image size is also rounded up to a multiple of 8 bytes. /// If the \a io_size is less than this amount (based on \a i_length) the /// call will fail. /// /// \returns See \ref scan_compression_codes int _rs4_compress(CompressedScanData* io_rs4, const uint32_t i_size, const uint8_t* i_data_str, const uint8_t* i_care_str, const uint32_t i_length, const uint32_t i_scanAddr, const uint16_t i_ringId); /// Compress a scan string using the RS4 compression algorithm /// /// \param[out] o_rs4 This algorithm uses malloc() to allocate memory for the /// compressed data, and returns a pointer to this memory in \a o_rs4. After /// the call this memory is owned by the caller who is responsible for /// free()-ing the data area once it is no longer required. Note that the /// CompressedScanData is always created in big-endian format, however the /// caller can use compresed_scan_data_translate() to create a copy of the /// header in host format. /// /// \param[in] i_data_str The string to compress. Scan data to compress is /// left-justified in this input string. /// /// \param[in] i_care_str The care mask that identifies which bits in the /// i_data_str that need to be scanned (written). String is left-justified. /// /// \param[in] i_length The length of the input string in \e bits. It is /// assumed the \a i_string contains at least (\a i_length + 7) / 8 bytes. /// /// \param[in] i_scanAddr The 32-bit scan address. /// /// \param[in] i_ringId The ring ID that uniquely identifies the ring name of /// a repair ring. (See p9_ring_id.c for more info.) /// /// \returns See \ref scan_compression_codes int rs4_compress(CompressedScanData** o_rs4, const uint8_t* i_data_str, const uint8_t* i_care_str, const uint32_t i_length, const uint32_t i_scanAddr, const uint8_t i_ringId); /// Decompress a scan string compressed using the RS4 compression algorithm /// /// \param[in,out] io_data_str A caller-supplied data area to contain the /// decompressed string. The \a i_stringSize must be large enough to contain /// the decompressed string, which is the size of the original string in bits /// rounded up to the nearest byte. /// /// \param[in,out] io_care_str A caller-supplied data area to contain the /// decompressed care mask. The \a i_stringSize must be large enough to contain /// the decompressed care mask, which is the size of the original string in /// bits rounded up to the nearest byte. /// /// \param[in] i_size The size in \e bytes of \a io_data_str and \a io_care_str. /// /// \param[out] o_length The length of the decompressed string in \e bits. /// /// \param[in] i_rs4 A pointer to the CompressedScanData header + data to be /// decompressed. /// /// This API is required for integration with PHYP which does not support /// malloc(). Applications in environments supporting malloc() can use /// rs4_decompress() instead. /// /// \returns See \ref scan_compression_codes int _rs4_decompress(uint8_t* io_data_str, uint8_t* io_care_str, uint32_t i_size, uint32_t* o_length, const CompressedScanData* i_rs4); /// Decompress a scan string compressed using the RS4 compression algorithm /// /// \param[out] o_data_str The API malloc()-s this data area to contain the /// decompressed string. After this call the caller owns \a o_data_str and is /// responsible for free()-ing this data area once it is no longer required. /// /// \param[out] o_care_str The API malloc()-s this data area to contain the /// decompressed care mask. After this call the caller owns \a o_care_str and /// is responsible for free()-ing this data area once it is no longer required. /// /// \param[out] o_length The length of the decompressed string and care mask /// in \e bits. The caller may assume that \a o_data_str and o_care_str each /// contain at least (\a o_length + 7) / 8 \e bytes. /// /// \param[in] i_rs4 A pointer to the CompressedScanData header and data to be /// decompressed. /// /// \returns See \ref scan_compression_codes int rs4_decompress(uint8_t** o_data_str, uint8_t** o_care_str, uint32_t* o_length, const CompressedScanData* i_rs4); /// Determine if an RS4 compressed scan string is all 0 /// /// \param[in] i_data A pointer to the CompressedScanData header + data to be /// /// \param[out] o_redundant Set to 1 if the RS4 string is the compressed form /// of a scan string that is all 0; Otherwise set to 0. /// /// \returns See \ref scan _compression_code int rs4_redundant(const CompressedScanData* i_data, int* o_redundant); /// Check for CMSK ring in RS4 /// /// \param[in] i_rs4 A pointer to the RS4 CompressedScanData [header + data] /// /// \returns 1 if CMSK ring found, 0 otherwise int rs4_is_cmsk(CompressedScanData* i_rs4); /// Embed CMSK ring into an RS4 ring /// /// \param[inout] io_rs4 A pointer to the CompressedScanData [header + data] /// /// \param[in] i_rs4_cmsk A pointer to the cmsk CompressedScanData header + data to be embedded /// /// \returns See \ref scan_compression_codes int rs4_embed_cmsk(CompressedScanData** io_rs4, CompressedScanData* i_rs4_cmsk); /// Extract Stump & CMSK rings from an RS4 ring /// /// \param[in] i_rs4 A pointer to the CompressedScanData [header + data] /// /// \param[inout] i_rs4_stump A pointer to the Stump CompressedScanData [header + data] /// /// \param[inout] i_rs4_cmsk A pointer to the Cmsk CompressedScanData [header + data] /// /// \returns See \ref scan_compression_codes int rs4_extract_cmsk(CompressedScanData* i_rs4, CompressedScanData** io_rs4_stump, CompressedScanData** io_rs4_cmsk); #endif // __ASSEMBLER__ // This function prints out the raw decompressed ring content in the same // format that it appears as in EKB's ifCompiler generated raw ring // files, i.e. *.bin.srd (DATA) and *.bin.srd.bitsModified (CARE). void print_raw_ring( uint8_t* data, uint32_t bits); /// \defgroup scan_compression_magic Scan Compression Magic Numbers /// /// @ { /// RS4 Magic #define RS4_MAGIC 0x5253 /* "RS" */ /// @} /// \defgroup scan_compression_version_type version and type accessors /// /// @{ /// The current version of the CompressedScanData structure /// /// This constant is required to be a #define to guarantee consistency between /// the header format and compiled code. #define RS4_VERSION 3 /// Scan data types #define RS4_SCAN_DATA_TYPE_CMSK 1 #define RS4_SCAN_DATA_TYPE_NON_CMSK 0 /// @} /// \defgroup scan_compression_codes Scan Compression Return Codes /// /// @{ /// Normal return code #define SCAN_COMPRESSION_OK (uint8_t)0 /// The (de)compression algorithm could not allocate enough memory for the /// (de)compression. #define SCAN_COMPRESSION_NO_MEMORY (uint8_t)1 /// Magic number mismatch on scan decompression #define SCAN_DECOMPRESSION_MAGIC_ERROR (uint8_t)2 /// Decompression size error /// /// Decompression produced a string of a size different than indicated in the /// header, indicating either a bug or data corruption. Note that the entire /// application should be considered corrupted if this error occurs since it /// may not be discovered until after the decompression buffer is /// overrun. This error may also be returned by rs4_redundant() in the event /// of inconsistencies in the compressed string. #define SCAN_DECOMPRESSION_SIZE_ERROR (uint8_t)3 /// A buffer would overflow /// /// Either the caller-supplied memory buffer to _rs4_decompress() was too /// small to contain the decompressed string, or a caller-supplied buffer to /// _rs4_compress() was not large enough to hold the worst-case compressed /// string. #define SCAN_COMPRESSION_BUFFER_OVERFLOW (uint8_t)4 /// Inconsistent input data /// /// 1 in data is masked by 0 in care mask #define SCAN_COMPRESSION_INPUT_ERROR 5 /// Invalid transition in state machine #define SCAN_COMPRESSION_STATE_ERROR 6 /// wrong compression version #define SCAN_COMPRESSION_VERSION_ERROR 7 /// @} #endif // __P9_SCAN_COMPRESSION_H__ <commit_msg>GPTR/Overlays stage-2 support<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/utils/imageProcs/p9_scan_compression.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __P9_SCAN_COMPRESSION_H__ #define __P9_SCAN_COMPRESSION_H__ /// This header declares and documents the entry points defined in /// p9_scan_compression.C. Some constants are also required by the scan /// decompression HOMER assembly procedures. #ifndef __ASSEMBLER__ #include <stdint.h> /// Compressed Scan Chain Data Structure Format /// /// The compressed scan ring data structure must be 8-byte aligned in /// memory. The container data structure consists of a header /// followed by an arbitrary number of 8 byte doublewords containing the /// compressed scan data. Images are always stored and processed in /// big-endian byte order. The header format is common across all /// decompression algorithms. /// /// ATTENTION: /// The RS4v2 CompressedScanData had a 4 byte magic value with 0x34 ("4") /// within its third byte, which is at the same byte position as iv_version /// now. Users of CompressedScanData which use the magic value to detect /// a ring data structure won't be able to distingish old and new /// CompressedScanData for iv_version being 0x34. In the very unlikely case /// that we would have that many versions of ComprossedScanData, it is /// strongly suggested to simply skip 0x34 as version number. /// /// Bytes - Content /// /// 0:1 - A 16-bit "magic number" that identifies and validates the /// compression algorithm used to compress the data ("RS"). /// /// 2 - An 8-bit version number (3 for the time being). /// /// 3 - An 8-bit type field distinguishing different scan data types /// (0 for non-CMSK, 1 for CMSK). /// /// 4:5 - The 16-bit size of the compressed scan data with /// this header in \e bytes. This is not the exact length of actual scan data /// in bits, but the number of bytes used by the RS4 encoding to store those /// compressed scan bits. /// /// 6:7 - The 16-bit ring ID uniquely identifying the ring. /// /// 8:11 - scan scom register value typedef struct { uint16_t iv_magic; uint8_t iv_version; uint8_t iv_type; uint16_t iv_size; uint16_t iv_ringId; uint32_t iv_scanAddr; } CompressedScanData; /// Endian-translate a CompressedScanData structure /// /// \param o_data A pointer to a CompressedScanData structure to receive the /// endian-translated form of \a i_data. /// /// \param i_data A pointer to the original CompressedScanData structure. /// /// This API performs an endian-converting copy of a CompressedScanData /// structure. This copy is guaranteed to be done in such a way that \a i_data /// and \a o_data may be the same pointer for in-place conversion. Due to the /// symmetry of reverse, translating a structure twice is always guaranteed to /// return the origial structure to its original byte order. void compressed_scan_data_translate(CompressedScanData* o_data, CompressedScanData* i_data); /// Compress a scan string using the RS4 compression algorithm /// /// \param[in,out] io_rs4 This is a pointer to a memory area which must be /// large enough to hold the worst-case result of compressing \a i_data_str /// and \a i_care_str (see below). Note that the CompressedScanData is /// always created in big-endian format, however the caller can use /// compresed_scan_data_translate() to create a copy of the header in /// host format. /// /// \param[in] i_size The size of the buffer pointed to by \a io_rs4. /// /// \param[in] i_data_str The string to compress. Scan data to compress is /// left-justified in this input string. /// /// \param[in] i_care_str The care mask that identifies which bits in the /// i_data_str that need to be scanned (written). String is left-justified. /// /// \param[in] i_length The length of the input string in \e bits. It is /// assumed the \a i_string contains at least (\a i_length + 7) / 8 bytes. /// /// \param[in] i_scanAddr The 32-bit scan address. /// /// \param[in] i_ringId The ring ID that uniquely identifies the ring name of /// a repair ring. (See p9_ring_id.h for more info.) /// /// This API is required for integration with PHYP which does not support /// malloc(). Applications in environments supporting malloc() can use /// rs4_compress() instead. /// /// We always require the worst-case amount of memory including the header and /// any rounding required to guarantee that the data size is a multiple of 8 /// bytes. The final image size is also rounded up to a multiple of 8 bytes. /// If the \a io_size is less than this amount (based on \a i_length) the /// call will fail. /// /// \returns See \ref scan_compression_codes int _rs4_compress(CompressedScanData* io_rs4, const uint32_t i_size, const uint8_t* i_data_str, const uint8_t* i_care_str, const uint32_t i_length, const uint32_t i_scanAddr, const uint16_t i_ringId); /// Compress a scan string using the RS4 compression algorithm /// /// \param[out] o_rs4 This algorithm uses malloc() to allocate memory for the /// compressed data, and returns a pointer to this memory in \a o_rs4. After /// the call this memory is owned by the caller who is responsible for /// free()-ing the data area once it is no longer required. Note that the /// CompressedScanData is always created in big-endian format, however the /// caller can use compresed_scan_data_translate() to create a copy of the /// header in host format. /// /// \param[in] i_data_str The string to compress. Scan data to compress is /// left-justified in this input string. /// /// \param[in] i_care_str The care mask that identifies which bits in the /// i_data_str that need to be scanned (written). String is left-justified. /// /// \param[in] i_length The length of the input string in \e bits. It is /// assumed the \a i_string contains at least (\a i_length + 7) / 8 bytes. /// /// \param[in] i_scanAddr The 32-bit scan address. /// /// \param[in] i_ringId The ring ID that uniquely identifies the ring name of /// a repair ring. (See p9_ring_id.c for more info.) /// /// \returns See \ref scan_compression_codes int rs4_compress(CompressedScanData** o_rs4, const uint8_t* i_data_str, const uint8_t* i_care_str, const uint32_t i_length, const uint32_t i_scanAddr, const uint8_t i_ringId); /// Decompress a scan string compressed using the RS4 compression algorithm /// /// \param[in,out] io_data_str A caller-supplied data area to contain the /// decompressed string. The \a i_stringSize must be large enough to contain /// the decompressed string, which is the size of the original string in bits /// rounded up to the nearest byte. /// /// \param[in,out] io_care_str A caller-supplied data area to contain the /// decompressed care mask. The \a i_stringSize must be large enough to contain /// the decompressed care mask, which is the size of the original string in /// bits rounded up to the nearest byte. /// /// \param[in] i_size The size in \e bytes of \a io_data_str and \a io_care_str. /// /// \param[out] o_length The length of the decompressed string in \e bits. /// /// \param[in] i_rs4 A pointer to the CompressedScanData header + data to be /// decompressed. /// /// This API is required for integration with PHYP which does not support /// malloc(). Applications in environments supporting malloc() can use /// rs4_decompress() instead. /// /// \returns See \ref scan_compression_codes int _rs4_decompress(uint8_t* io_data_str, uint8_t* io_care_str, uint32_t i_size, uint32_t* o_length, const CompressedScanData* i_rs4); /// Decompress a scan string compressed using the RS4 compression algorithm /// /// \param[out] o_data_str The API malloc()-s this data area to contain the /// decompressed string. After this call the caller owns \a o_data_str and is /// responsible for free()-ing this data area once it is no longer required. /// /// \param[out] o_care_str The API malloc()-s this data area to contain the /// decompressed care mask. After this call the caller owns \a o_care_str and /// is responsible for free()-ing this data area once it is no longer required. /// /// \param[out] o_length The length of the decompressed string and care mask /// in \e bits. The caller may assume that \a o_data_str and o_care_str each /// contain at least (\a o_length + 7) / 8 \e bytes. /// /// \param[in] i_rs4 A pointer to the CompressedScanData header and data to be /// decompressed. /// /// \returns See \ref scan_compression_codes int rs4_decompress(uint8_t** o_data_str, uint8_t** o_care_str, uint32_t* o_length, const CompressedScanData* i_rs4); /// Determine if an RS4 compressed scan string is all 0 /// /// \param[in] i_data A pointer to the CompressedScanData header + data to be /// /// \param[out] o_redundant Set to 1 if the RS4 string is the compressed form /// of a scan string that is all 0; Otherwise set to 0. /// /// \returns See \ref scan _compression_code int rs4_redundant(const CompressedScanData* i_data, int* o_redundant); /// Check for CMSK ring in RS4 /// /// \param[in] i_rs4 A pointer to the RS4 CompressedScanData [header + data] /// /// \returns 1 if CMSK ring found, 0 otherwise int rs4_is_cmsk(CompressedScanData* i_rs4); /// Embed CMSK ring into an RS4 ring /// /// \param[inout] io_rs4 A pointer to the CompressedScanData [header + data] /// /// \param[in] i_rs4_cmsk A pointer to the cmsk CompressedScanData header + data to be embedded /// /// \returns See \ref scan_compression_codes int rs4_embed_cmsk(CompressedScanData** io_rs4, CompressedScanData* i_rs4_cmsk); /// Extract Stump & CMSK rings from an RS4 ring /// /// \param[in] i_rs4 A pointer to the CompressedScanData [header + data] /// /// \param[inout] i_rs4_stump A pointer to the Stump CompressedScanData [header + data] /// /// \param[inout] i_rs4_cmsk A pointer to the Cmsk CompressedScanData [header + data] /// /// \returns See \ref scan_compression_codes int rs4_extract_cmsk(CompressedScanData* i_rs4, CompressedScanData** io_rs4_stump, CompressedScanData** io_rs4_cmsk); #endif // __ASSEMBLER__ /// Function: print_raw_ring() /// @brief: Prints out the raw decompressed RS4 ring content. /// /// Desc.:It displays the raw decompressed ring content in the same /// format that it appears as in EKB's ifCompiler generated raw ring /// files, i.e. *.bin.srd (DATA) and *.bin.srd.bitsModified (CARE). /// /// \param[in] data Its Data (*.bin.srd) or Care (*.bin.srd.bitsModified) /// \param[in] bits Length of raw ring in bits void print_raw_ring( uint8_t* data, uint32_t bits); /// \defgroup scan_compression_magic Scan Compression Magic Numbers /// /// @ { /// RS4 Magic #define RS4_MAGIC 0x5253 /* "RS" */ /// @} /// \defgroup scan_compression_version_type version and type accessors /// /// @{ /// The current version of the CompressedScanData structure /// /// This constant is required to be a #define to guarantee consistency between /// the header format and compiled code. #define RS4_VERSION 3 /// Scan data types #define RS4_SCAN_DATA_TYPE_CMSK 1 #define RS4_SCAN_DATA_TYPE_NON_CMSK 0 /// @} /// \defgroup scan_compression_codes Scan Compression Return Codes /// /// @{ /// Normal return code #define SCAN_COMPRESSION_OK (uint8_t)0 /// The (de)compression algorithm could not allocate enough memory for the /// (de)compression. #define SCAN_COMPRESSION_NO_MEMORY (uint8_t)1 /// Magic number mismatch on scan decompression #define SCAN_DECOMPRESSION_MAGIC_ERROR (uint8_t)2 /// Decompression size error /// /// Decompression produced a string of a size different than indicated in the /// header, indicating either a bug or data corruption. Note that the entire /// application should be considered corrupted if this error occurs since it /// may not be discovered until after the decompression buffer is /// overrun. This error may also be returned by rs4_redundant() in the event /// of inconsistencies in the compressed string. #define SCAN_DECOMPRESSION_SIZE_ERROR (uint8_t)3 /// A buffer would overflow /// /// Either the caller-supplied memory buffer to _rs4_decompress() was too /// small to contain the decompressed string, or a caller-supplied buffer to /// _rs4_compress() was not large enough to hold the worst-case compressed /// string. #define SCAN_COMPRESSION_BUFFER_OVERFLOW (uint8_t)4 /// Inconsistent input data /// /// 1 in data is masked by 0 in care mask #define SCAN_COMPRESSION_INPUT_ERROR 5 /// Invalid transition in state machine #define SCAN_COMPRESSION_STATE_ERROR 6 /// wrong compression version #define SCAN_COMPRESSION_VERSION_ERROR 7 /// @} #endif // __P9_SCAN_COMPRESSION_H__ <|endoftext|>
<commit_before>// RUN: rm -rf %t // Test that only forward declarations are emitted for types dfined in modules. // Modules: // RUN: %clang_cc1 -x objective-c++ -std=c++11 -g -dwarf-ext-refs -fmodules \ // RUN: -fmodule-format=obj -fimplicit-module-maps -DMODULES \ // RUN: -fmodules-cache-path=%t %s -I %S/Inputs -I %t -emit-llvm -o %t-mod.ll // RUN: cat %t-mod.ll | FileCheck %s // PCH: // RUN: %clang_cc1 -x c++ -std=c++11 -fmodule-format=obj -emit-pch -I%S/Inputs \ // RUN: -o %t.pch %S/Inputs/DebugCXX.h // RUN: %clang_cc1 -std=c++11 -g -dwarf-ext-refs -fmodule-format=obj \ // RUN: -include-pch %t.pch %s -emit-llvm -o %t-pch.ll %s // RUN: cat %t-pch.ll | FileCheck %s #ifdef MODULES @import DebugCXX; #endif using DebugCXX::Struct; Struct s; DebugCXX::Enum e; DebugCXX::Template<long> implicitTemplate; DebugCXX::Template<int> explicitTemplate; DebugCXX::FloatInstatiation typedefTemplate; int Struct::static_member = -1; enum { e3 = -1 } conflicting_uid = e3; auto anon_enum = DebugCXX::e2; char _anchor = anon_enum + conflicting_uid; // CHECK: ![[ANON_ENUM:[0-9]+]] = !DICompositeType(tag: DW_TAG_enumeration_type // CHECK-SAME: scope: ![[MOD:[0-9]+]], // CHECK-SAME: {{.*}}line: 16, {{.*}}, elements: ![[EE:[0-9]+]]) // CHECK: ![[NS:.*]] = !DINamespace(name: "DebugCXX", scope: ![[MOD:[0-9]+]], // CHECK: ![[MOD]] = !DIModule(scope: null, name: {{.*}}DebugCXX // CHECK: ![[EE]] = !{![[E2:[0-9]+]]} // CHECK: ![[E2]] = !DIEnumerator(name: "e2", value: 50) // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Struct", // CHECK-SAME: scope: ![[NS]], // CHECK-SAME: flags: DIFlagFwdDecl, // CHECK-SAME: identifier: "_ZTSN8DebugCXX6StructE") // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum", // CHECK-SAME: scope: ![[NS]], // CHECK-SAME: flags: DIFlagFwdDecl, // CHECK-SAME: identifier: "_ZTSN8DebugCXX4EnumE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<int, DebugCXX::traits<int> >", // CHECK-SAME: scope: ![[NS]], // CHECK-SAME: flags: DIFlagFwdDecl, // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIiNS_6traitsIiEEEE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<float, DebugCXX::traits<float> >", // CHECK-SAME: scope: ![[NS]], // CHECK-SAME: flags: DIFlagFwdDecl, // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIfNS_6traitsIfEEEE") // CHECK: !DIDerivedType(tag: DW_TAG_member, name: "static_member", // CHECK-SAME: scope: !"_ZTSN8DebugCXX6StructE" // CHECK: !DIGlobalVariable(name: "anon_enum", {{.*}}, type: ![[ANON_ENUM]] // CHECK: !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: !0, entity: !"_ZTSN8DebugCXX6StructE", line: 21) <commit_msg>clang/test/Modules/ExtDebugInfo.cpp: Use [[@LINE]].<commit_after>// RUN: rm -rf %t // Test that only forward declarations are emitted for types dfined in modules. // Modules: // RUN: %clang_cc1 -x objective-c++ -std=c++11 -g -dwarf-ext-refs -fmodules \ // RUN: -fmodule-format=obj -fimplicit-module-maps -DMODULES \ // RUN: -fmodules-cache-path=%t %s -I %S/Inputs -I %t -emit-llvm -o %t-mod.ll // RUN: cat %t-mod.ll | FileCheck %s // PCH: // RUN: %clang_cc1 -x c++ -std=c++11 -fmodule-format=obj -emit-pch -I%S/Inputs \ // RUN: -o %t.pch %S/Inputs/DebugCXX.h // RUN: %clang_cc1 -std=c++11 -g -dwarf-ext-refs -fmodule-format=obj \ // RUN: -include-pch %t.pch %s -emit-llvm -o %t-pch.ll %s // RUN: cat %t-pch.ll | FileCheck %s #ifdef MODULES @import DebugCXX; #endif using DebugCXX::Struct; Struct s; DebugCXX::Enum e; DebugCXX::Template<long> implicitTemplate; DebugCXX::Template<int> explicitTemplate; DebugCXX::FloatInstatiation typedefTemplate; int Struct::static_member = -1; enum { e3 = -1 } conflicting_uid = e3; auto anon_enum = DebugCXX::e2; char _anchor = anon_enum + conflicting_uid; // CHECK: ![[ANON_ENUM:[0-9]+]] = !DICompositeType(tag: DW_TAG_enumeration_type // CHECK-SAME: scope: ![[MOD:[0-9]+]], // CHECK-SAME: {{.*}}line: 16, {{.*}}, elements: ![[EE:[0-9]+]]) // CHECK: ![[NS:.*]] = !DINamespace(name: "DebugCXX", scope: ![[MOD:[0-9]+]], // CHECK: ![[MOD]] = !DIModule(scope: null, name: {{.*}}DebugCXX // CHECK: ![[EE]] = !{![[E2:[0-9]+]]} // CHECK: ![[E2]] = !DIEnumerator(name: "e2", value: 50) // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Struct", // CHECK-SAME: scope: ![[NS]], // CHECK-SAME: flags: DIFlagFwdDecl, // CHECK-SAME: identifier: "_ZTSN8DebugCXX6StructE") // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum", // CHECK-SAME: scope: ![[NS]], // CHECK-SAME: flags: DIFlagFwdDecl, // CHECK-SAME: identifier: "_ZTSN8DebugCXX4EnumE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<int, DebugCXX::traits<int> >", // CHECK-SAME: scope: ![[NS]], // CHECK-SAME: flags: DIFlagFwdDecl, // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIiNS_6traitsIiEEEE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<float, DebugCXX::traits<float> >", // CHECK-SAME: scope: ![[NS]], // CHECK-SAME: flags: DIFlagFwdDecl, // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIfNS_6traitsIfEEEE") // CHECK: !DIDerivedType(tag: DW_TAG_member, name: "static_member", // CHECK-SAME: scope: !"_ZTSN8DebugCXX6StructE" // CHECK: !DIGlobalVariable(name: "anon_enum", {{.*}}, type: ![[ANON_ENUM]] // CHECK: !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: !0, entity: !"_ZTSN8DebugCXX6StructE", line: [[@LINE-53]]) <|endoftext|>
<commit_before>// Copyright (c) 2014 GitHub, Inc. All rights reserved. #include <string> #include <vector> #include "object_helper.h" namespace { #define DEFINE_NONE_PARAMETER_FUNC(name) \ NanScope(); \ Handle<Function> func; \ Handle<Object> data = args.Data()->ToObject(); \ if (!ObjectGet(data, name, &func)) \ return NanThrowError("Cannot find " name); \ Handle<Value> argv[] = { data->Get(NanSymbol("data")) }; \ Handle<Value> return_value = func->Call(args.This(), 1, argv) #define DEFINE_ONE_PARAMETER_FUNC(name, key) \ NanScope(); \ Handle<Function> func; \ Handle<Object> data = args.Data()->ToObject(); \ if (!ObjectGet(args.Data()->ToObject(), name, &func)) \ return NanThrowError("Cannot find " name); \ Handle<Value> argv[] = { key, data->Get(NanSymbol("data")) }; \ Handle<Value> return_value = func->Call(args.This(), 2, argv) #define DEFINE_TWO_PARAMETERS_FUNC(name, key, value) \ NanScope(); \ Handle<Function> func; \ Handle<Object> data = args.Data()->ToObject(); \ if (!ObjectGet(args.Data()->ToObject(), name, &func)) \ return NanThrowError("Cannot find " name); \ Handle<Value> argv[] = { key, value, data->Get(NanSymbol("data")) }; \ Handle<Value> return_value = func->Call(args.This(), 3, argv) NAN_INDEX_GETTER(CustomIndexGetter) { DEFINE_ONE_PARAMETER_FUNC("getter", Integer::New(index)); NanReturnValue(return_value); } NAN_INDEX_SETTER(CustomIndexSetter) { DEFINE_TWO_PARAMETERS_FUNC("setter", Integer::New(index), value); NanReturnValue(return_value); } NAN_INDEX_QUERY(CustomIndexQuery) { DEFINE_ONE_PARAMETER_FUNC("query", Integer::New(index)); NanReturnValue(return_value->ToInteger()); } NAN_INDEX_DELETER(CustomIndexDeleter) { DEFINE_ONE_PARAMETER_FUNC("deleter", Integer::New(index)); NanReturnValue(return_value->ToBoolean()); } NAN_INDEX_ENUMERATOR(CustomIndexEnumerator) { DEFINE_NONE_PARAMETER_FUNC("enumerator"); NanReturnValue(Handle<Array>::Cast(return_value)); } NAN_GETTER(CustomAccessorGetter) { DEFINE_ONE_PARAMETER_FUNC("getter", property); NanReturnValue(return_value); } NAN_SETTER(CustomAccessorSetter) { DEFINE_TWO_PARAMETERS_FUNC("setter", property, value); NanReturnValue(return_value); } NAN_METHOD(CustomFunctionCallback) { NanScope(); Handle<Function> constructor = Handle<Function>::Cast(args.Data()); std::vector<Handle<Value> > argv(args.Length()); for (size_t i = 0; i < argv.size(); ++i) argv[i] = args[i]; NanReturnValue(constructor->Call(args.This(), argv.size(), argv.data())); } bool SetObjectTemplate(Handle<ObjectTemplate> object_template, Handle<Object> options, std::string* error) { // accessor: [ { name: String, getter: Function, setter: Function } ] Handle<Array> accessor_array; if (ObjectGet(options, "accessor", &accessor_array)) { for (uint32_t i = 0; i < accessor_array->Length(); ++i) { Handle<Object> accessor = accessor_array->Get(i)->ToObject(); Handle<String> name; if (!ObjectGet(accessor, "name", &name)) { *error = "The 'name' is required when setting accessor"; return false; } if (!accessor->Has(NanSymbol("getter"))) { *error = "The 'getter' is required when setting accessor"; return false; } // The "setter" is optional. AccessorSetterCallback setter = NULL; if (accessor->Has(NanSymbol("setter"))) setter = CustomAccessorSetter; object_template->SetAccessor( name, CustomAccessorGetter, setter, accessor); } } // index: { getter: Function, setter: Function, query: Function, // deleter: Function, enumerator: Function } Handle<Object> index; if (ObjectGet(options, "index", &index)) { if (!index->Has(NanSymbol("getter"))) { *error = "The 'getter' is required when setting index"; return false; } IndexedPropertySetterCallback setter = NULL; if (index->Has(NanSymbol("setter"))) setter = CustomIndexSetter; IndexedPropertyQueryCallback query = NULL; if (index->Has(NanSymbol("query"))) query = CustomIndexQuery; IndexedPropertyDeleterCallback deleter = NULL; if (index->Has(NanSymbol("deleter"))) deleter = CustomIndexDeleter; IndexedPropertyEnumeratorCallback enumerator = NULL; if (index->Has(NanSymbol("enumerator"))) enumerator = CustomIndexEnumerator; object_template->SetIndexedPropertyHandler( CustomIndexGetter, setter, query, deleter, enumerator, index); } return true; } NAN_METHOD(CreateConstructor) { NanScope(); if (!args[0]->IsFunction() || !args[1]->IsObject()) return NanThrowTypeError("Bad argument"); // Extract args. Handle<Function> constructor = Handle<Function>::Cast(args[0]); Handle<Object> options = args[1]->ToObject(); // Create a new FunctionTemplate which will call passed callback. Handle<FunctionTemplate> function_template = FunctionTemplate::New( CustomFunctionCallback, constructor); Handle<Value> function_name = constructor->GetName(); function_template->SetClassName(function_name->ToString()); // Modify the FunctionTemplate's InstanceTemplate. std::string error; if (!SetObjectTemplate(function_template->InstanceTemplate(), options, &error)) return NanThrowError(error.c_str()); NanReturnValue(function_template->GetFunction()); } NAN_METHOD(CreateObject) { NanScope(); if (!args[0]->IsObject()) return NanThrowTypeError("Bad argument"); // Create a new ObjectTemplate based on the passed handler. Local<ObjectTemplate> object_template = ObjectTemplate::New(); std::string error; if (!SetObjectTemplate(object_template, args[0]->ToObject(), &error)) return NanThrowError(error.c_str()); NanReturnValue(object_template->NewInstance()); } void Init(Handle<Object> exports) { NODE_SET_METHOD(exports, "createConstructor", CreateConstructor); NODE_SET_METHOD(exports, "createObject", CreateObject); } } // namespace NODE_MODULE(custom_object, Init) <commit_msg>Fix callbacks names in node v0.10.x.<commit_after>// Copyright (c) 2014 GitHub, Inc. All rights reserved. #include <string> #include <vector> #include "object_helper.h" namespace { #if !NODE_VERSION_AT_LEAST(0, 11, 0) #define AccessorSetterCallback AccessorSetter #define IndexedPropertySetterCallback IndexedPropertySetter #define IndexedPropertyQueryCallback IndexedPropertyQuery #define IndexedPropertyDeleterCallback IndexedPropertyDeleter #define IndexedPropertyEnumeratorCallback IndexedPropertyEnumerator #endif #define DEFINE_NONE_PARAMETER_FUNC(name) \ NanScope(); \ Handle<Function> func; \ Handle<Object> data = args.Data()->ToObject(); \ if (!ObjectGet(data, name, &func)) \ return NanThrowError("Cannot find " name); \ Handle<Value> argv[] = { data->Get(NanSymbol("data")) }; \ Handle<Value> return_value = func->Call(args.This(), 1, argv) #define DEFINE_ONE_PARAMETER_FUNC(name, key) \ NanScope(); \ Handle<Function> func; \ Handle<Object> data = args.Data()->ToObject(); \ if (!ObjectGet(args.Data()->ToObject(), name, &func)) \ return NanThrowError("Cannot find " name); \ Handle<Value> argv[] = { key, data->Get(NanSymbol("data")) }; \ Handle<Value> return_value = func->Call(args.This(), 2, argv) #define DEFINE_TWO_PARAMETERS_FUNC(name, key, value) \ NanScope(); \ Handle<Function> func; \ Handle<Object> data = args.Data()->ToObject(); \ if (!ObjectGet(args.Data()->ToObject(), name, &func)) \ return NanThrowError("Cannot find " name); \ Handle<Value> argv[] = { key, value, data->Get(NanSymbol("data")) }; \ Handle<Value> return_value = func->Call(args.This(), 3, argv) NAN_INDEX_GETTER(CustomIndexGetter) { DEFINE_ONE_PARAMETER_FUNC("getter", Integer::New(index)); NanReturnValue(return_value); } NAN_INDEX_SETTER(CustomIndexSetter) { DEFINE_TWO_PARAMETERS_FUNC("setter", Integer::New(index), value); NanReturnValue(return_value); } NAN_INDEX_QUERY(CustomIndexQuery) { DEFINE_ONE_PARAMETER_FUNC("query", Integer::New(index)); NanReturnValue(return_value->ToInteger()); } NAN_INDEX_DELETER(CustomIndexDeleter) { DEFINE_ONE_PARAMETER_FUNC("deleter", Integer::New(index)); NanReturnValue(return_value->ToBoolean()); } NAN_INDEX_ENUMERATOR(CustomIndexEnumerator) { DEFINE_NONE_PARAMETER_FUNC("enumerator"); NanReturnValue(Handle<Array>::Cast(return_value)); } NAN_GETTER(CustomAccessorGetter) { DEFINE_ONE_PARAMETER_FUNC("getter", property); NanReturnValue(return_value); } NAN_SETTER(CustomAccessorSetter) { DEFINE_TWO_PARAMETERS_FUNC("setter", property, value); NanReturnValue(return_value); } NAN_METHOD(CustomFunctionCallback) { NanScope(); Handle<Function> constructor = Handle<Function>::Cast(args.Data()); std::vector<Handle<Value> > argv(args.Length()); for (size_t i = 0; i < argv.size(); ++i) argv[i] = args[i]; NanReturnValue(constructor->Call(args.This(), argv.size(), argv.data())); } bool SetObjectTemplate(Handle<ObjectTemplate> object_template, Handle<Object> options, std::string* error) { // accessor: [ { name: String, getter: Function, setter: Function } ] Handle<Array> accessor_array; if (ObjectGet(options, "accessor", &accessor_array)) { for (uint32_t i = 0; i < accessor_array->Length(); ++i) { Handle<Object> accessor = accessor_array->Get(i)->ToObject(); Handle<String> name; if (!ObjectGet(accessor, "name", &name)) { *error = "The 'name' is required when setting accessor"; return false; } if (!accessor->Has(NanSymbol("getter"))) { *error = "The 'getter' is required when setting accessor"; return false; } // The "setter" is optional. AccessorSetterCallback setter = NULL; if (accessor->Has(NanSymbol("setter"))) setter = CustomAccessorSetter; object_template->SetAccessor( name, CustomAccessorGetter, setter, accessor); } } // index: { getter: Function, setter: Function, query: Function, // deleter: Function, enumerator: Function } Handle<Object> index; if (ObjectGet(options, "index", &index)) { if (!index->Has(NanSymbol("getter"))) { *error = "The 'getter' is required when setting index"; return false; } IndexedPropertySetterCallback setter = NULL; if (index->Has(NanSymbol("setter"))) setter = CustomIndexSetter; IndexedPropertyQueryCallback query = NULL; if (index->Has(NanSymbol("query"))) query = CustomIndexQuery; IndexedPropertyDeleterCallback deleter = NULL; if (index->Has(NanSymbol("deleter"))) deleter = CustomIndexDeleter; IndexedPropertyEnumeratorCallback enumerator = NULL; if (index->Has(NanSymbol("enumerator"))) enumerator = CustomIndexEnumerator; object_template->SetIndexedPropertyHandler( CustomIndexGetter, setter, query, deleter, enumerator, index); } return true; } NAN_METHOD(CreateConstructor) { NanScope(); if (!args[0]->IsFunction() || !args[1]->IsObject()) return NanThrowTypeError("Bad argument"); // Extract args. Handle<Function> constructor = Handle<Function>::Cast(args[0]); Handle<Object> options = args[1]->ToObject(); // Create a new FunctionTemplate which will call passed callback. Handle<FunctionTemplate> function_template = FunctionTemplate::New( CustomFunctionCallback, constructor); Handle<Value> function_name = constructor->GetName(); function_template->SetClassName(function_name->ToString()); // Modify the FunctionTemplate's InstanceTemplate. std::string error; if (!SetObjectTemplate(function_template->InstanceTemplate(), options, &error)) return NanThrowError(error.c_str()); NanReturnValue(function_template->GetFunction()); } NAN_METHOD(CreateObject) { NanScope(); if (!args[0]->IsObject()) return NanThrowTypeError("Bad argument"); // Create a new ObjectTemplate based on the passed handler. Local<ObjectTemplate> object_template = ObjectTemplate::New(); std::string error; if (!SetObjectTemplate(object_template, args[0]->ToObject(), &error)) return NanThrowError(error.c_str()); NanReturnValue(object_template->NewInstance()); } void Init(Handle<Object> exports) { NODE_SET_METHOD(exports, "createConstructor", CreateConstructor); NODE_SET_METHOD(exports, "createObject", CreateObject); } } // namespace NODE_MODULE(custom_object, Init) <|endoftext|>
<commit_before>#include "cvm.h" #include <dlfcn.h> #define STR2(s) #s #define STR(s) STR2(s) #ifdef __linux__ #define DAB_LIBC_NAME "libc.so.6" // LINUX #else #define DAB_LIBC_NAME "libc.dylib" // APPLE #endif DabValue DabVM::merge_arrays(const DabValue &arg0, const DabValue &arg1) { auto & a0 = arg0.array(); auto & a1 = arg1.array(); DabValue array_class = classes[CLASS_ARRAY]; DabValue value = array_class.create_instance(); auto & array = value.array(); array.resize(a0.size() + a1.size()); fprintf(stderr, "vm: merge %d and %d items into new %d-sized array\n", (int)a0.size(), (int)a1.size(), (int)array.size()); size_t i = 0; for (auto &item : a0) { array[i++] = item; } for (auto &item : a1) { array[i++] = item; } return value; } dab_function_t import_external_function(void *symbol, const DabFunctionReflection &reflection, Stack &stack) { return [symbol, &reflection, &stack](size_t n_args, size_t n_ret, void *blockaddr) { const auto &arg_klasses = reflection.arg_klasses; const auto ret_klass = reflection.ret_klass; assert(blockaddr == 0); assert(n_args == arg_klasses.size()); assert(n_ret == 1); if (false) { } #include "ffi_signatures.h" else { fprintf(stderr, "vm: unsupported signature\n"); exit(1); } }; } void DabVM::define_defaults() { fprintf(stderr, "vm: define defaults\n"); define_default_classes(); fprintf(stderr, "vm: define default functions\n"); auto make_import_function = [this](const char *name) { return [this, name](size_t n_args, size_t n_ret, void *blockaddr) { assert(blockaddr == 0); assert(n_args == 2 || n_args == 1); assert(n_ret == 1); std::string libc_name; if (n_args == 2) { auto _libc_name = stack.pop_value(); libc_name = _libc_name.string(); } auto method = stack.pop_value(); assert(method.class_index() == CLASS_METHOD); auto method_name = method.string(); if (n_args == 1) { libc_name = method_name; } fprintf(stderr, "vm: readjust '%s' to libc function '%s'\n", method_name.c_str(), libc_name.c_str()); auto handle = dlopen(name, RTLD_LAZY); if (!handle) { fprintf(stderr, "vm: dlopen error: %s", dlerror()); exit(1); } if (options.verbose) { fprintf(stderr, "vm: dlopen handle: %p\n", handle); } auto symbol = dlsym(handle, libc_name.c_str()); if (!symbol) { fprintf(stderr, "vm: dlsym error: %s", dlerror()); exit(1); } if (options.verbose) { fprintf(stderr, "vm: dlsym handle: %p\n", symbol); } auto func_index = get_or_create_symbol_index(method_name); auto &function = functions[func_index]; function.regular = false; function.address = -1; function.extra = import_external_function(symbol, function.reflection, this->stack); stack.push_value(DabValue(nullptr)); }; }; { DabFunction fun; fun.name = "__import_libc"; fun.regular = false; fun.extra = make_import_function(DAB_LIBC_NAME); auto func_index = get_or_create_symbol_index("__import_libc"); functions[func_index] = fun; } { DabFunction fun; fun.name = "__import_sdl"; fun.regular = false; fun.extra = make_import_function("/usr/local/lib/libSDL2.dylib"); auto func_index = get_or_create_symbol_index("__import_sdl"); functions[func_index] = fun; } { DabFunction fun; fun.name = "__import_pq"; fun.regular = false; fun.extra = make_import_function("/usr/local/lib/libpq.dylib"); auto func_index = get_or_create_symbol_index("__import_pq"); functions[func_index] = fun; } { DabFunction fun; fun.name = "||"; fun.regular = false; fun.extra_reg = [this](DabValue, std::vector<DabValue> args) { assert(args.size() == 2); auto arg0 = args[0]; auto arg1 = args[1]; return arg0.truthy() ? arg0 : arg1; }; auto func_index = get_or_create_symbol_index("||"); functions[func_index] = fun; } { DabFunction fun; fun.name = "&&"; fun.regular = false; fun.extra = [this](size_t n_args, size_t n_ret, void *blockaddr) { assert(blockaddr == 0); // dump(); assert(n_args == 2); assert(n_ret == 1); auto arg1 = stack.pop_value(); auto arg0 = stack.pop_value(); stack.push_value(arg0.truthy() ? arg1 : arg0); }; auto func_index = get_or_create_symbol_index("&&"); functions[func_index] = fun; } } <commit_msg>vm: registerify &&<commit_after>#include "cvm.h" #include <dlfcn.h> #define STR2(s) #s #define STR(s) STR2(s) #ifdef __linux__ #define DAB_LIBC_NAME "libc.so.6" // LINUX #else #define DAB_LIBC_NAME "libc.dylib" // APPLE #endif DabValue DabVM::merge_arrays(const DabValue &arg0, const DabValue &arg1) { auto & a0 = arg0.array(); auto & a1 = arg1.array(); DabValue array_class = classes[CLASS_ARRAY]; DabValue value = array_class.create_instance(); auto & array = value.array(); array.resize(a0.size() + a1.size()); fprintf(stderr, "vm: merge %d and %d items into new %d-sized array\n", (int)a0.size(), (int)a1.size(), (int)array.size()); size_t i = 0; for (auto &item : a0) { array[i++] = item; } for (auto &item : a1) { array[i++] = item; } return value; } dab_function_t import_external_function(void *symbol, const DabFunctionReflection &reflection, Stack &stack) { return [symbol, &reflection, &stack](size_t n_args, size_t n_ret, void *blockaddr) { const auto &arg_klasses = reflection.arg_klasses; const auto ret_klass = reflection.ret_klass; assert(blockaddr == 0); assert(n_args == arg_klasses.size()); assert(n_ret == 1); if (false) { } #include "ffi_signatures.h" else { fprintf(stderr, "vm: unsupported signature\n"); exit(1); } }; } void DabVM::define_defaults() { fprintf(stderr, "vm: define defaults\n"); define_default_classes(); fprintf(stderr, "vm: define default functions\n"); auto make_import_function = [this](const char *name) { return [this, name](size_t n_args, size_t n_ret, void *blockaddr) { assert(blockaddr == 0); assert(n_args == 2 || n_args == 1); assert(n_ret == 1); std::string libc_name; if (n_args == 2) { auto _libc_name = stack.pop_value(); libc_name = _libc_name.string(); } auto method = stack.pop_value(); assert(method.class_index() == CLASS_METHOD); auto method_name = method.string(); if (n_args == 1) { libc_name = method_name; } fprintf(stderr, "vm: readjust '%s' to libc function '%s'\n", method_name.c_str(), libc_name.c_str()); auto handle = dlopen(name, RTLD_LAZY); if (!handle) { fprintf(stderr, "vm: dlopen error: %s", dlerror()); exit(1); } if (options.verbose) { fprintf(stderr, "vm: dlopen handle: %p\n", handle); } auto symbol = dlsym(handle, libc_name.c_str()); if (!symbol) { fprintf(stderr, "vm: dlsym error: %s", dlerror()); exit(1); } if (options.verbose) { fprintf(stderr, "vm: dlsym handle: %p\n", symbol); } auto func_index = get_or_create_symbol_index(method_name); auto &function = functions[func_index]; function.regular = false; function.address = -1; function.extra = import_external_function(symbol, function.reflection, this->stack); stack.push_value(DabValue(nullptr)); }; }; { DabFunction fun; fun.name = "__import_libc"; fun.regular = false; fun.extra = make_import_function(DAB_LIBC_NAME); auto func_index = get_or_create_symbol_index("__import_libc"); functions[func_index] = fun; } { DabFunction fun; fun.name = "__import_sdl"; fun.regular = false; fun.extra = make_import_function("/usr/local/lib/libSDL2.dylib"); auto func_index = get_or_create_symbol_index("__import_sdl"); functions[func_index] = fun; } { DabFunction fun; fun.name = "__import_pq"; fun.regular = false; fun.extra = make_import_function("/usr/local/lib/libpq.dylib"); auto func_index = get_or_create_symbol_index("__import_pq"); functions[func_index] = fun; } { DabFunction fun; fun.name = "||"; fun.regular = false; fun.extra_reg = [this](DabValue, std::vector<DabValue> args) { assert(args.size() == 2); auto arg0 = args[0]; auto arg1 = args[1]; return arg0.truthy() ? arg0 : arg1; }; auto func_index = get_or_create_symbol_index("||"); functions[func_index] = fun; } { DabFunction fun; fun.name = "&&"; fun.regular = false; fun.extra_reg = [this](DabValue, std::vector<DabValue> args) { assert(args.size() == 2); auto arg0 = args[0]; auto arg1 = args[1]; return arg0.truthy() ? arg1 : arg0; }; auto func_index = get_or_create_symbol_index("&&"); functions[func_index] = fun; } } <|endoftext|>
<commit_before>#include "inner_readers.h" #include "../flags.h" using namespace dariadb; using namespace dariadb::compression; using namespace dariadb::storage; InnerReader::InnerReader(dariadb::Flag flag, dariadb::Time from, dariadb::Time to) : _chunks{}, _flag(flag), _from(from), _to(to), _tp_readed(false) { is_time_point_reader = false; end = false; } void InnerReader::add(Chunk_Ptr c, size_t count) { std::lock_guard<std::mutex> lg(_mutex); ReadChunk rc; rc.chunk = c; rc.count = count; this->_chunks[c->first.id].push_back(rc); } void InnerReader::add_tp(Chunk_Ptr c, size_t count) { std::lock_guard<std::mutex> lg(_mutex); ReadChunk rc; rc.chunk = c; rc.count = count; this->_tp_chunks[c->first.id].push_back(rc); } bool InnerReader::isEnd() const { return this->end && this->_tp_readed; } dariadb::IdArray InnerReader::getIds()const { dariadb::IdArray result; result.resize(_chunks.size()); size_t pos = 0; for (auto &kv : _chunks) { result[pos] = kv.first; pos++; } return result; } void InnerReader::readNext(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex); if (!_tp_readed) { this->readTimePoint(clb); } for (auto ch : _chunks) { for (size_t i = 0; i < ch.second.size(); i++) { auto cur_ch = ch.second[i].chunk; auto bw = std::make_shared<BinaryBuffer>(cur_ch->bw->get_range()); bw->reset_pos(); CopmressedReader crr(bw, cur_ch->first); if (check_meas(ch.second[i].chunk->first)) { auto sub = ch.second[i].chunk->first; clb->call(sub); } for (size_t j = 0; j < ch.second[i].count; j++) { auto sub = crr.read(); sub.id = ch.second[i].chunk->first.id; if (check_meas(sub)) { clb->call(sub); } else { if (sub.time > _to) { break; } } } } } end = true; } void InnerReader::readTimePoint(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex_tp); std::list<ReadChunk> to_read_chunks{}; for (auto ch : _tp_chunks) { auto candidate = ch.second.front(); for (size_t i = 0; i < ch.second.size(); i++) { auto cur_chunk = ch.second[i].chunk; if (candidate.chunk->first.time < cur_chunk->first.time) { candidate = ch.second[i]; } } to_read_chunks.push_back(candidate); } for (auto ch : to_read_chunks) { auto bw = std::make_shared<BinaryBuffer>(ch.chunk->bw->get_range()); bw->reset_pos(); CopmressedReader crr(bw, ch.chunk->first); Meas candidate; candidate = ch.chunk->first; for (size_t i = 0; i < ch.count; i++) { auto sub = crr.read(); sub.id = ch.chunk->first.id; if ((sub.time <= _from) && (sub.time >= candidate.time)) { candidate = sub; }if (sub.time > _from) { break; } } if (candidate.time <= _from) { //TODO make as options candidate.time = _from; clb->call(candidate); _tp_readed_times.insert(std::make_tuple(candidate.id, candidate.time)); } } auto m = dariadb::Meas::empty(); m.time = _from; m.flag = dariadb::Flags::NO_DATA; for (auto id : _not_exist) { m.id = id; clb->call(m); } _tp_readed = true; } bool InnerReader::check_meas(const Meas&m)const { auto tmp = std::make_tuple(m.id, m.time); if (this->_tp_readed_times.find(tmp) != _tp_readed_times.end()) { return false; } using utils::inInterval; if ((in_filter(_flag, m.flag)) && (inInterval(_from, _to, m.time))) { return true; } return false; } Reader_ptr InnerReader::clone()const { auto res = std::make_shared<InnerReader>(_flag, _from, _to); res->_chunks = _chunks; res->_tp_chunks = _tp_chunks; res->_flag = _flag; res->_from = _from; res->_to = _to; res->_tp_readed = _tp_readed; res->end = end; res->_not_exist = _not_exist; res->_tp_readed_times = _tp_readed_times; return res; } void InnerReader::reset() { end = false; _tp_readed = false; _tp_readed_times.clear(); } InnerCurrentValuesReader::InnerCurrentValuesReader() { this->end = false; } InnerCurrentValuesReader::~InnerCurrentValuesReader() {} bool InnerCurrentValuesReader::isEnd() const { return this->end; } void InnerCurrentValuesReader::readCurVals(storage::ReaderClb*clb) { for (auto v : _cur_values) { clb->call(v); } } void InnerCurrentValuesReader::readNext(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex); readCurVals(clb); this->end = true; } IdArray InnerCurrentValuesReader::getIds()const { dariadb::IdArray result; result.resize(_cur_values.size()); size_t pos = 0; for (auto v : _cur_values) { result[pos] = v.id; pos++; } return result; } Reader_ptr InnerCurrentValuesReader::clone()const { auto raw_reader = new InnerCurrentValuesReader(); Reader_ptr result{ raw_reader }; raw_reader->_cur_values = _cur_values; return result; } void InnerCurrentValuesReader::reset() { end = false; } <commit_msg>inner_readers refact.<commit_after>#include "inner_readers.h" #include "../flags.h" using namespace dariadb; using namespace dariadb::compression; using namespace dariadb::storage; InnerReader::InnerReader(dariadb::Flag flag, dariadb::Time from, dariadb::Time to) : _chunks{}, _flag(flag), _from(from), _to(to), _tp_readed(false) { is_time_point_reader = false; end = false; } void InnerReader::add(Chunk_Ptr c, size_t count) { std::lock_guard<std::mutex> lg(_mutex); ReadChunk rc; rc.chunk = c; rc.count = count; this->_chunks[c->first.id].push_back(rc); } void InnerReader::add_tp(Chunk_Ptr c, size_t count) { std::lock_guard<std::mutex> lg(_mutex); ReadChunk rc; rc.chunk = c; rc.count = count; this->_tp_chunks[c->first.id].push_back(rc); } bool InnerReader::isEnd() const { return this->end && this->_tp_readed; } dariadb::IdArray InnerReader::getIds()const { dariadb::IdArray result; result.resize(_chunks.size()); size_t pos = 0; for (auto &kv : _chunks) { result[pos] = kv.first; pos++; } return result; } void InnerReader::readNext(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex); if (!_tp_readed) { this->readTimePoint(clb); } for (auto ch : _chunks) { for (size_t i = 0; i < ch.second.size(); i++) { auto cur_ch = ch.second[i].chunk; auto bw = std::make_shared<BinaryBuffer>(cur_ch->bw->get_range()); bw->reset_pos(); CopmressedReader crr(bw, cur_ch->first); if (check_meas(cur_ch->first)) { auto sub = cur_ch->first; clb->call(sub); } for (size_t j = 0; j < cur_ch->count; j++) { auto sub = crr.read(); sub.id = cur_ch->first.id; if (check_meas(sub)) { clb->call(sub); } else { if (sub.time > _to) { break; } } } } } end = true; } void InnerReader::readTimePoint(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex_tp); std::list<ReadChunk> to_read_chunks{}; for (auto ch : _tp_chunks) { auto candidate = ch.second.front(); for (size_t i = 0; i < ch.second.size(); i++) { auto cur_chunk = ch.second[i].chunk; if (candidate.chunk->first.time < cur_chunk->first.time) { candidate = ch.second[i]; } } to_read_chunks.push_back(candidate); } for (auto ch : to_read_chunks) { auto bw = std::make_shared<BinaryBuffer>(ch.chunk->bw->get_range()); bw->reset_pos(); CopmressedReader crr(bw, ch.chunk->first); Meas candidate; candidate = ch.chunk->first; for (size_t i = 0; i < ch.count; i++) { auto sub = crr.read(); sub.id = ch.chunk->first.id; if ((sub.time <= _from) && (sub.time >= candidate.time)) { candidate = sub; }if (sub.time > _from) { break; } } if (candidate.time <= _from) { //TODO make as options candidate.time = _from; clb->call(candidate); _tp_readed_times.insert(std::make_tuple(candidate.id, candidate.time)); } } auto m = dariadb::Meas::empty(); m.time = _from; m.flag = dariadb::Flags::NO_DATA; for (auto id : _not_exist) { m.id = id; clb->call(m); } _tp_readed = true; } bool InnerReader::check_meas(const Meas&m)const { auto tmp = std::make_tuple(m.id, m.time); if (this->_tp_readed_times.find(tmp) != _tp_readed_times.end()) { return false; } using utils::inInterval; if ((in_filter(_flag, m.flag)) && (inInterval(_from, _to, m.time))) { return true; } return false; } Reader_ptr InnerReader::clone()const { auto res = std::make_shared<InnerReader>(_flag, _from, _to); res->_chunks = _chunks; res->_tp_chunks = _tp_chunks; res->_flag = _flag; res->_from = _from; res->_to = _to; res->_tp_readed = _tp_readed; res->end = end; res->_not_exist = _not_exist; res->_tp_readed_times = _tp_readed_times; return res; } void InnerReader::reset() { end = false; _tp_readed = false; _tp_readed_times.clear(); } InnerCurrentValuesReader::InnerCurrentValuesReader() { this->end = false; } InnerCurrentValuesReader::~InnerCurrentValuesReader() {} bool InnerCurrentValuesReader::isEnd() const { return this->end; } void InnerCurrentValuesReader::readCurVals(storage::ReaderClb*clb) { for (auto v : _cur_values) { clb->call(v); } } void InnerCurrentValuesReader::readNext(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex); readCurVals(clb); this->end = true; } IdArray InnerCurrentValuesReader::getIds()const { dariadb::IdArray result; result.resize(_cur_values.size()); size_t pos = 0; for (auto v : _cur_values) { result[pos] = v.id; pos++; } return result; } Reader_ptr InnerCurrentValuesReader::clone()const { auto raw_reader = new InnerCurrentValuesReader(); Reader_ptr result{ raw_reader }; raw_reader->_cur_values = _cur_values; return result; } void InnerCurrentValuesReader::reset() { end = false; } <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // User message widget //============================================================================== #include "coreguiutils.h" #include "usermessagewidget.h" //============================================================================== #include <Qt> //============================================================================== #include <QBuffer> #include <QFont> #include <QIcon> #include <QSizePolicy> #include <QWidget> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== void UserMessageWidget::constructor(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage) { // Some initialisations mIcon = QString(); mMessage = QString(); mExtraMessage = QString(); // Customise our background setAutoFillBackground(true); setBackgroundRole(QPalette::Base); // Increase the size of our font QFont newFont = font(); newFont.setPointSizeF(1.35*newFont.pointSize()); setFont(newFont); // Some other customisations setContextMenuPolicy(Qt::NoContextMenu); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setTextInteractionFlags(Qt::NoTextInteraction); setWordWrap(true); // 'Initialise' our message setIconMessage(pIcon, pMessage, pExtraMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon, pMessage, pExtraMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, const QString &pMessage, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon, pMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon); } //============================================================================== UserMessageWidget::UserMessageWidget(QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(); } //============================================================================== void UserMessageWidget::setIconMessage(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage) { // Set our message, if needed if ( pIcon.compare(mIcon) || pMessage.compare(mMessage) || pExtraMessage.compare(mExtraMessage)) { // Keep track of the new values for our icon, message and extra message mIcon = pIcon; mMessage = pMessage; mExtraMessage = pExtraMessage; // Set our text as HTML // Note: we want our icon to have a final size of 32px by 32px. However, // it may be that it has a different size to begin with. Normally, // we would rely on QLabel's HTML support (and in particular on // the width and height attributes of the img element) to have our // icon resized for us, but this results in a pixelated and // therefore ugly image. So, instead, we retrieve a data URI for // our resized icon... if (pIcon.isEmpty() && pMessage.isEmpty() && pExtraMessage.isEmpty()) setText(QString()); else if (pExtraMessage.isEmpty()) setText(QString("<table align=center>\n" " <tbody>\n" " <tr valign=middle>\n" " <td>\n" " <img src=\"%1\"/>\n" " </td>\n" " <td>\n" " %2\n" " </td>\n" " </tr>\n" " </tbody>\n" "</table>\n").arg(iconDataUri(pIcon, 32, 32), pMessage)); else setText(QString("<table align=center>\n" " <tbody>\n" " <tr valign=middle>\n" " <td>\n" " <img src=\"%1\"/>\n" " </td>\n" " <td>\n" " %2\n" " </td>\n" " </tr>\n" " <tr valign=middle>\n" " <td/>\n" " <td align=center>\n" " <small><em>(%3)</em></small>\n" " </td>\n" " </tr>\n" " </tbody>\n" "</table>\n").arg(iconDataUri(pIcon, 32, 32), pMessage, pExtraMessage)); } } //============================================================================== void UserMessageWidget::setMessage(const QString &pMessage, const QString &pExtraMessage) { // Set our message setIconMessage(mIcon, pMessage, pExtraMessage); } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // User message widget //============================================================================== #include "coreguiutils.h" #include "usermessagewidget.h" //============================================================================== #include <Qt> //============================================================================== #include <QBuffer> #include <QFont> #include <QIcon> #include <QSizePolicy> #include <QWidget> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== void UserMessageWidget::constructor(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage) { // Some initialisations mIcon = QString(); mMessage = QString(); mExtraMessage = QString(); // Customise our background setAutoFillBackground(true); setBackgroundRole(QPalette::Base); // Increase the size of our font QFont newFont = font(); newFont.setPointSizeF(1.35*newFont.pointSize()); setFont(newFont); // Some other customisations setContextMenuPolicy(Qt::NoContextMenu); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setTextInteractionFlags(Qt::NoTextInteraction); setWordWrap(true); // 'Initialise' our message setIconMessage(pIcon, pMessage, pExtraMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon, pMessage, pExtraMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, const QString &pMessage, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon, pMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon); } //============================================================================== UserMessageWidget::UserMessageWidget(QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(); } //============================================================================== void UserMessageWidget::setIconMessage(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage) { // Set our message, if needed if ( pIcon.compare(mIcon) || pMessage.compare(mMessage) || pExtraMessage.compare(mExtraMessage)) { // Keep track of the new values for our icon, message and extra message mIcon = pIcon; mMessage = pMessage; mExtraMessage = pExtraMessage; // Set our text as HTML // Note: we want our icon to have a final size of 32px by 32px. However, // it may be that it has a different size to begin with. Normally, // we would rely on QLabel's HTML support (and in particular on // the width and height attributes of the img element) to have our // icon resized for us, but this results in a pixelated and // therefore ugly image. So, instead, we retrieve a data URI for // our resized icon... if (pIcon.isEmpty() && pMessage.isEmpty() && pExtraMessage.isEmpty()) { setText(QString()); } else if (pExtraMessage.isEmpty()) { setText(QString("<table align=center>\n" " <tbody>\n" " <tr valign=middle>\n" " <td>\n" " <img src=\"%1\"/>\n" " </td>\n" " <td>\n" " %2\n" " </td>\n" " </tr>\n" " </tbody>\n" "</table>\n").arg(iconDataUri(pIcon, 32, 32), pMessage)); } else { setText(QString("<table align=center>\n" " <tbody>\n" " <tr valign=middle>\n" " <td>\n" " <img src=\"%1\"/>\n" " </td>\n" " <td>\n" " %2\n" " </td>\n" " </tr>\n" " <tr valign=middle>\n" " <td/>\n" " <td align=center>\n" " <small><em>(%3)</em></small>\n" " </td>\n" " </tr>\n" " </tbody>\n" "</table>\n").arg(iconDataUri(pIcon, 32, 32), pMessage, pExtraMessage)); } } } //============================================================================== void UserMessageWidget::setMessage(const QString &pMessage, const QString &pExtraMessage) { // Set our message setIconMessage(mIcon, pMessage, pExtraMessage); } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>// Copyright 2017 Google 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 "AssetD.h" #include <AssetThrowPolicy.h> // **************************************************************************** // *** MutableAssetD // **************************************************************************** template <> MutableAssetD::DirtyMap MutableAssetD::dirtyMap = MutableAssetD::DirtyMap(); // **************************************************************************** // *** AssetImplD // **************************************************************************** khRefGuard<AssetImplD> AssetImplD::Load(const std::string &boundref) { khRefGuard<AssetImplD> result; // make sure the base class loader actually instantiated one of me // this should always happen, but there are no compile time guarantees result.dyncastassign(AssetImpl::Load(boundref)); if (!result) { AssetThrowPolicy::FatalOrThrow(kh::tr("Internal error: AssetImplD loaded wrong type for ") + boundref); } return result; } void AssetImplD::AddVersionRef(const std::string &verref) { // add to beginning of my list of versions versions.insert(versions.begin(), verref); } void AssetImplD::Modify(const std::vector<std::string>& inputs_, const khMetaData &meta_) { inputs = inputs_; meta = meta_; } bool AssetImplD::InputsUpToDate(const AssetVersion &version, const std::vector<AssetVersion> &cachedInputs) const { if (cachedInputs.size() != version->inputs.size()) return false; for (uint i = 0; i < cachedInputs.size(); ++i) { if (cachedInputs[i]->GetRef() != version->inputs[i]) return false; } return true; } void AssetImplD::UpdateInputs(std::vector<AssetVersion> &inputvers) const { inputvers.reserve(inputs.size()); for (std::vector<std::string>::const_iterator i = inputs.begin(); i != inputs.end(); ++i) { AssetVersionRef verref(*i); if (verref.Version() == "current") { // we only need to update our input if it's an asset ref // or a version ref with "current" // if it points to a specific version there's nothing to do AssetD asset(verref.AssetRef()); bool needed = false; inputvers.push_back(asset->Update(needed)); } else { inputvers.push_back(AssetVersion(verref)); } } } <commit_msg>#936: Add progress log messages to `gesystemmanager`. (#937)<commit_after>// Copyright 2017 Google 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 "AssetD.h" #include <AssetThrowPolicy.h> // **************************************************************************** // *** MutableAssetD // **************************************************************************** template <> MutableAssetD::DirtyMap MutableAssetD::dirtyMap = MutableAssetD::DirtyMap(); // **************************************************************************** // *** AssetImplD // **************************************************************************** khRefGuard<AssetImplD> AssetImplD::Load(const std::string &boundref) { khRefGuard<AssetImplD> result; // make sure the base class loader actually instantiated one of me // this should always happen, but there are no compile time guarantees result.dyncastassign(AssetImpl::Load(boundref)); if (!result) { AssetThrowPolicy::FatalOrThrow(kh::tr("Internal error: AssetImplD loaded wrong type for ") + boundref); } return result; } void AssetImplD::AddVersionRef(const std::string &verref) { // add to beginning of my list of versions versions.insert(versions.begin(), verref); } void AssetImplD::Modify(const std::vector<std::string>& inputs_, const khMetaData &meta_) { inputs = inputs_; meta = meta_; } bool AssetImplD::InputsUpToDate(const AssetVersion &version, const std::vector<AssetVersion> &cachedInputs) const { if (cachedInputs.size() != version->inputs.size()) return false; for (uint i = 0; i < cachedInputs.size(); ++i) { if (cachedInputs[i]->GetRef() != version->inputs[i]) return false; } return true; } void AssetImplD::UpdateInputs(std::vector<AssetVersion> &inputvers) const { std::size_t inputs_count = inputs.size(); inputvers.reserve(inputs_count); for (std::vector<std::string>::const_iterator i = inputs.begin(); i != inputs.end(); ++i) { AssetVersionRef verref(*i); if (verref.Version() == "current") { // we only need to update our input if it's an asset ref // or a version ref with "current" // if it points to a specific version there's nothing to do AssetD asset(verref.AssetRef()); bool needed = false; inputvers.push_back(asset->Update(needed)); notify(NFY_PROGRESS, "Updating asset input %lu (of %lu input%s).", i - inputs.begin(), inputs_count, inputs_count == 1 ? "" : "s"); } else { inputvers.push_back(AssetVersion(verref)); } } notify(NFY_PROGRESS, "Updating asset inputs complete."); } <|endoftext|>
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */ #include <granary.h> using namespace granary; // In kernel space, we make this GRANARY_DEFINE_bool(transparent_returns, GRANARY_IF_USER_ELSE(true, false), "Enable transparent return addresses? The default is `" GRANARY_IF_USER_ELSE("yes", "no") "`."); // Tool that implements several user-space special cases for instrumenting // common binaries. class TransparentRetsInstrumenter : public InstrumentationTool { public: virtual ~TransparentRetsInstrumenter(void) = default; // Push on a return address for either of a direct or indirect function // call. void AddTransparentRetAddr(ControlFlowInstruction *cfi) { GRANARY_ASSERT(cfi->IsAppInstruction()); // Compute return address. auto ret_addr_pc = cfi->DecodedPC() + cfi->DecodedLength(); ImmediateOperand ret_addr(reinterpret_cast<uintptr_t>(ret_addr_pc), arch::ADDRESS_WIDTH_BYTES); // Push on the native return address. BeginInlineAssembly({&ret_addr}); InlineBefore(cfi, "MOV r64 %1, i64 %0;" "PUSH r64 %1;"_x86_64); EndInlineAssembly(); // Convert the (in)direct call into a jump. if (cfi->HasIndirectTarget()) { RegisterOperand target_reg; GRANARY_IF_DEBUG( auto matched = ) cfi->MatchOperands( ReadFrom(target_reg)); GRANARY_ASSERT(matched); cfi->InsertBefore(lir::IndirectJump(cfi->TargetBlock(), target_reg)); } else { cfi->InsertBefore(lir::Jump(cfi->TargetBlock())); } } // Remove all instructions starting from (and including) `search_instr`. void RemoveTailInstructions(DecodedBasicBlock *block, const Instruction *search_instr) { auto last_instr = block->LastInstruction(); Instruction *instr(nullptr); do { instr = last_instr->Previous(); Instruction::Unlink(instr); } while (instr != search_instr); } // Instrument the control-flow instructions, specifically: function call // instructions. virtual void InstrumentControlFlow(BlockFactory *, LocalControlFlowGraph *cfg) { for (auto block : cfg->NewBlocks()) { auto decoded_block = DynamicCast<DecodedBasicBlock *>(block); if (!decoded_block) continue; for (auto succ : block->Successors()) { // Convert a function call into a `PUSH; JMP` combination. if (succ.cfi->IsFunctionCall()) { AddTransparentRetAddr(succ.cfi); RemoveTailInstructions(decoded_block, succ.cfi); break; // Won't have any more successors. // Specialize the return. Behind the scenes, this will convert the // return into an indirect jump. // // Note: `ReturnBasicBlock`s can have meta-data, but usually don't. // Their meta-data is created lazily when first requested with // `MetaData`. One can check if a `ReturnBasicBlock` has meta-data // and optionally operate on it if non-NULL by invoking the // `UnsafeMetaData` method instead. } else if (succ.cfi->IsFunctionReturn()) { DynamicCast<ReturnBasicBlock *>(succ.block)->MetaData(); } } } } }; // Initialize the `transparent_rets` tool. This tool implements transparent // return addresses. This means that the return addresses from instrumented // function calls will point to native code/ GRANARY_CLIENT_INIT({ if (FLAG_transparent_returns) { RegisterInstrumentationTool<TransparentRetsInstrumenter>( "transparent_rets"); } }) <commit_msg>Improved transparent_rets documentation further.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */ #include <granary.h> using namespace granary; GRANARY_DEFINE_bool(transparent_returns, GRANARY_IF_USER_ELSE(true, false), "Enable transparent return addresses? The default is `" GRANARY_IF_USER_ELSE("yes", "no") "`."); // Implements transparent return addresses. This means that the return // addresses from instrumented function calls will point to native code and // not into Granary's code cache. // // Transparent returns impose a performance overhead because it expands every // function call/return into many instructions, instead of just a single // instruction (in practice). // // The benefit of transparent return addresses is that it improves: // 1) The debugging experience, as program backtraces will appear natural. // 2) Likely improves the correctness of instrumentation, lest any programs // (e.g. `ld` and `dl`) make decisions based on their return addresses. // 2) Opens up the door to return target specialization. class TransparentRetsInstrumenter : public InstrumentationTool { public: virtual ~TransparentRetsInstrumenter(void) = default; // Push on a return address for either of a direct or indirect function // call. void AddTransparentRetAddr(ControlFlowInstruction *cfi) { GRANARY_ASSERT(cfi->IsAppInstruction()); // Compute return address. auto ret_addr_pc = cfi->DecodedPC() + cfi->DecodedLength(); ImmediateOperand ret_addr(reinterpret_cast<uintptr_t>(ret_addr_pc), arch::ADDRESS_WIDTH_BYTES); // Push on the native return address. BeginInlineAssembly({&ret_addr}); InlineBefore(cfi, "MOV r64 %1, i64 %0;" "PUSH r64 %1;"_x86_64); EndInlineAssembly(); // Convert the (in)direct call into a jump. if (cfi->HasIndirectTarget()) { RegisterOperand target_reg; GRANARY_IF_DEBUG( auto matched = ) cfi->MatchOperands( ReadFrom(target_reg)); GRANARY_ASSERT(matched); cfi->InsertBefore(lir::IndirectJump(cfi->TargetBlock(), target_reg)); } else { cfi->InsertBefore(lir::Jump(cfi->TargetBlock())); } } // Remove all instructions starting from (and including) `search_instr`. void RemoveTailInstructions(DecodedBasicBlock *block, const Instruction *search_instr) { auto last_instr = block->LastInstruction(); Instruction *instr(nullptr); do { instr = last_instr->Previous(); Instruction::Unlink(instr); } while (instr != search_instr); } // Instrument the control-flow instructions, specifically: function call // instructions. virtual void InstrumentControlFlow(BlockFactory *, LocalControlFlowGraph *cfg) { for (auto block : cfg->NewBlocks()) { auto decoded_block = DynamicCast<DecodedBasicBlock *>(block); if (!decoded_block) continue; for (auto succ : block->Successors()) { // Convert a function call into a `PUSH; JMP` combination. if (succ.cfi->IsFunctionCall()) { AddTransparentRetAddr(succ.cfi); RemoveTailInstructions(decoded_block, succ.cfi); break; // Won't have any more successors. // Specialize the return. Behind the scenes, this will convert the // return into an indirect jump. // // Note: `ReturnBasicBlock`s can have meta-data, but usually don't. // Their meta-data is created lazily when first requested with // `MetaData`. One can check if a `ReturnBasicBlock` has meta-data // and optionally operate on it if non-NULL by invoking the // `UnsafeMetaData` method instead. } else if (succ.cfi->IsFunctionReturn()) { DynamicCast<ReturnBasicBlock *>(succ.block)->MetaData(); } } } } }; // Initialize the `transparent_rets` tool. GRANARY_CLIENT_INIT({ if (FLAG_transparent_returns) { RegisterInstrumentationTool<TransparentRetsInstrumenter>( "transparent_rets"); } }) <|endoftext|>
<commit_before>/* * AtmoChannelAssignment.cpp: Class for storing a hardware channel to zone mapping * List * * See the README.txt file for copyright information and how to reach the author(s). * * $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <string.h> #include <stdlib.h> #include <malloc.h> #include "AtmoChannelAssignment.h" CAtmoChannelAssignment::CAtmoChannelAssignment(void) { m_psz_name = strdup(""); m_mappings = NULL; m_num_channels = 0; system = ATMO_FALSE; } CAtmoChannelAssignment::CAtmoChannelAssignment(CAtmoChannelAssignment &source) { m_num_channels = 0; m_psz_name = NULL; m_mappings = source.getMapArrayClone(m_num_channels); setName( source.getName() ); system = source.system; } CAtmoChannelAssignment::~CAtmoChannelAssignment(void) { free(m_psz_name); } void CAtmoChannelAssignment::setName(const char *pszNewName) { free(m_psz_name); m_psz_name = pszNewName ? strdup(pszNewName) : strdup(""); } void CAtmoChannelAssignment::setSize(int numChannels) { if(numChannels != m_num_channels) { delete []m_mappings; m_mappings = NULL; m_num_channels = numChannels; if(m_num_channels > 0) { m_mappings = new int[m_num_channels]; memset(m_mappings, 0, sizeof(int) * m_num_channels); } } } int *CAtmoChannelAssignment::getMapArrayClone(int &count) { count = m_num_channels; if(count == 0) return NULL; int *temp = new int[m_num_channels]; memcpy(temp, m_mappings, sizeof(int) * m_num_channels); return(temp); } int CAtmoChannelAssignment::getZoneIndex(int channel) { if(m_mappings && (channel>=0) && (channel<m_num_channels)) return m_mappings[channel] ; else return -1; } void CAtmoChannelAssignment::setZoneIndex(int channel, int zone) { if(m_mappings && (channel>=0) && (channel<m_num_channels)) m_mappings[channel] = zone; } <commit_msg>atmo: memory leak<commit_after>/* * AtmoChannelAssignment.cpp: Class for storing a hardware channel to zone mapping * List * * See the README.txt file for copyright information and how to reach the author(s). * * $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <string.h> #include <stdlib.h> #include <malloc.h> #include "AtmoChannelAssignment.h" CAtmoChannelAssignment::CAtmoChannelAssignment(void) { m_psz_name = strdup(""); m_mappings = NULL; m_num_channels = 0; system = ATMO_FALSE; } CAtmoChannelAssignment::CAtmoChannelAssignment(CAtmoChannelAssignment &source) { m_num_channels = 0; m_psz_name = NULL; m_mappings = source.getMapArrayClone(m_num_channels); setName( source.getName() ); system = source.system; } CAtmoChannelAssignment::~CAtmoChannelAssignment(void) { delete[] m_mappings; free(m_psz_name); } void CAtmoChannelAssignment::setName(const char *pszNewName) { free(m_psz_name); m_psz_name = pszNewName ? strdup(pszNewName) : strdup(""); } void CAtmoChannelAssignment::setSize(int numChannels) { if(numChannels != m_num_channels) { delete[] m_mappings; m_num_channels = numChannels; if(m_num_channels > 0) { m_mappings = new int[m_num_channels]; memset(m_mappings, 0, sizeof(int) * m_num_channels); } else m_mappings = NULL; } } int *CAtmoChannelAssignment::getMapArrayClone(int &count) { count = m_num_channels; if(count == 0) return NULL; int *temp = new int[m_num_channels]; memcpy(temp, m_mappings, sizeof(int) * m_num_channels); return(temp); } int CAtmoChannelAssignment::getZoneIndex(int channel) { if(m_mappings && (channel>=0) && (channel<m_num_channels)) return m_mappings[channel] ; else return -1; } void CAtmoChannelAssignment::setZoneIndex(int channel, int zone) { if(m_mappings && (channel>=0) && (channel<m_num_channels)) m_mappings[channel] = zone; } <|endoftext|>
<commit_before>#define PY_ARRAY_UNIQUE_SYMBOL PyArrayHandleCoreOPENGM #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <boost/python/exception_translator.hpp> #include <stddef.h> #include <deque> #include <exception> #include <opengm/graphicalmodel/graphicalmodel.hxx> #include <opengm/utilities/tribool.hxx> #include <opengm/inference/inference.hxx> #include "copyhelper.hxx" #include "pyConfig.hxx" #include "pyFactor.hxx" #include "pyMovemaker.hxx" #include "pyGmManipulator.hxx" #include "pyIfactor.hxx" #include "pyGm.hxx" #include "pyFid.hxx" #include "pyEnum.hxx" #include "pyFunctionTypes.hxx" #include "pyFunctionGen.hxx" #include "pySpace.hxx" #include "pyVector.hxx" #include "export_typedes.hxx" #include "converter.hxx" using namespace opengm::python; void translateOpenGmRuntimeError(opengm::RuntimeError const& e){ PyErr_SetString(PyExc_RuntimeError, e.what()); } void translateStdRuntimeError(std::runtime_error const& e){ PyErr_SetString(PyExc_RuntimeError, e.what()); } using namespace boost::python; opengm::python::IndexVectorVectorType * secondOrderGridVis( const size_t dx, const size_t dy, bool order ){ // calculate the number of factors... const size_t hFactors=(dx-1)*dy; const size_t vFactors=(dy-1)*dx; const size_t numFac=hFactors+vFactors; // opengm::python::IndexVectorVectorType * vecVec=new opengm::python::IndexVectorVectorType( numFac,opengm::python::IndexVectorType(2)); size_t fi=0; if(order){ for(size_t x=0;x<dx;++x) for(size_t y=0;y<dy;++y){ if(x+1<dx){ (*vecVec)[fi][0]=(y+x*dy); (*vecVec)[fi][1]=(y+(x+1)*dy); ++fi; } if(y+1<dy){ boost::python::list vis; (*vecVec)[fi][0]=(y+x*dy); (*vecVec)[fi][1]=((y+1)+x*dy); ++fi; } } } else{ for(size_t x=0;x<dx;++x) for(size_t y=0;y<dy;++y){ if(y+1<dy){ (*vecVec)[fi][0]=(x+y*dx); (*vecVec)[fi][1]=(x+(y+1)*dx); ++fi; } if(x+1<dx){ boost::python::list vis; (*vecVec)[fi][0]=(x+y*dx); (*vecVec)[fi][1]=((x+1)+y*dx); ++fi; } } } return vecVec; } // numpy extensions template<class V> boost::python::tuple findFirst( NumpyView<V,1> toFind, NumpyView<V,1> container ){ typedef opengm::UInt64Type ResultTypePosition; // position boost::python::object position = get1dArray<ResultTypePosition>(toFind.size()); ResultTypePosition * castPtrPosition = getCastedPtr<ResultTypePosition>(position); // found boost::python::object found = get1dArray<bool>(toFind.size()); bool * castPtrFound = getCastedPtr<bool>(found); // fill map with positions of values to find typedef std::map<V,size_t> MapType; typedef typename MapType::const_iterator MapIter; std::map<V,size_t> toFindPosition; for(size_t i=0;i<toFind.size();++i){ toFindPosition.insert(std::pair<V,size_t>(toFind(i),i)); castPtrFound[i]=false; } // find values size_t numFound=0; for(size_t i=0;i<container.size();++i){ const V value = container(i); MapIter findVal=toFindPosition.find(value); if( findVal!=toFindPosition.end()){ const size_t posInToFind = findVal->second; if(castPtrFound[posInToFind]==false){ castPtrPosition[posInToFind]=static_cast<ResultTypePosition>(i); castPtrFound[posInToFind]=true; numFound+=1; } if(numFound==toFind.size()){ break; } } } // return the positions and where if they have been found return boost::python::make_tuple(position,found); } template<class D> typename D::value_type dequeFront(const D & deque){return deque.front();} template<class D> typename D::value_type dequeBack(const D & deque){return deque.back();} template<class D> typename D::value_type dequePushBack( D & deque, NumpyView<typename D::value_type,1> values ){ for(size_t i=0;i<values.size();++i) deque.push_back(values(i)); } BOOST_PYTHON_MODULE_INIT(_opengmcore) { Py_Initialize(); PyEval_InitThreads(); boost::python::numeric::array::set_module_and_type("numpy", "ndarray"); boost::python::docstring_options docstringOptions(true,true,false); // specify that this module is actually a package object package = scope(); package.attr("__path__") = "opengm"; import_array(); register_exception_translator<opengm::RuntimeError>(&translateOpenGmRuntimeError); register_exception_translator<std::runtime_error>(&translateStdRuntimeError); // converters 1d initializeNumpyViewConverters<bool,1>(); initializeNumpyViewConverters<float,1>(); initializeNumpyViewConverters<double,1>(); initializeNumpyViewConverters<opengm::UInt32Type,1>(); initializeNumpyViewConverters<opengm::UInt64Type,1>(); initializeNumpyViewConverters<opengm::Int32Type,1>(); initializeNumpyViewConverters<opengm::Int64Type,1>(); // converters 2d initializeNumpyViewConverters<bool,2>(); initializeNumpyViewConverters<float,2>(); initializeNumpyViewConverters<double,2>(); initializeNumpyViewConverters<opengm::UInt32Type,2>(); initializeNumpyViewConverters<opengm::UInt64Type,2>(); initializeNumpyViewConverters<opengm::Int32Type,2>(); initializeNumpyViewConverters<opengm::Int64Type,2>(); // converters 3d initializeNumpyViewConverters<bool,3>(); initializeNumpyViewConverters<float,3>(); initializeNumpyViewConverters<double,3>(); initializeNumpyViewConverters<opengm::UInt32Type,3>(); initializeNumpyViewConverters<opengm::UInt64Type,3>(); initializeNumpyViewConverters<opengm::Int32Type,3>(); initializeNumpyViewConverters<opengm::Int64Type,3>(); // converters nd initializeNumpyViewConverters<bool,0>(); initializeNumpyViewConverters<float,0>(); initializeNumpyViewConverters<double,0>(); initializeNumpyViewConverters<opengm::UInt32Type,0>(); initializeNumpyViewConverters<opengm::UInt64Type,0>(); initializeNumpyViewConverters<opengm::Int32Type,0>(); initializeNumpyViewConverters<opengm::Int64Type,0>(); std::string adderString="adder"; std::string multiplierString="multiplier"; scope current; std::string currentScopeName(extract<const char*>(current.attr("__name__"))); currentScopeName="opengm"; class_< opengm::meta::EmptyType > ("_EmptyType",init<>()) ; def("secondOrderGridVis", &secondOrderGridVis,return_value_policy<manage_new_object>(),(arg("dimX"),arg("dimY"),arg("numpyOrder")=true), "Todo.." ); // utilities { std::string substring="utilities"; std::string submoduleName = currentScopeName + std::string(".") + substring; // Create the submodule, and attach it to the current scope. object submodule(borrowed(PyImport_AddModule(submoduleName.c_str()))); current.attr(substring.c_str()) = submodule; // Switch the scope to the submodule scope submoduleScope = submodule; //boost::python::def("findFirst",& findFirst<opengm::UInt32Type>); boost::python::def("findFirst",& findFirst<opengm::UInt64Type>); //boost::python::def("findFirst",& findFirst<opengm::Int32Type>); //boost::python::def("findFirst",& findFirst<opengm::Int64Type>); typedef std::deque<opengm::UInt64Type> DequeUInt64; boost::python::class_<DequeUInt64>("DequeUInt64" ,init<>()) .def("pop_front",&DequeUInt64::pop_front) .def("pop_back",&DequeUInt64::pop_back) .def("front",&dequeFront<DequeUInt64>) .def("back",&dequeBack<DequeUInt64>) .def("push_front",&DequeUInt64::push_front) .def("push_back",&DequeUInt64::push_back) .def("push_back",&dequePushBack<DequeUInt64>) .def("__len__",&DequeUInt64::size) .def("empty",&DequeUInt64::empty) .def("clear",&DequeUInt64::clear) ; } //export_rag(); export_config(); export_vectors<GmIndexType>(); export_space<GmIndexType>(); export_functiontypes<GmValueType,GmIndexType>(); export_fid<GmIndexType>(); export_ifactor<GmValueType,GmIndexType>(); export_enum(); export_function_generator<GmAdder,GmMultiplier>(); //adder { std::string substring=adderString; std::string submoduleName = currentScopeName + std::string(".") + substring; // Create the submodule, and attach it to the current scope. object submodule(borrowed(PyImport_AddModule(submoduleName.c_str()))); current.attr(substring.c_str()) = submodule; // Switch the scope to the submodule, add methods and classes. scope submoduleScope = submodule; export_gm<GmAdder>(); export_factor<GmAdder>(); export_movemaker<GmAdder>(); export_gm_manipulator<GmAdder>(); } //multiplier { std::string substring=multiplierString; std::string submoduleName = currentScopeName + std::string(".") + substring; // Create the submodule, and attach it to the current scope. object submodule(borrowed(PyImport_AddModule(submoduleName.c_str()))); current.attr(substring.c_str()) = submodule; // Switch the scope to the submodule, add methods and classes. scope submoduleScope = submodule; export_gm<GmMultiplier>(); export_factor<GmMultiplier>(); export_movemaker<GmMultiplier>(); export_gm_manipulator<GmMultiplier>(); } } <commit_msg>hotfix part2<commit_after>#define PY_ARRAY_UNIQUE_SYMBOL PyArrayHandleCoreOPENGM #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <boost/python/exception_translator.hpp> #include <stddef.h> #include <deque> #include <exception> #include <opengm/graphicalmodel/graphicalmodel.hxx> #include <opengm/utilities/tribool.hxx> #include <opengm/inference/inference.hxx> #include "copyhelper.hxx" #include "pyConfig.hxx" #include "pyFactor.hxx" #include "pyMovemaker.hxx" #include "pyGmManipulator.hxx" #include "pyIfactor.hxx" #include "pyGm.hxx" #include "pyFid.hxx" #include "pyEnum.hxx" #include "pyFunctionTypes.hxx" #include "pyFunctionGen.hxx" #include "pySpace.hxx" #include "pyVector.hxx" #include "export_typedes.hxx" #include "converter.hxx" using namespace opengm::python; void translateOpenGmRuntimeError(opengm::RuntimeError const& e){ PyErr_SetString(PyExc_RuntimeError, e.what()); } void translateStdRuntimeError(std::runtime_error const& e){ PyErr_SetString(PyExc_RuntimeError, e.what()); } using namespace boost::python; template<class INDEX> std::vector< std::vector < INDEX > > * secondOrderGridVis( const size_t dx, const size_t dy, bool order ){ typedef std::vector<INDEX> InnerVec : typedef std::vector<InnerVec> VeVec; // calculate the number of factors... const size_t hFactors=(dx-1)*dy; const size_t vFactors=(dy-1)*dx; const size_t numFac=hFactors+vFactors; // VeVec * vecVec=new VeVec(numFac,InnerVec(2)); size_t fi=0; if(order){ for(size_t x=0;x<dx;++x) for(size_t y=0;y<dy;++y){ if(x+1<dx){ (*vecVec)[fi][0]=(y+x*dy); (*vecVec)[fi][1]=(y+(x+1)*dy); ++fi; } if(y+1<dy){ boost::python::list vis; (*vecVec)[fi][0]=(y+x*dy); (*vecVec)[fi][1]=((y+1)+x*dy); ++fi; } } } else{ for(size_t x=0;x<dx;++x) for(size_t y=0;y<dy;++y){ if(y+1<dy){ (*vecVec)[fi][0]=(x+y*dx); (*vecVec)[fi][1]=(x+(y+1)*dx); ++fi; } if(x+1<dx){ boost::python::list vis; (*vecVec)[fi][0]=(x+y*dx); (*vecVec)[fi][1]=((x+1)+y*dx); ++fi; } } } return vecVec; } // numpy extensions template<class V> boost::python::tuple findFirst( NumpyView<V,1> toFind, NumpyView<V,1> container ){ typedef opengm::UInt64Type ResultTypePosition; // position boost::python::object position = get1dArray<ResultTypePosition>(toFind.size()); ResultTypePosition * castPtrPosition = getCastedPtr<ResultTypePosition>(position); // found boost::python::object found = get1dArray<bool>(toFind.size()); bool * castPtrFound = getCastedPtr<bool>(found); // fill map with positions of values to find typedef std::map<V,size_t> MapType; typedef typename MapType::const_iterator MapIter; std::map<V,size_t> toFindPosition; for(size_t i=0;i<toFind.size();++i){ toFindPosition.insert(std::pair<V,size_t>(toFind(i),i)); castPtrFound[i]=false; } // find values size_t numFound=0; for(size_t i=0;i<container.size();++i){ const V value = container(i); MapIter findVal=toFindPosition.find(value); if( findVal!=toFindPosition.end()){ const size_t posInToFind = findVal->second; if(castPtrFound[posInToFind]==false){ castPtrPosition[posInToFind]=static_cast<ResultTypePosition>(i); castPtrFound[posInToFind]=true; numFound+=1; } if(numFound==toFind.size()){ break; } } } // return the positions and where if they have been found return boost::python::make_tuple(position,found); } template<class D> typename D::value_type dequeFront(const D & deque){return deque.front();} template<class D> typename D::value_type dequeBack(const D & deque){return deque.back();} template<class D> typename D::value_type dequePushBack( D & deque, NumpyView<typename D::value_type,1> values ){ for(size_t i=0;i<values.size();++i) deque.push_back(values(i)); } BOOST_PYTHON_MODULE_INIT(_opengmcore) { Py_Initialize(); PyEval_InitThreads(); boost::python::numeric::array::set_module_and_type("numpy", "ndarray"); boost::python::docstring_options docstringOptions(true,true,false); // specify that this module is actually a package object package = scope(); package.attr("__path__") = "opengm"; import_array(); register_exception_translator<opengm::RuntimeError>(&translateOpenGmRuntimeError); register_exception_translator<std::runtime_error>(&translateStdRuntimeError); // converters 1d initializeNumpyViewConverters<bool,1>(); initializeNumpyViewConverters<float,1>(); initializeNumpyViewConverters<double,1>(); initializeNumpyViewConverters<opengm::UInt32Type,1>(); initializeNumpyViewConverters<opengm::UInt64Type,1>(); initializeNumpyViewConverters<opengm::Int32Type,1>(); initializeNumpyViewConverters<opengm::Int64Type,1>(); // converters 2d initializeNumpyViewConverters<bool,2>(); initializeNumpyViewConverters<float,2>(); initializeNumpyViewConverters<double,2>(); initializeNumpyViewConverters<opengm::UInt32Type,2>(); initializeNumpyViewConverters<opengm::UInt64Type,2>(); initializeNumpyViewConverters<opengm::Int32Type,2>(); initializeNumpyViewConverters<opengm::Int64Type,2>(); // converters 3d initializeNumpyViewConverters<bool,3>(); initializeNumpyViewConverters<float,3>(); initializeNumpyViewConverters<double,3>(); initializeNumpyViewConverters<opengm::UInt32Type,3>(); initializeNumpyViewConverters<opengm::UInt64Type,3>(); initializeNumpyViewConverters<opengm::Int32Type,3>(); initializeNumpyViewConverters<opengm::Int64Type,3>(); // converters nd initializeNumpyViewConverters<bool,0>(); initializeNumpyViewConverters<float,0>(); initializeNumpyViewConverters<double,0>(); initializeNumpyViewConverters<opengm::UInt32Type,0>(); initializeNumpyViewConverters<opengm::UInt64Type,0>(); initializeNumpyViewConverters<opengm::Int32Type,0>(); initializeNumpyViewConverters<opengm::Int64Type,0>(); std::string adderString="adder"; std::string multiplierString="multiplier"; scope current; std::string currentScopeName(extract<const char*>(current.attr("__name__"))); currentScopeName="opengm"; class_< opengm::meta::EmptyType > ("_EmptyType",init<>()) ; def("secondOrderGridVis", &secondOrderGridVis<UInt64Type>,return_value_policy<manage_new_object>(),(arg("dimX"),arg("dimY"),arg("numpyOrder")=true), "Todo.." ); // utilities { std::string substring="utilities"; std::string submoduleName = currentScopeName + std::string(".") + substring; // Create the submodule, and attach it to the current scope. object submodule(borrowed(PyImport_AddModule(submoduleName.c_str()))); current.attr(substring.c_str()) = submodule; // Switch the scope to the submodule scope submoduleScope = submodule; //boost::python::def("findFirst",& findFirst<opengm::UInt32Type>); boost::python::def("findFirst",& findFirst<opengm::UInt64Type>); //boost::python::def("findFirst",& findFirst<opengm::Int32Type>); //boost::python::def("findFirst",& findFirst<opengm::Int64Type>); typedef std::deque<opengm::UInt64Type> DequeUInt64; boost::python::class_<DequeUInt64>("DequeUInt64" ,init<>()) .def("pop_front",&DequeUInt64::pop_front) .def("pop_back",&DequeUInt64::pop_back) .def("front",&dequeFront<DequeUInt64>) .def("back",&dequeBack<DequeUInt64>) .def("push_front",&DequeUInt64::push_front) .def("push_back",&DequeUInt64::push_back) .def("push_back",&dequePushBack<DequeUInt64>) .def("__len__",&DequeUInt64::size) .def("empty",&DequeUInt64::empty) .def("clear",&DequeUInt64::clear) ; } //export_rag(); export_config(); export_vectors<GmIndexType>(); export_space<GmIndexType>(); export_functiontypes<GmValueType,GmIndexType>(); export_fid<GmIndexType>(); export_ifactor<GmValueType,GmIndexType>(); export_enum(); export_function_generator<GmAdder,GmMultiplier>(); //adder { std::string substring=adderString; std::string submoduleName = currentScopeName + std::string(".") + substring; // Create the submodule, and attach it to the current scope. object submodule(borrowed(PyImport_AddModule(submoduleName.c_str()))); current.attr(substring.c_str()) = submodule; // Switch the scope to the submodule, add methods and classes. scope submoduleScope = submodule; export_gm<GmAdder>(); export_factor<GmAdder>(); export_movemaker<GmAdder>(); export_gm_manipulator<GmAdder>(); } //multiplier { std::string substring=multiplierString; std::string submoduleName = currentScopeName + std::string(".") + substring; // Create the submodule, and attach it to the current scope. object submodule(borrowed(PyImport_AddModule(submoduleName.c_str()))); current.attr(substring.c_str()) = submodule; // Switch the scope to the submodule, add methods and classes. scope submoduleScope = submodule; export_gm<GmMultiplier>(); export_factor<GmMultiplier>(); export_movemaker<GmMultiplier>(); export_gm_manipulator<GmMultiplier>(); } } <|endoftext|>
<commit_before>#include "compiler.h" #include "brainfuck.h" #include "Interpreter/ConvenienceFuck.h" #include "NasmGenerator/BrainfuckNasmConverter.h" #include "boost/program_options.hpp" #include <iostream> #include <fstream> #include <sstream> #include <string> #include <stack> #include <stdlib.h> namespace { const size_t ERROR_IN_COMMAND_LINE = 1; const size_t SUCCESS = 0; const size_t ERROR_UNHANDLED_EXCEPTION = 2; } int main(int argc, char** argv) { try { // Define and parse the program options namespace po = boost::program_options; po::options_description desc("Options"); desc.add_options() ("help", "Print help messages") ("output,o", po::value<std::string>(), "Output filename (default is <input filename>.bf)") ("input,i", po::value<std::string>()->required(), "File to compile") ("print,p", "Print the program on the screen after compiling (does not save it if --output is not set)") ("run,r", "Run the program after compiling it") ("nasm,n", po::value<std::string>(), "Convert generated brainfuck code to NASM (specify target platform by this parameter, may be win32 or unix)"); po::positional_options_description positionalOptions; positionalOptions.add("input", 1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv).options(desc).positional(positionalOptions).run(), vm); // --help if (vm.count("help")) { std::cout << "Metafuck Compiler" << std::endl << desc << std::endl; return SUCCESS; } po::notify(vm); // throws on error } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; std::cerr << desc << std::endl; return ERROR_IN_COMMAND_LINE; } // Application code std::ifstream in; in.open(vm["input"].as<std::string>()); std::stringstream mfstream; mfstream << in.rdbuf();//read the file in.close(); bool shallOptimize = !vm.count("nasm"); //TODO: add a command-line parameter for this Compiler com(mfstream.str(), shallOptimize); com.lex(); com.compile(); if (vm.count("nasm")) { TargetPlatform target = TargetPlatform::UNKNOWN; if (vm["nasm"].as<std::string>() == "win32") target = TargetPlatform::WIN32NT; else if (vm["nasm"].as<std::string>() == "unix") target = TargetPlatform::UNIX; if (target != TargetPlatform::UNKNOWN && (vm.count("output") || !vm.count("print"))) { std::ofstream out; std::string asmFilename = vm.count("output") ? vm["output"].as<std::string>() : vm["input"].as<std::string>() + ".asm"; out.open(asmFilename); out << bf2nasm(com.getGeneratedCode(), target); out.close(); if (target == TargetPlatform::WIN32NT){ system(("nasm -fobj \"" + asmFilename + "\" -o \"" + asmFilename + ".obj\"").c_str()); system(("alink -oPE -subsys console \"" + asmFilename + ".obj\" -o \"" + asmFilename + ".exe\"").c_str()); } else { system(("nasm -felf \"" + asmFilename + "\" -o \"" + asmFilename + ".obj\"").c_str()); system(("ld -melf_i386 -s -o \"" + asmFilename + ".out\" \"" + asmFilename + ".obj\"").c_str()); } } } else { if (vm.count("output") || !vm.count("print")) { std::ofstream out; out.open(vm.count("output") ? vm["output"].as<std::string>() : vm["input"].as<std::string>() + ".bf"); out << com.getGeneratedCode(); out.close(); } } if (vm.count("print")) { std::cout << com.getGeneratedCode() << std::endl; } if (vm.count("run")) { std::cout << "___" << std::endl << "Running:" << std::endl; RunBrainfuckProgram(com.getGeneratedCode()); } return SUCCESS; } catch (std::exception& e) { std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl; return ERROR_UNHANDLED_EXCEPTION; } } <commit_msg>Added error messages when nasm, alink or ld fail.<commit_after>#include "compiler.h" #include "brainfuck.h" #include "Interpreter/ConvenienceFuck.h" #include "NasmGenerator/BrainfuckNasmConverter.h" #include "boost/program_options.hpp" #include <iostream> #include <fstream> #include <sstream> #include <string> #include <stack> #include <stdlib.h> namespace { const size_t ERROR_IN_COMMAND_LINE = 1; const size_t SUCCESS = 0; const size_t ERROR_UNHANDLED_EXCEPTION = 2; } int main(int argc, char** argv) { try { // Define and parse the program options namespace po = boost::program_options; po::options_description desc("Options"); desc.add_options() ("help", "Print help messages") ("output,o", po::value<std::string>(), "Output filename (default is <input filename>.bf)") ("input,i", po::value<std::string>()->required(), "File to compile") ("print,p", "Print the program on the screen after compiling (does not save it if --output is not set)") ("run,r", "Run the program after compiling it") ("nasm,n", po::value<std::string>(), "Convert generated brainfuck code to NASM (specify target platform by this parameter, may be win32 or unix)"); po::positional_options_description positionalOptions; positionalOptions.add("input", 1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv).options(desc).positional(positionalOptions).run(), vm); // --help if (vm.count("help")) { std::cout << "Metafuck Compiler" << std::endl << desc << std::endl; return SUCCESS; } po::notify(vm); // throws on error } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; std::cerr << desc << std::endl; return ERROR_IN_COMMAND_LINE; } // Application code std::ifstream in; in.open(vm["input"].as<std::string>()); std::stringstream mfstream; mfstream << in.rdbuf();//read the file in.close(); bool shallOptimize = !vm.count("nasm"); //TODO: add a command-line parameter for this Compiler com(mfstream.str(), shallOptimize); com.lex(); com.compile(); if (vm.count("nasm")) { TargetPlatform target = TargetPlatform::UNKNOWN; if (vm["nasm"].as<std::string>() == "win32") target = TargetPlatform::WIN32NT; else if (vm["nasm"].as<std::string>() == "unix") target = TargetPlatform::UNIX; if (target != TargetPlatform::UNKNOWN && (vm.count("output") || !vm.count("print"))) { std::ofstream out; std::string asmFilename = vm.count("output") ? vm["output"].as<std::string>() : vm["input"].as<std::string>() + ".asm"; out.open(asmFilename); out << bf2nasm(com.getGeneratedCode(), target); out.close(); if (target == TargetPlatform::WIN32NT){ int nasm_res = system(("nasm -fobj \"" + asmFilename + "\" -o \"" + asmFilename + ".obj\"").c_str()); if (nasm_res == 0) { int alink_res = system(("alink -oPE -subsys console \"" + asmFilename + ".obj\" -o \"" + asmFilename + ".exe\"").c_str()); if (alink_res != 0) { std::cerr << "alink failed" << std::endl; } } else { std::cerr << "nasm failed" << std::endl; } } else { int nasm_res = system(("nasm -felf \"" + asmFilename + "\" -o \"" + asmFilename + ".obj\"").c_str()); if (nasm_res == 0) { int ld_res = system(("ld -melf_i386 -s -o \"" + asmFilename + ".out\" \"" + asmFilename + ".obj\"").c_str()); if (ld_res != 0) { std::cerr << "ld failed" << std::endl; } } else { std::cerr << "nasm failed" << std::endl; } } } } else { if (vm.count("output") || !vm.count("print")) { std::ofstream out; out.open(vm.count("output") ? vm["output"].as<std::string>() : vm["input"].as<std::string>() + ".bf"); out << com.getGeneratedCode(); out.close(); } } if (vm.count("print")) { std::cout << com.getGeneratedCode() << std::endl; } if (vm.count("run")) { std::cout << "___" << std::endl << "Running:" << std::endl; RunBrainfuckProgram(com.getGeneratedCode()); } return SUCCESS; } catch (std::exception& e) { std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl; return ERROR_UNHANDLED_EXCEPTION; } } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * adiosMemory.cpp * * Created on: Oct 31, 2018 * Author: William F Godoy [email protected] */ #include "adiosMemory.h" #include <algorithm> #include <stddef.h> // max_align_t #include "adios2/helper/adiosType.h" namespace adios2 { namespace helper { namespace { void CopyPayloadStride(const char *src, const size_t payloadStride, char *dest, const bool endianReverse, const DataType destType) { #ifdef ADIOS2_HAVE_ENDIAN_REVERSE if (endianReverse) { if (destType == "") { } #define declare_type(T) \ else if (destType == GetDataType<T>()) \ { \ CopyEndianReverse<T>(src, payloadStride, reinterpret_cast<T *>(dest)); \ } ADIOS2_FOREACH_PRIMITIVE_STDTYPE_1ARG(declare_type) #undef declare_type } else { std::copy(src, src + payloadStride, dest); } #else std::copy(src, src + payloadStride, dest); #endif } Dims DestDimsFinal(const Dims &destDims, const bool destRowMajor, const bool srcRowMajor) { Dims destDimsFinal = destDims; if (srcRowMajor != destRowMajor) { std::reverse(destDimsFinal.begin(), destDimsFinal.end()); } return destDimsFinal; } void ClipRowMajor(char *dest, const Dims &destStart, const Dims &destCount, const bool destRowMajor, const char *src, const Dims &srcStart, const Dims &srcCount, const Dims & /*destMemStart*/, const Dims & /*destMemCount*/, const Dims &srcMemStart, const Dims &srcMemCount, const bool endianReverse, const DataType destType) { const Dims destStartFinal = DestDimsFinal(destStart, destRowMajor, true); const Dims destCountFinal = DestDimsFinal(destCount, destRowMajor, true); const Box<Dims> intersectionBox = IntersectionStartCount( destStartFinal, destCountFinal, srcStart, srcCount); const Dims &interStart = intersectionBox.first; const Dims &interCount = intersectionBox.second; // loop through intersection start and end and check if it's equal to the // srcBox contiguous part const size_t dimensions = interStart.size(); size_t stride = interCount.back(); size_t startCoord = dimensions - 2; // bool isWholeCopy = false; // // for (size_t i = dimensions - 1; i >= 0; --i) // { // // same as source // if (interCount[i] == srcCount[i]) // { // stride *= interCount[i - 1]; // if (startCoord > 0) // { // --startCoord; // } // if (startCoord == 0) // { // isWholeCopy = true; // } // } // else // { // break; // } // } /// start iteration Dims currentPoint(interStart); // current point for memory copy const size_t interOffset = LinearIndex(srcStart, srcCount, interStart, true); bool run = true; while (run) { // here copy current linear memory between currentPoint and end const size_t srcBeginOffset = srcMemStart.empty() ? LinearIndex(srcStart, srcCount, currentPoint, true) - interOffset : LinearIndex(Dims(srcMemCount.size(), 0), srcMemCount, VectorsOp(std::plus<size_t>(), VectorsOp(std::minus<size_t>(), currentPoint, interStart), srcMemStart), true); const size_t destBeginOffset = helper::LinearIndex( destStartFinal, destCountFinal, currentPoint, true); CopyPayloadStride(src + srcBeginOffset, stride, dest + destBeginOffset, endianReverse, destType); size_t p = startCoord; while (true) { ++currentPoint[p]; if (currentPoint[p] > interStart[p] + interCount[p] - 1) { if (p == 0) { run = false; // we are done break; } else { currentPoint[p] = interStart[p]; --p; } } else { break; // break inner p loop } } // dimension index update } } void ClipColumnMajor(char *dest, const Dims &destStart, const Dims &destCount, const bool destRowMajor, const char *src, const Dims &srcStart, const Dims &srcCount, const Dims & /*destMemStart*/, const Dims & /*destMemCount*/, const Dims &srcMemStart, const Dims &srcMemCount, const bool endianReverse, const DataType destType) { const Dims destStartFinal = DestDimsFinal(destStart, destRowMajor, false); const Dims destCountFinal = DestDimsFinal(destCount, destRowMajor, false); const Box<Dims> intersectionBox = IntersectionStartCount( destStartFinal, destCountFinal, srcStart, srcCount); const Dims &interStart = intersectionBox.first; const Dims &interCount = intersectionBox.second; // loop through intersection start and end and check if it's equal to the // srcBox contiguous part const size_t dimensions = interStart.size(); size_t stride = interCount.front(); size_t startCoord = 1; // for (size_t i = 0; i < dimensions; ++i) // { // // same as source // if (interCount[i] == srcCount[i]) // { // stride *= interCount[i]; // // startCoord = i + 1; // } // else // { // break; // } // } /// start iteration Dims currentPoint(interStart); // current point for memory copy const size_t interOffset = LinearIndex(srcStart, srcCount, interStart, false); bool run = true; while (run) { // here copy current linear memory between currentPoint and end const size_t srcBeginOffset = srcMemStart.empty() ? LinearIndex(srcStart, srcCount, currentPoint, false) - interOffset : LinearIndex(Dims(srcMemCount.size(), 0), srcMemCount, VectorsOp(std::plus<size_t>(), VectorsOp(std::minus<size_t>(), currentPoint, interStart), srcMemStart), false); const size_t destBeginOffset = helper::LinearIndex( destStartFinal, destCountFinal, currentPoint, false); CopyPayloadStride(src + srcBeginOffset, stride, dest + destBeginOffset, endianReverse, destType); size_t p = startCoord; while (true) { ++currentPoint[p]; if (currentPoint[p] > interStart[p] + interCount[p] - 1) { if (p == dimensions - 1) { run = false; // we are done break; } else { currentPoint[p] = interStart[p]; ++p; } } else { break; // break inner p loop } } // dimension index update } } } // end empty namespace void CopyPayload(char *dest, const Dims &destStart, const Dims &destCount, const bool destRowMajor, const char *src, const Dims &srcStart, const Dims &srcCount, const bool srcRowMajor, const Dims &destMemStart, const Dims &destMemCount, const Dims &srcMemStart, const Dims &srcMemCount, const bool endianReverse, const DataType destType) noexcept { if (srcStart.size() == 1) // 1D copy memory { const Box<Dims> intersectionBox = IntersectionStartCount(destStart, destCount, srcStart, srcCount); const Dims &interStart = intersectionBox.first; const Dims &interCount = intersectionBox.second; const size_t srcBeginOffset = srcMemStart.empty() ? interStart.front() - srcStart.front() : interStart.front() - srcStart.front() + srcMemStart.front(); const size_t stride = interCount.front(); const size_t destBeginOffset = interStart.front() - destStart.front(); CopyPayloadStride(src + srcBeginOffset, stride, dest + destBeginOffset, endianReverse, destType); return; } if (srcRowMajor) // stored with C, C++, Python { ClipRowMajor(dest, destStart, destCount, destRowMajor, src, srcStart, srcCount, destMemStart, destMemCount, srcMemStart, srcMemCount, endianReverse, destType); } else // stored with Fortran, R { ClipColumnMajor(dest, destStart, destCount, destRowMajor, src, srcStart, srcCount, destMemStart, destMemCount, srcMemStart, srcMemCount, endianReverse, destType); } } size_t PaddingToAlignPointer(const void *ptr) { auto memLocation = reinterpret_cast<std::uintptr_t>(ptr); size_t padSize = sizeof(max_align_t) - (memLocation % sizeof(max_align_t)); if (padSize == sizeof(max_align_t)) { padSize = 0; } return padSize; } } // end namespace helper } // end namespace adios2 <commit_msg>Fix Broken Endinage Reverse Compile<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * adiosMemory.cpp * * Created on: Oct 31, 2018 * Author: William F Godoy [email protected] */ #include "adiosMemory.h" #include <algorithm> #include <stddef.h> // max_align_t #include "adios2/helper/adiosType.h" namespace adios2 { namespace helper { namespace { void CopyPayloadStride(const char *src, const size_t payloadStride, char *dest, const bool endianReverse, const DataType destType) { #ifdef ADIOS2_HAVE_ENDIAN_REVERSE if (endianReverse) { if (destType == DataType::None) { } #define declare_type(T) \ else if (destType == GetDataType<T>()) \ { \ CopyEndianReverse<T>(src, payloadStride, reinterpret_cast<T *>(dest)); \ } ADIOS2_FOREACH_PRIMITIVE_STDTYPE_1ARG(declare_type) #undef declare_type } else { std::copy(src, src + payloadStride, dest); } #else std::copy(src, src + payloadStride, dest); #endif } Dims DestDimsFinal(const Dims &destDims, const bool destRowMajor, const bool srcRowMajor) { Dims destDimsFinal = destDims; if (srcRowMajor != destRowMajor) { std::reverse(destDimsFinal.begin(), destDimsFinal.end()); } return destDimsFinal; } void ClipRowMajor(char *dest, const Dims &destStart, const Dims &destCount, const bool destRowMajor, const char *src, const Dims &srcStart, const Dims &srcCount, const Dims & /*destMemStart*/, const Dims & /*destMemCount*/, const Dims &srcMemStart, const Dims &srcMemCount, const bool endianReverse, const DataType destType) { const Dims destStartFinal = DestDimsFinal(destStart, destRowMajor, true); const Dims destCountFinal = DestDimsFinal(destCount, destRowMajor, true); const Box<Dims> intersectionBox = IntersectionStartCount( destStartFinal, destCountFinal, srcStart, srcCount); const Dims &interStart = intersectionBox.first; const Dims &interCount = intersectionBox.second; // loop through intersection start and end and check if it's equal to the // srcBox contiguous part const size_t dimensions = interStart.size(); size_t stride = interCount.back(); size_t startCoord = dimensions - 2; // bool isWholeCopy = false; // // for (size_t i = dimensions - 1; i >= 0; --i) // { // // same as source // if (interCount[i] == srcCount[i]) // { // stride *= interCount[i - 1]; // if (startCoord > 0) // { // --startCoord; // } // if (startCoord == 0) // { // isWholeCopy = true; // } // } // else // { // break; // } // } /// start iteration Dims currentPoint(interStart); // current point for memory copy const size_t interOffset = LinearIndex(srcStart, srcCount, interStart, true); bool run = true; while (run) { // here copy current linear memory between currentPoint and end const size_t srcBeginOffset = srcMemStart.empty() ? LinearIndex(srcStart, srcCount, currentPoint, true) - interOffset : LinearIndex(Dims(srcMemCount.size(), 0), srcMemCount, VectorsOp(std::plus<size_t>(), VectorsOp(std::minus<size_t>(), currentPoint, interStart), srcMemStart), true); const size_t destBeginOffset = helper::LinearIndex( destStartFinal, destCountFinal, currentPoint, true); CopyPayloadStride(src + srcBeginOffset, stride, dest + destBeginOffset, endianReverse, destType); size_t p = startCoord; while (true) { ++currentPoint[p]; if (currentPoint[p] > interStart[p] + interCount[p] - 1) { if (p == 0) { run = false; // we are done break; } else { currentPoint[p] = interStart[p]; --p; } } else { break; // break inner p loop } } // dimension index update } } void ClipColumnMajor(char *dest, const Dims &destStart, const Dims &destCount, const bool destRowMajor, const char *src, const Dims &srcStart, const Dims &srcCount, const Dims & /*destMemStart*/, const Dims & /*destMemCount*/, const Dims &srcMemStart, const Dims &srcMemCount, const bool endianReverse, const DataType destType) { const Dims destStartFinal = DestDimsFinal(destStart, destRowMajor, false); const Dims destCountFinal = DestDimsFinal(destCount, destRowMajor, false); const Box<Dims> intersectionBox = IntersectionStartCount( destStartFinal, destCountFinal, srcStart, srcCount); const Dims &interStart = intersectionBox.first; const Dims &interCount = intersectionBox.second; // loop through intersection start and end and check if it's equal to the // srcBox contiguous part const size_t dimensions = interStart.size(); size_t stride = interCount.front(); size_t startCoord = 1; // for (size_t i = 0; i < dimensions; ++i) // { // // same as source // if (interCount[i] == srcCount[i]) // { // stride *= interCount[i]; // // startCoord = i + 1; // } // else // { // break; // } // } /// start iteration Dims currentPoint(interStart); // current point for memory copy const size_t interOffset = LinearIndex(srcStart, srcCount, interStart, false); bool run = true; while (run) { // here copy current linear memory between currentPoint and end const size_t srcBeginOffset = srcMemStart.empty() ? LinearIndex(srcStart, srcCount, currentPoint, false) - interOffset : LinearIndex(Dims(srcMemCount.size(), 0), srcMemCount, VectorsOp(std::plus<size_t>(), VectorsOp(std::minus<size_t>(), currentPoint, interStart), srcMemStart), false); const size_t destBeginOffset = helper::LinearIndex( destStartFinal, destCountFinal, currentPoint, false); CopyPayloadStride(src + srcBeginOffset, stride, dest + destBeginOffset, endianReverse, destType); size_t p = startCoord; while (true) { ++currentPoint[p]; if (currentPoint[p] > interStart[p] + interCount[p] - 1) { if (p == dimensions - 1) { run = false; // we are done break; } else { currentPoint[p] = interStart[p]; ++p; } } else { break; // break inner p loop } } // dimension index update } } } // end empty namespace void CopyPayload(char *dest, const Dims &destStart, const Dims &destCount, const bool destRowMajor, const char *src, const Dims &srcStart, const Dims &srcCount, const bool srcRowMajor, const Dims &destMemStart, const Dims &destMemCount, const Dims &srcMemStart, const Dims &srcMemCount, const bool endianReverse, const DataType destType) noexcept { if (srcStart.size() == 1) // 1D copy memory { const Box<Dims> intersectionBox = IntersectionStartCount(destStart, destCount, srcStart, srcCount); const Dims &interStart = intersectionBox.first; const Dims &interCount = intersectionBox.second; const size_t srcBeginOffset = srcMemStart.empty() ? interStart.front() - srcStart.front() : interStart.front() - srcStart.front() + srcMemStart.front(); const size_t stride = interCount.front(); const size_t destBeginOffset = interStart.front() - destStart.front(); CopyPayloadStride(src + srcBeginOffset, stride, dest + destBeginOffset, endianReverse, destType); return; } if (srcRowMajor) // stored with C, C++, Python { ClipRowMajor(dest, destStart, destCount, destRowMajor, src, srcStart, srcCount, destMemStart, destMemCount, srcMemStart, srcMemCount, endianReverse, destType); } else // stored with Fortran, R { ClipColumnMajor(dest, destStart, destCount, destRowMajor, src, srcStart, srcCount, destMemStart, destMemCount, srcMemStart, srcMemCount, endianReverse, destType); } } size_t PaddingToAlignPointer(const void *ptr) { auto memLocation = reinterpret_cast<std::uintptr_t>(ptr); size_t padSize = sizeof(max_align_t) - (memLocation % sizeof(max_align_t)); if (padSize == sizeof(max_align_t)) { padSize = 0; } return padSize; } } // end namespace helper } // end namespace adios2 <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * adiosSystem.cpp implementation of adiosSystem.h functions * * Created on: May 17, 2017 * Author: William F Godoy [email protected] */ #include "adiosSystem.h" #include <arpa/inet.h> //AvailableIpAddresses() inet_ntoa #include <net/if.h> //AvailableIpAddresses() struct if_nameindex #include <string.h> //AvailableIpAddresses() strncp #include <sys/ioctl.h> //AvailableIpAddresses() ioctl #include <unistd.h> //AvailableIpAddresses() close #include <chrono> //system_clock, now #include <ctime> #include <iostream> //std::cerr #include <stdexcept> // std::runtime_error, std::exception #include <system_error> #include <adios2sys/SystemTools.hxx> #include "adios2/ADIOSMPI.h" #include "adios2/ADIOSTypes.h" #include "adios2/helper/adiosString.h" // remove ctime warning on Windows #ifdef _WIN32 #pragma warning(disable : 4996) // ctime warning #endif namespace adios2 { namespace helper { bool CreateDirectory(const std::string &fullPath) noexcept { return adios2sys::SystemTools::MakeDirectory(fullPath); } bool IsLittleEndian() noexcept { uint16_t hexa = 0x1234; return *reinterpret_cast<uint8_t *>(&hexa) != 0x12; // NOLINT } std::string LocalTimeDate() noexcept { std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); return std::string(ctime(&now)); } bool IsRowMajor(const std::string hostLanguage) noexcept { bool isRowMajor = true; if (hostLanguage == "Fortran" || hostLanguage == "R" || hostLanguage == "Matlab") { isRowMajor = false; } return isRowMajor; } bool IsZeroIndexed(const std::string hostLanguage) noexcept { bool isZeroIndexed = true; if (hostLanguage == "Fortran" || hostLanguage == "R") { isZeroIndexed = false; } return isZeroIndexed; } #ifndef _WIN32 std::vector<std::string> AvailableIpAddresses() noexcept { std::vector<std::string> ips; int socket_handler = -1; struct if_nameindex *p = 0; struct if_nameindex *head = 0; if ((socket_handler = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { return ips; } head = if_nameindex(); p = if_nameindex(); while ((p != NULL) && (p->if_name != NULL)) { struct ifreq req; strncpy(req.ifr_name, p->if_name, IFNAMSIZ); if (ioctl(socket_handler, SIOCGIFADDR, &req) < 0) { if (errno == EADDRNOTAVAIL) { ++p; continue; } close(socket_handler); return ips; } const std::string ip = inet_ntoa(((struct sockaddr_in *)&req.ifr_addr)->sin_addr); if (ip != "127.0.0.1") { ips.emplace_back(ip); } ++p; } if_freenameindex(head); close(socket_handler); return ips; } #endif int ExceptionToError(const std::string &function) { try { throw; } catch (std::invalid_argument &e) { std::cerr << e.what() << "\n"; std::cerr << function << "\n"; return 1; } catch (std::system_error &e) { std::cerr << e.what() << "\n"; std::cerr << function << "\n"; return 2; } catch (std::runtime_error &e) { std::cerr << e.what() << "\n"; std::cerr << function << "\n"; return 3; } catch (std::exception &e) { std::cerr << e.what() << "\n"; std::cerr << function << "\n"; return 4; } } } // end namespace helper } // end namespace adios2 <commit_msg>Update source/adios2/helper/adiosSystem.cpp<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * adiosSystem.cpp implementation of adiosSystem.h functions * * Created on: May 17, 2017 * Author: William F Godoy [email protected] */ #include "adiosSystem.h" #ifndef _WIN32 #include <arpa/inet.h> //AvailableIpAddresses() inet_ntoa #include <net/if.h> //AvailableIpAddresses() struct if_nameindex #include <string.h> //AvailableIpAddresses() strncp #include <sys/ioctl.h> //AvailableIpAddresses() ioctl #include <unistd.h> //AvailableIpAddresses() close #include <chrono> //system_clock, now #include <ctime> #include <iostream> //std::cerr #include <stdexcept> // std::runtime_error, std::exception #include <system_error> #include <adios2sys/SystemTools.hxx> #include "adios2/ADIOSMPI.h" #include "adios2/ADIOSTypes.h" #include "adios2/helper/adiosString.h" // remove ctime warning on Windows #ifdef _WIN32 #pragma warning(disable : 4996) // ctime warning #endif namespace adios2 { namespace helper { bool CreateDirectory(const std::string &fullPath) noexcept { return adios2sys::SystemTools::MakeDirectory(fullPath); } bool IsLittleEndian() noexcept { uint16_t hexa = 0x1234; return *reinterpret_cast<uint8_t *>(&hexa) != 0x12; // NOLINT } std::string LocalTimeDate() noexcept { std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); return std::string(ctime(&now)); } bool IsRowMajor(const std::string hostLanguage) noexcept { bool isRowMajor = true; if (hostLanguage == "Fortran" || hostLanguage == "R" || hostLanguage == "Matlab") { isRowMajor = false; } return isRowMajor; } bool IsZeroIndexed(const std::string hostLanguage) noexcept { bool isZeroIndexed = true; if (hostLanguage == "Fortran" || hostLanguage == "R") { isZeroIndexed = false; } return isZeroIndexed; } #ifndef _WIN32 std::vector<std::string> AvailableIpAddresses() noexcept { std::vector<std::string> ips; int socket_handler = -1; struct if_nameindex *p = 0; struct if_nameindex *head = 0; if ((socket_handler = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { return ips; } head = if_nameindex(); p = if_nameindex(); while ((p != NULL) && (p->if_name != NULL)) { struct ifreq req; strncpy(req.ifr_name, p->if_name, IFNAMSIZ); if (ioctl(socket_handler, SIOCGIFADDR, &req) < 0) { if (errno == EADDRNOTAVAIL) { ++p; continue; } close(socket_handler); return ips; } const std::string ip = inet_ntoa(((struct sockaddr_in *)&req.ifr_addr)->sin_addr); if (ip != "127.0.0.1") { ips.emplace_back(ip); } ++p; } if_freenameindex(head); close(socket_handler); return ips; } #endif int ExceptionToError(const std::string &function) { try { throw; } catch (std::invalid_argument &e) { std::cerr << e.what() << "\n"; std::cerr << function << "\n"; return 1; } catch (std::system_error &e) { std::cerr << e.what() << "\n"; std::cerr << function << "\n"; return 2; } catch (std::runtime_error &e) { std::cerr << e.what() << "\n"; std::cerr << function << "\n"; return 3; } catch (std::exception &e) { std::cerr << e.what() << "\n"; std::cerr << function << "\n"; return 4; } } } // end namespace helper } // end namespace adios2 <|endoftext|>