text
stringlengths
54
60.6k
<commit_before>/* * Copyright (C) 2008-2009 J-P Nurmi [email protected] * * 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 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. * * $Id$ */ #include "ircutil.h" #include <QString> #include <QRegExp> /*! \class Irc::Util ircutil.h \brief The Irc::Util class provides IRC related utility functions. */ static QRegExp URL_PATTERN(QLatin1String("((www\\.(?!\\.)|(ssh|fish|irc|(f|sf|ht)tp(|s))://)(\\.?[\\d\\w/,\\':~\\?=;#@\\-\\+\\%\\*\\{\\}\\!\\(\\)]|&)+)|([-.\\d\\w]+@[-.\\d\\w]{2,}\\.[\\w]{2,})"), Qt::CaseInsensitive); namespace Irc { /*! Parses and returns the nick part from \a target. */ QString Util::nickFromTarget(const QString& target) { int index = target.indexOf(QLatin1Char('!')); return target.left(index); } /*! Parses and returns the host part from \a target. */ QString Util::hostFromTarget(const QString& target) { int index = target.indexOf(QLatin1Char('!')); return target.mid(index + 1); } /*! Converts \a message to HTML. This function parses the message and replaces IRC-style formatting like colors, bold and underline to the corresponding HTML formatting. Furthermore, this function detects URLs and replaces them with appropriate HTML hyperlinks. */ QString Util::messageToHtml(const QString& message) { QString processed = message; processed.replace(QLatin1Char('<'), QLatin1String("&lt;")); processed.replace(QLatin1Char('>'), QLatin1String("&gt;")); processed.replace(QLatin1Char('&'), QLatin1String("&amp;")); enum { None = 0x0, Bold = 0x1, Color = 0x2, Italic = 0x4, StrikeThrough = 0x8, Underline = 0x10, Inverse = 0x20 }; int state = None; int pos = 0; while (pos < processed.size()) { if (state & Color) { QString tmp = processed.mid(pos, 2); processed.remove(pos, 2); processed = processed.arg(colorNameFromCode(tmp.toInt())); state &= ~Color; pos += 2; continue; } QString replacement; switch (processed.at(pos).unicode()) { case '\x02': // bold if (state & Bold) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='font-weight: bold'>"); state ^= Bold; break; case '\x03': // color if (state & Color) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='color: %1'>"); state ^= Color; break; case '\x09': // italic if (state & Italic) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='text-decoration: underline'>"); state ^= Italic; break; case '\x13': // strike-through if (state & StrikeThrough) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='text-decoration: line-through'>"); state ^= StrikeThrough; break; case '\x15': // underline case '\x1f': // underline if (state & Underline) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='text-decoration: underline'>"); state ^= Underline; break; case '\x16': // inverse state ^= Inverse; break; case '\x0f': // none replacement = QLatin1String("</span>"); state = None; break; default: break; } if (!replacement.isNull()) { processed.replace(pos, 1, replacement); pos += replacement.length(); } else { ++pos; } } pos = 0; while ((pos = URL_PATTERN.indexIn(processed, pos)) >= 0) { int len = URL_PATTERN.matchedLength(); QString href = processed.mid(pos, len); // Don't consider trailing &gt; as part of the link. QString append; if (href.endsWith(QLatin1String("&gt;"))) { append.append(href.right(4)); href.chop(4); } // Don't consider trailing comma or semi-colon as part of the link. if (href.endsWith(QLatin1Char(',')) || href.endsWith(QLatin1Char(';'))) { append.append(href.right(1)); href.chop(1); } // Don't consider trailing closing parenthesis part of the link when // there's an opening parenthesis preceding in the beginning of the // URL or there is no opening parenthesis in the URL at all. if (pos > 0 && href.endsWith(QLatin1Char(')')) && (processed.at(pos-1) == QLatin1Char('(') || !href.contains(QLatin1Char('(')))) { append.prepend(href.right(1)); href.chop(1); } // Qt doesn't support (?<=pattern) so we do it here if (pos > 0 && processed.at(pos-1).isLetterOrNumber()) { pos++; continue; } QString protocol; if (URL_PATTERN.cap(1).startsWith(QLatin1String("www."), Qt::CaseInsensitive)) protocol = QLatin1String("http://"); else if (URL_PATTERN.cap(1).isEmpty()) protocol = QLatin1String("mailto:"); QString link = QString(QLatin1String("<a href='%1%2'>%3</a>")).arg(protocol, href, href) + append; processed.replace(pos, len, link); pos += link.length(); } return processed; } /*! Converts \a code to a color name. */ QString Util::colorNameFromCode(int code) { switch (code) { case 0: return QLatin1String("white"); case 1: return QLatin1String("black"); case 2: return QLatin1String("navy"); case 3: return QLatin1String("green"); case 4: return QLatin1String("red"); case 5: return QLatin1String("maroon"); case 6: return QLatin1String("purple"); case 7: return QLatin1String("orange"); case 8: return QLatin1String("yellow"); case 9: return QLatin1String("lime"); case 10: return QLatin1String("darkcyan"); case 11: return QLatin1String("cyan"); case 12: return QLatin1String("blue"); case 13: return QLatin1String("magenta"); case 14: return QLatin1String("gray"); case 15: return QLatin1String("lightgray"); default: return QLatin1String("black"); } } } <commit_msg>Replace &amp; first, then < and >.<commit_after>/* * Copyright (C) 2008-2009 J-P Nurmi [email protected] * * 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 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. * * $Id$ */ #include "ircutil.h" #include <QString> #include <QRegExp> /*! \class Irc::Util ircutil.h \brief The Irc::Util class provides IRC related utility functions. */ static QRegExp URL_PATTERN(QLatin1String("((www\\.(?!\\.)|(ssh|fish|irc|(f|sf|ht)tp(|s))://)(\\.?[\\d\\w/,\\':~\\?=;#@\\-\\+\\%\\*\\{\\}\\!\\(\\)]|&)+)|([-.\\d\\w]+@[-.\\d\\w]{2,}\\.[\\w]{2,})"), Qt::CaseInsensitive); namespace Irc { /*! Parses and returns the nick part from \a target. */ QString Util::nickFromTarget(const QString& target) { int index = target.indexOf(QLatin1Char('!')); return target.left(index); } /*! Parses and returns the host part from \a target. */ QString Util::hostFromTarget(const QString& target) { int index = target.indexOf(QLatin1Char('!')); return target.mid(index + 1); } /*! Converts \a message to HTML. This function parses the message and replaces IRC-style formatting like colors, bold and underline to the corresponding HTML formatting. Furthermore, this function detects URLs and replaces them with appropriate HTML hyperlinks. */ QString Util::messageToHtml(const QString& message) { QString processed = message; processed.replace(QLatin1Char('&'), QLatin1String("&amp;")); processed.replace(QLatin1Char('<'), QLatin1String("&lt;")); processed.replace(QLatin1Char('>'), QLatin1String("&gt;")); enum { None = 0x0, Bold = 0x1, Color = 0x2, Italic = 0x4, StrikeThrough = 0x8, Underline = 0x10, Inverse = 0x20 }; int state = None; int pos = 0; while (pos < processed.size()) { if (state & Color) { QString tmp = processed.mid(pos, 2); processed.remove(pos, 2); processed = processed.arg(colorNameFromCode(tmp.toInt())); state &= ~Color; pos += 2; continue; } QString replacement; switch (processed.at(pos).unicode()) { case '\x02': // bold if (state & Bold) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='font-weight: bold'>"); state ^= Bold; break; case '\x03': // color if (state & Color) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='color: %1'>"); state ^= Color; break; case '\x09': // italic if (state & Italic) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='text-decoration: underline'>"); state ^= Italic; break; case '\x13': // strike-through if (state & StrikeThrough) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='text-decoration: line-through'>"); state ^= StrikeThrough; break; case '\x15': // underline case '\x1f': // underline if (state & Underline) replacement = QLatin1String("</span>"); else replacement = QLatin1String("<span style='text-decoration: underline'>"); state ^= Underline; break; case '\x16': // inverse state ^= Inverse; break; case '\x0f': // none replacement = QLatin1String("</span>"); state = None; break; default: break; } if (!replacement.isNull()) { processed.replace(pos, 1, replacement); pos += replacement.length(); } else { ++pos; } } pos = 0; while ((pos = URL_PATTERN.indexIn(processed, pos)) >= 0) { int len = URL_PATTERN.matchedLength(); QString href = processed.mid(pos, len); // Don't consider trailing &gt; as part of the link. QString append; if (href.endsWith(QLatin1String("&gt;"))) { append.append(href.right(4)); href.chop(4); } // Don't consider trailing comma or semi-colon as part of the link. if (href.endsWith(QLatin1Char(',')) || href.endsWith(QLatin1Char(';'))) { append.append(href.right(1)); href.chop(1); } // Don't consider trailing closing parenthesis part of the link when // there's an opening parenthesis preceding in the beginning of the // URL or there is no opening parenthesis in the URL at all. if (pos > 0 && href.endsWith(QLatin1Char(')')) && (processed.at(pos-1) == QLatin1Char('(') || !href.contains(QLatin1Char('(')))) { append.prepend(href.right(1)); href.chop(1); } // Qt doesn't support (?<=pattern) so we do it here if (pos > 0 && processed.at(pos-1).isLetterOrNumber()) { pos++; continue; } QString protocol; if (URL_PATTERN.cap(1).startsWith(QLatin1String("www."), Qt::CaseInsensitive)) protocol = QLatin1String("http://"); else if (URL_PATTERN.cap(1).isEmpty()) protocol = QLatin1String("mailto:"); QString link = QString(QLatin1String("<a href='%1%2'>%3</a>")).arg(protocol, href, href) + append; processed.replace(pos, len, link); pos += link.length(); } return processed; } /*! Converts \a code to a color name. */ QString Util::colorNameFromCode(int code) { switch (code) { case 0: return QLatin1String("white"); case 1: return QLatin1String("black"); case 2: return QLatin1String("navy"); case 3: return QLatin1String("green"); case 4: return QLatin1String("red"); case 5: return QLatin1String("maroon"); case 6: return QLatin1String("purple"); case 7: return QLatin1String("orange"); case 8: return QLatin1String("yellow"); case 9: return QLatin1String("lime"); case 10: return QLatin1String("darkcyan"); case 11: return QLatin1String("cyan"); case 12: return QLatin1String("blue"); case 13: return QLatin1String("magenta"); case 14: return QLatin1String("gray"); case 15: return QLatin1String("lightgray"); default: return QLatin1String("black"); } } } <|endoftext|>
<commit_before>#define MAIN #include <iostream.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <unistd.h> #include <sys/time.h> #include <globals.h> #include "RTcmix.h" double irand(double low, double high) { double frac = random() / (double) RAND_MAX; return low + frac * (high - low); } int main(int argc, char *argv[]) { RTcmix *rrr; int num; unsigned totalcmds = 0; int numcommands = 4; int minsleep = 1000; // in microseconds int maxsleep = 10000; int checkCount, checkInterval; int i; int verbose = 0; int bufsize = 256; int duration = 10000; // in seconds double start, pval, pval2, pval3, spread; struct timeval tv; struct timezone tz; double base_sec, sec, usec; for (int arg = 1; arg < argc; ++arg) { char *a = argv[arg]; if (a[0] == '-') { switch (a[1]) { case 's': srand(atoi(argv[++arg])); break; case 'v': verbose = 1; break; case 'd': duration = atoi(argv[++arg]); printf("Running for %d seconds...\n", duration); break; case 'b': bufsize = atoi(argv[++arg]); break; default: fprintf(stderr, "usage: %s <-b bufsize> <-s randseed> <-v>\n", argv[0]); exit(1); } } else { fprintf(stderr, "usage: %s <-s randseed> <-v>\n", argv[0]); exit(1); } } rrr = new RTcmix(44100.0, 2, bufsize); if (verbose) rrr->printOn(); else rrr->printOff(); rrr->cmd("load", 1, "../../insts.std/STRUM/libSTRUM.so"); rrr->cmd("load", 1, "../../insts.std/TRANS/libTRANS.so"); rrr->cmd("load", 1, "../../insts.std/STEREO/libSTEREO.so"); rrr->cmd("rtinput", 1, "./sinetone.wav"); rrr->cmd("setline", 8, 0., 0., 1., 1., 100., 1., 110., 0.); checkInterval = 1000000 / maxsleep; // about once per second checkCount = checkInterval; gettimeofday(&tv, &tz); base_sec = (double)tv.tv_sec; // usec = (double)tv.tv_usec; while(1) { usleep(minsleep + random() % maxsleep); // random sleep num = random() % numcommands; // random command switch (num) { case 0: case 3: pval = irand(5.0, 5.05); spread = irand(0.0, 1.0); rrr->cmd("bus_config", 2, "START", "out0-1"); rrr->cmd("START", 9, 0.0, 1.0, pval, 1.0, 0.7, 5000.0, 1.0, spread, 1.0); totalcmds += 2; break; case 1: pval = irand(-0.07, 0.07); // transp pval2 = irand(0.0, 1.0); // pan pval3 = irand(0.05, 0.5); // dur rrr->cmd("bus_config", 3, "TRANS3", "in0", "out0-1"); rrr->cmd("TRANS3", 5, 0.0, 0.0, pval3, 0.04, pval, pval2); totalcmds += 2; break; case 2: rrr->cmd("bus_config", 3, "TRANS", "in0", "aox0"); rrr->cmd("bus_config", 3, "STEREO", "aix0", "out0-1"); pval = irand(-0.04, 0.04); pval3 = irand(0.05, 0.5); // dur rrr->cmd("TRANS", 5, 0.0, 0.0, pval3, 1.0, pval); pval2 = irand(0.0, 1.0); rrr->cmd("STEREO", 5, 0.0, 0.0, pval3, 0.04, pval2); totalcmds += 2; break; default: break; } // Check time if (--checkCount == 0) { gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; if ((int) (sec - base_sec) > duration) { printf("Reached %d seconds. Shutting down...", duration); sleep(2); rrr->close(); sleep(1); printf("Exiting.\n"); exit(0); } checkCount = checkInterval; } } return 0; } <commit_msg>Added -h option for setting HW device<commit_after>#define MAIN #include <iostream.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <unistd.h> #include <sys/time.h> #include <globals.h> #include "RTcmix.h" double irand(double low, double high) { double frac = random() / (double) RAND_MAX; return low + frac * (high - low); } int main(int argc, char *argv[]) { RTcmix *rrr; int num; unsigned totalcmds = 0; int numcommands = 4; int minsleep = 1000; // in microseconds int maxsleep = 10000; const char *hwopt = NULL; int checkCount, checkInterval; int i; int verbose = 0; int bufsize = 256; int duration = 10000; // in seconds double start, pval, pval2, pval3, spread; struct timeval tv; struct timezone tz; double base_sec, sec, usec; for (int arg = 1; arg < argc; ++arg) { char *a = argv[arg]; if (a[0] == '-') { switch (a[1]) { case 's': srand(atoi(argv[++arg])); break; case 'v': verbose = 1; break; case 'd': duration = atoi(argv[++arg]); printf("Running for %d seconds...\n", duration); break; case 'b': bufsize = atoi(argv[++arg]); break; case 'h': hwopt = argv[++arg]; break; default: fprintf(stderr, "usage: %s <-h device=name> <-b bufsize> <-s randseed> <-v>\n", argv[0]); exit(1); } } else { fprintf(stderr, "usage: %s <-h device=name> <-b bufsize> <-s randseed> <-v>\n", argv[0]); exit(1); } } rrr = new RTcmix(44100.0, 2, bufsize, hwopt); if (verbose) rrr->printOn(); else rrr->printOff(); rrr->cmd("load", 1, "../../insts.std/STRUM/libSTRUM.so"); rrr->cmd("load", 1, "../../insts.std/TRANS/libTRANS.so"); rrr->cmd("load", 1, "../../insts.std/STEREO/libSTEREO.so"); rrr->cmd("rtinput", 1, "./sinetone.wav"); rrr->cmd("setline", 8, 0., 0., 1., 1., 100., 1., 110., 0.); checkInterval = 1000000 / maxsleep; // about once per second checkCount = checkInterval; gettimeofday(&tv, &tz); base_sec = (double)tv.tv_sec; // usec = (double)tv.tv_usec; while(1) { usleep(minsleep + random() % maxsleep); // random sleep num = random() % numcommands; // random command switch (num) { case 0: case 3: pval = irand(5.0, 5.05); spread = irand(0.0, 1.0); rrr->cmd("bus_config", 2, "START", "out0-1"); rrr->cmd("START", 9, 0.0, 1.0, pval, 1.0, 0.7, 5000.0, 1.0, spread, 1.0); totalcmds += 2; break; case 1: pval = irand(-0.07, 0.07); // transp pval2 = irand(0.0, 1.0); // pan pval3 = irand(0.05, 0.5); // dur rrr->cmd("bus_config", 3, "TRANS3", "in0", "out0-1"); rrr->cmd("TRANS3", 5, 0.0, 0.0, pval3, 0.04, pval, pval2); totalcmds += 2; break; case 2: rrr->cmd("bus_config", 3, "TRANS", "in0", "aox0"); rrr->cmd("bus_config", 3, "STEREO", "aix0", "out0-1"); pval = irand(-0.04, 0.04); pval3 = irand(0.05, 0.5); // dur rrr->cmd("TRANS", 5, 0.0, 0.0, pval3, 1.0, pval); pval2 = irand(0.0, 1.0); rrr->cmd("STEREO", 5, 0.0, 0.0, pval3, 0.04, pval2); totalcmds += 2; break; default: break; } // Check time if (--checkCount == 0) { gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; if ((int) (sec - base_sec) > duration) { printf("Reached %d seconds. Shutting down...", duration); sleep(2); rrr->close(); sleep(1); printf("Exiting.\n"); exit(0); } checkCount = checkInterval; } } return 0; } <|endoftext|>
<commit_before>#include "backends.hpp" #include<string> #include<armadillo> using namespace std; using namespace arma; #define DIM_NAME "__hide" #define ATTR_NAME "sample" #define ROW_NAME "samples" #define COL_NAME "channels" #define RANGE_SIZE 4 #define TILEDB_READ_MODE "r" #define TILEDB_WRITE_MODE "w" #define TILEDB_APPEND_MODE "a" string TileDBBackend::mrn_to_array_name(string mrn) { return _mrn_to_array_name(mrn, "-tiledb"); } string TileDBBackend::get_array_name(string mrn) { return mrn + "-tiledb"; } string TileDBBackend::get_workspace() { return DATADIR; } string TileDBBackend::get_group() { return ""; } ArrayMetadata TileDBBackend::get_array_metadata(string mrn) { string array_name = mrn_to_array_name(mrn) + "-metadata"; ifstream file; file.open(array_name, ios::binary); uint32_t header_len; file.read((char*) &header_len, sizeof(uint32_t)); string header = ""; header.resize(header_len, ' '); file.read((char*) header.c_str(), header_len); file.close(); string err; Json json = Json::parse(header, err); int fs = json["fs"].int_value(); int nsamples = json["nsamples"].int_value(); int nrows = json["nrows"].int_value(); int ncols = json["ncols"].int_value(); return ArrayMetadata(fs, nsamples, nrows, ncols); } void TileDBBackend::write_metadata(string mrn, ArrayMetadata* metadata) { ofstream file; string path = mrn_to_array_name(mrn) + "-metadata"; file.open(path, ios::trunc|ios::binary); // Store metadata in header; string header = metadata->to_string(); uint32_t header_len = get_byte_aligned_length(header); header.resize(header_len, ' '); file.write((char*) &header_len, sizeof(uint32_t)); file.write(header.c_str(), header_len); file.close(); } void TileDBBackend::create_array(string mrn, ArrayMetadata* metadata) { // tmp fix until TileDB metadata is implemented write_metadata(mrn, metadata); string group = get_group(); string workspace = get_workspace(); string array_name = get_array_name(mrn); // csv of array schema string array_schema_str = array_name + ",1," + ATTR_NAME + ",2," + COL_NAME + "," + ROW_NAME + ",0," + to_string(metadata->ncols) + ",0," + to_string(metadata->nrows) + ",float32,int32,*,column-major,*,*,*,*"; // Initialize TileDB TileDB_CTX* tiledb_ctx; tiledb_ctx_init(tiledb_ctx); // Store the array schema tiledb_array_define(tiledb_ctx, workspace.c_str(), group.c_str(), array_schema_str.c_str()); tiledb_ctx_finalize(tiledb_ctx); } void TileDBBackend::open_array(string mrn) { _open_array(mrn, TILEDB_READ_MODE); } void TileDBBackend::_open_array(string mrn, const char* mode) { if (in_cache(mrn)) { return; } TileDB_CTX* tiledb_ctx; tiledb_ctx_init(tiledb_ctx); string group = get_group(); string workspace = get_workspace(); string array_name = get_array_name(mrn); int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode); put_cache(mrn, tiledb_cache_pair(tiledb_ctx, array_id)); } void TileDBBackend::read_array(string mrn, int ch, int start_offset, int end_offset, frowvec& buf) { double* range = new double[RANGE_SIZE]; range[0] = CH_REVERSE_IDX[ch]; range[1] = CH_REVERSE_IDX[ch]; range[2] = start_offset; range[3] = end_offset; _read_array(mrn, range, buf); } void TileDBBackend::read_array(string mrn, int start_offset, int end_offset, fmat& buf) { double* range = new double[RANGE_SIZE]; range[0] = 0; range[1] = get_ncols(mrn); range[2] = start_offset; range[3] = end_offset; _read_array(mrn, range, buf); } void TileDBBackend::_read_array(string mrn, double* range, fmat& buf) { tiledb_cache_pair cache_pair = get_cache(mrn); TileDB_CTX* tiledb_ctx = cache_pair.first; int array_id = cache_pair.second; const char* dim_names = DIM_NAME; int dim_names_num = 1; const char* attribute_names = ATTR_NAME; int attribute_names_num = 1; size_t cell_buf_size = sizeof(float) * buf.n_elem; tiledb_subarray_buf(tiledb_ctx, array_id, range, RANGE_SIZE, &dim_names, dim_names_num, &attribute_names, attribute_names_num, buf.memptr(), &cell_buf_size); } void TileDBBackend::write_array(string mrn, int ch, int start_offset, int end_offset, fmat& buf) { if (in_cache(mrn)) { close_array(mrn); // we need to reopen in append mode } _open_array(mrn, TILEDB_APPEND_MODE); tiledb_cache_pair pair = get_cache(mrn); TileDB_CTX* tiledb_ctx = pair.first; int array_id = pair.second; cell_t cell; if (ch == ALL) { buf = buf.t(); } for (uword i = 0; i < buf.n_rows; i++) { for (uword j = 0; j < buf.n_cols; j++) { // x (col) coord, y (row) coord, attribute cell.x = ch == ALL ? start_offset + j : CH_REVERSE_IDX[ch]; cell.y = ch == ALL ? i : start_offset + j; cell.sample = buf(i, j); tiledb_cell_write_sorted(tiledb_ctx, array_id, &cell); } } // Finalize TileDB close_array(mrn); } void TileDBBackend::close_array(string mrn) { if (in_cache(mrn)) { tiledb_cache_pair pair = get_cache(mrn); tiledb_array_close(pair.first, pair.second); tiledb_ctx_finalize(pair.first); pop_cache(mrn); } } <commit_msg>Delete array when recreating in TileDB<commit_after>#include "backends.hpp" #include<string> #include<armadillo> using namespace std; using namespace arma; #define DIM_NAME "__hide" #define ATTR_NAME "sample" #define ROW_NAME "samples" #define COL_NAME "channels" #define RANGE_SIZE 4 #define TILEDB_READ_MODE "r" #define TILEDB_WRITE_MODE "w" #define TILEDB_APPEND_MODE "a" string TileDBBackend::mrn_to_array_name(string mrn) { return _mrn_to_array_name(mrn, "-tiledb"); } string TileDBBackend::get_array_name(string mrn) { return mrn + "-tiledb"; } string TileDBBackend::get_workspace() { return DATADIR; } string TileDBBackend::get_group() { return ""; } ArrayMetadata TileDBBackend::get_array_metadata(string mrn) { string array_name = mrn_to_array_name(mrn) + "-metadata"; ifstream file; file.open(array_name, ios::binary); uint32_t header_len; file.read((char*) &header_len, sizeof(uint32_t)); string header = ""; header.resize(header_len, ' '); file.read((char*) header.c_str(), header_len); file.close(); string err; Json json = Json::parse(header, err); int fs = json["fs"].int_value(); int nsamples = json["nsamples"].int_value(); int nrows = json["nrows"].int_value(); int ncols = json["ncols"].int_value(); return ArrayMetadata(fs, nsamples, nrows, ncols); } void TileDBBackend::write_metadata(string mrn, ArrayMetadata* metadata) { ofstream file; string path = mrn_to_array_name(mrn) + "-metadata"; file.open(path, ios::trunc|ios::binary); // Store metadata in header; string header = metadata->to_string(); uint32_t header_len = get_byte_aligned_length(header); header.resize(header_len, ' '); file.write((char*) &header_len, sizeof(uint32_t)); file.write(header.c_str(), header_len); file.close(); } void TileDBBackend::create_array(string mrn, ArrayMetadata* metadata) { // tmp fix until TileDB metadata is implemented write_metadata(mrn, metadata); string group = get_group(); string workspace = get_workspace(); string array_name = get_array_name(mrn); // csv of array schema string array_schema_str = array_name + ",1," + ATTR_NAME + ",2," + COL_NAME + "," + ROW_NAME + ",0," + to_string(metadata->ncols) + ",0," + to_string(metadata->nrows) + ",float32,int32,*,column-major,*,*,*,*"; // Initialize TileDB TileDB_CTX* tiledb_ctx; tiledb_ctx_init(tiledb_ctx); if (array_exists(mrn)) { // Necessary for clean since arrays are not cleared when redefined tiledb_array_delete(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str()); } // Store the array schema tiledb_array_define(tiledb_ctx, workspace.c_str(), group.c_str(), array_schema_str.c_str()); tiledb_ctx_finalize(tiledb_ctx); } void TileDBBackend::open_array(string mrn) { _open_array(mrn, TILEDB_READ_MODE); } void TileDBBackend::_open_array(string mrn, const char* mode) { if (in_cache(mrn)) { return; } TileDB_CTX* tiledb_ctx; tiledb_ctx_init(tiledb_ctx); string group = get_group(); string workspace = get_workspace(); string array_name = get_array_name(mrn); int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode); put_cache(mrn, tiledb_cache_pair(tiledb_ctx, array_id)); } void TileDBBackend::read_array(string mrn, int ch, int start_offset, int end_offset, frowvec& buf) { double* range = new double[RANGE_SIZE]; range[0] = CH_REVERSE_IDX[ch]; range[1] = CH_REVERSE_IDX[ch]; range[2] = start_offset; range[3] = end_offset; _read_array(mrn, range, buf); } void TileDBBackend::read_array(string mrn, int start_offset, int end_offset, fmat& buf) { double* range = new double[RANGE_SIZE]; range[0] = 0; range[1] = get_ncols(mrn); range[2] = start_offset; range[3] = end_offset; _read_array(mrn, range, buf); } void TileDBBackend::_read_array(string mrn, double* range, fmat& buf) { tiledb_cache_pair cache_pair = get_cache(mrn); TileDB_CTX* tiledb_ctx = cache_pair.first; int array_id = cache_pair.second; const char* dim_names = DIM_NAME; int dim_names_num = 1; const char* attribute_names = ATTR_NAME; int attribute_names_num = 1; size_t cell_buf_size = sizeof(float) * buf.n_elem; tiledb_subarray_buf(tiledb_ctx, array_id, range, RANGE_SIZE, &dim_names, dim_names_num, &attribute_names, attribute_names_num, buf.memptr(), &cell_buf_size); } void TileDBBackend::write_array(string mrn, int ch, int start_offset, int end_offset, fmat& buf) { if (in_cache(mrn)) { close_array(mrn); // we need to reopen in append mode } _open_array(mrn, TILEDB_APPEND_MODE); tiledb_cache_pair pair = get_cache(mrn); TileDB_CTX* tiledb_ctx = pair.first; int array_id = pair.second; cell_t cell; if (ch == ALL) { buf = buf.t(); } for (uword i = 0; i < buf.n_rows; i++) { for (uword j = 0; j < buf.n_cols; j++) { // x (col) coord, y (row) coord, attribute cell.x = ch == ALL ? start_offset + j : CH_REVERSE_IDX[ch]; cell.y = ch == ALL ? i : start_offset + j; cell.sample = buf(i, j); tiledb_cell_write_sorted(tiledb_ctx, array_id, &cell); } } // Finalize TileDB close_array(mrn); } void TileDBBackend::close_array(string mrn) { if (in_cache(mrn)) { tiledb_cache_pair pair = get_cache(mrn); tiledb_array_close(pair.first, pair.second); tiledb_ctx_finalize(pair.first); pop_cache(mrn); } } <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 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 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 Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include <algorithm> #include <functional> #include "Album.h" #include "AlbumTrack.h" #include "Artist.h" #include "AudioTrack.h" #include "discoverer/DiscovererWorker.h" #include "Media.h" #include "Folder.h" #include "MediaLibrary.h" #include "IMetadataService.h" #include "Label.h" #include "logging/Logger.h" #include "Movie.h" #include "Parser.h" #include "Show.h" #include "ShowEpisode.h" #include "database/SqliteTools.h" #include "database/SqliteConnection.h" #include "Utils.h" #include "VideoTrack.h" // Discoverers: #include "discoverer/FsDiscoverer.h" // Metadata services: #include "metadata_services/vlc/VLCMetadataService.h" #include "metadata_services/vlc/VLCThumbnailer.h" #include "filesystem/IDirectory.h" #include "filesystem/IFile.h" #include "factory/FileSystem.h" const std::vector<std::string> MediaLibrary::supportedVideoExtensions { // Videos "avi", "3gp", "amv", "asf", "divx", "dv", "flv", "gxf", "iso", "m1v", "m2v", "m2t", "m2ts", "m4v", "mkv", "mov", "mp2", "mp4", "mpeg", "mpeg1", "mpeg2", "mpeg4", "mpg", "mts", "mxf", "nsv", "nuv", "ogg", "ogm", "ogv", "ogx", "ps", "rec", "rm", "rmvb", "tod", "ts", "vob", "vro", "webm", "wmv" }; const std::vector<std::string> MediaLibrary::supportedAudioExtensions { // Audio "a52", "aac", "ac3", "aiff", "amr", "aob", "ape", "dts", "flac", "it", "m4a", "m4p", "mid", "mka", "mlp", "mod", "mp1", "mp2", "mp3", "mpc", "oga", "ogg", "oma", "rmi", "s3m", "spx", "tta", "voc", "vqf", "w64", "wav", "wma", "wv", "xa", "xm" }; const uint32_t MediaLibrary::DbModelVersion = 1; MediaLibrary::MediaLibrary() : m_discoverer( new DiscovererWorker ) , m_verbosity( LogLevel::Error ) { Log::setLogLevel( m_verbosity ); } MediaLibrary::~MediaLibrary() { // The log callback isn't shared by all VLC::Instance's, yet since // they all share a single libvlc_instance_t, any VLC::Instance still alive // with a log callback set will try to invoke it. // We manually call logUnset to ensure that the callback that is about to be deleted will // not be called anymore. if ( m_vlcInstance.isValid() ) m_vlcInstance.logUnset(); // Explicitely stop the discoverer, to avoid it writting while tearing down. m_discoverer->stop(); Media::clear(); Folder::clear(); Label::clear(); Album::clear(); AlbumTrack::clear(); Show::clear(); ShowEpisode::clear(); Movie::clear(); VideoTrack::clear(); AudioTrack::clear(); Artist::clear(); // Explicitely release the connection's TLS if ( m_dbConnection != nullptr ) m_dbConnection->release(); } void MediaLibrary::setFsFactory(std::shared_ptr<factory::IFileSystem> fsFactory) { m_fsFactory = fsFactory; } bool MediaLibrary::initialize( const std::string& dbPath, const std::string& snapshotPath, IMediaLibraryCb* mlCallback ) { if ( m_fsFactory == nullptr ) m_fsFactory.reset( new factory::FileSystemDefaultFactory ); m_snapshotPath = snapshotPath; m_callback = mlCallback; m_dbConnection.reset( new SqliteConnection( dbPath ) ); m_parser.reset( new Parser( m_dbConnection.get(), m_callback ) ); if ( mlCallback != nullptr ) { const char* args[] = { "-vv", }; m_vlcInstance = VLC::Instance( sizeof(args) / sizeof(args[0]), args ); m_vlcInstance.logSet([this](int lvl, const libvlc_log_t*, std::string msg) { if ( m_verbosity != LogLevel::Verbose ) return ; if ( lvl == LIBVLC_ERROR ) Log::Error( msg ); else if ( lvl == LIBVLC_WARNING ) Log::Warning( msg ); else Log::Info( msg ); }); auto vlcService = std::unique_ptr<VLCMetadataService>( new VLCMetadataService( m_vlcInstance, m_dbConnection.get(), m_fsFactory ) ); auto thumbnailerService = std::unique_ptr<VLCThumbnailer>( new VLCThumbnailer( m_vlcInstance ) ); addMetadataService( std::move( vlcService ) ); addMetadataService( std::move( thumbnailerService ) ); } auto t = m_dbConnection->newTransaction(); if ( ( Media::createTable( m_dbConnection.get() ) && Folder::createTable( m_dbConnection.get() ) && Label::createTable( m_dbConnection.get() ) && Album::createTable( m_dbConnection.get() ) && AlbumTrack::createTable( m_dbConnection.get() ) && Show::createTable( m_dbConnection.get() ) && ShowEpisode::createTable( m_dbConnection.get() ) && Movie::createTable( m_dbConnection.get() ) && VideoTrack::createTable( m_dbConnection.get() ) && AudioTrack::createTable( m_dbConnection.get() ) && Artist::createTable( m_dbConnection.get() ) && Artist::createDefaultArtists( m_dbConnection.get() ) && Settings::createTable( m_dbConnection.get() ) ) == false ) { LOG_ERROR( "Failed to create database structure" ); return false; } if ( m_settings.load( m_dbConnection.get() ) == false ) return false; // We only have one version so far, so a mismatching version is an error if ( m_settings.dbModelVersion() != DbModelVersion ) return false; t->commit(); m_discoverer->setCallback( m_callback ); m_discoverer->addDiscoverer( std::unique_ptr<IDiscoverer>( new FsDiscoverer( m_fsFactory, this, m_dbConnection.get() ) ) ); m_discoverer->reload(); m_parser->start(); return true; } void MediaLibrary::setVerbosity(LogLevel v) { m_verbosity = v; Log::setLogLevel( v ); } std::vector<MediaPtr> MediaLibrary::files() { return Media::fetchAll<IMedia>( m_dbConnection.get() ); } std::vector<MediaPtr> MediaLibrary::audioFiles() { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE type = ? ORDER BY title"; return Media::fetchAll<IMedia>( m_dbConnection.get(), req, IMedia::Type::AudioType ); } std::vector<MediaPtr> MediaLibrary::videoFiles() { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE type = ? ORDER BY title"; return Media::fetchAll<IMedia>( m_dbConnection.get(), req, IMedia::Type::VideoType ); } MediaPtr MediaLibrary::file( const std::string& path ) { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE mrl = ?"; return Media::fetch( m_dbConnection.get(), req, path ); } std::shared_ptr<Media> MediaLibrary::addFile( const std::string& path, FolderPtr parentFolder ) { LOG_INFO( "Adding ", path ); std::unique_ptr<fs::IFile> file; try { file = m_fsFactory->createFile( path ); } catch (std::exception& ex) { LOG_ERROR( "Failed to create an IFile for ", path, ": ", ex.what() ); return nullptr; } auto type = IMedia::Type::UnknownType; auto ext = file->extension(); auto predicate = [ext](const std::string& v) { return strcasecmp(v.c_str(), ext.c_str()) == 0; }; if ( std::find_if( begin( supportedVideoExtensions ), end( supportedVideoExtensions ), predicate ) != end( supportedVideoExtensions ) ) { type = IMedia::Type::VideoType; } else if ( std::find_if( begin( supportedAudioExtensions ), end( supportedAudioExtensions ), predicate ) != end( supportedAudioExtensions ) ) { type = IMedia::Type::AudioType; } if ( type == IMedia::Type::UnknownType ) return nullptr; auto fptr = Media::create( m_dbConnection.get(), type, file.get(), parentFolder != nullptr ? parentFolder->id() : 0 ); if ( fptr == nullptr ) { LOG_ERROR( "Failed to add file ", file->fullPath(), " to the media library" ); return nullptr; } if ( m_callback != nullptr ) m_callback->onFileAdded( fptr ); m_parser->parse( fptr ); return fptr; } FolderPtr MediaLibrary::folder( const std::string& path ) { return Folder::fromPath( m_dbConnection.get(), path ); } bool MediaLibrary::deleteFile( const Media* file ) { return Media::destroy( m_dbConnection.get(), file->id() ); } bool MediaLibrary::deleteFolder( FolderPtr folder ) { if ( Folder::destroy( m_dbConnection.get(), folder->id() ) == false ) return false; Media::clear(); return true; } LabelPtr MediaLibrary::createLabel( const std::string& label ) { return Label::create( m_dbConnection.get(), label ); } bool MediaLibrary::deleteLabel( LabelPtr label ) { return Label::destroy( m_dbConnection.get(), label->id() ); } AlbumPtr MediaLibrary::album( unsigned int id ) { return Album::fetch( m_dbConnection.get(), id ); } std::shared_ptr<Album> MediaLibrary::createAlbum(const std::string& title ) { return Album::create( m_dbConnection.get(), title ); } std::vector<AlbumPtr> MediaLibrary::albums() { static const std::string req = "SELECT * FROM " + policy::AlbumTable::Name + " ORDER BY title ASC"; return Album::fetchAll<IAlbum>( m_dbConnection.get(), req ); } ShowPtr MediaLibrary::show(const std::string& name) { static const std::string req = "SELECT * FROM " + policy::ShowTable::Name + " WHERE name = ?"; return Show::fetch( m_dbConnection.get(), req, name ); } std::shared_ptr<Show> MediaLibrary::createShow(const std::string& name) { return Show::create( m_dbConnection.get(), name ); } MoviePtr MediaLibrary::movie( const std::string& title ) { static const std::string req = "SELECT * FROM " + policy::MovieTable::Name + " WHERE title = ?"; return Movie::fetch( m_dbConnection.get(), req, title ); } std::shared_ptr<Movie> MediaLibrary::createMovie( const std::string& title ) { return Movie::create( m_dbConnection.get(), title ); } ArtistPtr MediaLibrary::artist(unsigned int id) { return Artist::fetch( m_dbConnection.get(), id ); } ArtistPtr MediaLibrary::artist( const std::string& name ) { static const std::string req = "SELECT * FROM " + policy::ArtistTable::Name + " WHERE name = ?"; return Artist::fetch( m_dbConnection.get(), req, name ); } std::shared_ptr<Artist> MediaLibrary::createArtist( const std::string& name ) { return Artist::create( m_dbConnection.get(), name ); } std::vector<ArtistPtr> MediaLibrary::artists() const { static const std::string req = "SELECT * FROM " + policy::ArtistTable::Name + " WHERE nb_albums > 0"; return Artist::fetchAll<IArtist>( m_dbConnection.get(), req ); } void MediaLibrary::addMetadataService(std::unique_ptr<IMetadataService> service) { if ( service->initialize( m_parser.get(), this ) == false ) { //FIXME: This is missing a name or something more specific LOG_ERROR( "Failed to initialize service" ); return; } m_parser->addService( std::move( service ) ); } void MediaLibrary::reload() { m_discoverer->reload(); } void MediaLibrary::pauseBackgroundOperations() { m_parser->pause(); } void MediaLibrary::resumeBackgroundOperations() { m_parser->resume(); } void MediaLibrary::discover( const std::string &entryPoint ) { m_discoverer->discover( entryPoint ); } bool MediaLibrary::ignoreFolder( const std::string& path ) { auto f = Folder::fromPath( m_dbConnection.get(), path ); if ( f != nullptr ) { // Let the foreign key destroy everything beneath this folder Folder::destroy( m_dbConnection.get(), f->id() ); } return Folder::blacklist( m_dbConnection.get(), path ); } const std::string& MediaLibrary::snapshotPath() const { return m_snapshotPath; } void MediaLibrary::setLogger( ILogger* logger ) { Log::SetLogger( logger ); } <commit_msg>MediaLibrary: Remove now unneeded libvlcpp workaround<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 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 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 Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include <algorithm> #include <functional> #include "Album.h" #include "AlbumTrack.h" #include "Artist.h" #include "AudioTrack.h" #include "discoverer/DiscovererWorker.h" #include "Media.h" #include "Folder.h" #include "MediaLibrary.h" #include "IMetadataService.h" #include "Label.h" #include "logging/Logger.h" #include "Movie.h" #include "Parser.h" #include "Show.h" #include "ShowEpisode.h" #include "database/SqliteTools.h" #include "database/SqliteConnection.h" #include "Utils.h" #include "VideoTrack.h" // Discoverers: #include "discoverer/FsDiscoverer.h" // Metadata services: #include "metadata_services/vlc/VLCMetadataService.h" #include "metadata_services/vlc/VLCThumbnailer.h" #include "filesystem/IDirectory.h" #include "filesystem/IFile.h" #include "factory/FileSystem.h" const std::vector<std::string> MediaLibrary::supportedVideoExtensions { // Videos "avi", "3gp", "amv", "asf", "divx", "dv", "flv", "gxf", "iso", "m1v", "m2v", "m2t", "m2ts", "m4v", "mkv", "mov", "mp2", "mp4", "mpeg", "mpeg1", "mpeg2", "mpeg4", "mpg", "mts", "mxf", "nsv", "nuv", "ogg", "ogm", "ogv", "ogx", "ps", "rec", "rm", "rmvb", "tod", "ts", "vob", "vro", "webm", "wmv" }; const std::vector<std::string> MediaLibrary::supportedAudioExtensions { // Audio "a52", "aac", "ac3", "aiff", "amr", "aob", "ape", "dts", "flac", "it", "m4a", "m4p", "mid", "mka", "mlp", "mod", "mp1", "mp2", "mp3", "mpc", "oga", "ogg", "oma", "rmi", "s3m", "spx", "tta", "voc", "vqf", "w64", "wav", "wma", "wv", "xa", "xm" }; const uint32_t MediaLibrary::DbModelVersion = 1; MediaLibrary::MediaLibrary() : m_discoverer( new DiscovererWorker ) , m_verbosity( LogLevel::Error ) { Log::setLogLevel( m_verbosity ); } MediaLibrary::~MediaLibrary() { // Explicitely stop the discoverer, to avoid it writting while tearing down. m_discoverer->stop(); Media::clear(); Folder::clear(); Label::clear(); Album::clear(); AlbumTrack::clear(); Show::clear(); ShowEpisode::clear(); Movie::clear(); VideoTrack::clear(); AudioTrack::clear(); Artist::clear(); // Explicitely release the connection's TLS if ( m_dbConnection != nullptr ) m_dbConnection->release(); } void MediaLibrary::setFsFactory(std::shared_ptr<factory::IFileSystem> fsFactory) { m_fsFactory = fsFactory; } bool MediaLibrary::initialize( const std::string& dbPath, const std::string& snapshotPath, IMediaLibraryCb* mlCallback ) { if ( m_fsFactory == nullptr ) m_fsFactory.reset( new factory::FileSystemDefaultFactory ); m_snapshotPath = snapshotPath; m_callback = mlCallback; m_dbConnection.reset( new SqliteConnection( dbPath ) ); m_parser.reset( new Parser( m_dbConnection.get(), m_callback ) ); if ( mlCallback != nullptr ) { const char* args[] = { "-vv", }; m_vlcInstance = VLC::Instance( sizeof(args) / sizeof(args[0]), args ); m_vlcInstance.logSet([this](int lvl, const libvlc_log_t*, std::string msg) { if ( m_verbosity != LogLevel::Verbose ) return ; if ( lvl == LIBVLC_ERROR ) Log::Error( msg ); else if ( lvl == LIBVLC_WARNING ) Log::Warning( msg ); else Log::Info( msg ); }); auto vlcService = std::unique_ptr<VLCMetadataService>( new VLCMetadataService( m_vlcInstance, m_dbConnection.get(), m_fsFactory ) ); auto thumbnailerService = std::unique_ptr<VLCThumbnailer>( new VLCThumbnailer( m_vlcInstance ) ); addMetadataService( std::move( vlcService ) ); addMetadataService( std::move( thumbnailerService ) ); } auto t = m_dbConnection->newTransaction(); if ( ( Media::createTable( m_dbConnection.get() ) && Folder::createTable( m_dbConnection.get() ) && Label::createTable( m_dbConnection.get() ) && Album::createTable( m_dbConnection.get() ) && AlbumTrack::createTable( m_dbConnection.get() ) && Show::createTable( m_dbConnection.get() ) && ShowEpisode::createTable( m_dbConnection.get() ) && Movie::createTable( m_dbConnection.get() ) && VideoTrack::createTable( m_dbConnection.get() ) && AudioTrack::createTable( m_dbConnection.get() ) && Artist::createTable( m_dbConnection.get() ) && Artist::createDefaultArtists( m_dbConnection.get() ) && Settings::createTable( m_dbConnection.get() ) ) == false ) { LOG_ERROR( "Failed to create database structure" ); return false; } if ( m_settings.load( m_dbConnection.get() ) == false ) return false; // We only have one version so far, so a mismatching version is an error if ( m_settings.dbModelVersion() != DbModelVersion ) return false; t->commit(); m_discoverer->setCallback( m_callback ); m_discoverer->addDiscoverer( std::unique_ptr<IDiscoverer>( new FsDiscoverer( m_fsFactory, this, m_dbConnection.get() ) ) ); m_discoverer->reload(); m_parser->start(); return true; } void MediaLibrary::setVerbosity(LogLevel v) { m_verbosity = v; Log::setLogLevel( v ); } std::vector<MediaPtr> MediaLibrary::files() { return Media::fetchAll<IMedia>( m_dbConnection.get() ); } std::vector<MediaPtr> MediaLibrary::audioFiles() { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE type = ? ORDER BY title"; return Media::fetchAll<IMedia>( m_dbConnection.get(), req, IMedia::Type::AudioType ); } std::vector<MediaPtr> MediaLibrary::videoFiles() { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE type = ? ORDER BY title"; return Media::fetchAll<IMedia>( m_dbConnection.get(), req, IMedia::Type::VideoType ); } MediaPtr MediaLibrary::file( const std::string& path ) { static const std::string req = "SELECT * FROM " + policy::MediaTable::Name + " WHERE mrl = ?"; return Media::fetch( m_dbConnection.get(), req, path ); } std::shared_ptr<Media> MediaLibrary::addFile( const std::string& path, FolderPtr parentFolder ) { LOG_INFO( "Adding ", path ); std::unique_ptr<fs::IFile> file; try { file = m_fsFactory->createFile( path ); } catch (std::exception& ex) { LOG_ERROR( "Failed to create an IFile for ", path, ": ", ex.what() ); return nullptr; } auto type = IMedia::Type::UnknownType; auto ext = file->extension(); auto predicate = [ext](const std::string& v) { return strcasecmp(v.c_str(), ext.c_str()) == 0; }; if ( std::find_if( begin( supportedVideoExtensions ), end( supportedVideoExtensions ), predicate ) != end( supportedVideoExtensions ) ) { type = IMedia::Type::VideoType; } else if ( std::find_if( begin( supportedAudioExtensions ), end( supportedAudioExtensions ), predicate ) != end( supportedAudioExtensions ) ) { type = IMedia::Type::AudioType; } if ( type == IMedia::Type::UnknownType ) return nullptr; auto fptr = Media::create( m_dbConnection.get(), type, file.get(), parentFolder != nullptr ? parentFolder->id() : 0 ); if ( fptr == nullptr ) { LOG_ERROR( "Failed to add file ", file->fullPath(), " to the media library" ); return nullptr; } if ( m_callback != nullptr ) m_callback->onFileAdded( fptr ); m_parser->parse( fptr ); return fptr; } FolderPtr MediaLibrary::folder( const std::string& path ) { return Folder::fromPath( m_dbConnection.get(), path ); } bool MediaLibrary::deleteFile( const Media* file ) { return Media::destroy( m_dbConnection.get(), file->id() ); } bool MediaLibrary::deleteFolder( FolderPtr folder ) { if ( Folder::destroy( m_dbConnection.get(), folder->id() ) == false ) return false; Media::clear(); return true; } LabelPtr MediaLibrary::createLabel( const std::string& label ) { return Label::create( m_dbConnection.get(), label ); } bool MediaLibrary::deleteLabel( LabelPtr label ) { return Label::destroy( m_dbConnection.get(), label->id() ); } AlbumPtr MediaLibrary::album( unsigned int id ) { return Album::fetch( m_dbConnection.get(), id ); } std::shared_ptr<Album> MediaLibrary::createAlbum(const std::string& title ) { return Album::create( m_dbConnection.get(), title ); } std::vector<AlbumPtr> MediaLibrary::albums() { static const std::string req = "SELECT * FROM " + policy::AlbumTable::Name + " ORDER BY title ASC"; return Album::fetchAll<IAlbum>( m_dbConnection.get(), req ); } ShowPtr MediaLibrary::show(const std::string& name) { static const std::string req = "SELECT * FROM " + policy::ShowTable::Name + " WHERE name = ?"; return Show::fetch( m_dbConnection.get(), req, name ); } std::shared_ptr<Show> MediaLibrary::createShow(const std::string& name) { return Show::create( m_dbConnection.get(), name ); } MoviePtr MediaLibrary::movie( const std::string& title ) { static const std::string req = "SELECT * FROM " + policy::MovieTable::Name + " WHERE title = ?"; return Movie::fetch( m_dbConnection.get(), req, title ); } std::shared_ptr<Movie> MediaLibrary::createMovie( const std::string& title ) { return Movie::create( m_dbConnection.get(), title ); } ArtistPtr MediaLibrary::artist(unsigned int id) { return Artist::fetch( m_dbConnection.get(), id ); } ArtistPtr MediaLibrary::artist( const std::string& name ) { static const std::string req = "SELECT * FROM " + policy::ArtistTable::Name + " WHERE name = ?"; return Artist::fetch( m_dbConnection.get(), req, name ); } std::shared_ptr<Artist> MediaLibrary::createArtist( const std::string& name ) { return Artist::create( m_dbConnection.get(), name ); } std::vector<ArtistPtr> MediaLibrary::artists() const { static const std::string req = "SELECT * FROM " + policy::ArtistTable::Name + " WHERE nb_albums > 0"; return Artist::fetchAll<IArtist>( m_dbConnection.get(), req ); } void MediaLibrary::addMetadataService(std::unique_ptr<IMetadataService> service) { if ( service->initialize( m_parser.get(), this ) == false ) { //FIXME: This is missing a name or something more specific LOG_ERROR( "Failed to initialize service" ); return; } m_parser->addService( std::move( service ) ); } void MediaLibrary::reload() { m_discoverer->reload(); } void MediaLibrary::pauseBackgroundOperations() { m_parser->pause(); } void MediaLibrary::resumeBackgroundOperations() { m_parser->resume(); } void MediaLibrary::discover( const std::string &entryPoint ) { m_discoverer->discover( entryPoint ); } bool MediaLibrary::ignoreFolder( const std::string& path ) { auto f = Folder::fromPath( m_dbConnection.get(), path ); if ( f != nullptr ) { // Let the foreign key destroy everything beneath this folder Folder::destroy( m_dbConnection.get(), f->id() ); } return Folder::blacklist( m_dbConnection.get(), path ); } const std::string& MediaLibrary::snapshotPath() const { return m_snapshotPath; } void MediaLibrary::setLogger( ILogger* logger ) { Log::SetLogger( logger ); } <|endoftext|>
<commit_before>#include <vector> #include <iostream> #include <utility> // std::pair<T,U> #include <pthread.h> #include "utils.hpp" int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones); void* does_work(void *ptr); //////global int problemSize =0; //int threadCount = 24; std::vector<vector<int> > results; std::vector<int> wholeCost; std::vector< std::vector<int> > Distance; std::vector<double> > Pher; //std::vector int main(int argc, char** argv) { if (argc < 2) { std::cerr << "I needs a file dammit!" << std::endl; return 1; } // well what now? // something about an algorithm... // oh yes! i think i need to build the distance and pheromones array // call shortest path with itthr_count // then print out the answer std::string fileName(argv[1]); std::vector< std::vector<int> > dist = read_the_file(fileName);// returns a filled distance vector std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector problemSize = (dist.size() * dist[0].size())/2; for(int i =0; i < threadCount; i++) { std::vector<int> temp; results.push_back(temp); wholeCost.push_back(0); } // start time int answer = shortest_path_dist(dist, pheromones); // end time std::cout << answer << std::endl; } // this algorithm has a structure similar to floyds // so look there for inspiration // note: a thread pool is the sort of thing desired int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones) { std::vector<pthread_t> cur; for(int i = 0; i < GENERATIONS; i++) { for(int i = 0;i < ANTCOUNT; i++) { int * ii = new int(i); pthread_t temp; pthread_create(&temp, NULL, does_work,(void*)ii); cur.push_back(temp); } while(!cur.empty()) { pthread_join(cur.back(),NULL); cur.pop_back(); } cur.clear(); //global update while ( for(int i =0; i < cur.size();i++) cur[i] = 0; } // start all needed threads // for each iteration // for each ant : IN PARALLEL // initialize the ant // share distance and pheromone graph for the thread // while a tour is not finished // choose the next city (eq 1,2) // atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without // end while // end of ant's travel // atomic: global pheromone update (eq 4) // terminate the thread, release resources //} // barrier: all ants //} // end of iteration } void *does_work(void *ptr) { int pos 0; int antDist = 0; int id = *((int *)ptr); //std::vector<double> res; std::vector<int> history; while(history < problemSize) { //res.clear(); //for(int i =0;i < problemSize; i++) //{ // res.push_back(0.0); //} double choice = ((double) rand() / (RAND_MAX)) + 1; double max = 0; int maxIndex =0; if(choice < Q0){ // expliait for(int i =0; i< problemSize; i++) { if(std::find(history.begin(), history.end(), i) != history.end()) continue; double temp = Pher[pos][i] / pow((Distance[pos][i],BETA)) ; if( temp > max) { max =temp; maxIndex = i; } } } else //we expolore { } Pher[pos][maxIndex] = eq3(Pher[pos][maxIndex],problemSize); antDist += Distance[pos][maxIndex]; pos = maxIndex; history.push_back(maxIndex); } results[id] = history; wholeCost[id] = antDist; } <commit_msg>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaahhhhhhhhhh!<commit_after>#include <vector> #include <iostream> #include <utility> // std::pair<T,U> #include <pthread.h> #include <algorithm> #include <cmath> #include "utils.hpp" int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones); void* does_work(void *ptr); //////global int problemSize =0; //int threadCount = 24; std::vector<std::vector<int> > results; std::vector<int> wholeCost; std::vector< std::vector<int> > Distance; std::vector<double> Pher; //std::vector int main(int argc, char** argv) { if (argc < 2) { std::cerr << "I needs a file dammit!" << std::endl; return 1; } // well what now? // something about an algorithm... // oh yes! i think i need to build the distance and pheromones array // call shortest path with itthr_count // then print out the answer std::string fileName(argv[1]); std::vector< std::vector<int> > dist = read_the_file(fileName);// returns a filled distance vector std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector problemSize = (dist.size() * dist[0].size())/2; for(int i =0; i < ANTCOUNT; i++) { std::vector<int> temp; results.push_back(temp); wholeCost.push_back(0); } // start time int answer = shortest_path_dist(dist, pheromones); // end time std::cout << answer << std::endl; } // this algorithm has a structure similar to floyds // so look there for inspiration // note: a thread pool is the sort of thing desired int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones) { std::vector<pthread_t> cur; for(int i = 0; i < GENERATIONS; i++) { for(int i = 0;i < ANTCOUNT; i++) { int * ii = new int(i); pthread_t temp; pthread_create(&temp, NULL, does_work,(void*)ii); cur.push_back(temp); } while(!cur.empty()) { pthread_join(cur.back(),NULL); cur.pop_back(); } cur.clear(); //global update for(int i =0; i < cur.size();i++) cur[i] = 0; } // start all needed threads // for each iteration // for each ant : IN PARALLEL // initialize the ant // share distance and pheromone graph for the thread // while a tour is not finished // choose the next city (eq 1,2) // atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without // end while // end of ant's travel // atomic: global pheromone update (eq 4) // terminate the thread, release resources //} // barrier: all ants //} // end of iteration } void *does_work(void *ptr) { int pos = 0; int antDist = 0; int id = *((int *)ptr); //std::vector<double> res; std::vector<int> history; while(history.size() < problemSize) { //res.clear(); //for(int i =0;i < problemSize; i++) //{ // res.push_back(0.0); //} double choice = ((double) rand() / (RAND_MAX)) + 1; double max = 0; int maxIndex =0; if(choice < Q0){ // expliait for(int i =0; i< problemSize; i++) { if(std::find(history.begin(), history.end(), i) != history.end()) continue; double temp = Pher[pos][i] / pow(Distance[pos][i],BETA) ; if( temp > max) { max =temp; maxIndex = i; } } } else //we expolore { } Pher[pos][maxIndex] = eq3(Pher[pos][maxIndex],problemSize); antDist += Distance[pos][maxIndex]; pos = maxIndex; history.push_back(maxIndex); } results[id] = history; wholeCost[id] = antDist; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2013-, Open Perception, 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef PCL_TRAJKOVIC_KEYPOINT_3D_IMPL_H_ #define PCL_TRAJKOVIC_KEYPOINT_3D_IMPL_H_ #include <pcl/features/integral_image_normal.h> template <typename PointInT, typename PointOutT, typename NormalT> bool pcl::TrajkovicKeypoint3D<PointInT, PointOutT, NormalT>::initCompute () { if (!PCLBase<PointInT>::initCompute ()) return (false); keypoints_indices_.reset (new pcl::PointIndices); keypoints_indices_->indices.reserve (input_->size ()); if (indices_->size () != input_->size ()) { PCL_ERROR ("[pcl::%s::initCompute] %s doesn't support setting indices!\n", name_.c_str ()); return (false); } if ((window_size_%2) == 0) { PCL_ERROR ("[pcl::%s::initCompute] Window size must be odd!\n", name_.c_str ()); return (false); } if (window_size_ < 3) { PCL_ERROR ("[pcl::%s::initCompute] Window size must be >= 3x3!\n", name_.c_str ()); return (false); } half_window_size_ = window_size_ / 2; if (!normals_) { NormalsPtr normals (new Normals ()); normals->reserve (normals->size ()); pcl::IntegralImageNormalEstimation<PointInT, NormalT> normal_estimation; normal_estimation.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointInT, NormalT>::SIMPLE_3D_GRADIENT); normal_estimation.setInputCloud (input_); normal_estimation.setNormalSmoothingSize (5.0); normal_estimation.compute (*normals); normals_ = normals; } if (normals_->size () != input_->size ()) { PCL_ERROR ("[pcl::%s::initCompute] normals given, but the number of normals does not match the number of input points!\n", name_.c_str (), method_); return (false); } return (true); } ///////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT, typename NormalT> void pcl::TrajkovicKeypoint3D<PointInT, PointOutT, NormalT>::detectKeypoints (PointCloudOut &output) { response_.reset (new pcl::PointCloud<float> (input_->width, input_->height)); const Normals &normals = *normals_; const PointCloudIn &input = *input_; pcl::PointCloud<float>& response = *response_; const int w = static_cast<int> (input_->width) - half_window_size_; const int h = static_cast<int> (input_->height) - half_window_size_; if (method_ == FOUR_CORNERS) { #ifdef _OPENMP #pragma omp parallel for num_threads (threads_) #endif for(int j = half_window_size_; j < h; ++j) { for(int i = half_window_size_; i < w; ++i) { if (!isFinite (input (i,j))) continue; const NormalT &center = normals (i,j); if (!isFinite (center)) continue; int count = 0; const NormalT &up = getNormalOrNull (i, j-half_window_size_, count); const NormalT &down = getNormalOrNull (i, j+half_window_size_, count); const NormalT &left = getNormalOrNull (i-half_window_size_, j, count); const NormalT &right = getNormalOrNull (i+half_window_size_, j, count); // Get rid of isolated points if (!count) continue; float sn1 = squaredNormalsDiff (up, center); float sn2 = squaredNormalsDiff (down, center); float r1 = sn1 + sn2; float r2 = squaredNormalsDiff (right, center) + squaredNormalsDiff (left, center); float d = std::min (r1, r2); if (d < first_threshold_) continue; sn1 = sqrt (sn1); sn2 = sqrt (sn2); float b1 = normalsDiff (right, up) * sn1; b1+= normalsDiff (left, down) * sn2; float b2 = normalsDiff (right, down) * sn2; b2+= normalsDiff (left, up) * sn1; float B = std::min (b1, b2); float A = r2 - r1 - 2*B; response (i,j) = ((B < 0) && ((B + A) > 0)) ? r1 - ((B*B)/A) : d; } } } else { #ifdef _OPENMP #pragma omp parallel for num_threads (threads_) #endif for(int j = half_window_size_; j < h; ++j) { for(int i = half_window_size_; i < w; ++i) { if (!isFinite (input (i,j))) continue; const NormalT &center = normals (i,j); if (!isFinite (center)) continue; int count = 0; const NormalT &up = getNormalOrNull (i, j-half_window_size_, count); const NormalT &down = getNormalOrNull (i, j+half_window_size_, count); const NormalT &left = getNormalOrNull (i-half_window_size_, j, count); const NormalT &right = getNormalOrNull (i+half_window_size_, j, count); const NormalT &upleft = getNormalOrNull (i-half_window_size_, j-half_window_size_, count); const NormalT &upright = getNormalOrNull (i+half_window_size_, j-half_window_size_, count); const NormalT &downleft = getNormalOrNull (i-half_window_size_, j+half_window_size_, count); const NormalT &downright = getNormalOrNull (i+half_window_size_, j+half_window_size_, count); // Get rid of isolated points if (!count) continue; std::vector<float> r (4,0); r[0] = squaredNormalsDiff (up, center); r[0]+= squaredNormalsDiff (down, center); r[1] = squaredNormalsDiff (upright, center); r[1]+= squaredNormalsDiff (downleft, center); r[2] = squaredNormalsDiff (right, center); r[2]+= squaredNormalsDiff (left, center); r[3] = squaredNormalsDiff (downright, center); r[3]+= squaredNormalsDiff (upleft, center); float d = *(std::min_element (r.begin (), r.end ())); if (d < first_threshold_) continue; std::vector<float> B (4,0); std::vector<float> A (4,0); std::vector<float> sumAB (4,0); B[0] = normalsDiff (upright, up) * normalsDiff (up, center); B[0]+= normalsDiff (downleft, down) * normalsDiff (down, center); B[1] = normalsDiff (right, upright) * normalsDiff (upright, center); B[1]+= normalsDiff (left, downleft) * normalsDiff (downleft, center); B[2] = normalsDiff (downright, right) * normalsDiff (downright, center); B[2]+= normalsDiff (upleft, left) * normalsDiff (upleft, center); B[3] = normalsDiff (down, downright) * normalsDiff (downright, center); B[3]+= normalsDiff (up, upleft) * normalsDiff (upleft, center); A[0] = r[1] - r[0] - B[0] - B[0]; A[1] = r[2] - r[1] - B[1] - B[1]; A[2] = r[3] - r[2] - B[2] - B[2]; A[3] = r[0] - r[3] - B[3] - B[3]; sumAB[0] = A[0] + B[0]; sumAB[1] = A[1] + B[1]; sumAB[2] = A[2] + B[2]; sumAB[3] = A[3] + B[3]; if ((*std::max_element (B.begin (), B.end ()) < 0) && (*std::min_element (sumAB.begin (), sumAB.end ()) > 0)) { std::vector<float> D (4,0); D[0] = B[0] * B[0] / A[0]; D[1] = B[1] * B[1] / A[1]; D[2] = B[2] * B[2] / A[2]; D[3] = B[3] * B[3] / A[3]; response (i,j) = *(std::min (D.begin (), D.end ())); } else response (i,j) = d; } } } // Non maximas suppression std::vector<int> indices = *indices_; std::sort (indices.begin (), indices.end (), boost::bind (&TrajkovicKeypoint3D::greaterCornernessAtIndices, this, _1, _2)); output.clear (); output.reserve (input_->size ()); std::vector<bool> occupency_map (indices.size (), false); const int width (input_->width); const int height (input_->height); const int occupency_map_size (indices.size ()); #ifdef _OPENMP #pragma omp parallel for shared (output, keypoints_indices_) num_threads (threads_) #endif for (int i = 0; i < indices.size (); ++i) { int idx = indices[i]; if ((response_->points[idx] < second_threshold_) || occupency_map[idx]) continue; PointOutT p; p.getVector3fMap () = input_->points[idx].getVector3fMap (); p.intensity = response_->points [idx]; #ifdef _OPENMP #pragma omp critical #endif { output.push_back (p); keypoints_indices_->indices.push_back (idx); } const int x = idx % width; const int y = idx / width; const int u_end = std::min (width, x + half_window_size_); const int v_end = std::min (height, y + half_window_size_); for(int v = std::max (0, y - half_window_size_); v < v_end; ++v) for(int u = std::max (0, x - half_window_size_); u < u_end; ++u) occupency_map[v*width + u] = true; } output.height = 1; output.width = static_cast<uint32_t> (output.size()); // we don not change the denseness output.is_dense = true; } #define PCL_INSTANTIATE_TrajkovicKeypoint3D(T,U,N) template class PCL_EXPORTS pcl::TrajkovicKeypoint3D<T,U,N>; #endif <commit_msg>Fix: removal of unused argument and normals_->resize statement<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2013-, Open Perception, 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef PCL_TRAJKOVIC_KEYPOINT_3D_IMPL_H_ #define PCL_TRAJKOVIC_KEYPOINT_3D_IMPL_H_ #include <pcl/features/integral_image_normal.h> template <typename PointInT, typename PointOutT, typename NormalT> bool pcl::TrajkovicKeypoint3D<PointInT, PointOutT, NormalT>::initCompute () { if (!PCLBase<PointInT>::initCompute ()) return (false); keypoints_indices_.reset (new pcl::PointIndices); keypoints_indices_->indices.reserve (input_->size ()); if (indices_->size () != input_->size ()) { PCL_ERROR ("[pcl::%s::initCompute] %s doesn't support setting indices!\n", name_.c_str ()); return (false); } if ((window_size_%2) == 0) { PCL_ERROR ("[pcl::%s::initCompute] Window size must be odd!\n", name_.c_str ()); return (false); } if (window_size_ < 3) { PCL_ERROR ("[pcl::%s::initCompute] Window size must be >= 3x3!\n", name_.c_str ()); return (false); } half_window_size_ = window_size_ / 2; if (!normals_) { NormalsPtr normals (new Normals ()); pcl::IntegralImageNormalEstimation<PointInT, NormalT> normal_estimation; normal_estimation.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointInT, NormalT>::SIMPLE_3D_GRADIENT); normal_estimation.setInputCloud (input_); normal_estimation.setNormalSmoothingSize (5.0); normal_estimation.compute (*normals); normals_ = normals; } if (normals_->size () != input_->size ()) { PCL_ERROR ("[pcl::%s::initCompute] normals given, but the number of normals does not match the number of input points!\n", name_.c_str ()); return (false); } return (true); } ///////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT, typename NormalT> void pcl::TrajkovicKeypoint3D<PointInT, PointOutT, NormalT>::detectKeypoints (PointCloudOut &output) { response_.reset (new pcl::PointCloud<float> (input_->width, input_->height)); const Normals &normals = *normals_; const PointCloudIn &input = *input_; pcl::PointCloud<float>& response = *response_; const int w = static_cast<int> (input_->width) - half_window_size_; const int h = static_cast<int> (input_->height) - half_window_size_; if (method_ == FOUR_CORNERS) { #ifdef _OPENMP #pragma omp parallel for num_threads (threads_) #endif for(int j = half_window_size_; j < h; ++j) { for(int i = half_window_size_; i < w; ++i) { if (!isFinite (input (i,j))) continue; const NormalT &center = normals (i,j); if (!isFinite (center)) continue; int count = 0; const NormalT &up = getNormalOrNull (i, j-half_window_size_, count); const NormalT &down = getNormalOrNull (i, j+half_window_size_, count); const NormalT &left = getNormalOrNull (i-half_window_size_, j, count); const NormalT &right = getNormalOrNull (i+half_window_size_, j, count); // Get rid of isolated points if (!count) continue; float sn1 = squaredNormalsDiff (up, center); float sn2 = squaredNormalsDiff (down, center); float r1 = sn1 + sn2; float r2 = squaredNormalsDiff (right, center) + squaredNormalsDiff (left, center); float d = std::min (r1, r2); if (d < first_threshold_) continue; sn1 = sqrt (sn1); sn2 = sqrt (sn2); float b1 = normalsDiff (right, up) * sn1; b1+= normalsDiff (left, down) * sn2; float b2 = normalsDiff (right, down) * sn2; b2+= normalsDiff (left, up) * sn1; float B = std::min (b1, b2); float A = r2 - r1 - 2*B; response (i,j) = ((B < 0) && ((B + A) > 0)) ? r1 - ((B*B)/A) : d; } } } else { #ifdef _OPENMP #pragma omp parallel for num_threads (threads_) #endif for(int j = half_window_size_; j < h; ++j) { for(int i = half_window_size_; i < w; ++i) { if (!isFinite (input (i,j))) continue; const NormalT &center = normals (i,j); if (!isFinite (center)) continue; int count = 0; const NormalT &up = getNormalOrNull (i, j-half_window_size_, count); const NormalT &down = getNormalOrNull (i, j+half_window_size_, count); const NormalT &left = getNormalOrNull (i-half_window_size_, j, count); const NormalT &right = getNormalOrNull (i+half_window_size_, j, count); const NormalT &upleft = getNormalOrNull (i-half_window_size_, j-half_window_size_, count); const NormalT &upright = getNormalOrNull (i+half_window_size_, j-half_window_size_, count); const NormalT &downleft = getNormalOrNull (i-half_window_size_, j+half_window_size_, count); const NormalT &downright = getNormalOrNull (i+half_window_size_, j+half_window_size_, count); // Get rid of isolated points if (!count) continue; std::vector<float> r (4,0); r[0] = squaredNormalsDiff (up, center); r[0]+= squaredNormalsDiff (down, center); r[1] = squaredNormalsDiff (upright, center); r[1]+= squaredNormalsDiff (downleft, center); r[2] = squaredNormalsDiff (right, center); r[2]+= squaredNormalsDiff (left, center); r[3] = squaredNormalsDiff (downright, center); r[3]+= squaredNormalsDiff (upleft, center); float d = *(std::min_element (r.begin (), r.end ())); if (d < first_threshold_) continue; std::vector<float> B (4,0); std::vector<float> A (4,0); std::vector<float> sumAB (4,0); B[0] = normalsDiff (upright, up) * normalsDiff (up, center); B[0]+= normalsDiff (downleft, down) * normalsDiff (down, center); B[1] = normalsDiff (right, upright) * normalsDiff (upright, center); B[1]+= normalsDiff (left, downleft) * normalsDiff (downleft, center); B[2] = normalsDiff (downright, right) * normalsDiff (downright, center); B[2]+= normalsDiff (upleft, left) * normalsDiff (upleft, center); B[3] = normalsDiff (down, downright) * normalsDiff (downright, center); B[3]+= normalsDiff (up, upleft) * normalsDiff (upleft, center); A[0] = r[1] - r[0] - B[0] - B[0]; A[1] = r[2] - r[1] - B[1] - B[1]; A[2] = r[3] - r[2] - B[2] - B[2]; A[3] = r[0] - r[3] - B[3] - B[3]; sumAB[0] = A[0] + B[0]; sumAB[1] = A[1] + B[1]; sumAB[2] = A[2] + B[2]; sumAB[3] = A[3] + B[3]; if ((*std::max_element (B.begin (), B.end ()) < 0) && (*std::min_element (sumAB.begin (), sumAB.end ()) > 0)) { std::vector<float> D (4,0); D[0] = B[0] * B[0] / A[0]; D[1] = B[1] * B[1] / A[1]; D[2] = B[2] * B[2] / A[2]; D[3] = B[3] * B[3] / A[3]; response (i,j) = *(std::min (D.begin (), D.end ())); } else response (i,j) = d; } } } // Non maximas suppression std::vector<int> indices = *indices_; std::sort (indices.begin (), indices.end (), boost::bind (&TrajkovicKeypoint3D::greaterCornernessAtIndices, this, _1, _2)); output.clear (); output.reserve (input_->size ()); std::vector<bool> occupency_map (indices.size (), false); const int width (input_->width); const int height (input_->height); const int occupency_map_size (indices.size ()); #ifdef _OPENMP #pragma omp parallel for shared (output, keypoints_indices_) num_threads (threads_) #endif for (int i = 0; i < indices.size (); ++i) { int idx = indices[i]; if ((response_->points[idx] < second_threshold_) || occupency_map[idx]) continue; PointOutT p; p.getVector3fMap () = input_->points[idx].getVector3fMap (); p.intensity = response_->points [idx]; #ifdef _OPENMP #pragma omp critical #endif { output.push_back (p); keypoints_indices_->indices.push_back (idx); } const int x = idx % width; const int y = idx / width; const int u_end = std::min (width, x + half_window_size_); const int v_end = std::min (height, y + half_window_size_); for(int v = std::max (0, y - half_window_size_); v < v_end; ++v) for(int u = std::max (0, x - half_window_size_); u < u_end; ++u) occupency_map[v*width + u] = true; } output.height = 1; output.width = static_cast<uint32_t> (output.size()); // we don not change the denseness output.is_dense = true; } #define PCL_INSTANTIATE_TrajkovicKeypoint3D(T,U,N) template class PCL_EXPORTS pcl::TrajkovicKeypoint3D<T,U,N>; #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2012 J-P Nurmi <[email protected]> * Copyright (C) 2010-2011 SmokeX <[email protected]> * Copyright (C) 2012 Mark Johnson <[email protected]> * * 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 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. */ /* Parts of this code come from Konversation and are copyrighted to: Copyright (C) 2002 Dario Abatianni <[email protected]> Copyright (C) 2004 Peter Simonsson <[email protected]> Copyright (C) 2006-2008 Eike Hein <[email protected]> Copyright (C) 2004-2009 Eli Mackenzie <[email protected]> */ #include "ircutil.h" #include <QStringList> #include <QRegExp> #include <QHash> /*! \file ircutil.h \brief #include &lt;IrcUtil&gt; */ /*! \class IrcUtil ircutil.h <IrcUtil> \ingroup utility \brief The IrcUtil class provides miscellaneous utility functions. */ static QRegExp URL_PATTERN(QLatin1String("((www\\.(?!\\.)|(ssh|fish|irc|amarok|(f|sf|ht)tp(|s))://)(\\.?[\\d\\w/,\\':~\\^\\?=;#@\\-\\+\\%\\*\\{\\}\\!\\(\\)\\[\\]]|&)+)|""([-.\\d\\w]+@[-.\\d\\w]{2,}\\.[\\w]{2,})"), Qt::CaseInsensitive); /*! Converts \a message to HTML using \a palette. This function parses the message and replaces IRC-style formatting like colors, bold and underline to the corresponding HTML formatting. Furthermore, this function detects URLs and replaces them with appropriate HTML hyperlinks. */ QString IrcUtil::messageToHtml(const QString& message, const IrcPalette& palette) { QString processed = message; processed.replace(QLatin1Char('&'), QLatin1String("&amp;")); processed.replace(QLatin1Char('<'), QLatin1String("&lt;")); processed.replace(QLatin1Char('>'), QLatin1String("&gt;")); processed.replace(QLatin1Char('"'), QLatin1String("&quot;")); processed.replace(QLatin1Char('\''), QLatin1String("&apos;")); processed.replace(QLatin1Char('\t'), QLatin1String("&nbsp;")); enum { None = 0x0, Bold = 0x1, Color = 0x2, Italic = 0x4, StrikeThrough = 0x8, Underline = 0x10, Inverse = 0x20 }; int state = None; int pos = 0; int depth = 0; bool parseColor = false; while (pos < processed.size()) { if (parseColor) { // fg(,bg) QRegExp rx(QLatin1String("(\\d{1,2})(?:,(\\d{1,2}))?")); int idx = rx.indexIn(processed, pos); if (idx == pos) { bool ok = false; QStringList styles; processed.remove(idx, rx.matchedLength()); // foreground int code = rx.cap(1).toInt(&ok); if (ok) styles += QString(QLatin1String("color:%1")).arg(palette.colorName(code, QLatin1String("black"))); // background code = rx.cap(2).toInt(&ok); if (ok) styles += QString(QLatin1String("background-color:%1")).arg(palette.colorName(code, QLatin1String("transparent"))); processed = processed.arg(styles.join(QLatin1String(";"))); } parseColor = false; continue; } QString replacement; switch (processed.at(pos).unicode()) { case '\x02': // bold if (state & Bold) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='font-weight: bold'>"); } state ^= Bold; break; case '\x03': // color if (state & Color) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='%1'>"); } state ^= Color; parseColor = state & Color; break; //case '\x09': // italic case '\x1d': // italic if (state & Italic) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='font-style: italic'>"); } state ^= Italic; break; case '\x13': // strike-through if (state & StrikeThrough) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='text-decoration: line-through'>"); } state ^= StrikeThrough; break; case '\x15': // underline case '\x1f': // underline if (state & Underline) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='text-decoration: underline'>"); } state ^= Underline; break; case '\x16': // inverse if (state & Inverse) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='font-weight: bold'>"); } state ^= Inverse; break; case '\x0f': // none if (depth > 0) replacement = QString(QLatin1String("</span>")).repeated(depth); else processed.remove(pos--, 1); // must rewind back for ++pos below... state = None; depth = 0; break; default: break; } if (!replacement.isEmpty()) { processed.replace(pos, 1, replacement); pos += replacement.length(); } else { ++pos; } } pos = 0; while ((pos = URL_PATTERN.indexIn(processed, pos)) >= 0) { int len = URL_PATTERN.matchedLength(); QString href = processed.mid(pos, len); // Don't consider trailing &gt; as part of the link. QString append; if (href.endsWith(QLatin1String("&gt;"))) { append.append(href.right(4)); href.chop(4); } // Don't consider trailing comma or semi-colon as part of the link. if (href.endsWith(QLatin1Char(',')) || href.endsWith(QLatin1Char(';'))) { append.append(href.right(1)); href.chop(1); } // Don't consider trailing closing parenthesis part of the link when // there's an opening parenthesis preceding in the beginning of the // URL or there is no opening parenthesis in the URL at all. if (pos > 0 && href.endsWith(QLatin1Char(')')) && (processed.at(pos - 1) == QLatin1Char('(') || !href.contains(QLatin1Char('(')))) { append.prepend(href.right(1)); href.chop(1); } // Qt doesn't support (?<=pattern) so we do it here if (pos > 0 && processed.at(pos - 1).isLetterOrNumber()) { pos++; continue; } QString protocol; if (URL_PATTERN.cap(1).startsWith(QLatin1String("www."), Qt::CaseInsensitive)) protocol = QLatin1String("http://"); else if (URL_PATTERN.cap(1).isEmpty()) protocol = QLatin1String("mailto:"); QString source = href; source.replace(QLatin1String("&amp;"), QLatin1String("&")); QString link = QString(QLatin1String("<a href='%1%2'>%3</a>")).arg(protocol, source, href) + append; processed.replace(pos, len, link); pos += link.length(); } return processed; } /*! \deprecated Use IrcPalette::colorName() instead. */ QString IrcUtil::colorCodeToName(int code, const QString& defaultColor) { return IrcPalette().colorName(code, defaultColor); } <commit_msg>IrcUtil: refactor color parsing<commit_after>/* * Copyright (C) 2008-2012 J-P Nurmi <[email protected]> * Copyright (C) 2010-2011 SmokeX <[email protected]> * Copyright (C) 2012 Mark Johnson <[email protected]> * * 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 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. */ /* Parts of this code come from Konversation and are copyrighted to: Copyright (C) 2002 Dario Abatianni <[email protected]> Copyright (C) 2004 Peter Simonsson <[email protected]> Copyright (C) 2006-2008 Eike Hein <[email protected]> Copyright (C) 2004-2009 Eli Mackenzie <[email protected]> */ #include "ircutil.h" #include <QStringList> #include <QRegExp> #include <QHash> /*! \file ircutil.h \brief #include &lt;IrcUtil&gt; */ /*! \class IrcUtil ircutil.h <IrcUtil> \ingroup utility \brief The IrcUtil class provides miscellaneous utility functions. */ static QRegExp URL_PATTERN(QLatin1String("((www\\.(?!\\.)|(ssh|fish|irc|amarok|(f|sf|ht)tp(|s))://)(\\.?[\\d\\w/,\\':~\\^\\?=;#@\\-\\+\\%\\*\\{\\}\\!\\(\\)\\[\\]]|&)+)|""([-.\\d\\w]+@[-.\\d\\w]{2,}\\.[\\w]{2,})"), Qt::CaseInsensitive); static QPair<int, int> parseColors(const QString& message, int pos) { // fg(,bg) QPair<int, int> color = qMakePair(-1, -1); QRegExp rx(QLatin1String("(\\d{2})(?:,(\\d{2}))?")); int idx = rx.indexIn(message, pos); if (idx == pos) { bool ok = false; int fg = rx.cap(1).toInt(&ok); if (ok) color.first = fg; int bg = rx.cap(2).toInt(&ok); if (ok) color.second = bg; } return color; } /*! Converts \a message to HTML using \a palette. This function parses the message and replaces IRC-style formatting like colors, bold and underline to the corresponding HTML formatting. Furthermore, this function detects URLs and replaces them with appropriate HTML hyperlinks. */ QString IrcUtil::messageToHtml(const QString& message, const IrcPalette& palette) { QString processed = message; processed.replace(QLatin1Char('&'), QLatin1String("&amp;")); processed.replace(QLatin1Char('<'), QLatin1String("&lt;")); processed.replace(QLatin1Char('>'), QLatin1String("&gt;")); processed.replace(QLatin1Char('"'), QLatin1String("&quot;")); processed.replace(QLatin1Char('\''), QLatin1String("&apos;")); processed.replace(QLatin1Char('\t'), QLatin1String("&nbsp;")); enum { None = 0x0, Bold = 0x1, Italic = 0x4, StrikeThrough = 0x8, Underline = 0x10, Inverse = 0x20 }; int state = None; int pos = 0; int depth = 0; QPair<int, int> colors; while (pos < processed.size()) { QString replacement; switch (processed.at(pos).unicode()) { case '\x02': // bold if (state & Bold) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='font-weight: bold'>"); } state ^= Bold; break; case '\x03': // color colors = parseColors(processed, pos + 1); if (colors.first == -1) { depth--; replacement = QLatin1String("</span>"); } else { depth++; QStringList styles; styles += QString(QLatin1String("color:%1")).arg(palette.colorName(colors.first, QLatin1String("black"))); if (colors.second != -1) styles += QString(QLatin1String("background-color:%1")).arg(palette.colorName(colors.second, QLatin1String("transparent"))); replacement = QString(QLatin1String("<span style='%1'>")).arg(styles.join(QLatin1String(";"))); // \x03FF(,BB) processed.replace(pos, colors.second != -1 ? 6 : 3, replacement); pos += replacement.length(); continue; } break; //case '\x09': // italic case '\x1d': // italic if (state & Italic) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='font-style: italic'>"); } state ^= Italic; break; case '\x13': // strike-through if (state & StrikeThrough) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='text-decoration: line-through'>"); } state ^= StrikeThrough; break; case '\x15': // underline case '\x1f': // underline if (state & Underline) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='text-decoration: underline'>"); } state ^= Underline; break; case '\x16': // inverse if (state & Inverse) { depth--; replacement = QLatin1String("</span>"); } else { depth++; replacement = QLatin1String("<span style='font-weight: bold'>"); } state ^= Inverse; break; case '\x0f': // none if (depth > 0) replacement = QString(QLatin1String("</span>")).repeated(depth); else processed.remove(pos--, 1); // must rewind back for ++pos below... state = None; depth = 0; break; default: break; } if (!replacement.isEmpty()) { processed.replace(pos, 1, replacement); pos += replacement.length(); } else { ++pos; } } pos = 0; while ((pos = URL_PATTERN.indexIn(processed, pos)) >= 0) { int len = URL_PATTERN.matchedLength(); QString href = processed.mid(pos, len); // Don't consider trailing &gt; as part of the link. QString append; if (href.endsWith(QLatin1String("&gt;"))) { append.append(href.right(4)); href.chop(4); } // Don't consider trailing comma or semi-colon as part of the link. if (href.endsWith(QLatin1Char(',')) || href.endsWith(QLatin1Char(';'))) { append.append(href.right(1)); href.chop(1); } // Don't consider trailing closing parenthesis part of the link when // there's an opening parenthesis preceding in the beginning of the // URL or there is no opening parenthesis in the URL at all. if (pos > 0 && href.endsWith(QLatin1Char(')')) && (processed.at(pos - 1) == QLatin1Char('(') || !href.contains(QLatin1Char('(')))) { append.prepend(href.right(1)); href.chop(1); } // Qt doesn't support (?<=pattern) so we do it here if (pos > 0 && processed.at(pos - 1).isLetterOrNumber()) { pos++; continue; } QString protocol; if (URL_PATTERN.cap(1).startsWith(QLatin1String("www."), Qt::CaseInsensitive)) protocol = QLatin1String("http://"); else if (URL_PATTERN.cap(1).isEmpty()) protocol = QLatin1String("mailto:"); QString source = href; source.replace(QLatin1String("&amp;"), QLatin1String("&")); QString link = QString(QLatin1String("<a href='%1%2'>%3</a>")).arg(protocol, source, href) + append; processed.replace(pos, len, link); pos += link.length(); } return processed; } /*! \deprecated Use IrcPalette::colorName() instead. */ QString IrcUtil::colorCodeToName(int code, const QString& defaultColor) { return IrcPalette().colorName(code, defaultColor); } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 <limits> #include <sstream> #include <stddef.h> #include <string> #include <vector> #include "gtest/gtest.h" #include "BitFunnel/Configuration/Factories.h" #include "BitFunnel/Configuration/IFileSystem.h" #include "BitFunnel/Data/Sonnets.h" #include "BitFunnelTool.h" namespace BitFunnel { TEST(BitFunnelTool, ThreeToolsEndToEnd) { // // This test is going to run out of a RAM filesystem. // auto fileSystem = BitFunnel::Factories::CreateRAMFileSystem(); auto fileManager = BitFunnel::Factories::CreateFileManager( "config", "statistics", "index", *fileSystem); // // Initialize RAM filesystem with input files. // { // Open the manifest file. auto manifest = fileSystem->OpenForWrite("manifest.txt"); // Iterate over sequence of Shakespeare sonnet chunk data. for (size_t i = 0; i < Sonnets::chunks.size(); ++i) { // Create chunk file name, and write chunk data. std::stringstream name; name << "sonnet" << i; auto out = fileSystem->OpenForWrite(name.str().c_str()); out->write(Sonnets::chunks[i].second, static_cast<std::streamsize>(Sonnets::chunks[i].first)); // Add chunk file to manifest. *manifest << name.str() << std::endl; } } // // Create the BitFunnelTool based on the RAM filesystem. // BitFunnel::BitFunnelTool tool(*fileSystem); // // Use the tool to run the statistics builder. // { std::vector<char const *> argv = { "BitFunnel", "statistics", "manifest.txt", "config" }; tool.Main(std::cin, std::cout, static_cast<int>(argv.size()), argv.data()); } // // Use the tool to run the TermTable builder. // { std::vector<char const *> argv = { "BitFunnel", "termtable", "config" }; tool.Main(std::cin, std::cout, static_cast<int>(argv.size()), argv.data()); } // // Use the tool to run the REPL. // { std::vector<char const *> argv = { "BitFunnel", "repl", "config" }; // Create an input stream with commands to // load a chunk, verify a query, and inspect // some rows. std::stringstream input; input << "cache chunk sonnet0" << std::endl << "verify one blood" << std::endl << "show rows blood" << std::endl; tool.Main(input, std::cout, static_cast<int>(argv.size()), argv.data()); } } } <commit_msg>Add -script in BitFunnelToolTest.<commit_after>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 <limits> #include <sstream> #include <stddef.h> #include <string> #include <vector> #include "gtest/gtest.h" #include "BitFunnel/Configuration/Factories.h" #include "BitFunnel/Configuration/IFileSystem.h" #include "BitFunnel/Data/Sonnets.h" #include "BitFunnelTool.h" namespace BitFunnel { TEST(BitFunnelTool, ThreeToolsEndToEnd) { // // This test is going to run out of a RAM filesystem. // auto fileSystem = BitFunnel::Factories::CreateRAMFileSystem(); auto fileManager = BitFunnel::Factories::CreateFileManager( "config", "statistics", "index", *fileSystem); // // Initialize RAM filesystem with input files. // { // Open the manifest file. auto manifest = fileSystem->OpenForWrite("manifest.txt"); // Iterate over sequence of Shakespeare sonnet chunk data. for (size_t i = 0; i < Sonnets::chunks.size(); ++i) { // Create chunk file name, and write chunk data. std::stringstream name; name << "sonnet" << i; auto out = fileSystem->OpenForWrite(name.str().c_str()); out->write(Sonnets::chunks[i].second, static_cast<std::streamsize>(Sonnets::chunks[i].first)); // Add chunk file to manifest. *manifest << name.str() << std::endl; } auto script = fileSystem->OpenForWrite("testScript"); *script << "cache chunk sonnet0" << std::endl; } // // Create the BitFunnelTool based on the RAM filesystem. // BitFunnel::BitFunnelTool tool(*fileSystem); // // Use the tool to run the statistics builder. // { std::vector<char const *> argv = { "BitFunnel", "statistics", "manifest.txt", "config" }; tool.Main(std::cin, std::cout, static_cast<int>(argv.size()), argv.data()); } // // Use the tool to run the TermTable builder. // { std::vector<char const *> argv = { "BitFunnel", "termtable", "config" }; tool.Main(std::cin, std::cout, static_cast<int>(argv.size()), argv.data()); } // // Use the tool to run the REPL. // { std::vector<char const *> argv = { "BitFunnel", "repl", "config", // -script and testScript must be on seperate lines because // tokens are delimited by whitespace. "-script", "testScript" }; // Create an input stream with commands to // load a chunk, verify a query, and inspect // some rows. std::stringstream input; input // This first line is run via -script. // << "cache chunk sonnet0" << std::endl << "verify one blood" << std::endl << "show rows blood" << std::endl; tool.Main(input, std::cout, static_cast<int>(argv.size()), argv.data()); } } } <|endoftext|>
<commit_before>#include <sstream> #include <stdexcept> #include <typeinfo> #include <json/istring.hpp> #include <json/util.hpp> namespace JSON { IValue::Type IString::type() const { return JSON_STRING; } IString* IString::clone() const { return new IString(value); } const std::string& IString::getString() const { return value; } bool IString::asBool() const { return value != "" && value != "0"; } template <typename T> inline T _parse(const std::string& s) { T ret; std::istringstream is(s); is >> ret; return ret; } int IString::asInt() const { return _parse<int>(value); } unsigned IString::asUInt() const { return _parse<unsigned>(value); } long long IString::asLong() const { return _parse<long long>(value); } unsigned long long IString::asULong() const { return _parse<unsigned long long>(value); } double IString::asDouble() const { return _parse<double>(value); } std::string IString::asString() const { return value; } bool IString::operator==(const IValue& r) const { return value == r.getString(); } bool IString::operator<(const IValue& r) const { return value < r.getString(); } bool IString::operator<=(const IValue& r) const { return value <= r.getString(); } void IString::toStream(std::ostream& o) const { stringtojsonstream(value, o); } void IString::fromStream(std::istream& i) { jsonstringtostring(value, i); } }; // namespace JSON <commit_msg>IString::asBool(): treat "f" as false<commit_after>#include <sstream> #include <stdexcept> #include <typeinfo> #include <json/istring.hpp> #include <json/util.hpp> namespace JSON { IValue::Type IString::type() const { return JSON_STRING; } IString* IString::clone() const { return new IString(value); } const std::string& IString::getString() const { return value; } bool IString::asBool() const { return value != "" && value != "0" && value != "f"; } template <typename T> inline T _parse(const std::string& s) { T ret; std::istringstream is(s); is >> ret; return ret; } int IString::asInt() const { return _parse<int>(value); } unsigned IString::asUInt() const { return _parse<unsigned>(value); } long long IString::asLong() const { return _parse<long long>(value); } unsigned long long IString::asULong() const { return _parse<unsigned long long>(value); } double IString::asDouble() const { return _parse<double>(value); } std::string IString::asString() const { return value; } bool IString::operator==(const IValue& r) const { return value == r.getString(); } bool IString::operator<(const IValue& r) const { return value < r.getString(); } bool IString::operator<=(const IValue& r) const { return value <= r.getString(); } void IString::toStream(std::ostream& o) const { stringtojsonstream(value, o); } void IString::fromStream(std::istream& i) { jsonstringtostring(value, i); } }; // namespace JSON <|endoftext|>
<commit_before>#include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <kernel/uvalue-cast.hh> #include <object/cxx-conversions.hh> #include <object/float.hh> #include <object/global.hh> #include <object/list.hh> #include <object/string.hh> #include <object/symbols.hh> #include <object/uvar.hh> #include <runner/raise.hh> #include <urbi/uvalue.hh> urbi::UDataType uvalue_type(const object::rObject& o) { CAPTURE_GLOBAL(Binary); if (o->as<object::Float>()) return urbi::DATA_DOUBLE; if (o->as<object::String>()) return urbi::DATA_STRING; if (o->as<object::List>()) return urbi::DATA_LIST; if (is_a(o, Binary)) return urbi::DATA_BINARY; if (o == object::void_class) return urbi::DATA_VOID; return urbi::DATA_OBJECT; } urbi::UValue uvalue_cast(const object::rObject& o) { CAPTURE_GLOBAL(Binary); urbi::UValue res; if (object::rUValue bv = o->as<object::UValue>()) return bv->value_get(); if (object::rFloat f = o->as<object::Float>()) res = f->value_get(); else if (object::rString s = o->as<object::String>()) res = s->value_get(); else if (object::rList s = o->as<object::List>()) { res.type = urbi::DATA_LIST; res.list = new urbi::UList; object::List::value_type& t = o.cast<object::List>()->value_get(); foreach (const object::rObject& co, t) res.list->array.push_back(new urbi::UValue(uvalue_cast(co))); } else if (is_a(o, Binary)) { const std::string& data = o->slot_get(SYMBOL(data))->as<object::String>()->value_get(); const std::string& keywords = o->slot_get(SYMBOL(keywords))-> as<object::String>()->value_get(); std::list<urbi::BinaryData> l; l.push_back(urbi::BinaryData(const_cast<char*>(data.c_str()), data.size())); std::list<urbi::BinaryData>::const_iterator i = l.begin(); res.type = urbi::DATA_BINARY; res.binary = new urbi::UBinary(); res.binary->parse( (boost::lexical_cast<std::string>(data.size()) + " " + keywords + '\n').c_str(), 0, l, i); } else // We could not find how to cast this value { const object::rString& rs = o->slot_get(SYMBOL(type))->as<object::String>(); runner::raise_argument_type_error (0, rs, object::to_urbi(SYMBOL(LT_exportable_SP_object_GT)), object::to_urbi(SYMBOL(cast))); } return res; } object::rObject object_cast(const urbi::UValue& v) { object::rObject res; switch(v.type) { case urbi::DATA_DOUBLE: return new object::Float(v.val); break; case urbi::DATA_STRING: return new object::String(*v.stringValue); break; case urbi::DATA_LIST: { object::rList l = new object::List(); foreach (urbi::UValue *cv, v.list->array) l->value_get().push_back(object_cast(*cv)); res = l; break; } case urbi::DATA_BINARY: { CAPTURE_GLOBAL(Binary); res = new object::Object(); res->proto_add(Binary); std::string msg = v.binary->getMessage(); // Trim it. if (!msg.empty() && msg[0] == ' ') msg = msg.substr(1, msg.npos); res->slot_set(SYMBOL(keywords), new object::String(msg)); res->slot_set(SYMBOL(data), new object::String (std::string(static_cast<char*>(v.binary->common.data), v.binary->common.size))); } break; case urbi::DATA_VOID: res = object::void_class; break; default: static boost::format m("<external data with type %1%>"); runner::raise_argument_type_error (0, object::to_urbi((m % v.type).str()), object::Object::proto, object::to_urbi(SYMBOL(backcast))); } return res; } <commit_msg>uobject: Fix UVar::type().<commit_after>#include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <kernel/uvalue-cast.hh> #include <object/cxx-conversions.hh> #include <object/float.hh> #include <object/global.hh> #include <object/list.hh> #include <object/string.hh> #include <object/symbols.hh> #include <object/uvar.hh> #include <runner/raise.hh> #include <urbi/uvalue.hh> urbi::UDataType uvalue_type(const object::rObject& o) { CAPTURE_GLOBAL(Binary); if (object::rUValue bv = o->as<object::UValue>()) return bv->value_get().type; if (o->as<object::Float>()) return urbi::DATA_DOUBLE; if (o->as<object::String>()) return urbi::DATA_STRING; if (o->as<object::List>()) return urbi::DATA_LIST; if (is_a(o, Binary)) return urbi::DATA_BINARY; if (o == object::void_class) return urbi::DATA_VOID; return urbi::DATA_OBJECT; } urbi::UValue uvalue_cast(const object::rObject& o) { CAPTURE_GLOBAL(Binary); urbi::UValue res; if (object::rUValue bv = o->as<object::UValue>()) return bv->value_get(); if (object::rFloat f = o->as<object::Float>()) res = f->value_get(); else if (object::rString s = o->as<object::String>()) res = s->value_get(); else if (object::rList s = o->as<object::List>()) { res.type = urbi::DATA_LIST; res.list = new urbi::UList; object::List::value_type& t = o.cast<object::List>()->value_get(); foreach (const object::rObject& co, t) res.list->array.push_back(new urbi::UValue(uvalue_cast(co))); } else if (is_a(o, Binary)) { const std::string& data = o->slot_get(SYMBOL(data))->as<object::String>()->value_get(); const std::string& keywords = o->slot_get(SYMBOL(keywords))-> as<object::String>()->value_get(); std::list<urbi::BinaryData> l; l.push_back(urbi::BinaryData(const_cast<char*>(data.c_str()), data.size())); std::list<urbi::BinaryData>::const_iterator i = l.begin(); res.type = urbi::DATA_BINARY; res.binary = new urbi::UBinary(); res.binary->parse( (boost::lexical_cast<std::string>(data.size()) + " " + keywords + '\n').c_str(), 0, l, i); } else // We could not find how to cast this value { const object::rString& rs = o->slot_get(SYMBOL(type))->as<object::String>(); runner::raise_argument_type_error (0, rs, object::to_urbi(SYMBOL(LT_exportable_SP_object_GT)), object::to_urbi(SYMBOL(cast))); } return res; } object::rObject object_cast(const urbi::UValue& v) { object::rObject res; switch(v.type) { case urbi::DATA_DOUBLE: return new object::Float(v.val); break; case urbi::DATA_STRING: return new object::String(*v.stringValue); break; case urbi::DATA_LIST: { object::rList l = new object::List(); foreach (urbi::UValue *cv, v.list->array) l->value_get().push_back(object_cast(*cv)); res = l; break; } case urbi::DATA_BINARY: { CAPTURE_GLOBAL(Binary); res = new object::Object(); res->proto_add(Binary); std::string msg = v.binary->getMessage(); // Trim it. if (!msg.empty() && msg[0] == ' ') msg = msg.substr(1, msg.npos); res->slot_set(SYMBOL(keywords), new object::String(msg)); res->slot_set(SYMBOL(data), new object::String (std::string(static_cast<char*>(v.binary->common.data), v.binary->common.size))); } break; case urbi::DATA_VOID: res = object::void_class; break; default: static boost::format m("<external data with type %1%>"); runner::raise_argument_type_error (0, object::to_urbi((m % v.type).str()), object::Object::proto, object::to_urbi(SYMBOL(backcast))); } return res; } <|endoftext|>
<commit_before>#include <iostream> #include <windows.h> LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int argc, char** argv) { return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX windowClass; // Register the Window Class windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.style = 0; windowClass.lpfnWndProc = WndProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = hInstance; windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); windowClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); windowClass.lpszMenuName = NULL; windowClass.lpszClassName = "myWindowClass"; windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); // make sure window class is valid if(!RegisterClassEx(&windowClass)) { MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 1; } HWND hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, g_szClassName, "The title of my window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL); // make sure window was created if(hwnd == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 2; } // start! ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); // Message Loop Msg msg; while(GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } <commit_msg>Windows OpenGL working now?<commit_after>#include <iostream> #include <windows.h> #include <GL/GL.h> LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); /*int main(int argc, char** argv) { return 0; }*/ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX windowClass; constexpr const char* className = "myWindowClass"; // Register the Window Class windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.style = CS_OWNDC; windowClass.lpfnWndProc = WndProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = hInstance; windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); windowClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); windowClass.lpszMenuName = NULL; windowClass.lpszClassName = className; windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); // make sure window class is valid if(!RegisterClassEx(&windowClass)) { MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 1; } PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // Flags PFD_TYPE_RGBA, // The kind of framebuffer. RGBA or palette. 32, // Colordepth of the framebuffer. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, // Number of bits for the depthbuffer 8, // Number of bits for the stencilbuffer 0, // Number of aux buffers in the framebuffer. PFD_MAIN_PLANE, 0, 0, 0, 0 }; HWND windowHandle = CreateWindowEx(WS_EX_CLIENTEDGE, className, "Windoze...", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL); // make sure window was created if(windowHandle == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 2; } HDC deviceContext = GetDC(windowHandle); int pixelFormatID = ChoosePixelFormat(deviceContext, &pfd); if(pixelFormatID == 0) { MessageBox(NULL, "Pixel Format selection failed.", "Error!", MB_ICONEXCLAMATION | MB_OK); return 3; } if(!SetPixelFormat(deviceContext, pixelFormatID, &pfd)) { MessageBox(NULL, "Pixel Format setting failed.", "Error!", MB_ICONEXCLAMATION | MB_OK); return 4; } // OpenGL HGLRC glContext = wglCreateContext(deviceContext); wglMakeCurrent(deviceContext, glContext); // start! ShowWindow(windowHandle, nCmdShow); UpdateWindow(windowHandle); MessageBoxA(0,(char*)glGetString(GL_VERSION), "OPENGL VERSION", 0); // Message Loop MSG msg; while(GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } wglMakeCurrent(NULL, NULL); wglDeleteContext(glContext); return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "volumepopup.h" #include "pulseaudiodevice.h" #include <qtxdg/xdgicon.h> #include <QtGui/QSlider> #include <QtGui/QToolButton> #include <QtGui/QVBoxLayout> #include <QtGui/QApplication> #include <QtGui/QDesktopWidget> #include <QtCore/QProcess> VolumePopup::VolumePopup(QWidget* parent): QWidget(parent, Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::X11BypassWindowManagerHint), m_pos(0,0), m_anchor(Qt::TopLeftCorner), m_device(0) { m_volumeSlider = new QSlider(Qt::Vertical, this); m_mixerButton = new QToolButton(this); m_mixerButton->setIcon(XdgIcon::fromTheme(QStringList() << "kmix")); m_volumeSlider->setSingleStep(m_volumeSlider->pageStep()); QVBoxLayout *l = new QVBoxLayout(this); l->setSpacing(0); l->setMargin(0); l->addWidget(m_volumeSlider, 0, Qt::AlignHCenter); l->addWidget(m_mixerButton); setLayout(new QVBoxLayout(this)); connect(m_mixerButton, SIGNAL(clicked()), this, SIGNAL(launchMixer())); connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); } VolumePopup::~VolumePopup() { } void VolumePopup::enterEvent(QEvent *event) { emit mouseEnter(); } void VolumePopup::leaveEvent(QEvent *event) { emit mouseExit(); } void VolumePopup::handleSliderValueChanged(int value) { if (!m_device) return; m_device->setVolume(value); } void VolumePopup::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); realign(); } void VolumePopup::open(QPoint pos, Qt::Corner anchor) { m_pos = pos; m_anchor = anchor; realign(); show(); } void VolumePopup::handleWheelEvent(QWheelEvent *event) { m_volumeSlider->event(reinterpret_cast<QEvent*>(event)); } void VolumePopup::setDevice(PulseAudioDevice *device) { if (device == m_device) return; // disconnect old device if (m_device) { disconnect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int))); disconnect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); } m_device = device; connect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int))); connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); emit deviceChanged(); } void VolumePopup::realign() { QRect rect; rect.setSize(sizeHint()); switch (m_anchor) { case Qt::TopLeftCorner: rect.moveTopLeft(m_pos); break; case Qt::TopRightCorner: rect.moveTopRight(m_pos); break; case Qt::BottomLeftCorner: rect.moveBottomLeft(m_pos); break; case Qt::BottomRightCorner: rect.moveBottomRight(m_pos); break; } QRect screen = QApplication::desktop()->availableGeometry(m_pos); if (rect.right() > screen.right()) rect.moveRight(screen.right()); if (rect.bottom() > screen.bottom()) rect.moveBottom(screen.bottom()); move(rect.topLeft()); } <commit_msg>panel-volume: Fix margin on popup layout<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "volumepopup.h" #include "pulseaudiodevice.h" #include <qtxdg/xdgicon.h> #include <QtGui/QSlider> #include <QtGui/QToolButton> #include <QtGui/QVBoxLayout> #include <QtGui/QApplication> #include <QtGui/QDesktopWidget> #include <QtCore/QProcess> VolumePopup::VolumePopup(QWidget* parent): QWidget(parent, Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::X11BypassWindowManagerHint), m_pos(0,0), m_anchor(Qt::TopLeftCorner), m_device(0) { m_volumeSlider = new QSlider(Qt::Vertical, this); m_mixerButton = new QToolButton(this); m_mixerButton->setIcon(XdgIcon::fromTheme(QStringList() << "kmix")); m_volumeSlider->setSingleStep(m_volumeSlider->pageStep()); QVBoxLayout *l = new QVBoxLayout(this); l->setSpacing(0); l->setMargin(2); l->addWidget(m_volumeSlider, 0, Qt::AlignHCenter); l->addWidget(m_mixerButton); setLayout(new QVBoxLayout(this)); connect(m_mixerButton, SIGNAL(clicked()), this, SIGNAL(launchMixer())); connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); } VolumePopup::~VolumePopup() { } void VolumePopup::enterEvent(QEvent *event) { emit mouseEnter(); } void VolumePopup::leaveEvent(QEvent *event) { emit mouseExit(); } void VolumePopup::handleSliderValueChanged(int value) { if (!m_device) return; m_device->setVolume(value); } void VolumePopup::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); realign(); } void VolumePopup::open(QPoint pos, Qt::Corner anchor) { m_pos = pos; m_anchor = anchor; realign(); show(); } void VolumePopup::handleWheelEvent(QWheelEvent *event) { m_volumeSlider->event(reinterpret_cast<QEvent*>(event)); } void VolumePopup::setDevice(PulseAudioDevice *device) { if (device == m_device) return; // disconnect old device if (m_device) { disconnect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int))); disconnect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); } m_device = device; connect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int))); connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); emit deviceChanged(); } void VolumePopup::realign() { QRect rect; rect.setSize(sizeHint()); switch (m_anchor) { case Qt::TopLeftCorner: rect.moveTopLeft(m_pos); break; case Qt::TopRightCorner: rect.moveTopRight(m_pos); break; case Qt::BottomLeftCorner: rect.moveBottomLeft(m_pos); break; case Qt::BottomRightCorner: rect.moveBottomRight(m_pos); break; } QRect screen = QApplication::desktop()->availableGeometry(m_pos); if (rect.right() > screen.right()) rect.moveRight(screen.right()); if (rect.bottom() > screen.bottom()) rect.moveBottom(screen.bottom()); move(rect.topLeft()); } <|endoftext|>
<commit_before>#include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <cal3d/buffersource.h> #include <cal3d/coreanimation.h> #include <cal3d/coreanimatedmorph.h> #include <cal3d/corebone.h> #include <cal3d/corematerial.h> #include <cal3d/coremesh.h> #include <cal3d/coreskeleton.h> #include <cal3d/coresubmesh.h> #include <cal3d/loader.h> #include <cal3d/saver.h> #include <cal3d/error.h> using namespace boost::python; CalCoreAnimationPtr loadCoreAnimationFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreAnimationPtr(CalLoader::loadCoreAnimation(cbs)); } bool saveCoreAnimation(const boost::shared_ptr<CalCoreAnimation>& animation, const std::string& path) { return CalSaver::saveCoreAnimation(path, animation.get()); } CalCoreSkeletonPtr loadCoreSkeletonFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreSkeletonPtr(CalLoader::loadCoreSkeleton(cbs)); } bool saveCoreSkeleton(const boost::shared_ptr<CalCoreSkeleton>& skeleton, const std::string& path) { return CalSaver::saveCoreSkeleton(path, skeleton.get()); } CalCoreMaterialPtr loadCoreMaterialFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreMaterialPtr(CalLoader::loadCoreMaterial(cbs)); } bool saveCoreMaterial(const boost::shared_ptr<CalCoreMaterial>& material, const std::string& path) { return CalSaver::saveCoreMaterial(path, material.get()); } CalCoreMeshPtr loadCoreMeshFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreMeshPtr(CalLoader::loadCoreMesh(cbs)); } bool saveCoreMesh(const boost::shared_ptr<CalCoreMesh>& mesh, const std::string& path) { return CalSaver::saveCoreMesh(path, mesh.get()); } CalCoreAnimatedMorphPtr loadCoreAnimatedMorphFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreAnimatedMorphPtr(CalLoader::loadCoreAnimatedMorph(cbs)); } bool saveCoreAnimatedMorph(const boost::shared_ptr<CalCoreAnimatedMorph>& animatedMorph, const std::string& path) { return CalSaver::saveCoreAnimatedMorph(path, animatedMorph.get()); } tuple getCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel) { CalVector sceneAmbient = skel->sceneAmbientColor; return make_tuple( sceneAmbient.x, sceneAmbient.y, sceneAmbient.z ); } void setCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel, tuple c) { if (len(c) != 3) { PyErr_SetString(PyExc_ValueError, "sceneAmbientColor must be a triple"); throw_error_already_set(); } skel->sceneAmbientColor.x = extract<float>(c[0]); skel->sceneAmbientColor.y = extract<float>(c[1]); skel->sceneAmbientColor.z = extract<float>(c[2]); } list getKeyframes(const CalCoreMorphTrack* t) { list rv; const std::vector<CalCoreMorphKeyframe>& keyframes = t->keyframes; for ( std::vector<CalCoreMorphKeyframe>::const_iterator i = keyframes.begin(); i != keyframes.end(); ++i ) { rv.append(*i); } return rv; } list getTracks(const CalCoreAnimatedMorph* m) { list rv; const std::vector<CalCoreMorphTrack>& tracks = m->tracks; for ( std::vector<CalCoreMorphTrack>::const_iterator i = tracks.begin(); i != tracks.end(); ++i ) { rv.append(*i); } return rv; } namespace cal3d { struct PythonBuffer : public Buffer { public: PythonBuffer(PyObject* p) { _ = p; incref(get()); } ~PythonBuffer() { boost::python::PyGILState_AssertIsCurrent(); decref(get()); } size_t size() const { void* data; return get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data); } const void* data() const { void* data; get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data); return data; } boost::shared_ptr<Buffer> clone() const { return boost::shared_ptr<Buffer>(new PythonBuffer(get())); } private: PyObject* get() const { return static_cast<PyObject*>(_); } }; struct BufferFromPythonObject { BufferFromPythonObject() { converter::registry::push_back( &convertible, &construct, boost::python::type_id<Buffer>() ); } static void* convertible(PyObject* obj_ptr) { return (obj_ptr->ob_type->tp_as_buffer && obj_ptr->ob_type->tp_as_buffer->bf_getreadbuffer) ? obj_ptr : 0; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data ) { // Note that we're registered as a converter to the Buffer interface, // so Boost has already allocated sizeof(Buffer) for us. Since we're // constructing PythonStringBuffer into that memory, assert that // PythonStringBuffer and Buffer have the same size. BOOST_STATIC_ASSERT(sizeof(Buffer) == sizeof(PythonBuffer)); void* storage = ((boost::python::converter::rvalue_from_python_storage<PythonBuffer>*)data)->storage.bytes; new(storage) PythonBuffer(obj_ptr); data->convertible = storage; } }; } template<unsigned i> CalIndex getFaceIndex(const CalCoreSubmesh::Face& f) { return f.vertexId[i]; } struct PythonVertex { PythonVertex() {} PythonVertex(const CalCoreSubmesh::Vertex& v) { position.x = v.position.x; position.y = v.position.y; position.z = v.position.z; normal.x = v.normal.x; normal.y = v.normal.y; normal.z = v.normal.z; } CalVector position; CalVector normal; bool operator==(const PythonVertex& rhs) const { return position == rhs.position && normal == rhs.normal; } }; std::vector<PythonVertex> getVertices(const CalCoreSubmesh& submesh) { return std::vector<PythonVertex>( submesh.getVectorVertex().begin(), submesh.getVectorVertex().end()); } template<typename T> void exportVector(const char* name) { class_<std::vector<typename T> >(name) .def(vector_indexing_suite< std::vector<typename T>, true>()) ; } #ifndef NDEBUG BOOST_PYTHON_MODULE(_cal3d_debug) #else BOOST_PYTHON_MODULE(_cal3d) #endif { cal3d::BufferFromPythonObject(); class_<CalVector>("Vector") .def_readwrite("x", &CalVector::x) .def_readwrite("y", &CalVector::y) .def_readwrite("z", &CalVector::z) ; class_<CalQuaternion>("Quaternion") .def_readwrite("x", &CalQuaternion::x) .def_readwrite("y", &CalQuaternion::y) .def_readwrite("z", &CalQuaternion::z) .def_readwrite("w", &CalQuaternion::w) ; class_<cal3d::Transform>("Transform") .def_readwrite("translation", &cal3d::Transform::translation) .def_readwrite("rotation", &cal3d::Transform::rotation) ; class_<CalCoreBone, boost::shared_ptr<CalCoreBone> >("CoreBone", no_init) .def(init<std::string>()) .def_readwrite("parentIndex", &CalCoreBone::parentId) .def_readwrite("name", &CalCoreBone::name) .def_readwrite("relativeTransform", &CalCoreBone::relativeTransform) .def_readwrite("boneSpaceTransform", &CalCoreBone::boneSpaceTransform) ; exportVector<CalCoreBonePtr>("BoneVector"); class_<CalCoreSkeleton, boost::shared_ptr<CalCoreSkeleton> >("CoreSkeleton") .def("addCoreBone", &CalCoreSkeleton::addCoreBone) .add_property("sceneAmbientColor", &getCoreSkeletonSceneAmbientColor, &setCoreSkeletonSceneAmbientColor) .add_property("bones", &CalCoreSkeleton::coreBones) ; { scope CalCoreMaterial_class( class_<CalCoreMaterial, boost::shared_ptr<CalCoreMaterial> >("CoreMaterial") .def_readwrite("maps", &CalCoreMaterial::maps) ); exportVector<CalCoreMaterial::Map>("MapVector"); class_<CalCoreMaterial::Map>("Map") .def_readwrite("filename", &CalCoreMaterial::Map::filename) .def_readwrite("type", &CalCoreMaterial::Map::type) ; } class_<CalCoreSubmesh::Face>("Triangle") .add_property("v1", &getFaceIndex<0>) .add_property("v2", &getFaceIndex<1>) .add_property("v3", &getFaceIndex<2>) ; exportVector<CalCoreSubmesh::Face>("TriangleVector"); class_<PythonVertex>("Vertex") .def_readwrite("position", &PythonVertex::position) .def_readwrite("normal", &PythonVertex::normal) ; exportVector<PythonVertex>("VertexVector"); class_<CalCoreSubmesh::TextureCoordinate>("TextureCoordinate") .def_readwrite("u", &CalCoreSubmesh::TextureCoordinate::u) .def_readwrite("v", &CalCoreSubmesh::TextureCoordinate::v) ; exportVector<CalCoreSubmesh::TextureCoordinate>("TextureCoordinateVector"); exportVector<std::vector<CalCoreSubmesh::TextureCoordinate> >("TextureCoordinateVectorVector"); class_<CalCoreSubmesh::Influence>("Influence") .def_readwrite("boneId", &CalCoreSubmesh::Influence::boneId) .def_readwrite("weight", &CalCoreSubmesh::Influence::weight) .def_readwrite("isLast", &CalCoreSubmesh::Influence::lastInfluenceForThisVertex) ; exportVector<CalCoreSubmesh::Influence>("InfluenceVector"); class_<CalCoreSubmesh, boost::shared_ptr<CalCoreSubmesh>, boost::noncopyable>("CoreSubmesh", no_init) .def_readwrite("coreMaterialThreadId", &CalCoreSubmesh::coreMaterialThreadId) .def_readwrite("triangles", &CalCoreSubmesh::faces) .add_property("vertices", &getVertices) .add_property("hasVertexColors", &CalCoreSubmesh::hasVertexColors) .add_property("colors", make_function(&CalCoreSubmesh::getVertexColors, return_value_policy<return_by_value>())) .add_property("texcoords", make_function(&CalCoreSubmesh::getVectorVectorTextureCoordinate, return_value_policy<return_by_value>())) .add_property("influences", make_function(&CalCoreSubmesh::getInfluences, return_value_policy<return_by_value>())) ; class_< CalCoreMesh::CalCoreSubmeshVector >("CalCoreSubmeshVector") .def(vector_indexing_suite<CalCoreMesh::CalCoreSubmeshVector, true>()) ; class_<CalCoreMesh, boost::shared_ptr<CalCoreMesh> >("CoreMesh") .def_readwrite("submeshes", &CalCoreMesh::submeshes) ; class_<CalCoreAnimation, boost::shared_ptr<CalCoreAnimation> >("CoreAnimation") ; class_<CalCoreMorphKeyframe>("CoreMorphKeyframe") .add_property("time", &CalCoreMorphKeyframe::time) .add_property("weight", &CalCoreMorphKeyframe::weight) ; class_<CalCoreMorphTrack, boost::shared_ptr<CalCoreMorphTrack> >("CoreMorphTrack") .def_readonly("name", &CalCoreMorphTrack::morphName) .add_property("keyframes", &getKeyframes) ; class_<CalCoreAnimatedMorph, boost::shared_ptr<CalCoreAnimatedMorph> >("CoreAnimatedMorph") .def("removeZeroScaleTracks", &CalCoreAnimatedMorph::removeZeroScaleTracks) .def_readonly("duration", &CalCoreAnimatedMorph::duration) .add_property("tracks", &getTracks) ; def("loadCoreAnimationFromBuffer", &loadCoreAnimationFromBuffer); def("saveCoreAnimation", &saveCoreAnimation); def("saveCoreAnimationToBuffer", &CalSaver::saveCoreAnimationToBuffer); def("loadCoreSkeletonFromBuffer", &loadCoreSkeletonFromBuffer); def("saveCoreSkeleton", &saveCoreSkeleton); def("saveCoreSkeletonToBuffer", &CalSaver::saveCoreSkeletonToBuffer); def("loadCoreMaterialFromBuffer", &loadCoreMaterialFromBuffer); def("saveCoreMaterial", &saveCoreMaterial); def("saveCoreMaterialToBuffer", &CalSaver::saveCoreMaterialToBuffer); def("loadCoreMeshFromBuffer", &loadCoreMeshFromBuffer); def("saveCoreMesh", &saveCoreMesh); def("saveCoreMeshToBuffer", &CalSaver::saveCoreMeshToBuffer); def("loadCoreAnimatedMorphFromBuffer", &loadCoreAnimatedMorphFromBuffer); def("saveCoreAnimatedMorph", &saveCoreAnimatedMorph); def("saveCoreAnimatedMorphToBuffer", &CalSaver::saveCoreAnimatedMorphToBuffer); def("getLastErrorText", &CalError::getLastErrorText); } <commit_msg>Fixing mac compile. Allow cit commits: this is chad<commit_after>#include <vector> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <cal3d/buffersource.h> #include <cal3d/coreanimation.h> #include <cal3d/coreanimatedmorph.h> #include <cal3d/corebone.h> #include <cal3d/corematerial.h> #include <cal3d/coremesh.h> #include <cal3d/coreskeleton.h> #include <cal3d/coresubmesh.h> #include <cal3d/loader.h> #include <cal3d/saver.h> #include <cal3d/error.h> using namespace boost::python; CalCoreAnimationPtr loadCoreAnimationFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreAnimationPtr(CalLoader::loadCoreAnimation(cbs)); } bool saveCoreAnimation(const boost::shared_ptr<CalCoreAnimation>& animation, const std::string& path) { return CalSaver::saveCoreAnimation(path, animation.get()); } CalCoreSkeletonPtr loadCoreSkeletonFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreSkeletonPtr(CalLoader::loadCoreSkeleton(cbs)); } bool saveCoreSkeleton(const boost::shared_ptr<CalCoreSkeleton>& skeleton, const std::string& path) { return CalSaver::saveCoreSkeleton(path, skeleton.get()); } CalCoreMaterialPtr loadCoreMaterialFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreMaterialPtr(CalLoader::loadCoreMaterial(cbs)); } bool saveCoreMaterial(const boost::shared_ptr<CalCoreMaterial>& material, const std::string& path) { return CalSaver::saveCoreMaterial(path, material.get()); } CalCoreMeshPtr loadCoreMeshFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreMeshPtr(CalLoader::loadCoreMesh(cbs)); } bool saveCoreMesh(const boost::shared_ptr<CalCoreMesh>& mesh, const std::string& path) { return CalSaver::saveCoreMesh(path, mesh.get()); } CalCoreAnimatedMorphPtr loadCoreAnimatedMorphFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreAnimatedMorphPtr(CalLoader::loadCoreAnimatedMorph(cbs)); } bool saveCoreAnimatedMorph(const boost::shared_ptr<CalCoreAnimatedMorph>& animatedMorph, const std::string& path) { return CalSaver::saveCoreAnimatedMorph(path, animatedMorph.get()); } tuple getCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel) { CalVector sceneAmbient = skel->sceneAmbientColor; return make_tuple( sceneAmbient.x, sceneAmbient.y, sceneAmbient.z ); } void setCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel, tuple c) { if (len(c) != 3) { PyErr_SetString(PyExc_ValueError, "sceneAmbientColor must be a triple"); throw_error_already_set(); } skel->sceneAmbientColor.x = extract<float>(c[0]); skel->sceneAmbientColor.y = extract<float>(c[1]); skel->sceneAmbientColor.z = extract<float>(c[2]); } list getKeyframes(const CalCoreMorphTrack* t) { list rv; const std::vector<CalCoreMorphKeyframe>& keyframes = t->keyframes; for ( std::vector<CalCoreMorphKeyframe>::const_iterator i = keyframes.begin(); i != keyframes.end(); ++i ) { rv.append(*i); } return rv; } list getTracks(const CalCoreAnimatedMorph* m) { list rv; const std::vector<CalCoreMorphTrack>& tracks = m->tracks; for ( std::vector<CalCoreMorphTrack>::const_iterator i = tracks.begin(); i != tracks.end(); ++i ) { rv.append(*i); } return rv; } namespace cal3d { struct PythonBuffer : public Buffer { public: PythonBuffer(PyObject* p) { _ = p; incref(get()); } ~PythonBuffer() { boost::python::PyGILState_AssertIsCurrent(); decref(get()); } size_t size() const { void* data; return get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data); } const void* data() const { void* data; get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data); return data; } boost::shared_ptr<Buffer> clone() const { return boost::shared_ptr<Buffer>(new PythonBuffer(get())); } private: PyObject* get() const { return static_cast<PyObject*>(_); } }; struct BufferFromPythonObject { BufferFromPythonObject() { converter::registry::push_back( &convertible, &construct, boost::python::type_id<Buffer>() ); } static void* convertible(PyObject* obj_ptr) { return (obj_ptr->ob_type->tp_as_buffer && obj_ptr->ob_type->tp_as_buffer->bf_getreadbuffer) ? obj_ptr : 0; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data ) { // Note that we're registered as a converter to the Buffer interface, // so Boost has already allocated sizeof(Buffer) for us. Since we're // constructing PythonStringBuffer into that memory, assert that // PythonStringBuffer and Buffer have the same size. BOOST_STATIC_ASSERT(sizeof(Buffer) == sizeof(PythonBuffer)); void* storage = ((boost::python::converter::rvalue_from_python_storage<PythonBuffer>*)data)->storage.bytes; new(storage) PythonBuffer(obj_ptr); data->convertible = storage; } }; } template<unsigned i> CalIndex getFaceIndex(const CalCoreSubmesh::Face& f) { return f.vertexId[i]; } struct PythonVertex { PythonVertex() {} PythonVertex(const CalCoreSubmesh::Vertex& v) { position.x = v.position.x; position.y = v.position.y; position.z = v.position.z; normal.x = v.normal.x; normal.y = v.normal.y; normal.z = v.normal.z; } CalVector position; CalVector normal; bool operator==(const PythonVertex& rhs) const { return position == rhs.position && normal == rhs.normal; } }; std::vector<PythonVertex> getVertices(const CalCoreSubmesh& submesh) { return std::vector<PythonVertex>( submesh.getVectorVertex().begin(), submesh.getVectorVertex().end()); } template<typename T> void exportVector(const char* name) { class_<std::vector<T> >(name) .def(vector_indexing_suite< std::vector<T>, true>()) ; } #ifndef NDEBUG BOOST_PYTHON_MODULE(_cal3d_debug) #else BOOST_PYTHON_MODULE(_cal3d) #endif { cal3d::BufferFromPythonObject(); class_<CalVector>("Vector") .def_readwrite("x", &CalVector::x) .def_readwrite("y", &CalVector::y) .def_readwrite("z", &CalVector::z) ; class_<CalQuaternion>("Quaternion") .def_readwrite("x", &CalQuaternion::x) .def_readwrite("y", &CalQuaternion::y) .def_readwrite("z", &CalQuaternion::z) .def_readwrite("w", &CalQuaternion::w) ; class_<cal3d::Transform>("Transform") .def_readwrite("translation", &cal3d::Transform::translation) .def_readwrite("rotation", &cal3d::Transform::rotation) ; class_<CalCoreBone, boost::shared_ptr<CalCoreBone> >("CoreBone", no_init) .def(init<std::string>()) .def_readwrite("parentIndex", &CalCoreBone::parentId) .def_readwrite("name", &CalCoreBone::name) .def_readwrite("relativeTransform", &CalCoreBone::relativeTransform) .def_readwrite("boneSpaceTransform", &CalCoreBone::boneSpaceTransform) ; exportVector<CalCoreBonePtr>("BoneVector"); class_<CalCoreSkeleton, boost::shared_ptr<CalCoreSkeleton> >("CoreSkeleton") .def("addCoreBone", &CalCoreSkeleton::addCoreBone) .add_property("sceneAmbientColor", &getCoreSkeletonSceneAmbientColor, &setCoreSkeletonSceneAmbientColor) .add_property("bones", &CalCoreSkeleton::coreBones) ; { scope CalCoreMaterial_class( class_<CalCoreMaterial, boost::shared_ptr<CalCoreMaterial> >("CoreMaterial") .def_readwrite("maps", &CalCoreMaterial::maps) ); exportVector<CalCoreMaterial::Map>("MapVector"); class_<CalCoreMaterial::Map>("Map") .def_readwrite("filename", &CalCoreMaterial::Map::filename) .def_readwrite("type", &CalCoreMaterial::Map::type) ; } class_<CalCoreSubmesh::Face>("Triangle") .add_property("v1", &getFaceIndex<0>) .add_property("v2", &getFaceIndex<1>) .add_property("v3", &getFaceIndex<2>) ; exportVector<CalCoreSubmesh::Face>("TriangleVector"); class_<PythonVertex>("Vertex") .def_readwrite("position", &PythonVertex::position) .def_readwrite("normal", &PythonVertex::normal) ; exportVector<PythonVertex>("VertexVector"); class_<CalCoreSubmesh::TextureCoordinate>("TextureCoordinate") .def_readwrite("u", &CalCoreSubmesh::TextureCoordinate::u) .def_readwrite("v", &CalCoreSubmesh::TextureCoordinate::v) ; exportVector<CalCoreSubmesh::TextureCoordinate>("TextureCoordinateVector"); exportVector<std::vector<CalCoreSubmesh::TextureCoordinate> >("TextureCoordinateVectorVector"); class_<CalCoreSubmesh::Influence>("Influence") .def_readwrite("boneId", &CalCoreSubmesh::Influence::boneId) .def_readwrite("weight", &CalCoreSubmesh::Influence::weight) .def_readwrite("isLast", &CalCoreSubmesh::Influence::lastInfluenceForThisVertex) ; exportVector<CalCoreSubmesh::Influence>("InfluenceVector"); class_<CalCoreSubmesh, boost::shared_ptr<CalCoreSubmesh>, boost::noncopyable>("CoreSubmesh", no_init) .def_readwrite("coreMaterialThreadId", &CalCoreSubmesh::coreMaterialThreadId) .def_readwrite("triangles", &CalCoreSubmesh::faces) .add_property("vertices", &getVertices) .add_property("hasVertexColors", &CalCoreSubmesh::hasVertexColors) .add_property("colors", make_function(&CalCoreSubmesh::getVertexColors, return_value_policy<return_by_value>())) .add_property("texcoords", make_function(&CalCoreSubmesh::getVectorVectorTextureCoordinate, return_value_policy<return_by_value>())) .add_property("influences", make_function(&CalCoreSubmesh::getInfluences, return_value_policy<return_by_value>())) ; class_< CalCoreMesh::CalCoreSubmeshVector >("CalCoreSubmeshVector") .def(vector_indexing_suite<CalCoreMesh::CalCoreSubmeshVector, true>()) ; class_<CalCoreMesh, boost::shared_ptr<CalCoreMesh> >("CoreMesh") .def_readwrite("submeshes", &CalCoreMesh::submeshes) ; class_<CalCoreAnimation, boost::shared_ptr<CalCoreAnimation> >("CoreAnimation") ; class_<CalCoreMorphKeyframe>("CoreMorphKeyframe") .add_property("time", &CalCoreMorphKeyframe::time) .add_property("weight", &CalCoreMorphKeyframe::weight) ; class_<CalCoreMorphTrack, boost::shared_ptr<CalCoreMorphTrack> >("CoreMorphTrack") .def_readonly("name", &CalCoreMorphTrack::morphName) .add_property("keyframes", &getKeyframes) ; class_<CalCoreAnimatedMorph, boost::shared_ptr<CalCoreAnimatedMorph> >("CoreAnimatedMorph") .def("removeZeroScaleTracks", &CalCoreAnimatedMorph::removeZeroScaleTracks) .def_readonly("duration", &CalCoreAnimatedMorph::duration) .add_property("tracks", &getTracks) ; def("loadCoreAnimationFromBuffer", &loadCoreAnimationFromBuffer); def("saveCoreAnimation", &saveCoreAnimation); def("saveCoreAnimationToBuffer", &CalSaver::saveCoreAnimationToBuffer); def("loadCoreSkeletonFromBuffer", &loadCoreSkeletonFromBuffer); def("saveCoreSkeleton", &saveCoreSkeleton); def("saveCoreSkeletonToBuffer", &CalSaver::saveCoreSkeletonToBuffer); def("loadCoreMaterialFromBuffer", &loadCoreMaterialFromBuffer); def("saveCoreMaterial", &saveCoreMaterial); def("saveCoreMaterialToBuffer", &CalSaver::saveCoreMaterialToBuffer); def("loadCoreMeshFromBuffer", &loadCoreMeshFromBuffer); def("saveCoreMesh", &saveCoreMesh); def("saveCoreMeshToBuffer", &CalSaver::saveCoreMeshToBuffer); def("loadCoreAnimatedMorphFromBuffer", &loadCoreAnimatedMorphFromBuffer); def("saveCoreAnimatedMorph", &saveCoreAnimatedMorph); def("saveCoreAnimatedMorphToBuffer", &CalSaver::saveCoreAnimatedMorphToBuffer); def("getLastErrorText", &CalError::getLastErrorText); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * @author <a href="mailto:[email protected]">David N. Bertoni</a> */ #if !defined(STYLESHEETCONSTRUCTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680) #define STYLESHEETCONSTRUCTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <XSLT/XSLTDefinitions.hpp> // Base class header file... #include <XSLT/StylesheetConstructionContext.hpp> #include <memory> #include <set> #include <vector> class XObjectFactory; class XPathEnvSupport; class XPathFactory; class XPathProcessor; class XSLTEngineImpl; /** * * An default implementation of an abtract class which provides support for * constructing the internal representation of a stylesheet. * */ class XALAN_XSLT_EXPORT StylesheetConstructionContextDefault : public StylesheetConstructionContext { public: StylesheetConstructionContextDefault( XSLTEngineImpl& processor, XPathEnvSupport& xpathEnvSupport, XObjectFactory& xobjectFactory, XPathFactory& xpathFactory); virtual ~StylesheetConstructionContextDefault(); // These interfaces are inherited from ExecutionContext... virtual void error( const XalanDOMString& msg, const XalanNode* sourceNode = 0, const XalanNode* styleNode = 0) const; virtual void warn( const XalanDOMString& msg, const XalanNode* sourceNode = 0, const XalanNode* styleNode = 0) const; virtual void message( const XalanDOMString& msg, const XalanNode* sourceNode = 0, const XalanNode* styleNode = 0) const; // These interfaces are inherited from StylesheetConstructionContext... virtual void reset(); virtual StylesheetRoot* create(const XalanDOMString& theBaseIdentifier); virtual StylesheetRoot* create(XSLTInputSource& theInputSource); virtual Stylesheet* create( StylesheetRoot& theStylesheetRoot, const XalanDOMString& theBaseIdentifier); virtual void destroy(StylesheetRoot* theStylesheetRoot); virtual int getAttrTok(const XalanDOMString& name) const; virtual URLAutoPtrType getURLFromString(const XalanDOMString& urlString); virtual URLAutoPtrType getURLFromString( const XalanDOMString& urlString, const XalanDOMString& base); virtual const XalanDOMString& getXSLTNamespaceURI() const; virtual XPath* createMatchPattern( const XalanDOMString& str, const PrefixResolver& resolver); virtual XPath* createXPath( const XalanDOMString& str, const PrefixResolver& resolver); virtual const Locator* getLocatorFromStack() const; virtual void pushLocatorOnStack(const Locator* locator); virtual void popLocatorStack(); virtual const XalanDOMString& getXalanXSLNameSpaceURL() const; virtual XalanDocument* parseXML( const XMLURL& url, DocumentHandler* docHandler, XalanDocument* docToRegister); virtual int getElementToken(const XalanDOMString& name) const; virtual double getXSLTVersionSupported() const; private: XSLTEngineImpl& m_processor; XPathEnvSupport& m_xpathEnvSupport; XObjectFactory& m_xobjectFactory; XPathFactory& m_xpathFactory; #if defined(XALAN_NO_NAMESPACES) auto_ptr<XPathProcessor> m_xpathProcessor; typedef set<StylesheetRoot*> StylesheetSetType; #else std::auto_ptr<XPathProcessor> m_xpathProcessor; typedef std::set<StylesheetRoot*> StylesheetSetType; #endif StylesheetSetType m_stylesheets; }; #endif // STYLESHEETCONSTRUCTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680 <commit_msg>Added constructor comments.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * @author <a href="mailto:[email protected]">David N. Bertoni</a> */ #if !defined(STYLESHEETCONSTRUCTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680) #define STYLESHEETCONSTRUCTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <XSLT/XSLTDefinitions.hpp> // Base class header file... #include <XSLT/StylesheetConstructionContext.hpp> #include <memory> #include <set> #include <vector> class XObjectFactory; class XPathEnvSupport; class XPathFactory; class XPathProcessor; class XSLTEngineImpl; /** * * An default implementation of an abtract class which provides support for * constructing the internal representation of a stylesheet. * */ class XALAN_XSLT_EXPORT StylesheetConstructionContextDefault : public StylesheetConstructionContext { public: /* * Construct an instance. If the stylesheet(s) constructed is/are meant to be reused (a.k.a. "compiled"), * the XObjectFactory and XPathFactory instance must exist for the lifetime of the construction context * and, therefore, for the lifetime of the stylesheet(s). Otherwise, XObject and XPath instance will be * destroyed when the corresponding factories are destryed, leaving pointers to destroyed objects in the. * stylesheet(s). * * @param processor a reference to an XSLTEngineImpl instance. Used for error reporting. * @param xpathEnvSupport a reference to an XPathEnvSupport instance. * @param xobjectFactory a reference to an XObjectFactory instance. See comments above for important details. * @param xpathFactory a reference to an XPathFactory instance. See comments above for important details. * */ StylesheetConstructionContextDefault( XSLTEngineImpl& processor, XPathEnvSupport& xpathEnvSupport, XObjectFactory& xobjectFactory, XPathFactory& xpathFactory); virtual ~StylesheetConstructionContextDefault(); // These interfaces are inherited from ExecutionContext... virtual void error( const XalanDOMString& msg, const XalanNode* sourceNode = 0, const XalanNode* styleNode = 0) const; virtual void warn( const XalanDOMString& msg, const XalanNode* sourceNode = 0, const XalanNode* styleNode = 0) const; virtual void message( const XalanDOMString& msg, const XalanNode* sourceNode = 0, const XalanNode* styleNode = 0) const; // These interfaces are inherited from StylesheetConstructionContext... virtual void reset(); virtual StylesheetRoot* create(const XalanDOMString& theBaseIdentifier); virtual StylesheetRoot* create(XSLTInputSource& theInputSource); virtual Stylesheet* create( StylesheetRoot& theStylesheetRoot, const XalanDOMString& theBaseIdentifier); virtual void destroy(StylesheetRoot* theStylesheetRoot); virtual int getAttrTok(const XalanDOMString& name) const; virtual URLAutoPtrType getURLFromString(const XalanDOMString& urlString); virtual URLAutoPtrType getURLFromString( const XalanDOMString& urlString, const XalanDOMString& base); virtual const XalanDOMString& getXSLTNamespaceURI() const; virtual XPath* createMatchPattern( const XalanDOMString& str, const PrefixResolver& resolver); virtual XPath* createXPath( const XalanDOMString& str, const PrefixResolver& resolver); virtual const Locator* getLocatorFromStack() const; virtual void pushLocatorOnStack(const Locator* locator); virtual void popLocatorStack(); virtual const XalanDOMString& getXalanXSLNameSpaceURL() const; virtual XalanDocument* parseXML( const XMLURL& url, DocumentHandler* docHandler, XalanDocument* docToRegister); virtual int getElementToken(const XalanDOMString& name) const; virtual double getXSLTVersionSupported() const; private: XSLTEngineImpl& m_processor; XPathEnvSupport& m_xpathEnvSupport; XObjectFactory& m_xobjectFactory; XPathFactory& m_xpathFactory; #if defined(XALAN_NO_NAMESPACES) auto_ptr<XPathProcessor> m_xpathProcessor; typedef set<StylesheetRoot*> StylesheetSetType; #else std::auto_ptr<XPathProcessor> m_xpathProcessor; typedef std::set<StylesheetRoot*> StylesheetSetType; #endif StylesheetSetType m_stylesheets; }; #endif // STYLESHEETCONSTRUCTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>/*************************************************************************/ /* navigation_obstacle_2d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "navigation_obstacle_2d.h" #include "scene/2d/collision_shape_2d.h" #include "scene/2d/navigation_2d.h" #include "scene/2d/physics_body_2d.h" #include "servers/navigation_2d_server.h" void NavigationObstacle2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_navigation", "navigation"), &NavigationObstacle2D::set_navigation_node); ClassDB::bind_method(D_METHOD("get_navigation"), &NavigationObstacle2D::get_navigation_node); ClassDB::bind_method(D_METHOD("set_estimate_radius", "estimate_radius"), &NavigationObstacle2D::set_estimate_radius); ClassDB::bind_method(D_METHOD("is_radius_estimated"), &NavigationObstacle2D::is_radius_estimated); ClassDB::bind_method(D_METHOD("set_radius", "radius"), &NavigationObstacle2D::set_radius); ClassDB::bind_method(D_METHOD("get_radius"), &NavigationObstacle2D::get_radius); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "estimate_radius"), "set_estimate_radius", "is_radius_estimated"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0.01,500,0.01"), "set_radius", "get_radius"); } void NavigationObstacle2D::_validate_property(PropertyInfo &p_property) const { if (p_property.name == "radius") { if (estimate_radius) { p_property.usage = PROPERTY_USAGE_NOEDITOR; } } } void NavigationObstacle2D::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { parent_node2d = Object::cast_to<Node2D>(get_parent()); reevaluate_agent_radius(); // Search the navigation node and set it { Navigation2D *nav = nullptr; Node *p = get_parent(); while (p != nullptr) { nav = Object::cast_to<Navigation2D>(p); if (nav != nullptr) { p = nullptr; } else { p = p->get_parent(); } } set_navigation(nav); } set_physics_process_internal(true); } break; case NOTIFICATION_EXIT_TREE: { set_navigation(nullptr); set_physics_process_internal(false); request_ready(); // required to solve an issue with losing the navigation } break; case NOTIFICATION_PARENTED: { parent_node2d = Object::cast_to<Node2D>(get_parent()); reevaluate_agent_radius(); } break; case NOTIFICATION_UNPARENTED: { parent_node2d = nullptr; } break; case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: { if (parent_node2d) { Navigation2DServer::get_singleton()->agent_set_position(agent, parent_node2d->get_global_transform().get_origin()); } } break; } } NavigationObstacle2D::NavigationObstacle2D() : navigation(nullptr), agent(RID()) { agent = Navigation2DServer::get_singleton()->agent_create(); initialize_agent(); } NavigationObstacle2D::~NavigationObstacle2D() { Navigation2DServer::get_singleton()->free(agent); agent = RID(); // Pointless } void NavigationObstacle2D::set_navigation(Navigation2D *p_nav) { if (navigation == p_nav) { return; // Pointless } navigation = p_nav; Navigation2DServer::get_singleton()->agent_set_map(agent, navigation == nullptr ? RID() : navigation->get_rid()); } void NavigationObstacle2D::set_navigation_node(Node *p_nav) { Navigation2D *nav = Object::cast_to<Navigation2D>(p_nav); ERR_FAIL_COND(nav == nullptr); set_navigation(nav); } Node *NavigationObstacle2D::get_navigation_node() const { return Object::cast_to<Node>(navigation); } String NavigationObstacle2D::get_configuration_warning() const { if (!Object::cast_to<Node2D>(get_parent())) { return TTR("The NavigationObstacle2D only serves to provide collision avoidance to a Node2D object."); } return String(); } void NavigationObstacle2D::initialize_agent() { Navigation2DServer::get_singleton()->agent_set_neighbor_dist(agent, 0.0); Navigation2DServer::get_singleton()->agent_set_max_neighbors(agent, 0); Navigation2DServer::get_singleton()->agent_set_time_horizon(agent, 0.0); Navigation2DServer::get_singleton()->agent_set_max_speed(agent, 0.0); } void NavigationObstacle2D::reevaluate_agent_radius() { if (!estimate_agent_radius()) { Navigation2DServer::get_singleton()->agent_set_radius(agent, radius); } else if (parent_node2d && parent_node2d->is_inside_tree()) { Navigation2DServer::get_singleton()->agent_set_radius(agent, estimate_agent_radius()); } } real_t NavigationObstacle2D::estimate_agent_radius() const { if (parent_node2d) { // Estimate the radius of this physics body real_t radius = 0.0; for (int i(0); i < parent_node2d->get_child_count(); i++) { // For each collision shape CollisionShape2D *cs = Object::cast_to<CollisionShape2D>(parent_node2d->get_child(i)); if (cs) { // Take the distance between the Body center to the shape center real_t r = cs->get_transform().get_origin().length(); if (cs->get_shape().is_valid()) { // and add the enclosing shape radius r += cs->get_shape()->get_enclosing_radius(); } Size2 s = cs->get_global_transform().get_scale(); r *= MAX(s.x, s.y); // Takes the biggest radius radius = MAX(radius, r); } } Vector2 s = parent_node2d->get_global_transform().get_scale(); radius *= MAX(s.x, s.y); if (radius > 0.0) { return radius; } } return 1.0; // Never a 0 radius } void NavigationObstacle2D::set_estimate_radius(bool p_estimate_radius) { estimate_radius = p_estimate_radius; _change_notify(); reevaluate_agent_radius(); } void NavigationObstacle2D::set_radius(real_t p_radius) { ERR_FAIL_COND_MSG(p_radius <= 0.0, "Radius must be greater than 0."); radius = p_radius; reevaluate_agent_radius(); } <commit_msg>NavigationObstacle2D: estimate agent radius only when configured to do so<commit_after>/*************************************************************************/ /* navigation_obstacle_2d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "navigation_obstacle_2d.h" #include "scene/2d/collision_shape_2d.h" #include "scene/2d/navigation_2d.h" #include "scene/2d/physics_body_2d.h" #include "servers/navigation_2d_server.h" void NavigationObstacle2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_navigation", "navigation"), &NavigationObstacle2D::set_navigation_node); ClassDB::bind_method(D_METHOD("get_navigation"), &NavigationObstacle2D::get_navigation_node); ClassDB::bind_method(D_METHOD("set_estimate_radius", "estimate_radius"), &NavigationObstacle2D::set_estimate_radius); ClassDB::bind_method(D_METHOD("is_radius_estimated"), &NavigationObstacle2D::is_radius_estimated); ClassDB::bind_method(D_METHOD("set_radius", "radius"), &NavigationObstacle2D::set_radius); ClassDB::bind_method(D_METHOD("get_radius"), &NavigationObstacle2D::get_radius); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "estimate_radius"), "set_estimate_radius", "is_radius_estimated"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0.01,500,0.01"), "set_radius", "get_radius"); } void NavigationObstacle2D::_validate_property(PropertyInfo &p_property) const { if (p_property.name == "radius") { if (estimate_radius) { p_property.usage = PROPERTY_USAGE_NOEDITOR; } } } void NavigationObstacle2D::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { parent_node2d = Object::cast_to<Node2D>(get_parent()); reevaluate_agent_radius(); // Search the navigation node and set it { Navigation2D *nav = nullptr; Node *p = get_parent(); while (p != nullptr) { nav = Object::cast_to<Navigation2D>(p); if (nav != nullptr) { p = nullptr; } else { p = p->get_parent(); } } set_navigation(nav); } set_physics_process_internal(true); } break; case NOTIFICATION_EXIT_TREE: { set_navigation(nullptr); set_physics_process_internal(false); request_ready(); // required to solve an issue with losing the navigation } break; case NOTIFICATION_PARENTED: { parent_node2d = Object::cast_to<Node2D>(get_parent()); reevaluate_agent_radius(); } break; case NOTIFICATION_UNPARENTED: { parent_node2d = nullptr; } break; case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: { if (parent_node2d) { Navigation2DServer::get_singleton()->agent_set_position(agent, parent_node2d->get_global_transform().get_origin()); } } break; } } NavigationObstacle2D::NavigationObstacle2D() : navigation(nullptr), agent(RID()) { agent = Navigation2DServer::get_singleton()->agent_create(); initialize_agent(); } NavigationObstacle2D::~NavigationObstacle2D() { Navigation2DServer::get_singleton()->free(agent); agent = RID(); // Pointless } void NavigationObstacle2D::set_navigation(Navigation2D *p_nav) { if (navigation == p_nav) { return; // Pointless } navigation = p_nav; Navigation2DServer::get_singleton()->agent_set_map(agent, navigation == nullptr ? RID() : navigation->get_rid()); } void NavigationObstacle2D::set_navigation_node(Node *p_nav) { Navigation2D *nav = Object::cast_to<Navigation2D>(p_nav); ERR_FAIL_COND(nav == nullptr); set_navigation(nav); } Node *NavigationObstacle2D::get_navigation_node() const { return Object::cast_to<Node>(navigation); } String NavigationObstacle2D::get_configuration_warning() const { if (!Object::cast_to<Node2D>(get_parent())) { return TTR("The NavigationObstacle2D only serves to provide collision avoidance to a Node2D object."); } return String(); } void NavigationObstacle2D::initialize_agent() { Navigation2DServer::get_singleton()->agent_set_neighbor_dist(agent, 0.0); Navigation2DServer::get_singleton()->agent_set_max_neighbors(agent, 0); Navigation2DServer::get_singleton()->agent_set_time_horizon(agent, 0.0); Navigation2DServer::get_singleton()->agent_set_max_speed(agent, 0.0); } void NavigationObstacle2D::reevaluate_agent_radius() { if (!estimate_radius) { Navigation2DServer::get_singleton()->agent_set_radius(agent, radius); } else if (parent_node2d && parent_node2d->is_inside_tree()) { Navigation2DServer::get_singleton()->agent_set_radius(agent, estimate_agent_radius()); } } real_t NavigationObstacle2D::estimate_agent_radius() const { if (parent_node2d) { // Estimate the radius of this physics body real_t radius = 0.0; for (int i(0); i < parent_node2d->get_child_count(); i++) { // For each collision shape CollisionShape2D *cs = Object::cast_to<CollisionShape2D>(parent_node2d->get_child(i)); if (cs) { // Take the distance between the Body center to the shape center real_t r = cs->get_transform().get_origin().length(); if (cs->get_shape().is_valid()) { // and add the enclosing shape radius r += cs->get_shape()->get_enclosing_radius(); } Size2 s = cs->get_global_transform().get_scale(); r *= MAX(s.x, s.y); // Takes the biggest radius radius = MAX(radius, r); } } Vector2 s = parent_node2d->get_global_transform().get_scale(); radius *= MAX(s.x, s.y); if (radius > 0.0) { return radius; } } return 1.0; // Never a 0 radius } void NavigationObstacle2D::set_estimate_radius(bool p_estimate_radius) { estimate_radius = p_estimate_radius; _change_notify(); reevaluate_agent_radius(); } void NavigationObstacle2D::set_radius(real_t p_radius) { ERR_FAIL_COND_MSG(p_radius <= 0.0, "Radius must be greater than 0."); radius = p_radius; reevaluate_agent_radius(); } <|endoftext|>
<commit_before>#include "../app/ShaderApp.cpp" class Swirl : public ShaderApp { protected: void mainImage(Color& color, int x, int y) { float angle = atan2(x - 8.0, y - 8.0); float radius = sqrt(pow(x - 8, 2) + pow(y - 8, 2)); float stretch = 2.0 + sin(time * 0.0001); radius += angle * stretch; color.hsv( int(time * 0.02 + radius * 0.5) % 255, 255, char(255.0 * (0.5 + 0.5 * sin(2.0 * radius / stretch - time * 0.006)))); } };<commit_msg>Update Swirl example<commit_after>#include "../app/ShaderApp.cpp" class Swirl : public ShaderApp { protected: void mainImage(Color& color, int x, int y) { float angle = atan2(x - 8.0, y - 8.0); float radius = sqrt(pow(x - 8, 2) + pow(y - 8, 2)); float stretch = 2.0 + sin(time * 0.0001); color.hsv( int(time * 0.02 - radius * 3.0) % 255, 255, char(255.0 * (0.5 + 0.5 * sin(2.0 * (radius + angle * stretch) / stretch - time * 0.006)))); } };<|endoftext|>
<commit_before>// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) 2006-2015, ARM Limited, All Rights Reserved // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include <ssl.h> #include "mbedtls.h" #include "mbedtls/debug.h" bool ssl_generic_init_internal( int sslMode, int sslVerify, const char *certificate, int certLength, const uint8_t *privateKey, int privateKeyLength, const char *password, int passwordLength, int &contextHandle, bool useDeviceCertificate, bool isServer) { (void)sslMode; int minVersion = MBEDTLS_SSL_MINOR_VERSION_3; int maxVersion = MBEDTLS_SSL_MINOR_VERSION_1; int sslContexIndex = -1; int authMode = MBEDTLS_SSL_VERIFY_NONE; int endpoint = 0; int ret = 0; mbedtls_x509_crt *ownCertificate = NULL; // we only have one CA root bundle, so this is fixed to 0 uint32_t configIndex = 0; /////////////////////// mbedTLS_NFContext *context; for (uint32_t i = 0; i < ARRAYSIZE(g_SSL_Driver.ContextArray); i++) { if (g_SSL_Driver.ContextArray[i].Context == NULL) { sslContexIndex = i; break; } } if (sslContexIndex == -1) return FALSE; // create and init mbedTLS nanoFramework context // this needs to be freed in ssl_exit_context_internal context = (mbedTLS_NFContext *)platform_malloc(sizeof(mbedTLS_NFContext)); if (context == NULL) { goto error; } // allocate memory for net context context->server_fd = (mbedtls_net_context *)platform_malloc(sizeof(mbedtls_net_context)); if (context->server_fd == NULL) { goto error; } if (isServer) { endpoint = MBEDTLS_SSL_IS_SERVER; } else { endpoint = MBEDTLS_SSL_IS_CLIENT; } // create and init CTR_DRBG // this needs to be freed in ssl_exit_context_internal context->ctr_drbg = (mbedtls_ctr_drbg_context *)platform_malloc(sizeof(mbedtls_ctr_drbg_context)); if (context->ctr_drbg == NULL) { goto error; } mbedtls_ctr_drbg_init(context->ctr_drbg); // create and init SSL context // this needs to be freed in ssl_exit_context_internal context->ssl = (mbedtls_ssl_context *)platform_malloc(sizeof(mbedtls_ssl_context)); if (context->ssl == NULL) { goto error; } mbedtls_ssl_init(context->ssl); // create and init SSL configuration // this needs to be freed in ssl_exit_context_internal context->conf = (mbedtls_ssl_config *)platform_malloc(sizeof(mbedtls_ssl_config)); if (context->conf == NULL) { goto error; } mbedtls_ssl_config_init(context->conf); // create and init X509 CRT // this needs to be freed in ssl_exit_context_internal context->x509_crt = (mbedtls_x509_crt *)platform_malloc(sizeof(mbedtls_x509_crt)); if (context->x509_crt == NULL) { goto error; } mbedtls_x509_crt_init(context->x509_crt); // create and init entropy context // this needs to be freed in ssl_exit_context_internal context->entropy = (mbedtls_entropy_context *)platform_malloc(sizeof(mbedtls_entropy_context)); if (context->entropy == NULL) { goto error; } mbedtls_entropy_init(context->entropy); // TODO: review if we can add some instance-unique data to the custom argument below if (mbedtls_ctr_drbg_seed(context->ctr_drbg, mbedtls_entropy_func, context->entropy, NULL, 0) != 0) { // ctr_drbg_seed_failed goto error; } if (mbedtls_ssl_config_defaults( context->conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { // ssl_config_defaults_failed goto error; } // figure out the min and max protocol version to support // sanity check for none, application has to set the supported protocols if ((SslProtocols)sslMode == SslProtocols_None) { goto error; } // find minimum version if (sslMode & (SslProtocols_TLSv11 | SslProtocols_TLSv1)) { minVersion = MBEDTLS_SSL_MINOR_VERSION_2; } if (sslMode & SslProtocols_TLSv1) { minVersion = MBEDTLS_SSL_MINOR_VERSION_1; } mbedtls_ssl_conf_min_version(context->conf, MBEDTLS_SSL_MAJOR_VERSION_3, minVersion); // find maximum version if (sslMode & (SslProtocols_TLSv12 | SslProtocols_TLSv11)) { maxVersion = MBEDTLS_SSL_MINOR_VERSION_2; } if (sslMode & SslProtocols_TLSv12) { maxVersion = MBEDTLS_SSL_MINOR_VERSION_3; } mbedtls_ssl_conf_max_version(context->conf, MBEDTLS_SSL_MAJOR_VERSION_3, maxVersion); // configure random generator mbedtls_ssl_conf_rng(context->conf, mbedtls_ctr_drbg_random, context->ctr_drbg); // CA root certs from store, if available if (g_TargetConfiguration.CertificateStore->Count > 0) { ///////////////////////////////////////////////////////////////////////////////////////////////// // developer notes: // // don't care about failure in processing the CA cert bundle // // the outcome is that the CA certs won't be loaded into the trusted CA chain // // this call parses certificates in both string and binary formats // // when the formart is a string it has to include the terminator otherwise the parse will fail // ///////////////////////////////////////////////////////////////////////////////////////////////// mbedtls_x509_crt_parse( context->x509_crt, (const unsigned char *)g_TargetConfiguration.CertificateStore->Certificates[configIndex]->Certificate, g_TargetConfiguration.CertificateStore->Certificates[configIndex]->CertificateSize); } // check if the device certificate is to be used if (useDeviceCertificate) { // check if there is a device certificate stored if (g_TargetConfiguration.DeviceCertificates->Count > 0) { // there is! // fill in the parameters like if it was supplied by the caller // OK to override, that's the intended behaviour certificate = (const char *)g_TargetConfiguration.DeviceCertificates->Certificates[0]->Certificate; certLength = g_TargetConfiguration.DeviceCertificates->Certificates[0]->CertificateSize; // clear private keys, just in case privateKey = NULL; privateKeyLength = 0; } } // parse "own" certificate if passed if (certificate != NULL && certLength > 0) { // create and init private key context // this needs to be freed in ssl_exit_context_internal context->pk = (mbedtls_pk_context *)platform_malloc(sizeof(mbedtls_pk_context)); if (context->pk == NULL) { goto error; } mbedtls_pk_init(context->pk); // is there a private key? if (privateKey != NULL && privateKeyLength > 0) { if (mbedtls_pk_parse_key( context->pk, privateKey, privateKeyLength, (const unsigned char *)password, passwordLength) < 0) { // private key parse failed goto error; } } // parse certificate ownCertificate = (mbedtls_x509_crt *)platform_malloc(sizeof(mbedtls_x509_crt)); if (ownCertificate == NULL) { goto error; } mbedtls_x509_crt_init(ownCertificate); if (mbedtls_x509_crt_parse(ownCertificate, (const unsigned char *)certificate, certLength)) { // failed parsing own certificate failed goto error; } if (mbedtls_ssl_conf_own_cert(context->conf, ownCertificate, context->pk)) { // configuring own certificate failed goto error; } } else { // no PK, need to set it to NULL context->pk = NULL; } mbedtls_ssl_conf_ca_chain(context->conf, context->x509_crt, NULL); // set certificate verification // the current options provided by mbed TLS are only verify or don't verify if ((SslVerification)sslVerify == SslVerification_CertificateRequired) { authMode = MBEDTLS_SSL_VERIFY_REQUIRED; } mbedtls_ssl_conf_authmode(context->conf, authMode); // setup debug stuff // only required if output debug is enabled in mbedtls_config.h #ifdef MBEDTLS_DEBUG_C mbedtls_debug_set_threshold(MBEDTLS_DEBUG_THRESHOLD); mbedtls_ssl_conf_dbg(context->conf, nf_debug, stdout); #endif ret = mbedtls_ssl_setup(context->ssl, context->conf); if (ret != 0) { // ssl_setup_failed goto error; } ////////////////////////////////////// g_SSL_Driver.ContextArray[sslContexIndex].Context = context; g_SSL_Driver.ContextCount++; contextHandle = sslContexIndex; return true; error: mbedtls_pk_free(context->pk); mbedtls_net_free(context->server_fd); mbedtls_ctr_drbg_free(context->ctr_drbg); mbedtls_entropy_free(context->entropy); mbedtls_x509_crt_free(context->x509_crt); mbedtls_ssl_config_free(context->conf); mbedtls_ssl_free(context->ssl); // check for any memory allocation that needs to be freed before exiting if (context->ssl != NULL) platform_free(context->ssl); if (context->conf != NULL) platform_free(context->conf); if (context->entropy != NULL) platform_free(context->entropy); if (context->ctr_drbg != NULL) platform_free(context->ctr_drbg); if (context->server_fd != NULL) platform_free(context->server_fd); if (context->x509_crt != NULL) platform_free(context->x509_crt); if (context->pk != NULL) platform_free(context->pk); if (ownCertificate != NULL) { mbedtls_x509_crt_free(ownCertificate); platform_free(ownCertificate); } if (context->pk != NULL) { platform_free(context); } return false; } <commit_msg>Rework TLS to use new config manager API (#2093)<commit_after>// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) 2006-2015, ARM Limited, All Rights Reserved // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include <ssl.h> #include "mbedtls.h" #include "mbedtls/debug.h" bool ssl_generic_init_internal( int sslMode, int sslVerify, const char *certificate, int certLength, const uint8_t *privateKey, int privateKeyLength, const char *password, int passwordLength, int &contextHandle, bool useDeviceCertificate, bool isServer) { (void)sslMode; int minVersion = MBEDTLS_SSL_MINOR_VERSION_3; int maxVersion = MBEDTLS_SSL_MINOR_VERSION_1; int sslContexIndex = -1; int authMode = MBEDTLS_SSL_VERIFY_NONE; int endpoint = 0; int ret = 0; mbedtls_x509_crt *ownCertificate = NULL; HAL_Configuration_X509CaRootBundle *certStore = NULL; HAL_Configuration_X509DeviceCertificate *deviceCert = NULL; /////////////////////// mbedTLS_NFContext *context; for (uint32_t i = 0; i < ARRAYSIZE(g_SSL_Driver.ContextArray); i++) { if (g_SSL_Driver.ContextArray[i].Context == NULL) { sslContexIndex = i; break; } } if (sslContexIndex == -1) return FALSE; // create and init mbedTLS nanoFramework context // this needs to be freed in ssl_exit_context_internal context = (mbedTLS_NFContext *)platform_malloc(sizeof(mbedTLS_NFContext)); if (context == NULL) { goto error; } // allocate memory for net context context->server_fd = (mbedtls_net_context *)platform_malloc(sizeof(mbedtls_net_context)); if (context->server_fd == NULL) { goto error; } if (isServer) { endpoint = MBEDTLS_SSL_IS_SERVER; } else { endpoint = MBEDTLS_SSL_IS_CLIENT; } // create and init CTR_DRBG // this needs to be freed in ssl_exit_context_internal context->ctr_drbg = (mbedtls_ctr_drbg_context *)platform_malloc(sizeof(mbedtls_ctr_drbg_context)); if (context->ctr_drbg == NULL) { goto error; } mbedtls_ctr_drbg_init(context->ctr_drbg); // create and init SSL context // this needs to be freed in ssl_exit_context_internal context->ssl = (mbedtls_ssl_context *)platform_malloc(sizeof(mbedtls_ssl_context)); if (context->ssl == NULL) { goto error; } mbedtls_ssl_init(context->ssl); // create and init SSL configuration // this needs to be freed in ssl_exit_context_internal context->conf = (mbedtls_ssl_config *)platform_malloc(sizeof(mbedtls_ssl_config)); if (context->conf == NULL) { goto error; } mbedtls_ssl_config_init(context->conf); // create and init X509 CRT // this needs to be freed in ssl_exit_context_internal context->x509_crt = (mbedtls_x509_crt *)platform_malloc(sizeof(mbedtls_x509_crt)); if (context->x509_crt == NULL) { goto error; } mbedtls_x509_crt_init(context->x509_crt); // create and init entropy context // this needs to be freed in ssl_exit_context_internal context->entropy = (mbedtls_entropy_context *)platform_malloc(sizeof(mbedtls_entropy_context)); if (context->entropy == NULL) { goto error; } mbedtls_entropy_init(context->entropy); // TODO: review if we can add some instance-unique data to the custom argument below if (mbedtls_ctr_drbg_seed(context->ctr_drbg, mbedtls_entropy_func, context->entropy, NULL, 0) != 0) { // ctr_drbg_seed_failed goto error; } if (mbedtls_ssl_config_defaults( context->conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { // ssl_config_defaults_failed goto error; } // figure out the min and max protocol version to support // sanity check for none, application has to set the supported protocols if ((SslProtocols)sslMode == SslProtocols_None) { goto error; } // find minimum version if (sslMode & (SslProtocols_TLSv11 | SslProtocols_TLSv1)) { minVersion = MBEDTLS_SSL_MINOR_VERSION_2; } if (sslMode & SslProtocols_TLSv1) { minVersion = MBEDTLS_SSL_MINOR_VERSION_1; } mbedtls_ssl_conf_min_version(context->conf, MBEDTLS_SSL_MAJOR_VERSION_3, minVersion); // find maximum version if (sslMode & (SslProtocols_TLSv12 | SslProtocols_TLSv11)) { maxVersion = MBEDTLS_SSL_MINOR_VERSION_2; } if (sslMode & SslProtocols_TLSv12) { maxVersion = MBEDTLS_SSL_MINOR_VERSION_3; } mbedtls_ssl_conf_max_version(context->conf, MBEDTLS_SSL_MAJOR_VERSION_3, maxVersion); // configure random generator mbedtls_ssl_conf_rng(context->conf, mbedtls_ctr_drbg_random, context->ctr_drbg); // CA root certs from store, if available if (g_TargetConfiguration.CertificateStore->Count > 0) { // get certificate store certStore = ConfigurationManager_GetCertificateStore(); if (certStore) { ///////////////////////////////////////////////////////////////////////////////////////////////// // developer notes: // // don't care about failure in processing the CA cert bundle // // the outcome is that the CA certs won't be loaded into the trusted CA chain // // this call parses certificates in both string and binary formats // // when the format is a string it has to include the terminator otherwise the parse will fail // ///////////////////////////////////////////////////////////////////////////////////////////////// mbedtls_x509_crt_parse( context->x509_crt, (const unsigned char *)certStore->Certificate, certStore->CertificateSize); platform_free(certStore); } } // check if the device certificate is to be used if (useDeviceCertificate) { deviceCert = ConfigurationManager_GetDeviceCertificate(); // check if there is a device certificate stored if (deviceCert) { // there is! // fill in the parameters like if it was supplied by the caller // OK to override, that's the intended behaviour certificate = (const char *)deviceCert->Certificate; certLength = deviceCert->CertificateSize; // clear private keys, just in case privateKey = NULL; privateKeyLength = 0; } } // parse "own" certificate if passed if (certificate != NULL && certLength > 0) { // create and init private key context // this needs to be freed in ssl_exit_context_internal context->pk = (mbedtls_pk_context *)platform_malloc(sizeof(mbedtls_pk_context)); if (context->pk == NULL) { goto error; } mbedtls_pk_init(context->pk); // is there a private key? if (privateKey != NULL && privateKeyLength > 0) { if (mbedtls_pk_parse_key( context->pk, privateKey, privateKeyLength, (const unsigned char *)password, passwordLength) < 0) { // private key parse failed goto error; } } // parse certificate ownCertificate = (mbedtls_x509_crt *)platform_malloc(sizeof(mbedtls_x509_crt)); if (ownCertificate == NULL) { goto error; } mbedtls_x509_crt_init(ownCertificate); if (mbedtls_x509_crt_parse(ownCertificate, (const unsigned char *)certificate, certLength)) { // failed parsing own certificate failed goto error; } if (mbedtls_ssl_conf_own_cert(context->conf, ownCertificate, context->pk)) { // configuring own certificate failed goto error; } // free memory, if allocated if (deviceCert) { platform_free(deviceCert); } } else { // no PK, need to set it to NULL context->pk = NULL; } mbedtls_ssl_conf_ca_chain(context->conf, context->x509_crt, NULL); // set certificate verification // the current options provided by mbed TLS are only verify or don't verify if ((SslVerification)sslVerify == SslVerification_CertificateRequired) { authMode = MBEDTLS_SSL_VERIFY_REQUIRED; } mbedtls_ssl_conf_authmode(context->conf, authMode); // setup debug stuff // only required if output debug is enabled in mbedtls_config.h #ifdef MBEDTLS_DEBUG_C mbedtls_debug_set_threshold(MBEDTLS_DEBUG_THRESHOLD); mbedtls_ssl_conf_dbg(context->conf, nf_debug, stdout); #endif ret = mbedtls_ssl_setup(context->ssl, context->conf); if (ret != 0) { // ssl_setup_failed goto error; } ////////////////////////////////////// g_SSL_Driver.ContextArray[sslContexIndex].Context = context; g_SSL_Driver.ContextCount++; contextHandle = sslContexIndex; return true; error: mbedtls_pk_free(context->pk); mbedtls_net_free(context->server_fd); mbedtls_ctr_drbg_free(context->ctr_drbg); mbedtls_entropy_free(context->entropy); mbedtls_x509_crt_free(context->x509_crt); mbedtls_ssl_config_free(context->conf); mbedtls_ssl_free(context->ssl); // check for any memory allocation that needs to be freed before exiting if (context->ssl) { platform_free(context->ssl); } if (context->conf) { platform_free(context->conf); } if (context->entropy) { platform_free(context->entropy); } if (context->ctr_drbg) { platform_free(context->ctr_drbg); } if (context->server_fd) { platform_free(context->server_fd); } if (context->x509_crt) { platform_free(context->x509_crt); } if (context->pk) { platform_free(context->pk); } if (ownCertificate) { mbedtls_x509_crt_free(ownCertificate); platform_free(ownCertificate); } if (context->pk) { platform_free(context); } if (certStore) { platform_free(certStore); } if (deviceCert) { platform_free(deviceCert); } return false; } <|endoftext|>
<commit_before>#include "ProfileStore.hpp" namespace BitProfile{ ProfileStore::ProfileStore() : _path(getDefaultPath(Main_Net)) { createIfNotExists(); } ProfileStore::ProfileStore(const char *path) : _path(fs::absolute(path)) { createIfNotExists(); } ProfileStore::ProfileStore(Network net) : _path(getDefaultPath(net)) { createIfNotExists(); } ProfileStore::ProfileStore(const fs::path &path) : _path(path) { createIfNotExists(); } fs::path ProfileStore::getDefaultPath(Network net) const { fs::path path; #if defined(__APPLE_OS__) path = getenv("HOME"); path /= "Library/BitProfile"; #elif defined(__LINUX_OS__) path = getenv("HOME"); path /= ".bitprofile"; #elif defined(__WINDOWS_OS__) char appdata[1024] = ""; if (SHGetSpecialFolderPathA(NULL, appdata, CSIDL_APPDATA, true)) { path = appdata; } else { path = getenv("HOMEPATH"); } path /= "BitProfile"; #endif if(net==Test_Net) { path /= "testnet"; } path /= "profiles"; return path; } void ProfileStore::createIfNotExists() { boost::filesystem::create_directories(_path); } ProfileStore::Iterator ProfileStore::begin() const { return Iterator(fs::directory_iterator(_path)); } ProfileStore::Iterator ProfileStore::end() const { return Iterator(fs::directory_iterator()); } ProfileStore::Iterator ProfileStore::find(const std::string &uri) const { std::string filename = makeFileName(uri); Iterator it = begin(); for(; it!= end(); ++it) { if(it.path().filename()==filename) { break; } } return it; } ProfileStore::Iterator ProfileStore::find(const Profile::URI &uri) const { return find(uri.toString()); } bool ProfileStore::contains(const char *uri) const { return fs::exists(makeProfilePath(uri)); } bool ProfileStore::changeProfileURI(const Profile::URI &oldURI, const Profile::URI &newURI) { return changeProfileURI(oldURI.toString(), newURI); } bool ProfileStore::changeProfileURI(const std::string &oldURI, const Profile::URI &newURI) { fs::path oldPath = makeProfilePath(oldURI); fs::path newPath = makeProfilePath(newURI.toString()); if(!fs::exists(oldPath)) { return false; } std::fstream file(oldPath.string().c_str()); ProfileDescriptor descriptor; file>>descriptor; descriptor.setURI(newURI); file<<descriptor; fs::rename(oldPath, newPath); return true; } bool ProfileStore::insert(const ProfileDescriptor &descriptor) { fs::path path = makeProfilePath(descriptor.getURI()); std::ofstream stream(path.string().c_str(), std::ofstream::trunc); stream<<descriptor; return (bool)stream; } bool ProfileStore::remove(const Profile::URI &uri) { return remove(uri.toString()); } bool ProfileStore::remove(const std::string &uri) { return fs::remove(makeProfilePath(uri)); } std::string ProfileStore::makeFileName(const std::string &uri) const { std::string filename = uri; size_t pos = filename.find('@'); if(pos!=std::string::npos) { filename.replace(pos, 1, 1, '_'); } filename += ".bp"; return filename; } fs::path ProfileStore::makeProfilePath(const std::string &uri) const { std::string filename = makeFileName(uri); fs::path path = _path; path /= filename; return path; } } <commit_msg>creating new profile file on change uri<commit_after>#include "ProfileStore.hpp" namespace BitProfile{ ProfileStore::ProfileStore() : _path(getDefaultPath(Main_Net)) { createIfNotExists(); } ProfileStore::ProfileStore(const char *path) : _path(fs::absolute(path)) { createIfNotExists(); } ProfileStore::ProfileStore(Network net) : _path(getDefaultPath(net)) { createIfNotExists(); } ProfileStore::ProfileStore(const fs::path &path) : _path(path) { createIfNotExists(); } fs::path ProfileStore::getDefaultPath(Network net) const { fs::path path; #if defined(__APPLE_OS__) path = getenv("HOME"); path /= "Library/BitProfile"; #elif defined(__LINUX_OS__) path = getenv("HOME"); path /= ".bitprofile"; #elif defined(__WINDOWS_OS__) char appdata[1024] = ""; if (SHGetSpecialFolderPathA(NULL, appdata, CSIDL_APPDATA, true)) { path = appdata; } else { path = getenv("HOMEPATH"); } path /= "BitProfile"; #endif if(net==Test_Net) { path /= "testnet"; } path /= "profiles"; return path; } void ProfileStore::createIfNotExists() { boost::filesystem::create_directories(_path); } ProfileStore::Iterator ProfileStore::begin() const { return Iterator(fs::directory_iterator(_path)); } ProfileStore::Iterator ProfileStore::end() const { return Iterator(fs::directory_iterator()); } ProfileStore::Iterator ProfileStore::find(const std::string &uri) const { std::string filename = makeFileName(uri); Iterator it = begin(); for(; it!= end(); ++it) { if(it.path().filename()==filename) { break; } } return it; } ProfileStore::Iterator ProfileStore::find(const Profile::URI &uri) const { return find(uri.toString()); } bool ProfileStore::contains(const char *uri) const { return fs::exists(makeProfilePath(uri)); } bool ProfileStore::changeProfileURI(const Profile::URI &oldURI, const Profile::URI &newURI) { return changeProfileURI(oldURI.toString(), newURI); } bool ProfileStore::changeProfileURI(const std::string &oldURI, const Profile::URI &newURI) { fs::path oldPath = makeProfilePath(oldURI); fs::path newPath = makeProfilePath(newURI.toString()); if(!fs::exists(oldPath)) { return false; } std::ifstream out(oldPath.string().c_str()); ProfileDescriptor descriptor; out>>descriptor; descriptor.setURI(newURI); std::ofstream in(newPath.string().c_str(), std::ofstream::trunc); in<<descriptor; fs::remove(oldPath); return true; } bool ProfileStore::insert(const ProfileDescriptor &descriptor) { fs::path path = makeProfilePath(descriptor.getURI()); std::ofstream stream(path.string().c_str(), std::ofstream::trunc); stream<<descriptor; return (bool)stream; } bool ProfileStore::remove(const Profile::URI &uri) { return remove(uri.toString()); } bool ProfileStore::remove(const std::string &uri) { return fs::remove(makeProfilePath(uri)); } std::string ProfileStore::makeFileName(const std::string &uri) const { std::string filename = uri; size_t pos = filename.find('@'); if(pos!=std::string::npos) { filename.replace(pos, 1, 1, '_'); } filename += ".bp"; return filename; } fs::path ProfileStore::makeProfilePath(const std::string &uri) const { std::string filename = makeFileName(uri); fs::path path = _path; path /= filename; return path; } } <|endoftext|>
<commit_before>/************************************************************************************ This source file is part of the Awesome Portable Rendering Interface Library For latest info, see http://libatres.sourceforge.net/ ************************************************************************************* Copyright (c) 2010 Kresimir Spes ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. *************************************************************************************/ #include <stdio.h> #include "RenderSystem.h" #include "RenderSystem_GL.h" April::RenderSystem* rendersys; namespace April { int hexstr_to_int(std::string s) { int i; sscanf(s.c_str(),"%x",&i); return i; } void hexstr_to_argb(std::string& hex,unsigned char* a,unsigned char* r,unsigned char* g,unsigned char* b) { if (hex.substr(0,2) != "0x") hex="0x"+hex; if (hex.size() == 8) { *r=hexstr_to_int(hex.substr(2,2)); *g=hexstr_to_int(hex.substr(4,2)); *b=hexstr_to_int(hex.substr(6,2)); *a=255; } else if (hex.size() == 10) { *r=hexstr_to_int(hex.substr(4,2)); *g=hexstr_to_int(hex.substr(6,2)); *b=hexstr_to_int(hex.substr(8,2)); *a=hexstr_to_int(hex.substr(2,2)); } else throw "Color format must be either 0xAARRGGBB or 0xRRGGBB"; } Color::Color(float r,float g,float b,float a) { this->r=r*255; this->g=g*255; this->b=b*255; this->a=a*255; } Color::Color() { r=g=b=a=1; } void Color::setHex(std::string hex) { // this is going to bite me in the arse on a little endian system... hexstr_to_argb(hex,&a,&r,&g,&b); } Texture::Texture() { } Texture::~Texture() { } RenderSystem::RenderSystem() { mAlphaMultiplier=1.0f; mUpdateCallback=0; mMouseDownCallback=0; mMouseUpCallback=0; mMouseMoveCallback=0; mKeyDownCallback=0; mKeyUpCallback=0; } void RenderSystem::drawColoredQuad(float x,float y,float w,float h,float r,float g,float b,float a) { PlainVertex v[4]; v[0].x=x; v[0].y=y; v[1].x=x+w; v[1].y=y; v[2].x=x; v[2].y=y+h; v[3].x=x+w; v[3].y=y+h; render(TriangleStrip,v,4,r,g,b,a); } void RenderSystem::logMessage(std::string message) { } void RenderSystem::registerUpdateCallback(bool (*callback)(float)) { mUpdateCallback=callback; } void RenderSystem::registerMouseCallbacks(void (*mouse_dn)(float,float,int), void (*mouse_up)(float,float,int), void (*mouse_move)(float,float,int)) { mMouseDownCallback=mouse_dn; mMouseUpCallback=mouse_up; mMouseMoveCallback=mouse_move; } void RenderSystem::registerKeyboardCallbacks(void (*key_dn)(unsigned int,unsigned int), void (*key_up)(unsigned int,unsigned int)) { mKeyDownCallback=key_dn; mKeyUpCallback=key_up; } /*********************************************************************************/ void init(std::string rendersystem_name,int w,int h,bool fullscreen,std::string title) { createGLRenderSystem(w,h,fullscreen,title); } void enterMainLoop() { } void destroy() { destroyGLRenderSystem(); } }<commit_msg>- fixed inconsistent line ending<commit_after>/************************************************************************************ This source file is part of the Awesome Portable Rendering Interface Library For latest info, see http://libatres.sourceforge.net/ ************************************************************************************* Copyright (c) 2010 Kresimir Spes ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. *************************************************************************************/ #include <stdio.h> #include "RenderSystem.h" #include "RenderSystem_GL.h" April::RenderSystem* rendersys; namespace April { int hexstr_to_int(std::string s) { int i; sscanf(s.c_str(),"%x",&i); return i; } void hexstr_to_argb(std::string& hex,unsigned char* a,unsigned char* r,unsigned char* g,unsigned char* b) { if (hex.substr(0,2) != "0x") hex="0x"+hex; if (hex.size() == 8) { *r=hexstr_to_int(hex.substr(2,2)); *g=hexstr_to_int(hex.substr(4,2)); *b=hexstr_to_int(hex.substr(6,2)); *a=255; } else if (hex.size() == 10) { *r=hexstr_to_int(hex.substr(4,2)); *g=hexstr_to_int(hex.substr(6,2)); *b=hexstr_to_int(hex.substr(8,2)); *a=hexstr_to_int(hex.substr(2,2)); } else throw "Color format must be either 0xAARRGGBB or 0xRRGGBB"; } Color::Color(float r,float g,float b,float a) { this->r=r*255; this->g=g*255; this->b=b*255; this->a=a*255; } Color::Color() { r=g=b=a=1; } void Color::setHex(std::string hex) { // this is going to bite me in the arse on a little endian system... hexstr_to_argb(hex,&a,&r,&g,&b); } Texture::Texture() { } Texture::~Texture() { } RenderSystem::RenderSystem() { mAlphaMultiplier=1.0f; mUpdateCallback=0; mMouseDownCallback=0; mMouseUpCallback=0; mMouseMoveCallback=0; mKeyDownCallback=0; mKeyUpCallback=0; } void RenderSystem::drawColoredQuad(float x,float y,float w,float h,float r,float g,float b,float a) { PlainVertex v[4]; v[0].x=x; v[0].y=y; v[1].x=x+w; v[1].y=y; v[2].x=x; v[2].y=y+h; v[3].x=x+w; v[3].y=y+h; render(TriangleStrip,v,4,r,g,b,a); } void RenderSystem::logMessage(std::string message) { } void RenderSystem::registerUpdateCallback(bool (*callback)(float)) { mUpdateCallback=callback; } void RenderSystem::registerMouseCallbacks(void (*mouse_dn)(float,float,int), void (*mouse_up)(float,float,int), void (*mouse_move)(float,float,int)) { mMouseDownCallback=mouse_dn; mMouseUpCallback=mouse_up; mMouseMoveCallback=mouse_move; } void RenderSystem::registerKeyboardCallbacks(void (*key_dn)(unsigned int,unsigned int), void (*key_up)(unsigned int,unsigned int)) { mKeyDownCallback=key_dn; mKeyUpCallback=key_up; } /*********************************************************************************/ void init(std::string rendersystem_name,int w,int h,bool fullscreen,std::string title) { createGLRenderSystem(w,h,fullscreen,title); } void enterMainLoop() { } void destroy() { destroyGLRenderSystem(); } }<|endoftext|>
<commit_before>// Copyright (c) 2010 Sean Middleditch <[email protected]> // Copyright (c) 2010 Petri Lehtinen <[email protected]> // // Jansson is free software; you can redistribute it and/or modify // it under the terms of the MIT license. See LICENSE for details. #ifndef JANSSON_HPP #define JANSSON_HPP #include <string> #include <ostream> #include <istream> #include <sstream> // Included so that standard functions don't end up in namespace json #include <cstdio> // For free() #include <cstdlib> namespace json { // include Jansson C library into the json namespace # include <jansson.h> class Iterator; class Value; // implementation details; do not use directly namespace detail { class ElementProxy; class PropertyProxy; // base class for JSON value interface template <typename _Base> class ValueBase : public _Base { public: // empty constructor ValueBase() : _Base() {} // copy constructor ValueBase(const _Base& base) : _Base(base) {} // create reference to value ValueBase(json_t* json) : _Base(json) {} // assignment operator inline ValueBase& operator=(const Value& value); // check value type inline bool is_undefined() const; inline bool is_object() const; inline bool is_array() const; inline bool is_string() const; inline bool is_integer() const; inline bool is_real() const; inline bool is_number() const; inline bool is_true() const; inline bool is_false() const; inline bool is_boolean() const; inline bool is_null() const; // get size of array or object inline unsigned int size() const; // get value at array index (const version) inline const Value at(unsigned int index) const; inline const Value operator[](signed int index) const; inline const Value operator[](unsigned int index) const; inline const Value operator[](signed short index) const; inline const Value operator[](unsigned short index) const; inline const Value operator[](signed long index) const; inline const Value operator[](unsigned long index) const; // get value at array index (non-const version) inline ValueBase<ElementProxy> at(unsigned int index); inline ValueBase<ElementProxy> operator[](signed int index); inline ValueBase<ElementProxy> operator[](unsigned int index); inline ValueBase<ElementProxy> operator[](signed short index); inline ValueBase<ElementProxy> operator[](unsigned short index); inline ValueBase<ElementProxy> operator[](signed long index); inline ValueBase<ElementProxy> operator[](unsigned long index); // get object property (const version) inline const Value get(const char* key) const; inline const Value get(const std::string& key) const; inline const Value operator[](const char* key) const; inline const Value operator[](const std::string& key) const; // get object property (non-const version) inline ValueBase<PropertyProxy> get(const char* key); inline ValueBase<PropertyProxy> get(const std::string& key); inline ValueBase<PropertyProxy> operator[](const char* key); inline ValueBase<PropertyProxy> operator[](const std::string& key); // clear all array/object values inline void clear(); // get value cast to specified type inline const char* as_cstring() const; inline std::string as_string() const; inline int as_integer() const; inline double as_real() const; inline double as_number() const; inline bool as_boolean() const; // set an object property (converts value to object is not one already) inline _Base& set_key(const char* key, const Value& value); inline _Base& set_key(const std::string& key, const Value& value); // set an array index (converts value to object is not one already) inline _Base& set_at(unsigned int index, const Value& value); // delete an object key inline _Base& del_key(const char* key); inline _Base& del_key(const std::string& key); // delete an item from an array by index inline _Base& del_at(unsigned int index); // insert an item into an array at a given index inline _Base& insert_at(unsigned int index, const Value& value); // write the value to a file inline int dump_file(const char* path, int flags = 0) const; inline int dump_file(const std::string& path, int flags = 0) const; // write the value to a string (caller must deallocate with free()!) inline char* dumps(int flags = 0) const; }; // represents any JSON value, private base class Basic { public: // construct new Value with an undefined value Basic() : _value(0) {} // copy constructor Basic(const Basic& value) : _value(json_incref(value._value)) {} // make a reference to an existing json_t value explicit Basic(json_t* value) : _value(json_incref(value)) {} // free Value resources inline ~Basic(); // copy an existing Value inline Basic& operator=(const Basic& e); // get the underlying json_t inline json_t* as_json() const; // take ownership of a json_t (does not increase reference count) inline static Basic take_ownership(json_t* json); protected: // internal value pointer json_t* _value; }; // proxies an array element class ElementProxy { public: ElementProxy(json_t* array, unsigned int index); ElementProxy(const ElementProxy& other); ~ElementProxy(); // assign to the proxied element inline ElementProxy& operator=(const Value& value); // get the proxied element inline json_t* as_json() const; private: // array object we wrap json_t* _array; // index of property unsigned int _index; }; // proxies an object property class PropertyProxy { public: PropertyProxy(json_t* object, const char *key); PropertyProxy(const PropertyProxy& other); ~PropertyProxy(); // assign to the proxied element inline PropertyProxy& operator=(const Value& value); // get the proxied element inline json_t* as_json() const; private: // array object we wrap json_t* _object; // iterator pointing to property void* _iter; // key of property char* _key; }; } // namespace json::detail // represents any JSON value class Value : public detail::ValueBase<detail::Basic> { public: // construct Value from input explicit inline Value(const char* value); explicit inline Value(const std::string& value); explicit inline Value(bool value); explicit inline Value(signed int value); explicit inline Value(unsigned int value); explicit inline Value(signed short value); explicit inline Value(unsigned short value); explicit inline Value(signed long value); explicit inline Value(unsigned long value); explicit inline Value(float value); explicit inline Value(double value); // empty constructor Value() : detail::ValueBase<detail::Basic>() {} // copy constructor for base Value(const detail::Basic& value) : detail::ValueBase<detail::Basic>(value) {} // copy constructor for base Value(const detail::ValueBase<detail::Basic>& value) : detail::ValueBase<detail::Basic>(value) {} // copy constructor Value(const Value& value) : detail::ValueBase<detail::Basic>(value) {} // create reference to value explicit Value(json_t* json) : detail::ValueBase<detail::Basic>(json) {} }; // iterators over a JSON object class Iterator { public: // construct a new iterator for a given object inline Iterator(const Value& value); // construct a new iterator for a given object inline Iterator(const detail::ValueBase<detail::PropertyProxy>& value); // increment iterator inline void next(); inline Iterator& operator++(); // test if iterator is still valid inline bool valid() const; inline operator bool() const; // get key inline const char* ckey() const; inline std::string key() const; // get value inline const Value value() const; // dereference value inline const Value operator*() const; private: // disallow copying Iterator(const Iterator&); Iterator& operator=(const Iterator&); // object being iterated over Value _object; // iterator value void* _iter; }; // create a new empty object inline Value object(); // create a new empty array inline Value array(); // create a new null value inline Value null(); // load a file as a JSON value inline Value load_file(const char* path, json_error_t* error = 0); inline Value load_file(const std::string& path, json_error_t* error = 0); // load a string as a JSON value inline Value loads(const char* string, json_error_t* error = 0); inline Value loads(const std::string& string, json_error_t* error = 0); } // namespace json // stream JSON value out -- inefficient and not recommended for production use inline std::ostream& operator<<(std::ostream& os, const json::Value& value); // read JSON value -- inefficient and not recommended for production use inline std::istream& operator>>(std::istream& is, json::Value& value); // include implementation code #define IN_JANSSON_HPP #include "jansson.ipp" #undef IN_JANSSON_HPP #endif // defined(JANSSON_HPP) <commit_msg>c++ wrapper: add missing 'inline' statements to various constructors<commit_after>// Copyright (c) 2010 Sean Middleditch <[email protected]> // Copyright (c) 2010 Petri Lehtinen <[email protected]> // // Jansson is free software; you can redistribute it and/or modify // it under the terms of the MIT license. See LICENSE for details. #ifndef JANSSON_HPP #define JANSSON_HPP #include <string> #include <ostream> #include <istream> #include <sstream> // Included so that standard functions don't end up in namespace json #include <cstdio> // For free() #include <cstdlib> namespace json { // include Jansson C library into the json namespace # include <jansson.h> class Iterator; class Value; // implementation details; do not use directly namespace detail { class ElementProxy; class PropertyProxy; // base class for JSON value interface template <typename _Base> class ValueBase : public _Base { public: // empty constructor ValueBase() : _Base() {} // copy constructor ValueBase(const _Base& base) : _Base(base) {} // create reference to value ValueBase(json_t* json) : _Base(json) {} // assignment operator inline ValueBase& operator=(const Value& value); // check value type inline bool is_undefined() const; inline bool is_object() const; inline bool is_array() const; inline bool is_string() const; inline bool is_integer() const; inline bool is_real() const; inline bool is_number() const; inline bool is_true() const; inline bool is_false() const; inline bool is_boolean() const; inline bool is_null() const; // get size of array or object inline unsigned int size() const; // get value at array index (const version) inline const Value at(unsigned int index) const; inline const Value operator[](signed int index) const; inline const Value operator[](unsigned int index) const; inline const Value operator[](signed short index) const; inline const Value operator[](unsigned short index) const; inline const Value operator[](signed long index) const; inline const Value operator[](unsigned long index) const; // get value at array index (non-const version) inline ValueBase<ElementProxy> at(unsigned int index); inline ValueBase<ElementProxy> operator[](signed int index); inline ValueBase<ElementProxy> operator[](unsigned int index); inline ValueBase<ElementProxy> operator[](signed short index); inline ValueBase<ElementProxy> operator[](unsigned short index); inline ValueBase<ElementProxy> operator[](signed long index); inline ValueBase<ElementProxy> operator[](unsigned long index); // get object property (const version) inline const Value get(const char* key) const; inline const Value get(const std::string& key) const; inline const Value operator[](const char* key) const; inline const Value operator[](const std::string& key) const; // get object property (non-const version) inline ValueBase<PropertyProxy> get(const char* key); inline ValueBase<PropertyProxy> get(const std::string& key); inline ValueBase<PropertyProxy> operator[](const char* key); inline ValueBase<PropertyProxy> operator[](const std::string& key); // clear all array/object values inline void clear(); // get value cast to specified type inline const char* as_cstring() const; inline std::string as_string() const; inline int as_integer() const; inline double as_real() const; inline double as_number() const; inline bool as_boolean() const; // set an object property (converts value to object is not one already) inline _Base& set_key(const char* key, const Value& value); inline _Base& set_key(const std::string& key, const Value& value); // set an array index (converts value to object is not one already) inline _Base& set_at(unsigned int index, const Value& value); // delete an object key inline _Base& del_key(const char* key); inline _Base& del_key(const std::string& key); // delete an item from an array by index inline _Base& del_at(unsigned int index); // insert an item into an array at a given index inline _Base& insert_at(unsigned int index, const Value& value); // write the value to a file inline int dump_file(const char* path, int flags = 0) const; inline int dump_file(const std::string& path, int flags = 0) const; // write the value to a string (caller must deallocate with free()!) inline char* dumps(int flags = 0) const; }; // represents any JSON value, private base class Basic { public: // construct new Value with an undefined value Basic() : _value(0) {} // copy constructor Basic(const Basic& value) : _value(json_incref(value._value)) {} // make a reference to an existing json_t value explicit Basic(json_t* value) : _value(json_incref(value)) {} // free Value resources inline ~Basic(); // copy an existing Value inline Basic& operator=(const Basic& e); // get the underlying json_t inline json_t* as_json() const; // take ownership of a json_t (does not increase reference count) inline static Basic take_ownership(json_t* json); protected: // internal value pointer json_t* _value; }; // proxies an array element class ElementProxy { public: inline ElementProxy(json_t* array, unsigned int index); inline ElementProxy(const ElementProxy& other); inline ~ElementProxy(); // assign to the proxied element inline ElementProxy& operator=(const Value& value); // get the proxied element inline json_t* as_json() const; private: // array object we wrap json_t* _array; // index of property unsigned int _index; }; // proxies an object property class PropertyProxy { public: inline PropertyProxy(json_t* object, const char *key); inline PropertyProxy(const PropertyProxy& other); inline ~PropertyProxy(); // assign to the proxied element inline PropertyProxy& operator=(const Value& value); // get the proxied element inline json_t* as_json() const; private: // array object we wrap json_t* _object; // iterator pointing to property void* _iter; // key of property char* _key; }; } // namespace json::detail // represents any JSON value class Value : public detail::ValueBase<detail::Basic> { public: // construct Value from input explicit inline Value(const char* value); explicit inline Value(const std::string& value); explicit inline Value(bool value); explicit inline Value(signed int value); explicit inline Value(unsigned int value); explicit inline Value(signed short value); explicit inline Value(unsigned short value); explicit inline Value(signed long value); explicit inline Value(unsigned long value); explicit inline Value(float value); explicit inline Value(double value); // empty constructor Value() : detail::ValueBase<detail::Basic>() {} // copy constructor for base Value(const detail::Basic& value) : detail::ValueBase<detail::Basic>(value) {} // copy constructor for base Value(const detail::ValueBase<detail::Basic>& value) : detail::ValueBase<detail::Basic>(value) {} // copy constructor Value(const Value& value) : detail::ValueBase<detail::Basic>(value) {} // create reference to value explicit Value(json_t* json) : detail::ValueBase<detail::Basic>(json) {} }; // iterators over a JSON object class Iterator { public: // construct a new iterator for a given object inline Iterator(const Value& value); // construct a new iterator for a given object inline Iterator(const detail::ValueBase<detail::PropertyProxy>& value); // increment iterator inline void next(); inline Iterator& operator++(); // test if iterator is still valid inline bool valid() const; inline operator bool() const; // get key inline const char* ckey() const; inline std::string key() const; // get value inline const Value value() const; // dereference value inline const Value operator*() const; private: // disallow copying Iterator(const Iterator&); Iterator& operator=(const Iterator&); // object being iterated over Value _object; // iterator value void* _iter; }; // create a new empty object inline Value object(); // create a new empty array inline Value array(); // create a new null value inline Value null(); // load a file as a JSON value inline Value load_file(const char* path, json_error_t* error = 0); inline Value load_file(const std::string& path, json_error_t* error = 0); // load a string as a JSON value inline Value loads(const char* string, json_error_t* error = 0); inline Value loads(const std::string& string, json_error_t* error = 0); } // namespace json // stream JSON value out -- inefficient and not recommended for production use inline std::ostream& operator<<(std::ostream& os, const json::Value& value); // read JSON value -- inefficient and not recommended for production use inline std::istream& operator>>(std::istream& is, json::Value& value); // include implementation code #define IN_JANSSON_HPP #include "jansson.ipp" #undef IN_JANSSON_HPP #endif // defined(JANSSON_HPP) <|endoftext|>
<commit_before>// v8 #include <v8.h> // node #include <node.h> #include <node_version.h> #include <node_object_wrap.h> // stl #include <iostream> #include <fstream> #include <algorithm> // boost #include <boost/spirit/include/qi.hpp> #include <boost/timer/timer.hpp> #include <boost/tokenizer.hpp> #include <boost/locale.hpp> #include <boost/regex/pending/unicode_iterator.hpp> #include <boost/make_shared.hpp> // geocoder #include "geocoder/fss.hpp" namespace node_fss { using namespace v8; // interfaces typedef geocoder::fss_engine<> geocoder; typedef boost::shared_ptr<geocoder> fss_ptr; class Engine: public node::ObjectWrap { public: static Persistent<FunctionTemplate> constructor; static void Initialize(Handle<Object> target); static Handle<Value> New(Arguments const& args); static Handle<Value> addSync(Arguments const& args); static Handle<Value> add(Arguments const& args); static void AsyncAdd(uv_work_t* req); static void AfterAdd(uv_work_t* req); static Handle<Value> query(Arguments const& args); Engine(); inline fss_ptr get() { return this_; } void _ref() { Ref(); } void _unref() { Unref(); } private: ~Engine(); fss_ptr this_; }; // implementations Persistent<FunctionTemplate> Engine::constructor; void Engine::Initialize(Handle<Object> target) { HandleScope scope; constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Engine::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Engine")); NODE_SET_PROTOTYPE_METHOD(constructor, "add", add); NODE_SET_PROTOTYPE_METHOD(constructor, "addSync", add); NODE_SET_PROTOTYPE_METHOD(constructor, "query", query); target->Set(String::NewSymbol("Engine"),constructor->GetFunction()); } Engine::Engine() : ObjectWrap(), this_(boost::make_shared<geocoder>()) { } Engine::~Engine() { } Handle<Value> Engine::New(Arguments const& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword")); } try { Engine* im = new Engine(); im->Wrap(args.This()); return args.This(); } catch (std::exception const& ex) { return ThrowException(String::New(ex.what())); } return Undefined(); } Handle<Value> Engine::addSync(Arguments const& args) { HandleScope scope; if (args.Length() < 1) { ThrowException(String::New("first argument must be an object")); } if (!args[0]->IsObject()) { return ThrowException(String::New("first argument must be an object")); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("valid object expected for first argument"))); } if (!obj->Has(String::NewSymbol("file")) || !obj->Has(String::NewSymbol("distance"))) { return ThrowException(String::New("must provide a file path and distance in object argument")); } Local<Value> file_obj = obj->Get(String::New("file")); if (!file_obj->IsString()) { return ThrowException(String::New("file must be a string")); } std::string file = *String::Utf8Value(file_obj->ToString()); Local<Value> distance_obj = obj->Get(String::New("distance")); if (!distance_obj->IsNumber()) { return ThrowException(String::New("distance must be a number")); } int distance = distance_obj->IntegerValue(); Engine* machine = ObjectWrap::Unwrap<Engine>(args.This()); // TODO parse file and build up dict fss_ptr dict = machine->get(); return scope.Close(String::New("TODO")); } typedef struct { uv_work_t request; Engine * machine; std::string query; bool error; std::string result; Persistent<Function> cb; } add_baton_t; Handle<Value> Engine::add(Arguments const& args) { HandleScope scope; return addSync(args); if (args.Length() == 1) { return addSync(args); } /*if (args.Length() < 1) { ThrowException(String::New("first argument must be an object")); } if (!args[0]->IsObject()) { return ThrowException(String::New("first argument must be an object")); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined()) { ThrowException(Exception::TypeError(String::New("an object expected for first argument"))); } // ensure callback is a function Local<Value> callback = args[args.Length()-1]; if (!args[args.Length()-1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("last argument must be a callback function"))); } Engine * machine = ObjectWrap::Unwrap<Engine>(args.This()); add_baton_t *closure = new add_baton_t(); closure->request.data = closure; closure->machine = machine; closure->query = query; closure->error = false; closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback)); uv_queue_work(uv_default_loop(), &closure->request, AsyncAdd, (uv_after_work_cb)AfterAdd); closure->machine->_ref(); closure->query->_ref(); */ return Undefined(); } /* void Engine::AsyncRun(uv_work_t* req) { add_baton_t *closure = static_cast<add_baton_t *>(req->data); try { http::Reply osrm_reply; closure->machine->this_->RunQuery(*(closure->query->get()), osrm_reply); closure->result = osrm_reply.content; } catch(std::exception const& ex) { closure->error = true; closure->result = ex.what(); } } void Engine::AfterRun(uv_work_t* req) { HandleScope scope; add_baton_t *closure = static_cast<add_baton_t *>(req->data); TryCatch try_catch; if (closure->error) { Local<Value> argv[1] = { Exception::Error(String::New(closure->result.c_str())) }; closure->cb->Call(Context::GetCurrent()->Global(), 1, argv); } else { Local<Value> argv[2] = { Local<Value>::New(Null()), String::New(closure->result.c_str()) }; closure->cb->Call(Context::GetCurrent()->Global(), 2, argv); } if (try_catch.HasCaught()) { node::FatalException(try_catch); } closure->machine->_unref(); closure->query->_unref(); closure->cb.Dispose(); delete closure; } */ Handle<Value> Engine::query(Arguments const& args) { HandleScope scope; return scope.Close(String::New("TODO")); } extern "C" { static void start(Handle<Object> target) { Engine::Initialize(target); } } } // namespace node_fss NODE_MODULE(_fss, node_fss::start) <commit_msg>add FSS implementation<commit_after>// v8 #include <v8.h> // node #include <node.h> #include <node_version.h> #include <node_object_wrap.h> // stl #include <iostream> #include <fstream> #include <algorithm> // boost #include <boost/spirit/include/qi.hpp> #include <boost/locale.hpp> #include <boost/regex/pending/unicode_iterator.hpp> #include <boost/make_shared.hpp> // geocoder #include "geocoder/fss.hpp" namespace node_fss { using namespace v8; // interfaces typedef geocoder::fss_engine<> geocoder; typedef boost::shared_ptr<geocoder> fss_ptr; class Engine: public node::ObjectWrap { public: static Persistent<FunctionTemplate> constructor; static void Initialize(Handle<Object> target); static Handle<Value> New(Arguments const& args); static Handle<Value> addSync(Arguments const& args); static Handle<Value> add(Arguments const& args); static void AsyncAdd(uv_work_t* req); static void AfterAdd(uv_work_t* req); static Handle<Value> search(Arguments const& args); Engine(); inline fss_ptr get() { return this_; } void _ref() { Ref(); } void _unref() { Unref(); } private: ~Engine(); fss_ptr this_; }; // implementations Persistent<FunctionTemplate> Engine::constructor; void Engine::Initialize(Handle<Object> target) { HandleScope scope; constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Engine::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Engine")); NODE_SET_PROTOTYPE_METHOD(constructor, "add", add); NODE_SET_PROTOTYPE_METHOD(constructor, "addSync", add); NODE_SET_PROTOTYPE_METHOD(constructor, "search", search); target->Set(String::NewSymbol("Engine"),constructor->GetFunction()); } Engine::Engine() : ObjectWrap(), this_(boost::make_shared<geocoder>()) { } Engine::~Engine() { } Handle<Value> Engine::New(Arguments const& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword")); } try { Engine* im = new Engine(); im->Wrap(args.This()); return args.This(); } catch (std::exception const& ex) { return ThrowException(String::New(ex.what())); } return Undefined(); } Handle<Value> Engine::addSync(Arguments const& args) { HandleScope scope; if (args.Length() < 1) { ThrowException(String::New("first argument must be an object")); } if (!args[0]->IsObject()) { return ThrowException(String::New("first argument must be an object")); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("valid object expected for first argument"))); } if (!obj->Has(String::NewSymbol("file")) || !obj->Has(String::NewSymbol("distance"))) { return ThrowException(String::New("must provide a file path and distance in object argument")); } Local<Value> file_obj = obj->Get(String::New("file")); if (!file_obj->IsString()) { return ThrowException(String::New("file must be a string")); } std::string filename = *String::Utf8Value(file_obj->ToString()); Local<Value> distance_obj = obj->Get(String::New("distance")); if (!distance_obj->IsNumber()) { return ThrowException(String::New("distance must be a number")); } int distance = distance_obj->IntegerValue(); Engine* machine = ObjectWrap::Unwrap<Engine>(args.This()); fss_ptr dict = machine->get(); std::ifstream file(filename); if (!file) { return ThrowException(String::New("Can't open dictinary file")); } boost::locale::generator gen; std::locale loc = gen(""); std::locale::global(loc); std::cerr.imbue(loc); std::string line; std::set<std::u32string> temp_dict; uint64_t count = 0; while (std::getline(file, line)) { ++count; if (count%1000 == 0) { std::cerr << "\rLoading " << count; } // normalize line = boost::locale::to_lower(line); boost::u8_to_u32_iterator<std::string::const_iterator> begin(line.begin()); boost::u8_to_u32_iterator<std::string::const_iterator> end(line.end()); std::vector<std::u32string> words; // extract tokens bool result = boost::spirit::qi::parse(begin, end, +(boost::spirit::standard_wide::char_ - boost::spirit::standard_wide::space) % +(boost::spirit::standard_wide::space | boost::spirit::qi::lit(L",")), temp_dict); if (!result) { std::cerr << "Failed parsing tokens:" << line << std::endl; //ThrowException(String::New("Failed parsing tokens")); } } count = 0; for (auto && word : temp_dict) { ++count; if (count%1000 == 0) { std::cerr << "\rCreating index " << count << "/" << temp_dict.size() << " " << int(100*(count/(float)temp_dict.size())) << "%"; } boost::u32_to_u8_iterator<std::u32string::const_iterator> begin(word.begin()); boost::u32_to_u8_iterator<std::u32string::const_iterator> end(word.end()); dict->add(std::string(begin,end)); } std::cerr << std::endl; temp_dict.clear(); return scope.Close(String::New("TODO")); } typedef struct { uv_work_t request; Engine * machine; std::string query; bool error; std::string result; Persistent<Function> cb; } add_baton_t; Handle<Value> Engine::add(Arguments const& args) { HandleScope scope; return addSync(args); if (args.Length() == 1) { return addSync(args); } /*if (args.Length() < 1) { ThrowException(String::New("first argument must be an object")); } if (!args[0]->IsObject()) { return ThrowException(String::New("first argument must be an object")); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined()) { ThrowException(Exception::TypeError(String::New("an object expected for first argument"))); } // ensure callback is a function Local<Value> callback = args[args.Length()-1]; if (!args[args.Length()-1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("last argument must be a callback function"))); } Engine * machine = ObjectWrap::Unwrap<Engine>(args.This()); add_baton_t *closure = new add_baton_t(); closure->request.data = closure; closure->machine = machine; closure->query = query; closure->error = false; closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback)); uv_queue_work(uv_default_loop(), &closure->request, AsyncAdd, (uv_after_work_cb)AfterAdd); closure->machine->_ref(); closure->query->_ref(); */ return Undefined(); } /* void Engine::AsyncRun(uv_work_t* req) { add_baton_t *closure = static_cast<add_baton_t *>(req->data); try { http::Reply osrm_reply; closure->machine->this_->RunQuery(*(closure->query->get()), osrm_reply); closure->result = osrm_reply.content; } catch(std::exception const& ex) { closure->error = true; closure->result = ex.what(); } } void Engine::AfterRun(uv_work_t* req) { HandleScope scope; add_baton_t *closure = static_cast<add_baton_t *>(req->data); TryCatch try_catch; if (closure->error) { Local<Value> argv[1] = { Exception::Error(String::New(closure->result.c_str())) }; closure->cb->Call(Context::GetCurrent()->Global(), 1, argv); } else { Local<Value> argv[2] = { Local<Value>::New(Null()), String::New(closure->result.c_str()) }; closure->cb->Call(Context::GetCurrent()->Global(), 2, argv); } if (try_catch.HasCaught()) { node::FatalException(try_catch); } closure->machine->_unref(); closure->query->_unref(); closure->cb.Dispose(); delete closure; } */ Handle<Value> Engine::search(Arguments const& args) { HandleScope scope; if (args.Length() < 1) { ThrowException(String::New("first argument must be an object")); } if (!args[0]->IsObject()) { return ThrowException(String::New("first argument must be an object")); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("valid object expected for first argument"))); } if (!obj->Has(String::NewSymbol("query")) || !obj->Has(String::NewSymbol("distance")) || !obj->Has(String::NewSymbol("num_results"))) { return ThrowException(String::New("must provide a query string and distance in object argument")); } // dict file-name Local<Value> file_obj = obj->Get(String::New("query")); if (!file_obj->IsString()) { return ThrowException(String::New("query must be an UTF8 encoded string")); } std::string query = *String::Utf8Value(file_obj->ToString()); // distance Local<Value> distance_obj = obj->Get(String::New("distance")); if (!distance_obj->IsNumber()) { return ThrowException(String::New("distance must be an integer")); } int distance = distance_obj->IntegerValue(); // num_results Local<Value> num_results_obj = obj->Get(String::New("num_results")); if (!num_results_obj->IsNumber()) { return ThrowException(String::New("num_results must be an integer")); } int num_results = num_results_obj->IntegerValue(); Engine* machine = ObjectWrap::Unwrap<Engine>(args.This()); fss_ptr dict = machine->get(); query = boost::locale::to_lower(query); boost::u8_to_u32_iterator<std::string::const_iterator> begin(query.begin()); boost::u8_to_u32_iterator<std::string::const_iterator> end(query.end()); std::vector<std::u32string> tokens; // extract tokens bool result = boost::spirit::qi::parse(begin, end, +(boost::spirit::standard_wide::char_ - boost::spirit::standard_wide::space) % +(boost::spirit::standard_wide::space | boost::spirit::qi::lit(L",")), tokens); if (!result) { ThrowException(String::New("FAIL parsing query tokens")); } Local<Array> results = Array::New(); unsigned index = 0; for (auto token : tokens) { boost::u32_to_u8_iterator<std::u32string::const_iterator> begin(token.begin()); boost::u32_to_u8_iterator<std::u32string::const_iterator> end(token.end()); Local<Array> result = Array::New(); unsigned idx = 0; for ( auto && p : dict->search(std::string(begin,end), distance, num_results)) { Local<Array> ar = Array::New(); ar->Set(0, String::New(p.first.c_str())); ar->Set(1, Integer::New(p.second)); result->Set(idx++,ar); //result->Set(String::New(token.c_str()),ar); } results->Set(index++,result); /* if (r.size() > 0) { if (r.front().second == 0) { std::cerr << r.front().first << " [" << r.front().second << "] "; } else { std::for_each(r.begin(), r.end(), [] (std::pair<std::string,unsigned> const& p) { std::cerr << p.first << "[" << p.second << "] ";} ); } std::cerr << "+ "; } */ } return scope.Close(results); } extern "C" { static void start(Handle<Object> target) { Engine::Initialize(target); } } } // namespace node_fss NODE_MODULE(_fss, node_fss::start) <|endoftext|>
<commit_before>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR 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 "BootIO.h" #include <processor/types.h> #include <machine/Machine.h> #include <machine/Vga.h> #include <machine/Serial.h> #include <Log.h> BootIO::BootIO() : m_CursorX(0), m_CursorY(0) { } BootIO::~BootIO() { } void BootIO::initialise() { Vga *pVga = Machine::instance().getVga(0); if (pVga) { pVga->setLargestTextMode(); uint16_t *pFramebuffer = *pVga; if (pFramebuffer != 0) for (size_t i = 0; i < pVga->getNumRows()*pVga->getNumCols(); i++) pFramebuffer[i] = 0; } } void BootIO::write(HugeStaticString &str, Colour foreColour, Colour backColour) { for(size_t i = 0; i < str.length(); i++) putCharVga(str[i], foreColour, backColour); if(!Log::instance().echoToSerial()) { for(size_t i = 0; i < Machine::instance().getNumSerial(); i++) { startColour(Machine::instance().getSerial(i), foreColour, backColour); for(size_t j = 0; j < str.length(); j++) Machine::instance().getSerial(i)->write(str[j]); endColour(Machine::instance().getSerial(i)); } } #ifdef PPC_COMMON // For PPC: causes the graphics framebuffer to be updated from the text one. Vga *pVga = Machine::instance().getVga(0); uint16_t *pFramebuffer = *pVga; pVga->pokeBuffer(reinterpret_cast<uint8_t*>(pFramebuffer),0); #endif } void BootIO::putCharVga(const char c, Colour foreColour, Colour backColour) { Vga *pVga = Machine::instance().getVga(0); if (pVga) { uint16_t *pFramebuffer = *pVga; if (pFramebuffer == 0) return; // Backspace? if (c == 0x08) { // Can we just move backwards? or do we have to go up? if (m_CursorX) m_CursorX--; else { m_CursorX = pVga->getNumCols()-1; if (m_CursorY > 0) m_CursorY--; } // Erase the contents of the cell currently. uint8_t attributeByte = (backColour << 4) | (foreColour & 0x0F); pFramebuffer[m_CursorY*pVga->getNumCols() + m_CursorX] = ' ' | (attributeByte << 8); } // Tab? else if (c == 0x09 && ( ((m_CursorX+8)&~(8-1)) < pVga->getNumCols()) ) m_CursorX = (m_CursorX+8) & ~(8-1); // Carriage return? else if (c == '\r') m_CursorX = 0; // Newline? else if (c == '\n') { m_CursorX = 0; m_CursorY++; } // Normal character? else if (c >= ' ') { uint8_t attributeByte = (backColour << 4) | (foreColour & 0x0F); pFramebuffer[m_CursorY*pVga->getNumCols() + m_CursorX] = c | (attributeByte << 8); // Increment the cursor. m_CursorX++; } // Do we need to wrap? if (m_CursorX >= pVga->getNumCols()) { m_CursorX = 0; m_CursorY ++; } // Get a space character with the default colour attributes. uint8_t attributeByte = (Black << 4) | (White & 0x0F); uint16_t blank = ' ' | (attributeByte << 8); if (m_CursorY >= pVga->getNumRows()) { for (size_t i = 0; i < (pVga->getNumRows()-1)*pVga->getNumCols(); i++) pFramebuffer[i] = pFramebuffer[i+pVga->getNumCols()]; for (size_t i = (pVga->getNumRows()-1)*pVga->getNumCols(); i < (pVga->getNumRows())*pVga->getNumCols(); i++) pFramebuffer[i] = blank; m_CursorY = pVga->getNumRows()-1; } } } void BootIO::startColour(Serial *pSerial, Colour foreColour, Colour backColour) { pSerial->write("\033["); switch(foreColour) { case Black: pSerial->write("30"); break; case Red: pSerial->write("31"); break; case Green: pSerial->write("32"); break; case Yellow: pSerial->write("1;33"); break; // It's actually brown. case Blue: pSerial->write("34"); break; case Magenta: pSerial->write("35"); break; case Cyan: pSerial->write("36"); break; case LightGrey: pSerial->write("0;37"); break; case DarkGrey: pSerial->write("1;30"); break; case LightRed: pSerial->write("1;31"); break; case LightGreen: pSerial->write("1;32"); break; case LightBlue: pSerial->write("1;34"); break; case LightMagenta: pSerial->write("1;35"); break; case LightCyan: pSerial->write("1;36"); break; case White: pSerial->write("1;37"); break; default: pSerial->write('1'); } pSerial->write(";"); switch(backColour) { case Black: pSerial->write("40"); break; case Red: pSerial->write("41"); break; case Green: pSerial->write("42"); break; case DarkGrey: pSerial->write("43"); break; // It's actually brown. case Blue: pSerial->write("44"); break; case Magenta: pSerial->write("45"); break; case Cyan: pSerial->write("46"); break; case White: pSerial->write("47"); break; default: pSerial->write('1'); } pSerial->write('m'); } void BootIO::endColour(Serial *pSerial) { } <commit_msg>Fix BootIO::write's incorrect logic.<commit_after>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR 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 "BootIO.h" #include <processor/types.h> #include <machine/Machine.h> #include <machine/Vga.h> #include <machine/Serial.h> #include <Log.h> BootIO::BootIO() : m_CursorX(0), m_CursorY(0) { } BootIO::~BootIO() { } void BootIO::initialise() { Vga *pVga = Machine::instance().getVga(0); if (pVga) { pVga->setLargestTextMode(); uint16_t *pFramebuffer = *pVga; if (pFramebuffer != 0) for (size_t i = 0; i < pVga->getNumRows()*pVga->getNumCols(); i++) pFramebuffer[i] = 0; } } void BootIO::write(HugeStaticString &str, Colour foreColour, Colour backColour) { for(size_t i = 0; i < str.length(); i++) putCharVga(str[i], foreColour, backColour); if(Log::instance().echoToSerial()) { for(size_t i = 0; i < Machine::instance().getNumSerial(); i++) { startColour(Machine::instance().getSerial(i), foreColour, backColour); for(size_t j = 0; j < str.length(); j++) Machine::instance().getSerial(i)->write(str[j]); endColour(Machine::instance().getSerial(i)); } } #ifdef PPC_COMMON // For PPC: causes the graphics framebuffer to be updated from the text one. Vga *pVga = Machine::instance().getVga(0); uint16_t *pFramebuffer = *pVga; pVga->pokeBuffer(reinterpret_cast<uint8_t*>(pFramebuffer),0); #endif } void BootIO::putCharVga(const char c, Colour foreColour, Colour backColour) { Vga *pVga = Machine::instance().getVga(0); if (pVga) { uint16_t *pFramebuffer = *pVga; if (pFramebuffer == 0) return; // Backspace? if (c == 0x08) { // Can we just move backwards? or do we have to go up? if (m_CursorX) m_CursorX--; else { m_CursorX = pVga->getNumCols()-1; if (m_CursorY > 0) m_CursorY--; } // Erase the contents of the cell currently. uint8_t attributeByte = (backColour << 4) | (foreColour & 0x0F); pFramebuffer[m_CursorY*pVga->getNumCols() + m_CursorX] = ' ' | (attributeByte << 8); } // Tab? else if (c == 0x09 && ( ((m_CursorX+8)&~(8-1)) < pVga->getNumCols()) ) m_CursorX = (m_CursorX+8) & ~(8-1); // Carriage return? else if (c == '\r') m_CursorX = 0; // Newline? else if (c == '\n') { m_CursorX = 0; m_CursorY++; } // Normal character? else if (c >= ' ') { uint8_t attributeByte = (backColour << 4) | (foreColour & 0x0F); pFramebuffer[m_CursorY*pVga->getNumCols() + m_CursorX] = c | (attributeByte << 8); // Increment the cursor. m_CursorX++; } // Do we need to wrap? if (m_CursorX >= pVga->getNumCols()) { m_CursorX = 0; m_CursorY ++; } // Get a space character with the default colour attributes. uint8_t attributeByte = (Black << 4) | (White & 0x0F); uint16_t blank = ' ' | (attributeByte << 8); if (m_CursorY >= pVga->getNumRows()) { for (size_t i = 0; i < (pVga->getNumRows()-1)*pVga->getNumCols(); i++) pFramebuffer[i] = pFramebuffer[i+pVga->getNumCols()]; for (size_t i = (pVga->getNumRows()-1)*pVga->getNumCols(); i < (pVga->getNumRows())*pVga->getNumCols(); i++) pFramebuffer[i] = blank; m_CursorY = pVga->getNumRows()-1; } } } void BootIO::startColour(Serial *pSerial, Colour foreColour, Colour backColour) { pSerial->write("\033["); switch(foreColour) { case Black: pSerial->write("30"); break; case Red: pSerial->write("31"); break; case Green: pSerial->write("32"); break; case Yellow: pSerial->write("1;33"); break; // It's actually brown. case Blue: pSerial->write("34"); break; case Magenta: pSerial->write("35"); break; case Cyan: pSerial->write("36"); break; case LightGrey: pSerial->write("0;37"); break; case DarkGrey: pSerial->write("1;30"); break; case LightRed: pSerial->write("1;31"); break; case LightGreen: pSerial->write("1;32"); break; case LightBlue: pSerial->write("1;34"); break; case LightMagenta: pSerial->write("1;35"); break; case LightCyan: pSerial->write("1;36"); break; case White: pSerial->write("1;37"); break; default: pSerial->write('1'); } pSerial->write(";"); switch(backColour) { case Black: pSerial->write("40"); break; case Red: pSerial->write("41"); break; case Green: pSerial->write("42"); break; case DarkGrey: pSerial->write("43"); break; // It's actually brown. case Blue: pSerial->write("44"); break; case Magenta: pSerial->write("45"); break; case Cyan: pSerial->write("46"); break; case White: pSerial->write("47"); break; default: pSerial->write('1'); } pSerial->write('m'); } void BootIO::endColour(Serial *pSerial) { } <|endoftext|>
<commit_before>// Copyright 2016 Alessio Sclocco <[email protected]> // // 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 <vector> #include <iostream> #include <exception> #include <iomanip> #include <ctime> #include <algorithm> #include <configuration.hpp> #include <ArgumentList.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <MD.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> const inputDataType magicValue = 42; const float LJ1 = 1.5f; const float LJ2 = 2.0f; void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d); int main(int argc, char * argv[]) { bool reInit = true; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int vectorSize = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int nrAtoms = 0; isa::OpenCL::KernelConf conf; try { isa::utils::ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); vectorSize = args.getSwitchArgument< unsigned int >("-vector"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); nrAtoms = args.getSwitchArgument< unsigned int >("-atoms"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... -iterations ... -vector ... -max_threads ... -max_items ... -atoms ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = 0; // Allocate host memory std::vector< inputDataType > input(nrAtoms * 4), output(nrAtoms * 4), output_c(nrAtoms * 4); cl::Buffer input_d, output_d; // Populate data structures srand48(time(0)); for ( unsigned int atom = 0; atom < nrAtoms; atom++ ) { input[(atom * 4)] = drand48() * magicValue; input[(atom * 4) + 1] = drand48() * magicValue; input[(atom * 4) + 2] = drand48() * magicValue; input[(atom * 4) + 3] = 0; } // Compute CPU control results std::fill(output.begin(), output.end(), 0); TuneBench::MD(input, output_c, nrAtoms); std::cout << std::fixed << std::endl; std::cout << "# nrAtoms nrThreadsD0 nrItemsD0 nrItemsD1 GFLOP/s time stdDeviation COV" << std::endl << std::endl; for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) { conf.setNrThreadsD0(threads); for ( unsigned int items = 1; items <= maxItems; items++ ) { conf.setNrItemsD0(items); if ( nrAtoms % (conf.getNrThreadsD0() * conf.getNrItemsD0()) != 0 ) { continue; } for ( unsigned int items = 1; (4 * conf.getNrItemsD0()) + (8 * conf.getNrItemsD0() * items) <= maxItems; items++ ) { conf.setNrItemsD1(items); if ( nrAtoms % (conf.getNrItemsD1()) != 0 ) { continue; } // Generate kernel // The number of operations (21) is not the real number in the code but the number of operations (less) used in the equivalent code from SHOC double gflops = isa::utils::giga(static_cast< uint64_t >(nrAtoms) * nrAtoms * 21); cl::Event clEvent; cl::Kernel * kernel; isa::utils::Timer timer; std::string * code = TuneBench::getMDOpenCL(conf, inputDataName, nrAtoms, LJ1, LJ2); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector< cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("MD", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global(nrAtoms / conf.getNrItemsD0()); cl::NDRange local(conf.getNrThreadsD0()); kernel->setArg(0, input_d); kernel->setArg(1, output_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); timer.stop(); } clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent); clEvent.wait(); } catch ( cl::Error & err ) { reInit = true; std::cerr << "OpenCL kernel execution error ("; std::cerr << conf.print(); std::cerr << "): "; std::cerr << isa::utils::toString(err.err()) << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } break; } delete kernel; bool error = false; for ( unsigned int atom = 0; atom < nrAtoms; atom++ ) { if ( !isa::utils::same(output[atom], output_c[atom]) ) { std::cerr << "Output error (" << conf.print() << ")." << std::endl; error = true; break; } } if ( error ) { continue; } std::cout << nrAtoms << " "; std::cout << conf.print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl; } } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, input->size() * sizeof(inputDataType), 0, 0); clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <commit_msg>Fixing a small bug.<commit_after>// Copyright 2016 Alessio Sclocco <[email protected]> // // 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 <vector> #include <iostream> #include <exception> #include <iomanip> #include <ctime> #include <algorithm> #include <configuration.hpp> #include <ArgumentList.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <MD.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> const inputDataType magicValue = 42; const float LJ1 = 1.5f; const float LJ2 = 2.0f; void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d); int main(int argc, char * argv[]) { bool reInit = true; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int vectorSize = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int nrAtoms = 0; isa::OpenCL::KernelConf conf; try { isa::utils::ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); vectorSize = args.getSwitchArgument< unsigned int >("-vector"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); nrAtoms = args.getSwitchArgument< unsigned int >("-atoms"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... -iterations ... -vector ... -max_threads ... -max_items ... -atoms ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = 0; // Allocate host memory std::vector< inputDataType > input(nrAtoms * 4), output(nrAtoms * 4), output_c(nrAtoms * 4); cl::Buffer input_d, output_d; // Populate data structures srand48(time(0)); for ( unsigned int atom = 0; atom < nrAtoms; atom++ ) { input[(atom * 4)] = drand48() * magicValue; input[(atom * 4) + 1] = drand48() * magicValue; input[(atom * 4) + 2] = drand48() * magicValue; input[(atom * 4) + 3] = 0; } // Compute CPU control results std::fill(output.begin(), output.end(), 0); TuneBench::MD(input, output_c, nrAtoms, LJ1, LJ2); std::cout << std::fixed << std::endl; std::cout << "# nrAtoms nrThreadsD0 nrItemsD0 nrItemsD1 GFLOP/s time stdDeviation COV" << std::endl << std::endl; for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) { conf.setNrThreadsD0(threads); for ( unsigned int items = 1; items <= maxItems; items++ ) { conf.setNrItemsD0(items); if ( nrAtoms % (conf.getNrThreadsD0() * conf.getNrItemsD0()) != 0 ) { continue; } for ( unsigned int items = 1; (4 * conf.getNrItemsD0()) + (8 * conf.getNrItemsD0() * items) <= maxItems; items++ ) { conf.setNrItemsD1(items); if ( nrAtoms % (conf.getNrItemsD1()) != 0 ) { continue; } // Generate kernel // The number of operations (21) is not the real number in the code but the number of operations (less) used in the equivalent code from SHOC double gflops = isa::utils::giga(static_cast< uint64_t >(nrAtoms) * nrAtoms * 21); cl::Event clEvent; cl::Kernel * kernel; isa::utils::Timer timer; std::string * code = TuneBench::getMDOpenCL(conf, inputDataName, nrAtoms, LJ1, LJ2); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector< cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("MD", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global(nrAtoms / conf.getNrItemsD0()); cl::NDRange local(conf.getNrThreadsD0()); kernel->setArg(0, input_d); kernel->setArg(1, output_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); timer.stop(); } clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent); clEvent.wait(); } catch ( cl::Error & err ) { reInit = true; std::cerr << "OpenCL kernel execution error ("; std::cerr << conf.print(); std::cerr << "): "; std::cerr << isa::utils::toString(err.err()) << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } break; } delete kernel; bool error = false; for ( unsigned int atom = 0; atom < nrAtoms; atom++ ) { if ( !isa::utils::same(output[atom], output_c[atom]) ) { std::cerr << "Output error (" << conf.print() << ")." << std::endl; error = true; break; } } if ( error ) { continue; } std::cout << nrAtoms << " "; std::cout << conf.print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl; } } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, input->size() * sizeof(inputDataType), 0, 0); clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file TimeWindowCreator.cpp */ #include <Unpacker2/Unpacker2/EventIII.h> #include <JPetWriter/JPetWriter.h> #include "TimeWindowCreator.h" #include <JPetGeomMapping/JPetGeomMapping.h> #include <JPetOptionsTools/JPetOptionsTools.h> using namespace jpet_options_tools; TimeWindowCreator::TimeWindowCreator(const char* name): JPetUserTask(name) {} bool TimeWindowCreator::init() { fOutputEvents = new JPetTimeWindow("JPetSigCh"); /// Reading values from the user options if available if (isOptionSet(fParams.getOptions(), kMaxTimeParamKey)) { fMaxTime = getOptionAsDouble(fParams.getOptions(), kMaxTimeParamKey); } if (isOptionSet(fParams.getOptions(), kMinTimeParamKey)) { fMinTime = getOptionAsDouble(fParams.getOptions(), kMinTimeParamKey); } // take coordinates of the main (irradiated strip) from user parameters if (fParams.getOptions().count(kMainStripKey)) { fMainStripSet = true; int code = boost::any_cast<int>(fParams.getOptions().at(kMainStripKey)); fMainStrip.first = code / 100; // layer number fMainStrip.second = code % 100; // strip number // build a list of allowed channels JPetGeomMapping mapper(fParamManager->getParamBank()); for(int thr=1;thr<=4;++thr){ int tomb_number = mapper.getTOMB(fMainStrip.first, fMainStrip.second, JPetPM::SideA, thr); fAllowedChannels.insert(tomb_number); tomb_number = mapper.getTOMB(fMainStrip.first, fMainStrip.second, JPetPM::SideB, thr); fAllowedChannels.insert(tomb_number); } // add all reference detector channels to allowed channels list for(int thr=1;thr<=4;++thr){ int tomb_number = mapper.getTOMB(4, 1, JPetPM::SideA, thr); fAllowedChannels.insert(tomb_number); tomb_number = mapper.getTOMB(4, 1, JPetPM::SideB, thr); fAllowedChannels.insert(tomb_number); } } getStatistics().createHistogram( new TH1F("HitsPerEvtCh", "Hits per channel in one event", 50, -0.5, 49.5) ); getStatistics().createHistogram( new TH1F("ChannelsPerEvt", "Channels fired in one event", 200, -0.5, 199.5) ); return true; } TimeWindowCreator::~TimeWindowCreator() {} bool TimeWindowCreator::exec() { if (auto evt = dynamic_cast <EventIII * const > (fEvent)) { int ntdc = evt->GetTotalNTDCChannels(); getStatistics().getHisto1D("ChannelsPerEvt").Fill( ntdc ); auto tdcHits = evt->GetTDCChannelsArray(); for (int i = 0; i < ntdc; ++i) { //const is commented because this class has inproper architecture: // all get-methods aren't tagged with const modifier auto tdcChannel = dynamic_cast </*const*/ TDCChannel * const > (tdcHits->At(i)); auto tomb_number = tdcChannel->GetChannel(); if (tomb_number % 65 == 0) { // skip trigger signals from TRB continue; } if ( getParamBank().getTOMBChannels().count(tomb_number) == 0 ) { WARNING(Form("DAQ Channel %d appears in data but does not exist in the setup from DB.", tomb_number)); continue; } JPetTOMBChannel& tomb_channel = getParamBank().getTOMBChannel(tomb_number); // ignore irrelevant channels // (for time calibration) if ( !filter(tomb_channel) ){ continue; } // one TDC channel may record multiple signals in one TSlot // iterate over all signals from one TDC channel // analyze number of hits per channel getStatistics().getHisto1D("HitsPerEvtCh").Fill( tdcChannel->GetHitsNum() ); const int kNumHits = tdcChannel->GetHitsNum(); for (int j = 0; j < kNumHits; ++j) { // check for unreasonable times // the times should be negative (measured w.r.t end of time window) // and not smaller than -1*timeWindowWidth (which can vary for different) // data but shoudl not exceed 1 ms, i.e. 1.e6 ns) if ( tdcChannel->GetLeadTime(j) > fMaxTime || tdcChannel->GetLeadTime(j) < fMinTime )continue; if ( tdcChannel->GetTrailTime(j) > fMaxTime || tdcChannel->GetTrailTime(j) < fMinTime )continue; JPetSigCh sigChTmpLead = generateSigCh(tomb_channel, JPetSigCh::Leading); JPetSigCh sigChTmpTrail = generateSigCh(tomb_channel, JPetSigCh::Trailing); // finally, set the times in ps [raw times are in ns] sigChTmpLead.setValue(tdcChannel->GetLeadTime(j) * 1000.); sigChTmpTrail.setValue(tdcChannel->GetTrailTime(j) * 1000.); fOutputEvents->add<JPetSigCh>(sigChTmpLead); fOutputEvents->add<JPetSigCh>(sigChTmpTrail); } } fCurrEventNumber++; }else{ return false; } return true; } bool TimeWindowCreator::terminate() { return true; } JPetSigCh TimeWindowCreator::generateSigCh(const JPetTOMBChannel& channel, JPetSigCh::EdgeType edge) const { JPetSigCh sigch; sigch.setDAQch(channel.getChannel()); sigch.setType(edge); sigch.setThresholdNumber(channel.getLocalChannelNumber()); sigch.setThreshold(channel.getThreshold()); sigch.setPM(channel.getPM()); sigch.setFEB(channel.getFEB()); sigch.setTRB(channel.getTRB()); sigch.setTOMBChannel(channel); return sigch; } /** * Returns true if signal from the channel given as argument should be passed */ bool TimeWindowCreator::filter(const JPetTOMBChannel& channel) const{ if( !fMainStripSet ){ // if main strip was not defined, pass all channels return true; } if( fAllowedChannels.find(channel.getChannel()) != fAllowedChannels.end() ){ return true; } return false; } <commit_msg>Use options facilities for filtering parameter<commit_after>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file TimeWindowCreator.cpp */ #include <Unpacker2/Unpacker2/EventIII.h> #include <JPetWriter/JPetWriter.h> #include "TimeWindowCreator.h" #include <JPetGeomMapping/JPetGeomMapping.h> #include <JPetOptionsTools/JPetOptionsTools.h> using namespace jpet_options_tools; TimeWindowCreator::TimeWindowCreator(const char* name): JPetUserTask(name) {} bool TimeWindowCreator::init() { fOutputEvents = new JPetTimeWindow("JPetSigCh"); /// Reading values from the user options if available if (isOptionSet(fParams.getOptions(), kMaxTimeParamKey)) { fMaxTime = getOptionAsDouble(fParams.getOptions(), kMaxTimeParamKey); } if (isOptionSet(fParams.getOptions(), kMinTimeParamKey)) { fMinTime = getOptionAsDouble(fParams.getOptions(), kMinTimeParamKey); } // take coordinates of the main (irradiated strip) from user parameters if (isOptionSet(fParams.getOptions(), kMainStripKey)) { fMainStripSet = true; int code = getOptionAsInt(fParams.getOptions(), kMainStripKey); fMainStrip.first = code / 100; // layer number fMainStrip.second = code % 100; // strip number INFO(Form("Filtering of SigCh-s was requested. Only data from strip %d in layer %d will be used.", fMainStrip.second, fMainStrip.first)); // build a list of allowed channels JPetGeomMapping mapper(fParamManager->getParamBank()); for(int thr=1;thr<=4;++thr){ int tomb_number = mapper.getTOMB(fMainStrip.first, fMainStrip.second, JPetPM::SideA, thr); fAllowedChannels.insert(tomb_number); tomb_number = mapper.getTOMB(fMainStrip.first, fMainStrip.second, JPetPM::SideB, thr); fAllowedChannels.insert(tomb_number); } // add all reference detector channels to allowed channels list for(int thr=1;thr<=4;++thr){ int tomb_number = mapper.getTOMB(4, 1, JPetPM::SideA, thr); fAllowedChannels.insert(tomb_number); tomb_number = mapper.getTOMB(4, 1, JPetPM::SideB, thr); fAllowedChannels.insert(tomb_number); } } getStatistics().createHistogram( new TH1F("HitsPerEvtCh", "Hits per channel in one event", 50, -0.5, 49.5) ); getStatistics().createHistogram( new TH1F("ChannelsPerEvt", "Channels fired in one event", 200, -0.5, 199.5) ); return true; } TimeWindowCreator::~TimeWindowCreator() {} bool TimeWindowCreator::exec() { if (auto evt = dynamic_cast <EventIII * const > (fEvent)) { int ntdc = evt->GetTotalNTDCChannels(); getStatistics().getHisto1D("ChannelsPerEvt").Fill( ntdc ); auto tdcHits = evt->GetTDCChannelsArray(); for (int i = 0; i < ntdc; ++i) { //const is commented because this class has inproper architecture: // all get-methods aren't tagged with const modifier auto tdcChannel = dynamic_cast </*const*/ TDCChannel * const > (tdcHits->At(i)); auto tomb_number = tdcChannel->GetChannel(); if (tomb_number % 65 == 0) { // skip trigger signals from TRB continue; } if ( getParamBank().getTOMBChannels().count(tomb_number) == 0 ) { WARNING(Form("DAQ Channel %d appears in data but does not exist in the setup from DB.", tomb_number)); continue; } JPetTOMBChannel& tomb_channel = getParamBank().getTOMBChannel(tomb_number); // ignore irrelevant channels // (for time calibration) if ( !filter(tomb_channel) ){ continue; } // one TDC channel may record multiple signals in one TSlot // iterate over all signals from one TDC channel // analyze number of hits per channel getStatistics().getHisto1D("HitsPerEvtCh").Fill( tdcChannel->GetHitsNum() ); const int kNumHits = tdcChannel->GetHitsNum(); for (int j = 0; j < kNumHits; ++j) { // check for unreasonable times // the times should be negative (measured w.r.t end of time window) // and not smaller than -1*timeWindowWidth (which can vary for different) // data but shoudl not exceed 1 ms, i.e. 1.e6 ns) if ( tdcChannel->GetLeadTime(j) > fMaxTime || tdcChannel->GetLeadTime(j) < fMinTime )continue; if ( tdcChannel->GetTrailTime(j) > fMaxTime || tdcChannel->GetTrailTime(j) < fMinTime )continue; JPetSigCh sigChTmpLead = generateSigCh(tomb_channel, JPetSigCh::Leading); JPetSigCh sigChTmpTrail = generateSigCh(tomb_channel, JPetSigCh::Trailing); // finally, set the times in ps [raw times are in ns] sigChTmpLead.setValue(tdcChannel->GetLeadTime(j) * 1000.); sigChTmpTrail.setValue(tdcChannel->GetTrailTime(j) * 1000.); fOutputEvents->add<JPetSigCh>(sigChTmpLead); fOutputEvents->add<JPetSigCh>(sigChTmpTrail); } } fCurrEventNumber++; }else{ return false; } return true; } bool TimeWindowCreator::terminate() { return true; } JPetSigCh TimeWindowCreator::generateSigCh(const JPetTOMBChannel& channel, JPetSigCh::EdgeType edge) const { JPetSigCh sigch; sigch.setDAQch(channel.getChannel()); sigch.setType(edge); sigch.setThresholdNumber(channel.getLocalChannelNumber()); sigch.setThreshold(channel.getThreshold()); sigch.setPM(channel.getPM()); sigch.setFEB(channel.getFEB()); sigch.setTRB(channel.getTRB()); sigch.setTOMBChannel(channel); return sigch; } /** * Returns true if signal from the channel given as argument should be passed */ bool TimeWindowCreator::filter(const JPetTOMBChannel& channel) const{ if( !fMainStripSet ){ // if main strip was not defined, pass all channels return true; } if( fAllowedChannels.find(channel.getChannel()) != fAllowedChannels.end() ){ return true; } return false; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkNetCDFPOPReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkNetCDFPOPReader - read NetCDF files // .Author Joshua Wu 09.15.2009 // .SECTION Description // vtkNetCDFPOPReader is a source object that reads NetCDF files. // It should be able to read most any NetCDF file that wants to output rectilinear grid // #include "vtkCallbackCommand.h" #include "vtkDataArraySelection.h" #include "netcdf.h" #include "string.h" #include "vtkNetCDFPOPReader.h" #include "vtkFloatArray.h" #include "vtkImageData.h" #include "vtkRectilinearGrid.h" #include "vtkRectilinearGridGeometryFilter.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkMultiThreader.h" vtkCxxRevisionMacro(vtkNetCDFPOPReader, "1.3"); vtkStandardNewMacro(vtkNetCDFPOPReader); //============================================================================ #include <iostream> #define CALL_NETCDF(call) \ { \ int errorcode = call; \ if (errorcode != NC_NOERR) \ { \ vtkErrorMacro(<< "netCDF Error: " << nc_strerror(errorcode)); \ return 0; \ } \ } #define NDIM 4 //============================================================================ //---------------------------------------------------------------------------- //set default values vtkNetCDFPOPReader::vtkNetCDFPOPReader() { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Filename = NULL; this->Origin[0] = this->Origin[1] = this->Origin[2] = 0.0; this->Spacing[0] = this->Spacing[1] = this->Spacing[2] = 1.0; this->Stride[0] = this->Stride[1] = this->Stride[2] = 1; this->BlockReadSize = 4*10; this->VariableArraySelection = vtkSmartPointer<vtkDataArraySelection>::New(); this->SelectionObserver = vtkCallbackCommand::New(); this->SelectionObserver->SetCallback(&vtkNetCDFPOPReader::SelectionModifiedCallback); this->SelectionObserver->SetClientData(this); this->VariableArraySelection->AddObserver(vtkCommand::ModifiedEvent, this->SelectionObserver); for(int f=0;f<100;f++){ //records what variable to output, default is 0, to output is 1 this->draw[f]=0; } } //---------------------------------------------------------------------------- //delete filename and netcdf file descriptor vtkNetCDFPOPReader::~vtkNetCDFPOPReader() { if (this->Filename) { delete[] this->Filename; } nc_close(this->ncFD); this->SelectionObserver->Delete(); } //---------------------------------------------------------------------------- void vtkNetCDFPOPReader::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "FileName: " << (this->Filename ? this->Filename : "(NULL)") << endl; os << indent << "VariableArraySelection:" << endl; this->VariableArraySelection->PrintSelf(os, indent.GetNextIndent()); } //---------------------------------------------------------------------------- // RequestInformation supplies global meta information // This should return the reality of what the reader is going to supply. // This retrieve the extents for the rectilinear grid // NC_MAX_VAR_DIMS comes from the nc library int vtkNetCDFPOPReader::RequestInformation( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector) { vtkInformation* outInfo = outputVector->GetInformationObject(0); int errorcode = nc_open(this->Filename, NC_NOWRITE, &this->ncFD);//read file if (errorcode != NC_NOERR)//checks if read file error { vtkErrorMacro(<< "can't read file " << nc_strerror(errorcode)); } nc_inq_nvars(this->ncFD, &this->nvarsp); // get number of variables from file // int dimId; not used? int dimidsp[NC_MAX_VAR_DIMS]; this->nvarspw=0; int extent[6]; int finaldim; //data dimension int Dimensions[4]; //dimension value // For every variable in the file for(int i=0;i<this->nvarsp;i++){ CALL_NETCDF(nc_inq_varndims(this->ncFD, i, &finaldim));//get number of dimensions CALL_NETCDF(nc_inq_varname(this->ncFD, i, this->VariableName[i])); //get variable name //Variable Dimension ID's containing x,y,z coords for the rectilinear grid spacing CALL_NETCDF(nc_inq_vardimid(this->ncFD, i, dimidsp)); if(finaldim == 3){ strcpy(this->VariableArrayInfo[this->nvarspw], this->VariableName[i]); this->nvarspw++; for(int m=0;m<finaldim;m++){ CALL_NETCDF(nc_inq_dimlen(this->ncFD, dimidsp[m], (size_t*) &Dimensions[m])); //acquire variable dimensions } extent[0] = extent[2] = extent[4] =0; //set extent extent[1] = Dimensions[2] -1; extent[3] = Dimensions[1] -1; extent[5] = Dimensions[0] -1; } } //fill in the extent information outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),extent,6); return 1; } //---------------------------------------------------------------------------- // Setting extents of the rectilinear grid /* int vtkNetCDFPOPReader::RequestUpdateExtent( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); vtkRectilinearGrid *output = vtkRectilinearGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); //retrieves extents from pipeline outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), this->SubExtent); //updates pipeline with extents output->SetExtent(this->SubExtent); return 1; } */ int vtkNetCDFPOPReader::RequestData(vtkInformation* request, vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector ) { // the default implimentation is to do what the old pipeline did find what // output is requesting the data, and pass that into ExecuteData // which output port did the request come from int outputPort = request->Get(vtkDemandDrivenPipeline::FROM_OUTPUT_PORT()); // if output port is negative then that means this filter is calling the // update directly, in that case just assume port 0 if (outputPort == -1) { outputPort = 0; } // get the data object vtkInformation *outInfo = outputVector->GetInformationObject(outputPort); vtkDataObject* output = outInfo->Get(vtkDataObject::DATA_OBJECT()); int varidp[100], dimidsp[NC_MAX_VAR_DIMS]; int subext[6]; //vtkInformation * outInfo = output->GetInformationObject(0); outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),subext); //setup extents for netcdf library to read the netcdf data file size_t start[]= {subext[4], subext[2], subext[0]}; size_t count[]= {subext[5]-subext[4]+1, subext[3]-subext[2]+1, subext[1]-subext[0]+1}; size_t start1[] = {subext[4]}; size_t start2[] = {subext[2]}; size_t start3[] = {subext[0]}; size_t count1[] = {subext[5]-subext[4]+1}; size_t count2[] = {subext[3]-subext[2]+1}; size_t count3[] = {subext[1]-subext[0]+1}; int bytestoallocate = (count[0])*(count[1])*(count[2]); vtkMultiThreaderIDType pid; if ((pid = vtkMultiThreader::GetCurrentThreadID()) < 0) { cerr<< "unable to get pid" << endl; } else { cout << "The process id is " << pid << endl; } cout << "subext " << subext[0] << " " << subext[1] << " " << subext[2] << " " << subext[3] << " " << subext[4] << " " << subext[5] << endl; cout << "floats to allocate" << bytestoallocate << endl; //initialize memory (raw data space, x y z axis space) and rectilinear grid vtkRectilinearGrid *rgrid = vtkRectilinearGrid::SafeDownCast(output); rgrid->SetExtent(subext); //reads data and draws rectilinear grid int counter=0; for(int i=0;i<this->nvarsp;i++){ if(this->draw[i]==1){ nc_inq_varid(this->ncFD, this->VariableName[i], &varidp[i]); nc_inq_vardimid(this->ncFD, varidp[i], dimidsp); if(counter==0){ vtkFloatArray *xCoords = vtkFloatArray::New(); vtkFloatArray *yCoords = vtkFloatArray::New(); vtkFloatArray *zCoords = vtkFloatArray::New(); float *x=new float[count[0]]; //x axis data float *y=new float[count[1]]; //y axis data float *z=new float[count[2]]; //z axis data //gets data from x,y,z axis (spacing) nc_get_vara_float(this->ncFD, dimidsp[0], start1, count1, x); nc_get_vara_float(this->ncFD, dimidsp[1], start2, count2, y); nc_get_vara_float(this->ncFD, dimidsp[2], start3, count3, z); //gets data // sets axis values/spacing for (int o=0; o<subext[1]-subext[0]+1; o++) { xCoords->InsertNextValue(z[o]); } for (int p=0; p<subext[3]-subext[2]+1; p++) { yCoords->InsertNextValue(y[p]); } for (int q=0; q<subext[5]-subext[4]+1; q++) { zCoords->InsertNextValue(-x[q]); } // set dimensions and coordinates // rgrid->SetDimensions(xCoords->GetNumberOfTuples(), yCoords->GetNumberOfTuples(), zCoords->GetNumberOfTuples()); rgrid->SetXCoordinates(xCoords); rgrid->SetYCoordinates(yCoords); rgrid->SetZCoordinates(zCoords); xCoords->Delete(); yCoords->Delete(); zCoords->Delete(); delete [] x; delete [] y; delete [] z; counter++; } //create vtkFloatArray and get the scalars into it vtkFloatArray *myscalars = vtkFloatArray::New(); float* data=new float[bytestoallocate]; //pointer to 3D data if 3D nc_get_vara_float(this->ncFD, varidp[i], start, count, data); myscalars->SetArray(data, bytestoallocate, 0); //set list of variables to display data on rectilinear grid myscalars->SetName(this->VariableName[i]); vtkDataSetAttributes *a=rgrid->GetPointData(); a->AddArray(myscalars); cerr << "---- Executed Data rectilinear grid dataset querries ------" << endl; cerr << "NumberOfPoints:" << rgrid->GetNumberOfPoints() << endl; cerr << "NumberOfCells: " << rgrid->GetNumberOfCells() << endl; cerr << "Dimensions:" << rgrid->GetDimensions()[0] << " " << rgrid->GetDimensions()[1] << " " << rgrid->GetDimensions()[2] << endl; cerr << "---- End Executed Data ------------------------------------" << endl; } } return 1; } //---------------------------------------------------------------------------- //following 5 functions are used for paraview user interface void vtkNetCDFPOPReader::SelectionModifiedCallback(vtkObject*, unsigned long, void* clientdata, void*) { static_cast<vtkNetCDFPOPReader*>(clientdata)->Modified(); } //----------------------------------------------------------------------------- int vtkNetCDFPOPReader::GetNumberOfVariableArrays() { return this->nvarspw; } //----------------------------------------------------------------------------- const char* vtkNetCDFPOPReader::GetVariableArrayName(int index) { return this->VariableArrayInfo[index]; } //----------------------------------------------------------------------------- int vtkNetCDFPOPReader::GetVariableArrayStatus(const char* name) { this->VariableArraySelection->EnableArray(name); return this->VariableArraySelection->ArrayIsEnabled(name); } //----------------------------------------------------------------------------- void vtkNetCDFPOPReader::SetVariableArrayStatus(const char* name, int status) { vtkDebugMacro("Set cell array \"" << name << "\" status to: " << status); if(status) { this->VariableArraySelection->EnableArray(name); } else { this->VariableArraySelection->DisableArray(name); } // vtkDebugMacro("Set cell array \"" << name << "\" status to: " << status); for(int i=0;i<this->nvarsp;i++){ if( strcmp(name, this->VariableName[i])==0 ){ if(status){ status=1; this->draw[i]=1; } else{ status=0; this->draw[i]=0; } } } } <commit_msg>BUG: Fix printself.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkNetCDFPOPReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkNetCDFPOPReader - read NetCDF files // .Author Joshua Wu 09.15.2009 // .SECTION Description // vtkNetCDFPOPReader is a source object that reads NetCDF files. // It should be able to read most any NetCDF file that wants to output rectilinear grid // #include "vtkCallbackCommand.h" #include "vtkDataArraySelection.h" #include "netcdf.h" #include "string.h" #include "vtkNetCDFPOPReader.h" #include "vtkFloatArray.h" #include "vtkImageData.h" #include "vtkRectilinearGrid.h" #include "vtkRectilinearGridGeometryFilter.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkMultiThreader.h" vtkCxxRevisionMacro(vtkNetCDFPOPReader, "1.4"); vtkStandardNewMacro(vtkNetCDFPOPReader); //============================================================================ #include <iostream> #define CALL_NETCDF(call) \ { \ int errorcode = call; \ if (errorcode != NC_NOERR) \ { \ vtkErrorMacro(<< "netCDF Error: " << nc_strerror(errorcode)); \ return 0; \ } \ } #define NDIM 4 //============================================================================ //---------------------------------------------------------------------------- //set default values vtkNetCDFPOPReader::vtkNetCDFPOPReader() { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Filename = NULL; this->Origin[0] = this->Origin[1] = this->Origin[2] = 0.0; this->Spacing[0] = this->Spacing[1] = this->Spacing[2] = 1.0; this->Stride[0] = this->Stride[1] = this->Stride[2] = 1; this->BlockReadSize = 4*10; this->VariableArraySelection = vtkSmartPointer<vtkDataArraySelection>::New(); this->SelectionObserver = vtkCallbackCommand::New(); this->SelectionObserver->SetCallback(&vtkNetCDFPOPReader::SelectionModifiedCallback); this->SelectionObserver->SetClientData(this); this->VariableArraySelection->AddObserver(vtkCommand::ModifiedEvent, this->SelectionObserver); for(int f=0;f<100;f++){ //records what variable to output, default is 0, to output is 1 this->draw[f]=0; } } //---------------------------------------------------------------------------- //delete filename and netcdf file descriptor vtkNetCDFPOPReader::~vtkNetCDFPOPReader() { if (this->Filename) { delete[] this->Filename; } nc_close(this->ncFD); this->SelectionObserver->Delete(); } //---------------------------------------------------------------------------- void vtkNetCDFPOPReader::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "FileName: " << (this->Filename ? this->Filename : "(NULL)") << endl; os << indent << "VariableArraySelection:" << endl; //int WholeExtent[6]; //extents of the rectilinear grid (not implemented) //int SubExtent[6]; //extents of the rectilinear grid //double Origin[3]; //default is 0,0,0 //double Spacing[3]; //default is 1,1,1 //int Stride[3]; // not implemented //int BlockReadSize; //not implemented os << indent << "WholeExtent: {" << this->WholeExtent[0] << ", " << this->WholeExtent[1] << ", " << this->WholeExtent[2] << ", " << this->WholeExtent[3] << ", " << this->WholeExtent[4] << ", " << this->WholeExtent[5] << "}" << endl; os << indent << "SubExtent: {" << this->SubExtent[0] << ", " << this->SubExtent[1] << ", " << this->SubExtent[2] << ", " << this->SubExtent[3] << ", " << this->SubExtent[4] << ", " << this->SubExtent[5] << "}" << endl; os << indent << "Origin: {" << this->Origin[0] << ", " << this->Origin[1] << ", " << this->Origin[2] << ", " << "}" << endl; os << indent << "Spacing: {" << this->Spacing[0] << ", " << this->Spacing[1] << ", " << this->Spacing[2] << ", " << "}" << endl; os << indent << "Stride: {" << this->Stride[0] << ", " << this->Stride[1] << ", " << this->Stride[2] << ", " << "}" << endl; os << indent << "BlockReadSize: " << this->BlockReadSize << endl; this->VariableArraySelection->PrintSelf(os, indent.GetNextIndent()); } //---------------------------------------------------------------------------- // RequestInformation supplies global meta information // This should return the reality of what the reader is going to supply. // This retrieve the extents for the rectilinear grid // NC_MAX_VAR_DIMS comes from the nc library int vtkNetCDFPOPReader::RequestInformation( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector) { vtkInformation* outInfo = outputVector->GetInformationObject(0); int errorcode = nc_open(this->Filename, NC_NOWRITE, &this->ncFD);//read file if (errorcode != NC_NOERR)//checks if read file error { vtkErrorMacro(<< "can't read file " << nc_strerror(errorcode)); } nc_inq_nvars(this->ncFD, &this->nvarsp); // get number of variables from file // int dimId; not used? int dimidsp[NC_MAX_VAR_DIMS]; this->nvarspw=0; int extent[6]; int finaldim; //data dimension int Dimensions[4]; //dimension value // For every variable in the file for(int i=0;i<this->nvarsp;i++){ CALL_NETCDF(nc_inq_varndims(this->ncFD, i, &finaldim));//get number of dimensions CALL_NETCDF(nc_inq_varname(this->ncFD, i, this->VariableName[i])); //get variable name //Variable Dimension ID's containing x,y,z coords for the rectilinear grid spacing CALL_NETCDF(nc_inq_vardimid(this->ncFD, i, dimidsp)); if(finaldim == 3){ strcpy(this->VariableArrayInfo[this->nvarspw], this->VariableName[i]); this->nvarspw++; for(int m=0;m<finaldim;m++){ CALL_NETCDF(nc_inq_dimlen(this->ncFD, dimidsp[m], (size_t*) &Dimensions[m])); //acquire variable dimensions } extent[0] = extent[2] = extent[4] =0; //set extent extent[1] = Dimensions[2] -1; extent[3] = Dimensions[1] -1; extent[5] = Dimensions[0] -1; } } //fill in the extent information outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),extent,6); return 1; } //---------------------------------------------------------------------------- // Setting extents of the rectilinear grid /* int vtkNetCDFPOPReader::RequestUpdateExtent( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); vtkRectilinearGrid *output = vtkRectilinearGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); //retrieves extents from pipeline outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), this->SubExtent); //updates pipeline with extents output->SetExtent(this->SubExtent); return 1; } */ int vtkNetCDFPOPReader::RequestData(vtkInformation* request, vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector ) { // the default implimentation is to do what the old pipeline did find what // output is requesting the data, and pass that into ExecuteData // which output port did the request come from int outputPort = request->Get(vtkDemandDrivenPipeline::FROM_OUTPUT_PORT()); // if output port is negative then that means this filter is calling the // update directly, in that case just assume port 0 if (outputPort == -1) { outputPort = 0; } // get the data object vtkInformation *outInfo = outputVector->GetInformationObject(outputPort); vtkDataObject* output = outInfo->Get(vtkDataObject::DATA_OBJECT()); int varidp[100], dimidsp[NC_MAX_VAR_DIMS]; int subext[6]; //vtkInformation * outInfo = output->GetInformationObject(0); outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),subext); //setup extents for netcdf library to read the netcdf data file size_t start[]= {subext[4], subext[2], subext[0]}; size_t count[]= {subext[5]-subext[4]+1, subext[3]-subext[2]+1, subext[1]-subext[0]+1}; size_t start1[] = {subext[4]}; size_t start2[] = {subext[2]}; size_t start3[] = {subext[0]}; size_t count1[] = {subext[5]-subext[4]+1}; size_t count2[] = {subext[3]-subext[2]+1}; size_t count3[] = {subext[1]-subext[0]+1}; int bytestoallocate = (count[0])*(count[1])*(count[2]); vtkMultiThreaderIDType pid; if ((pid = vtkMultiThreader::GetCurrentThreadID()) < 0) { cerr<< "unable to get pid" << endl; } else { cout << "The process id is " << pid << endl; } cout << "subext " << subext[0] << " " << subext[1] << " " << subext[2] << " " << subext[3] << " " << subext[4] << " " << subext[5] << endl; cout << "floats to allocate" << bytestoallocate << endl; //initialize memory (raw data space, x y z axis space) and rectilinear grid vtkRectilinearGrid *rgrid = vtkRectilinearGrid::SafeDownCast(output); rgrid->SetExtent(subext); //reads data and draws rectilinear grid int counter=0; for(int i=0;i<this->nvarsp;i++){ if(this->draw[i]==1){ nc_inq_varid(this->ncFD, this->VariableName[i], &varidp[i]); nc_inq_vardimid(this->ncFD, varidp[i], dimidsp); if(counter==0){ vtkFloatArray *xCoords = vtkFloatArray::New(); vtkFloatArray *yCoords = vtkFloatArray::New(); vtkFloatArray *zCoords = vtkFloatArray::New(); float *x=new float[count[0]]; //x axis data float *y=new float[count[1]]; //y axis data float *z=new float[count[2]]; //z axis data //gets data from x,y,z axis (spacing) nc_get_vara_float(this->ncFD, dimidsp[0], start1, count1, x); nc_get_vara_float(this->ncFD, dimidsp[1], start2, count2, y); nc_get_vara_float(this->ncFD, dimidsp[2], start3, count3, z); //gets data // sets axis values/spacing for (int o=0; o<subext[1]-subext[0]+1; o++) { xCoords->InsertNextValue(z[o]); } for (int p=0; p<subext[3]-subext[2]+1; p++) { yCoords->InsertNextValue(y[p]); } for (int q=0; q<subext[5]-subext[4]+1; q++) { zCoords->InsertNextValue(-x[q]); } // set dimensions and coordinates // rgrid->SetDimensions(xCoords->GetNumberOfTuples(), yCoords->GetNumberOfTuples(), zCoords->GetNumberOfTuples()); rgrid->SetXCoordinates(xCoords); rgrid->SetYCoordinates(yCoords); rgrid->SetZCoordinates(zCoords); xCoords->Delete(); yCoords->Delete(); zCoords->Delete(); delete [] x; delete [] y; delete [] z; counter++; } //create vtkFloatArray and get the scalars into it vtkFloatArray *myscalars = vtkFloatArray::New(); float* data=new float[bytestoallocate]; //pointer to 3D data if 3D nc_get_vara_float(this->ncFD, varidp[i], start, count, data); myscalars->SetArray(data, bytestoallocate, 0); //set list of variables to display data on rectilinear grid myscalars->SetName(this->VariableName[i]); vtkDataSetAttributes *a=rgrid->GetPointData(); a->AddArray(myscalars); cerr << "---- Executed Data rectilinear grid dataset querries ------" << endl; cerr << "NumberOfPoints:" << rgrid->GetNumberOfPoints() << endl; cerr << "NumberOfCells: " << rgrid->GetNumberOfCells() << endl; cerr << "Dimensions:" << rgrid->GetDimensions()[0] << " " << rgrid->GetDimensions()[1] << " " << rgrid->GetDimensions()[2] << endl; cerr << "---- End Executed Data ------------------------------------" << endl; } } return 1; } //---------------------------------------------------------------------------- //following 5 functions are used for paraview user interface void vtkNetCDFPOPReader::SelectionModifiedCallback(vtkObject*, unsigned long, void* clientdata, void*) { static_cast<vtkNetCDFPOPReader*>(clientdata)->Modified(); } //----------------------------------------------------------------------------- int vtkNetCDFPOPReader::GetNumberOfVariableArrays() { return this->nvarspw; } //----------------------------------------------------------------------------- const char* vtkNetCDFPOPReader::GetVariableArrayName(int index) { return this->VariableArrayInfo[index]; } //----------------------------------------------------------------------------- int vtkNetCDFPOPReader::GetVariableArrayStatus(const char* name) { this->VariableArraySelection->EnableArray(name); return this->VariableArraySelection->ArrayIsEnabled(name); } //----------------------------------------------------------------------------- void vtkNetCDFPOPReader::SetVariableArrayStatus(const char* name, int status) { vtkDebugMacro("Set cell array \"" << name << "\" status to: " << status); if(status) { this->VariableArraySelection->EnableArray(name); } else { this->VariableArraySelection->DisableArray(name); } // vtkDebugMacro("Set cell array \"" << name << "\" status to: " << status); for(int i=0;i<this->nvarsp;i++){ if( strcmp(name, this->VariableName[i])==0 ){ if(status){ status=1; this->draw[i]=1; } else{ status=0; this->draw[i]=0; } } } } <|endoftext|>
<commit_before>// // Copyright Renga Software LLC, 2016. All rights reserved. // // Renga Software LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // Renga Software LLC DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // #include "stdafx.h" #include "ObjectPropertyViewBuilder.h" #include <RengaAPI/Materials.h> #include <RengaAPI/Project.h> #include <RengaAPI/UserAttributeRegister.h> #include <RengaAPI/UserAttributeDescription.h> #include <RengaBase/AreaMeasure.h> #include <RengaBase/LengthMeasure.h> #include <RengaBase/VolumeMeasure.h> ObjectPropertyViewBuilder::ObjectPropertyViewBuilder(const PropertyManagers* pPropertyManagers) : m_pPropertyManagers(pPropertyManagers) {} PropertyList ObjectPropertyViewBuilder::createUserAttributesProperties(rengaapi::ModelObject* pObject) { PropertyList pResult; rengaapi::UserAttributeRegister userAttributeRegister = rengaapi::Project::userAttributeRegister(); rengaapi::UserAttributeIdCollection attributeCollection = userAttributeRegister.attributes(); // block signals before filling properties m_pPropertyManagers->m_pStringUserAttributeManager->blockSignals(true); m_pPropertyManagers->m_pDoubleUserAttributeManager->blockSignals(true); // check all attributes for (size_t i = 0; i < attributeCollection.size(); ++i) { const rengaapi::UserAttributeId& attributeId = attributeCollection.get(i); // check if objectType has attribute if (userAttributeRegister.typeHasAttribute(pObject->type(), attributeId)) { rengaapi::UserAttributeDescription userAttributeDescription; // get attribute description if (userAttributeRegister.attributeDescription(attributeId, userAttributeDescription).code() == rengaapi::Status::Success) { rengaapi::UserAttributeValue userAttributeValue; // check if object has value for current attribute rengaapi::Status status = pObject->getUserAttributeValue(attributeId, userAttributeValue); QtProperty* pUserAttributeProperty = nullptr; QString attributeName = rengaStringToQString(userAttributeDescription.name()); switch (userAttributeDescription.type()) { case rengaapi::UserAttributeType::Double: { pUserAttributeProperty = m_pPropertyManagers->m_pDoubleUserAttributeManager->addProperty(attributeName); if (status.code() == rengaapi::Status::Success) { m_pPropertyManagers->m_pDoubleUserAttributeManager->setValue(pUserAttributeProperty, userAttributeValue.asDouble()); } pUserAttributeProperty->setModified(true); pUserAttributeProperty->setData(rengaStringToQString(attributeId.id().toString())); } break; case rengaapi::UserAttributeType::String: { pUserAttributeProperty = m_pPropertyManagers->m_pStringUserAttributeManager->addProperty(attributeName); if (status.code() == rengaapi::Status::Success) { m_pPropertyManagers->m_pStringUserAttributeManager->setValue(pUserAttributeProperty, rengaStringToQString(userAttributeValue.asString())); } pUserAttributeProperty->setModified(true); pUserAttributeProperty->setData(rengaStringToQString(attributeId.id().toString())); } break; default: assert(false); } if (pUserAttributeProperty != nullptr) pResult.push_back(pUserAttributeProperty); } } } // unblock signals m_pPropertyManagers->m_pDoubleUserAttributeManager->blockSignals(false); m_pPropertyManagers->m_pStringUserAttributeManager->blockSignals(false); return pResult; } QString ObjectPropertyViewBuilder::getMaterialName(const rengaapi::MaterialId& materialId) { rengaapi::Materials::MaterialType materialType= rengaapi::Materials::materialType(materialId); QString resultString = QString(); switch(materialType) { case rengaapi::Materials::MaterialType::Grid: { rengaapi::GridMaterial gridMaterial; rengaapi::Materials::gridMaterial(materialId, gridMaterial); // grid materials are nameless, return collection name resultString = rengaStringToQString(materialId.collectionName()); } break; case rengaapi::Materials::MaterialType::OneLayered: { rengaapi::Material material; rengaapi::Materials::material(materialId, material); resultString = rengaStringToQString(material.name_()); } break; case rengaapi::Materials::MaterialType::MultiLayered: { rengaapi::LayeredMaterial layeredMaterial; rengaapi::Materials::layeredMaterial(materialId, layeredMaterial); resultString = rengaStringToQString(layeredMaterial.name_()); } break; } return resultString; } void ObjectPropertyViewBuilder::setLengthMeasureOptional(PropertyList& insertPlace, const rengabase::LengthMeasureOptional& measure, QtProperty* pProperty, MeasureUnit unit) { if (measure.hasValue()) { const rengabase::LengthMeasure* lengthMeasure = measure.getValue(); double propertyValue; switch (unit) { case Meter: propertyValue = lengthMeasure->inMeters(); break; case Centimeter: propertyValue = lengthMeasure->inCentimeters(); break; case Inch: propertyValue = lengthMeasure->inInches(); break; case Millimeter: default: propertyValue = lengthMeasure->inMillimeters(); break; } m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, propertyValue); insertPlace.push_back(pProperty); } } void ObjectPropertyViewBuilder::setAreaMeasureOptional(PropertyList& insertPlace, const rengabase::AreaMeasureOptional& measure, QtProperty* pProperty, MeasureUnit unit) { if (measure.hasValue()) { const rengabase::AreaMeasure* areaMeasure = measure.getValue(); double propertyValue; switch (unit) { case Centimeter: propertyValue = areaMeasure->inCentimeters2(); break; case Millimeter: propertyValue = areaMeasure->inMillimeters2(); break; case Meter: default: propertyValue = areaMeasure->inMeters2(); break; } m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, propertyValue); insertPlace.push_back(pProperty); } } void ObjectPropertyViewBuilder::setVolumeMeasureOptional(PropertyList& insertPlace, const rengabase::VolumeMeasureOptional& measure, QtProperty* pProperty, MeasureUnit unit) { if (measure.hasValue()) { const rengabase::VolumeMeasure* volumeMeasure = measure.getValue(); double propertyValue; switch (unit) { case Centimeter: propertyValue = volumeMeasure->inCentimeters3(); break; case Millimeter: propertyValue = volumeMeasure->inMillimeters3(); break; case Meter: default: propertyValue = volumeMeasure->inMeters3(); break; } m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, propertyValue); insertPlace.push_back(pProperty); } } void ObjectPropertyViewBuilder::setOneLayeredMass(PropertyList& insertPlace, const rengaapi::MaterialId& materialId, const rengabase::VolumeMeasureOptional& volumeMeasure, QtProperty* pProperty) { assert(rengaapi::Materials::materialType(materialId) == rengaapi::Materials::MaterialType::OneLayered); if (!volumeMeasure.hasValue()) return; rengaapi::Material material; rengaapi::Materials::material(materialId, material); if (material.isNull()) return; double mass = material.density() * volumeMeasure.getValue()->inMeters3(); m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, mass); insertPlace.push_back(pProperty); } void ObjectPropertyViewBuilder::setMultiLayeredMass(PropertyList& insertPlace, const rengaapi::MaterialId& materialId, const std::vector<rengabase::VolumeMeasureOptional> volumeMeasureCollection, QtProperty* pProperty) { assert (rengaapi::Materials::materialType(materialId) == rengaapi::Materials::MaterialType::MultiLayered); rengaapi::LayeredMaterial layeredMaterial; rengaapi::Materials::layeredMaterial(materialId, layeredMaterial); if (layeredMaterial.isNull()) return; rengaapi::MaterialLayersCollection materialLayers = layeredMaterial.layers(); assert(volumeMeasureCollection.size() == materialLayers.size()); double mass = 0.0; for(size_t i = 0; i < materialLayers.size(); ++i) { if (volumeMeasureCollection[i].hasValue()) { rengaapi::Material materialLayer = materialLayers.get(i).material(); if (!materialLayer.isNull()) mass += materialLayer.density() * volumeMeasureCollection[i].getValue()->inMeters3(); } } m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, mass); insertPlace.push_back(pProperty); }<commit_msg>- workaround for a case when Renga cannot calculate layers volume<commit_after>// // Copyright Renga Software LLC, 2016. All rights reserved. // // Renga Software LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // Renga Software LLC DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // #include "stdafx.h" #include "ObjectPropertyViewBuilder.h" #include <RengaAPI/Materials.h> #include <RengaAPI/Project.h> #include <RengaAPI/UserAttributeRegister.h> #include <RengaAPI/UserAttributeDescription.h> #include <RengaBase/AreaMeasure.h> #include <RengaBase/LengthMeasure.h> #include <RengaBase/VolumeMeasure.h> ObjectPropertyViewBuilder::ObjectPropertyViewBuilder(const PropertyManagers* pPropertyManagers) : m_pPropertyManagers(pPropertyManagers) {} PropertyList ObjectPropertyViewBuilder::createUserAttributesProperties(rengaapi::ModelObject* pObject) { PropertyList pResult; rengaapi::UserAttributeRegister userAttributeRegister = rengaapi::Project::userAttributeRegister(); rengaapi::UserAttributeIdCollection attributeCollection = userAttributeRegister.attributes(); // block signals before filling properties m_pPropertyManagers->m_pStringUserAttributeManager->blockSignals(true); m_pPropertyManagers->m_pDoubleUserAttributeManager->blockSignals(true); // check all attributes for (size_t i = 0; i < attributeCollection.size(); ++i) { const rengaapi::UserAttributeId& attributeId = attributeCollection.get(i); // check if objectType has attribute if (userAttributeRegister.typeHasAttribute(pObject->type(), attributeId)) { rengaapi::UserAttributeDescription userAttributeDescription; // get attribute description if (userAttributeRegister.attributeDescription(attributeId, userAttributeDescription).code() == rengaapi::Status::Success) { rengaapi::UserAttributeValue userAttributeValue; // check if object has value for current attribute rengaapi::Status status = pObject->getUserAttributeValue(attributeId, userAttributeValue); QtProperty* pUserAttributeProperty = nullptr; QString attributeName = rengaStringToQString(userAttributeDescription.name()); switch (userAttributeDescription.type()) { case rengaapi::UserAttributeType::Double: { pUserAttributeProperty = m_pPropertyManagers->m_pDoubleUserAttributeManager->addProperty(attributeName); if (status.code() == rengaapi::Status::Success) { m_pPropertyManagers->m_pDoubleUserAttributeManager->setValue(pUserAttributeProperty, userAttributeValue.asDouble()); } pUserAttributeProperty->setModified(true); pUserAttributeProperty->setData(rengaStringToQString(attributeId.id().toString())); } break; case rengaapi::UserAttributeType::String: { pUserAttributeProperty = m_pPropertyManagers->m_pStringUserAttributeManager->addProperty(attributeName); if (status.code() == rengaapi::Status::Success) { m_pPropertyManagers->m_pStringUserAttributeManager->setValue(pUserAttributeProperty, rengaStringToQString(userAttributeValue.asString())); } pUserAttributeProperty->setModified(true); pUserAttributeProperty->setData(rengaStringToQString(attributeId.id().toString())); } break; default: assert(false); } if (pUserAttributeProperty != nullptr) pResult.push_back(pUserAttributeProperty); } } } // unblock signals m_pPropertyManagers->m_pDoubleUserAttributeManager->blockSignals(false); m_pPropertyManagers->m_pStringUserAttributeManager->blockSignals(false); return pResult; } QString ObjectPropertyViewBuilder::getMaterialName(const rengaapi::MaterialId& materialId) { rengaapi::Materials::MaterialType materialType= rengaapi::Materials::materialType(materialId); QString resultString = QString(); switch(materialType) { case rengaapi::Materials::MaterialType::Grid: { rengaapi::GridMaterial gridMaterial; rengaapi::Materials::gridMaterial(materialId, gridMaterial); // grid materials are nameless, return collection name resultString = rengaStringToQString(materialId.collectionName()); } break; case rengaapi::Materials::MaterialType::OneLayered: { rengaapi::Material material; rengaapi::Materials::material(materialId, material); resultString = rengaStringToQString(material.name_()); } break; case rengaapi::Materials::MaterialType::MultiLayered: { rengaapi::LayeredMaterial layeredMaterial; rengaapi::Materials::layeredMaterial(materialId, layeredMaterial); resultString = rengaStringToQString(layeredMaterial.name_()); } break; } return resultString; } void ObjectPropertyViewBuilder::setLengthMeasureOptional(PropertyList& insertPlace, const rengabase::LengthMeasureOptional& measure, QtProperty* pProperty, MeasureUnit unit) { if (measure.hasValue()) { const rengabase::LengthMeasure* lengthMeasure = measure.getValue(); double propertyValue; switch (unit) { case Meter: propertyValue = lengthMeasure->inMeters(); break; case Centimeter: propertyValue = lengthMeasure->inCentimeters(); break; case Inch: propertyValue = lengthMeasure->inInches(); break; case Millimeter: default: propertyValue = lengthMeasure->inMillimeters(); break; } m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, propertyValue); insertPlace.push_back(pProperty); } } void ObjectPropertyViewBuilder::setAreaMeasureOptional(PropertyList& insertPlace, const rengabase::AreaMeasureOptional& measure, QtProperty* pProperty, MeasureUnit unit) { if (measure.hasValue()) { const rengabase::AreaMeasure* areaMeasure = measure.getValue(); double propertyValue; switch (unit) { case Centimeter: propertyValue = areaMeasure->inCentimeters2(); break; case Millimeter: propertyValue = areaMeasure->inMillimeters2(); break; case Meter: default: propertyValue = areaMeasure->inMeters2(); break; } m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, propertyValue); insertPlace.push_back(pProperty); } } void ObjectPropertyViewBuilder::setVolumeMeasureOptional(PropertyList& insertPlace, const rengabase::VolumeMeasureOptional& measure, QtProperty* pProperty, MeasureUnit unit) { if (measure.hasValue()) { const rengabase::VolumeMeasure* volumeMeasure = measure.getValue(); double propertyValue; switch (unit) { case Centimeter: propertyValue = volumeMeasure->inCentimeters3(); break; case Millimeter: propertyValue = volumeMeasure->inMillimeters3(); break; case Meter: default: propertyValue = volumeMeasure->inMeters3(); break; } m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, propertyValue); insertPlace.push_back(pProperty); } } void ObjectPropertyViewBuilder::setOneLayeredMass(PropertyList& insertPlace, const rengaapi::MaterialId& materialId, const rengabase::VolumeMeasureOptional& volumeMeasure, QtProperty* pProperty) { assert(rengaapi::Materials::materialType(materialId) == rengaapi::Materials::MaterialType::OneLayered); if (!volumeMeasure.hasValue()) return; rengaapi::Material material; rengaapi::Materials::material(materialId, material); if (material.isNull()) return; double mass = material.density() * volumeMeasure.getValue()->inMeters3(); m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, mass); insertPlace.push_back(pProperty); } void ObjectPropertyViewBuilder::setMultiLayeredMass(PropertyList& insertPlace, const rengaapi::MaterialId& materialId, const std::vector<rengabase::VolumeMeasureOptional> volumeMeasureCollection, QtProperty* pProperty) { assert (rengaapi::Materials::materialType(materialId) == rengaapi::Materials::MaterialType::MultiLayered); rengaapi::LayeredMaterial layeredMaterial; rengaapi::Materials::layeredMaterial(materialId, layeredMaterial); if (layeredMaterial.isNull()) return; rengaapi::MaterialLayersCollection materialLayers = layeredMaterial.layers(); if (volumeMeasureCollection.size() != materialLayers.size()) return; double mass = 0.0; for(size_t i = 0; i < materialLayers.size(); ++i) { if (volumeMeasureCollection[i].hasValue()) { rengaapi::Material materialLayer = materialLayers.get(i).material(); if (!materialLayer.isNull()) mass += materialLayer.density() * volumeMeasureCollection[i].getValue()->inMeters3(); } } m_pPropertyManagers->m_pDoubleManager->setValue(pProperty, mass); insertPlace.push_back(pProperty); }<|endoftext|>
<commit_before>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbGeometryMetadata.h" #include <iostream> namespace { constexpr int STRING_PRECISION = 20; // the precision of std::to_string is limited to 6 digits template <typename T> std::string to_string_with_precision(const T value) { std::ostringstream out; out.precision(STRING_PRECISION); out << std::fixed << value; return out.str(); } template<class T> void KeywordlistToVector(std::vector<T> & vector, const otb::MetaData::Keywordlist & kwl, const std::string & prefix) { vector.clear(); const auto size = std::stoi(kwl.at(prefix + ".number")); for (int i = 0; i < size; i++) { auto t = T::FromKeywordlist(kwl, prefix + "_" + to_string_with_precision(i) + "."); vector.push_back(t); } } template <class T> void VectorToKeywordList(otb::MetaData::Keywordlist & kwl, const std::vector<T> & input, const std::string & prefix) { int i = 0; for (const auto & elem: input) { elem.ToKeywordlist(kwl, prefix + "_" + to_string_with_precision(i) + "."); i++; } kwl.insert({prefix + ".number" , to_string_with_precision(i)}); } } namespace otb { GCP::GCP(std::string id, std::string info, double col, double row, double px, double py, double pz) : m_Id(move(id)), m_Info(move(info)), m_GCPCol(col), m_GCPRow(row), m_GCPX(px), m_GCPY(py), m_GCPZ(pz) { } void GCP::Print(std::ostream& os) const { os << " GCP Id = " << this->m_Id << std::endl; os << " GCP Info = " << this->m_Info << std::endl; os << " GCP (Row, Col) = (" << this->m_GCPRow << "," << this->m_GCPCol << ")" << std::endl; os << " GCP (X, Y, Z) = (" << this->m_GCPX << "," << this->m_GCPY << "," << this->m_GCPZ << ")" << std::endl; } std::string GCP::ToJSON(bool multiline) const { std::ostringstream oss; std::string sep; if (multiline) { sep = "\n"; } oss << "{" << "\"GCP_Id\": \"" << this->m_Id << "\", " << sep << "\"GCP_Info\": \"" << this->m_Info << "\", " << sep << "\"GCP_Row\": \"" << this->m_GCPRow << "\", " << sep << "\"GCP_Col\": \"" << this->m_GCPCol << "\", " << sep << "\"GCP_X\": \"" << this->m_GCPX << "\", " << sep << "\"GCP_Y\": \"" << this->m_GCPY << "\", " << sep << "\"GCP_Z\": \"" << this->m_GCPZ << "\", " << sep << "}"; return oss.str(); } void GCP::ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix) const { kwl.insert({prefix + "Id", m_Id}); kwl.insert({prefix + "Info", m_Info}); kwl.insert({prefix + "Row", to_string_with_precision(m_GCPRow)}); kwl.insert({prefix + "Col", to_string_with_precision(m_GCPCol)}); kwl.insert({prefix + "X", to_string_with_precision(m_GCPX)}); kwl.insert({prefix + "Y", to_string_with_precision(m_GCPY)}); kwl.insert({prefix + "Z", to_string_with_precision(m_GCPZ)}); } GCP GCP::FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix) { //Info is optional in GCPs, the key might not be in the keywordlist std::string info; auto infoFound = kwl.find(prefix + "Info"); if (infoFound != kwl.end()) { info = infoFound->second; } return GCP(kwl.at(prefix + "Id"), info, std::stod(kwl.at(prefix + "Row")), std::stod(kwl.at(prefix + "Col")), std::stod(kwl.at(prefix + "X")), std::stod(kwl.at(prefix + "Y")), std::stod(kwl.at(prefix + "Z"))); } namespace Projection { std::string GCPParam::ToJSON(bool multiline) const { std::ostringstream oss; std::string sep; if (multiline) { sep = "\n"; } oss << "{" << "\"Projection\": \"" << GCPProjection << "\", " << sep << "["; for (const auto& gcp : GCPs) oss << gcp.ToJSON() << ", " << sep; oss << "]}"; return oss.str(); } void GCPParam::ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix) const { kwl.insert({prefix + "GCPProjection", GCPProjection}); VectorToKeywordList(kwl, GCPs, prefix + "GCP"); } void GCPParam::FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix) { GCPProjection = kwl.at(prefix + "GCPProjection"); KeywordlistToVector(GCPs, kwl, prefix + "GCP"); } std::string RPCParam::ToJSON(bool multiline) const { std::ostringstream oss; std::string sep; if (multiline) { sep = "\n"; } oss << "{" << "\"LineOffset\": \"" << LineOffset << "\", " << sep << "\"SampleOffset\": \"" << SampleOffset << "\", " << sep << "\"LatOffset\": \"" << LatOffset << "\", " << sep << "\"LonOffset\": \"" << LonOffset << "\", " << sep << "\"HeightOffset\": \"" << HeightOffset << "\", " << sep << "\"LineScale\": \"" << LineScale << "\", " << sep << "\"SampleScale\": \"" << SampleScale << "\", " << sep << "\"LatScale\": \"" << LatScale << "\", " << sep << "\"LonScale\": \"" << LonScale << "\", " << sep << "\"HeightScale\": \"" << HeightScale << "\", " << sep << "\"LineNum\": " << doubleArrayToString(LineNum) << ", " << sep << "\"LineDen\": " << doubleArrayToString(LineDen) << ", " << sep << "\"SampleNum\": " << doubleArrayToString(SampleNum) << ", " << sep << "\"SampleDen\": " << doubleArrayToString(SampleDen) << ", " << sep << "}"; return oss.str(); } } // end namespace Projection } // end namespace otb <commit_msg>BUG: fix inverted coordinates in GCP<commit_after>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbGeometryMetadata.h" #include <iostream> namespace { constexpr int STRING_PRECISION = 20; // the precision of std::to_string is limited to 6 digits template <typename T> std::string to_string_with_precision(const T value) { std::ostringstream out; out.precision(STRING_PRECISION); out << std::fixed << value; return out.str(); } template<class T> void KeywordlistToVector(std::vector<T> & vector, const otb::MetaData::Keywordlist & kwl, const std::string & prefix) { vector.clear(); const auto size = std::stoi(kwl.at(prefix + ".number")); for (int i = 0; i < size; i++) { auto t = T::FromKeywordlist(kwl, prefix + "_" + to_string_with_precision(i) + "."); vector.push_back(t); } } template <class T> void VectorToKeywordList(otb::MetaData::Keywordlist & kwl, const std::vector<T> & input, const std::string & prefix) { int i = 0; for (const auto & elem: input) { elem.ToKeywordlist(kwl, prefix + "_" + to_string_with_precision(i) + "."); i++; } kwl.insert({prefix + ".number" , to_string_with_precision(i)}); } } namespace otb { GCP::GCP(std::string id, std::string info, double col, double row, double px, double py, double pz) : m_Id(move(id)), m_Info(move(info)), m_GCPCol(col), m_GCPRow(row), m_GCPX(px), m_GCPY(py), m_GCPZ(pz) { } void GCP::Print(std::ostream& os) const { os << " GCP Id = " << this->m_Id << std::endl; os << " GCP Info = " << this->m_Info << std::endl; os << " GCP (Row, Col) = (" << this->m_GCPRow << "," << this->m_GCPCol << ")" << std::endl; os << " GCP (X, Y, Z) = (" << this->m_GCPX << "," << this->m_GCPY << "," << this->m_GCPZ << ")" << std::endl; } std::string GCP::ToJSON(bool multiline) const { std::ostringstream oss; std::string sep; if (multiline) { sep = "\n"; } oss << "{" << "\"GCP_Id\": \"" << this->m_Id << "\", " << sep << "\"GCP_Info\": \"" << this->m_Info << "\", " << sep << "\"GCP_Row\": \"" << this->m_GCPRow << "\", " << sep << "\"GCP_Col\": \"" << this->m_GCPCol << "\", " << sep << "\"GCP_X\": \"" << this->m_GCPX << "\", " << sep << "\"GCP_Y\": \"" << this->m_GCPY << "\", " << sep << "\"GCP_Z\": \"" << this->m_GCPZ << "\", " << sep << "}"; return oss.str(); } void GCP::ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix) const { kwl.insert({prefix + "Id", m_Id}); kwl.insert({prefix + "Info", m_Info}); kwl.insert({prefix + "Row", to_string_with_precision(m_GCPRow)}); kwl.insert({prefix + "Col", to_string_with_precision(m_GCPCol)}); kwl.insert({prefix + "X", to_string_with_precision(m_GCPX)}); kwl.insert({prefix + "Y", to_string_with_precision(m_GCPY)}); kwl.insert({prefix + "Z", to_string_with_precision(m_GCPZ)}); } GCP GCP::FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix) { //Info is optional in GCPs, the key might not be in the keywordlist std::string info; auto infoFound = kwl.find(prefix + "Info"); if (infoFound != kwl.end()) { info = infoFound->second; } return GCP(kwl.at(prefix + "Id"), info, std::stod(kwl.at(prefix + "Col")), std::stod(kwl.at(prefix + "Row")), std::stod(kwl.at(prefix + "X")), std::stod(kwl.at(prefix + "Y")), std::stod(kwl.at(prefix + "Z"))); } namespace Projection { std::string GCPParam::ToJSON(bool multiline) const { std::ostringstream oss; std::string sep; if (multiline) { sep = "\n"; } oss << "{" << "\"Projection\": \"" << GCPProjection << "\", " << sep << "["; for (const auto& gcp : GCPs) oss << gcp.ToJSON() << ", " << sep; oss << "]}"; return oss.str(); } void GCPParam::ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix) const { kwl.insert({prefix + "GCPProjection", GCPProjection}); VectorToKeywordList(kwl, GCPs, prefix + "GCP"); } void GCPParam::FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix) { GCPProjection = kwl.at(prefix + "GCPProjection"); KeywordlistToVector(GCPs, kwl, prefix + "GCP"); } std::string RPCParam::ToJSON(bool multiline) const { std::ostringstream oss; std::string sep; if (multiline) { sep = "\n"; } oss << "{" << "\"LineOffset\": \"" << LineOffset << "\", " << sep << "\"SampleOffset\": \"" << SampleOffset << "\", " << sep << "\"LatOffset\": \"" << LatOffset << "\", " << sep << "\"LonOffset\": \"" << LonOffset << "\", " << sep << "\"HeightOffset\": \"" << HeightOffset << "\", " << sep << "\"LineScale\": \"" << LineScale << "\", " << sep << "\"SampleScale\": \"" << SampleScale << "\", " << sep << "\"LatScale\": \"" << LatScale << "\", " << sep << "\"LonScale\": \"" << LonScale << "\", " << sep << "\"HeightScale\": \"" << HeightScale << "\", " << sep << "\"LineNum\": " << doubleArrayToString(LineNum) << ", " << sep << "\"LineDen\": " << doubleArrayToString(LineDen) << ", " << sep << "\"SampleNum\": " << doubleArrayToString(SampleNum) << ", " << sep << "\"SampleDen\": " << doubleArrayToString(SampleDen) << ", " << sep << "}"; return oss.str(); } } // end namespace Projection } // end namespace otb <|endoftext|>
<commit_before>#include "ScrollingMsg.hpp" #include <pango/pangocairo.h> ScrollingMsg::ScrollingMsg() :m_current_w(0) ,m_current_h(0) ,m_friendly_name("None") ,m_msg("None") ,m_loops(0) ,m_current_loop(0) ,m_fontfamily("Sans Bold 12") ,m_ypos(300) ,m_xpos(0) ,m_scroll_time(12.0f) { }; ScrollingMsg::ScrollingMsg( const int width, const int height, const std::string& font, const std::string& friendly_name, const int& loop, const std::string& msg, const double& scroll_time, const int& y_pos) :m_current_w(width) ,m_current_h(height) ,m_friendly_name(friendly_name) ,m_msg(msg) ,m_loops(loop) ,m_current_loop(0) ,m_fontfamily(font) ,m_ypos(y_pos) ,m_xpos(width) ,m_scroll_time(scroll_time) { }; void ScrollingMsg::Resize(const int width, const int height) { m_current_w = width; m_current_h = height; }; void ScrollingMsg::Update(const float dt) { //TODO: separate update and drawing of msg to facilitate different ordering. }; void ScrollingMsg::Draw(cairo_t* context, const float dt) { cairo_save(context); PangoLayout *pango_layout; PangoFontDescription *pango_fontdesc; pango_layout = pango_cairo_create_layout(context); PangoAttrList* pTextAttributes = pango_attr_list_new(); gchar *text = 0;//stupidly gchar disallows deallocation, but not in code if(!pango_parse_markup (m_msg.c_str(), -1,//null terminated text string above 0,//no accellerated marker &pTextAttributes, &text, NULL, NULL)) { } pango_layout_set_text(pango_layout, text, -1); pango_layout_set_attributes (pango_layout, pTextAttributes); pango_attr_list_unref(pTextAttributes); pango_fontdesc = pango_font_description_from_string(m_fontfamily.c_str()); pango_layout_set_font_description(pango_layout, pango_fontdesc); pango_font_description_free(pango_fontdesc); cairo_text_extents_t te; cairo_set_source_rgb (context, 1.0, 1.0, 0.0); PangoRectangle ink_rect, logical_rect; pango_layout_get_pixel_extents(pango_layout, &ink_rect, &logical_rect); //d_pos = d/t * dt m_xpos -= ((m_current_w + ink_rect.width)/m_scroll_time)*dt; if(m_xpos<(-1.0f*ink_rect.width)) {//wraparound m_xpos = m_current_w; m_current_loop += 1; if(m_current_loop==m_loops) { m_current_loop = -1;//indicates controller should remove this msg. } } cairo_translate(context, m_xpos, m_ypos); pango_cairo_update_layout(context, pango_layout); pango_cairo_show_layout(context, pango_layout); g_object_unref(pango_layout); cairo_restore (context); } ScrollingMsgController::ScrollingMsgController() { } void ScrollingMsgController::AddMsg(const int width, const int height, const std::string& font, const std::string& friendly_name, const int& loop, const std::string& msg, const double& scroll_time, const int& y_pos) { if(m_msgs.find(friendly_name)==m_msgs.end()) { m_msgs[friendly_name]=ScrollingMsg(width, height, font, friendly_name, loop, msg, scroll_time, y_pos); } } void ScrollingMsgController::RemoveMsg(const std::string& friendly_name) { std::map< std::string, ScrollingMsg >::iterator msg = m_msgs.find(friendly_name); if(msg!=m_msgs.end()) { m_msgs.erase(msg); } }; void ScrollingMsgController::Update(float dt) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end();) { imsg->second.Update(dt); //remove those msgs that are 'done' if(imsg->second.CurrentLoop()<0) { imsg = m_msgs.erase(imsg); }else{ ++imsg; } } }; void ScrollingMsgController::Draw(cairo_t* context, const float dt) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end(); ++imsg) { imsg->second.Draw(context, dt); } } void ScrollingMsgController::Resize(const int width, const int height) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end(); ++imsg) { imsg->second.Resize(width, height); } } <commit_msg>Smoother handling of incorrect pango markup.<commit_after>#include "ScrollingMsg.hpp" #include <pango/pangocairo.h> ScrollingMsg::ScrollingMsg() :m_current_w(0) ,m_current_h(0) ,m_friendly_name("None") ,m_msg("None") ,m_loops(0) ,m_current_loop(0) ,m_fontfamily("Sans Bold 12") ,m_ypos(300) ,m_xpos(0) ,m_scroll_time(12.0f) { }; ScrollingMsg::ScrollingMsg( const int width, const int height, const std::string& font, const std::string& friendly_name, const int& loop, const std::string& msg, const double& scroll_time, const int& y_pos) :m_current_w(width) ,m_current_h(height) ,m_friendly_name(friendly_name) ,m_msg(msg) ,m_loops(loop) ,m_current_loop(0) ,m_fontfamily(font) ,m_ypos(y_pos) ,m_xpos(width) ,m_scroll_time(scroll_time) { }; void ScrollingMsg::Resize(const int width, const int height) { m_current_w = width; m_current_h = height; }; void ScrollingMsg::Update(const float dt) { //TODO: separate update and drawing of msg to facilitate different ordering. }; void ScrollingMsg::Draw(cairo_t* context, const float dt) { cairo_save(context); PangoLayout *pango_layout; PangoFontDescription *pango_fontdesc; pango_layout = pango_cairo_create_layout(context); pango_fontdesc = pango_font_description_from_string(m_fontfamily.c_str()); PangoAttrList* pTextAttributes = pango_attr_list_new(); gchar *text = 0;//stupidly gchar disallows deallocation, but not in code if(pango_parse_markup(m_msg.c_str(), -1,//null terminated text string above 0,//no accellerated marker &pTextAttributes, &text, NULL, NULL)) { //(relay:30805): Pango-CRITICAL **: pango_layout_set_text: assertion 'length == 0 || text != NULL' failed pango_layout_set_text(pango_layout, text, -1); pango_layout_set_attributes (pango_layout, pTextAttributes); pango_layout_set_font_description(pango_layout, pango_fontdesc); }else{ pango_layout_set_font_description(pango_layout, pango_fontdesc); pango_layout_set_text(pango_layout, m_msg.c_str(), -1); } cairo_text_extents_t te; cairo_set_source_rgb (context, 1.0, 1.0, 1.0); PangoRectangle ink_rect, logical_rect; pango_layout_get_pixel_extents(pango_layout, &ink_rect, &logical_rect); //d_pos = d/t * dt m_xpos -= ((m_current_w + ink_rect.width)/m_scroll_time)*dt; if(m_xpos<(-1.0f*ink_rect.width)) {//wraparound m_xpos = m_current_w; m_current_loop += 1; if(m_current_loop==m_loops) { m_current_loop = -1;//indicates controller should remove this msg. } } cairo_translate(context, m_xpos, m_ypos); pango_cairo_update_layout(context, pango_layout); pango_cairo_show_layout(context, pango_layout); pango_attr_list_unref(pTextAttributes); pango_font_description_free(pango_fontdesc); g_object_unref(pango_layout); cairo_restore (context); } ScrollingMsgController::ScrollingMsgController() { } void ScrollingMsgController::AddMsg(const int width, const int height, const std::string& font, const std::string& friendly_name, const int& loop, const std::string& msg, const double& scroll_time, const int& y_pos) { if(m_msgs.find(friendly_name)==m_msgs.end()) { m_msgs[friendly_name]=ScrollingMsg(width, height, font, friendly_name, loop, msg, scroll_time, y_pos); } } void ScrollingMsgController::RemoveMsg(const std::string& friendly_name) { std::map< std::string, ScrollingMsg >::iterator msg = m_msgs.find(friendly_name); if(msg!=m_msgs.end()) { m_msgs.erase(msg); } }; void ScrollingMsgController::Update(float dt) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end();) { imsg->second.Update(dt); //remove those msgs that are 'done' if(imsg->second.CurrentLoop()<0) { imsg = m_msgs.erase(imsg); }else{ ++imsg; } } }; void ScrollingMsgController::Draw(cairo_t* context, const float dt) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end(); ++imsg) { imsg->second.Draw(context, dt); } } void ScrollingMsgController::Resize(const int width, const int height) { for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin(); imsg!=m_msgs.end(); ++imsg) { imsg->second.Resize(width, height); } } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2018 Nathan Osman * * 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 <QMetaObject> #include <QMetaProperty> #include <QVariantList> #include <nitroshare/action.h> #include <nitroshare/actionregistry.h> #include <nitroshare/application.h> #include <nitroshare/config.h> #include "actionsaction.h" ActionsAction::ActionsAction(Application *application) : mApplication(application) { } QString ActionsAction::name() const { return "actions"; } bool ActionsAction::api() const { return true; } QString ActionsAction::description() const { return tr( "Retrieve a list of all registered actions." "This action takes no parameters and returns an array of action " "objects. Each action object includes details such as the action's " "name and description, which lists the expected parameters." ); } QVariant ActionsAction::invoke(const QVariantMap &) { // Create a list of the metadata for each action QVariantList actions; foreach (auto &action, mApplication->actionRegistry()->actions()) { // For each action, create a QVariantMap of its metadata QVariantMap properties; for (int i = 1; i < action->metaObject()->propertyCount(); ++i) { auto property = action->metaObject()->property(i); auto name = property.name(); properties.insert(name, action->property(name)); } // Add to the list actions.append(properties); } return actions; } <commit_msg>Use QtUtil::properties() in ActionsAction in api plugin.<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2018 Nathan Osman * * 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 <QVariantList> #include <nitroshare/action.h> #include <nitroshare/actionregistry.h> #include <nitroshare/application.h> #include <nitroshare/config.h> #include <nitroshare/qtutil.h> #include "actionsaction.h" ActionsAction::ActionsAction(Application *application) : mApplication(application) { } QString ActionsAction::name() const { return "actions"; } bool ActionsAction::api() const { return true; } QString ActionsAction::description() const { return tr( "Retrieve a list of all registered actions." "This action takes no parameters and returns an array of action " "objects. Each action object includes details such as the action's " "name and description, which lists the expected parameters." ); } QVariant ActionsAction::invoke(const QVariantMap &) { QVariantList actions; foreach (auto &action, mApplication->actionRegistry()->actions()) { actions.append(QtUtil::properties(action)); } return actions; } <|endoftext|>
<commit_before>/* Copyright (c) 2009-2015 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include <string.h> #include <getopt.h> #include <assert.h> #include <iostream> #include <fstream> #include "ClusterMetrics.h" #include "Context.h" #include "Cycles.h" #include "Dispatch.h" #include "ShortMacros.h" #include "Crc32C.h" #include "ObjectFinder.h" #include "OptionParser.h" #include "RamCloud.h" #include "Tub.h" #include "IndexLookup.h" #include "TableEnumerator.h" using namespace RAMCloud; int main(int argc, char *argv[]) try { int clientIndex; int numClients; string tableName; int serverSpan; string imageFileName; // Set line buffering for stdout so that printf's and log messages // interleave properly. setvbuf(stdout, NULL, _IOLBF, 1024); // need external context to set log levels with OptionParser Context context(false); OptionsDescription clientOptions("TableUploader"); clientOptions.add_options() // These first two options are currently ignored. They're here so that // this script can be run with cluster.py. ("clientIndex", ProgramOptions::value<int>(&clientIndex)-> default_value(0), "Index of this client (first client is 0; currently ignored)") ("numClients", ProgramOptions::value<int>(&numClients)-> default_value(1), "Total number of clients running (currently ignored)") ("tableName", ProgramOptions::value<string>(&tableName), "Name of the table to image.") ("serverSpan", ProgramOptions::value<int>(&serverSpan), "Server span for the table.") ("imageFile", ProgramOptions::value<string>(&imageFileName), "Name of the image file to create."); OptionParser optionParser(clientOptions, argc, argv); context.transportManager->setSessionTimeout( optionParser.options.getSessionTimeout()); LOG(NOTICE, "Connecting to %s", optionParser.options.getCoordinatorLocator().c_str()); string locator = optionParser.options.getExternalStorageLocator(); if (locator.size() == 0) { locator = optionParser.options.getCoordinatorLocator(); } RamCloud client(&context, locator.c_str(), optionParser.options.getClusterName().c_str()); LOG(NOTICE, "Uploading table %s with server span %d from file %s", tableName.c_str(), serverSpan, imageFileName.c_str()); uint64_t tableId; tableId = client.createTable(tableName.c_str(), serverSpan); std::ifstream inFile; inFile.open(imageFileName.c_str(), std::ios::binary); int objCount = 0; int byteCount = 0; char lenBuffer[sizeof(uint32_t)]; while(inFile.read(lenBuffer, sizeof(lenBuffer))) { uint32_t keyLength = *((uint32_t*) lenBuffer); char keyBuffer[keyLength]; inFile.read(keyBuffer, keyLength); string key(keyBuffer, keyLength); inFile.read(lenBuffer, sizeof(lenBuffer)); uint32_t dataLength = *((uint32_t*) lenBuffer); char dataBuffer[dataLength]; inFile.read(dataBuffer, dataLength); string data(dataBuffer, dataLength); // LOG(NOTICE, "[%s, %s]", key.c_str(), data.c_str()); objCount++; byteCount += keyLength + dataLength; if (objCount % 100000 == 0) { LOG(NOTICE, "Uploaded %d objects totalling %d bytes.", objCount, byteCount); } } inFile.close(); LOG(NOTICE, "Table uploaded."); return 0; } catch (RAMCloud::ClientException& e) { fprintf(stderr, "RAMCloud exception: %s\n", e.str().c_str()); return 1; } catch (RAMCloud::Exception& e) { fprintf(stderr, "RAMCloud exception: %s\n", e.str().c_str()); return 1; } <commit_msg>Added object writing to TableUploader.<commit_after>/* Copyright (c) 2009-2015 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include <string.h> #include <getopt.h> #include <assert.h> #include <iostream> #include <fstream> #include "ClusterMetrics.h" #include "Context.h" #include "Cycles.h" #include "Dispatch.h" #include "ShortMacros.h" #include "Crc32C.h" #include "ObjectFinder.h" #include "OptionParser.h" #include "RamCloud.h" #include "Tub.h" #include "IndexLookup.h" #include "TableEnumerator.h" using namespace RAMCloud; int main(int argc, char *argv[]) try { int clientIndex; int numClients; string tableName; int serverSpan; string imageFileName; // Set line buffering for stdout so that printf's and log messages // interleave properly. setvbuf(stdout, NULL, _IOLBF, 1024); // need external context to set log levels with OptionParser Context context(false); OptionsDescription clientOptions("TableUploader"); clientOptions.add_options() // These first two options are currently ignored. They're here so that // this script can be run with cluster.py. ("clientIndex", ProgramOptions::value<int>(&clientIndex)-> default_value(0), "Index of this client (first client is 0; currently ignored)") ("numClients", ProgramOptions::value<int>(&numClients)-> default_value(1), "Total number of clients running (currently ignored)") ("tableName", ProgramOptions::value<string>(&tableName), "Name of the table to image.") ("serverSpan", ProgramOptions::value<int>(&serverSpan), "Server span for the table.") ("imageFile", ProgramOptions::value<string>(&imageFileName), "Name of the image file to create."); OptionParser optionParser(clientOptions, argc, argv); context.transportManager->setSessionTimeout( optionParser.options.getSessionTimeout()); LOG(NOTICE, "Connecting to %s", optionParser.options.getCoordinatorLocator().c_str()); string locator = optionParser.options.getExternalStorageLocator(); if (locator.size() == 0) { locator = optionParser.options.getCoordinatorLocator(); } RamCloud client(&context, locator.c_str(), optionParser.options.getClusterName().c_str()); LOG(NOTICE, "Uploading table %s with server span %d from file %s", tableName.c_str(), serverSpan, imageFileName.c_str()); uint64_t tableId; tableId = client.createTable(tableName.c_str(), serverSpan); std::ifstream inFile; inFile.open(imageFileName.c_str(), std::ios::binary); int objCount = 0; int byteCount = 0; char lenBuffer[sizeof(uint32_t)]; uint64_t startTime = Cycles::rdtsc(); while(inFile.read(lenBuffer, sizeof(lenBuffer))) { uint32_t keyLength = *((uint32_t*) lenBuffer); char keyBuffer[keyLength]; inFile.read(keyBuffer, keyLength); inFile.read(lenBuffer, sizeof(lenBuffer)); uint32_t dataLength = *((uint32_t*) lenBuffer); char dataBuffer[dataLength]; inFile.read(dataBuffer, dataLength); client.write(tableId, (const void*) keyBuffer, keyLength, (const void*) dataBuffer, dataLength); objCount++; byteCount += keyLength + dataLength; if (objCount % 100000 == 0) { LOG(NOTICE, "Status (objects: %d, size: %dMB/%dKB/%dB, time: %0.2fs).", objCount, byteCount/(1024*1024), byteCount/(1024), byteCount, Cycles::toSeconds(Cycles::rdtsc() - startTime)); } } uint64_t endTime = Cycles::rdtsc(); inFile.close(); LOG(NOTICE, "Table uploaded (objects: %d, size: %dMB/%dKB/%dB, time: %0.2fs).", objCount, byteCount/(1024*1024), byteCount/(1024), byteCount, Cycles::toSeconds(endTime - startTime)); return 0; } catch (RAMCloud::ClientException& e) { fprintf(stderr, "RAMCloud exception: %s\n", e.str().c_str()); return 1; } catch (RAMCloud::Exception& e) { fprintf(stderr, "RAMCloud exception: %s\n", e.str().c_str()); return 1; } <|endoftext|>
<commit_before>#include "GL.h" #include "TextureAtlas.h" #include <Context.h> #include <OpenGLTexture.h> #include <Image.h> #include <cmath> #include <iostream> #include <cassert> using namespace std; TextureAtlas::TextureAtlas(AtlasType _type, unsigned int _block_size, unsigned int _texture_width, unsigned int _texture_height, unsigned int _texture_levels, canvas::InternalFormat _internal_format) : type(_type), block_size(_block_size), texture_width(_texture_width), texture_height(_texture_height), texture_levels(_texture_levels), internal_format(_internal_format) { } void TextureAtlas::initializeTexture() { if (!texture.get()) { cerr << "creating texture for atlas, w = " << texture_width << ", h = " << texture_height << ", l = " << texture_levels << endl; canvas::FilterMode min_filter2 = min_filter; if (min_filter2 == canvas::LINEAR_MIPMAP_LINEAR && texture_levels <= 1) min_filter2 = canvas::LINEAR; texture = canvas::OpenGLTexture::createTexture(texture_width, texture_height, texture_width, texture_height, min_filter2, mag_filter, internal_format, texture_levels); } } void TextureAtlas::updateTexture() { initializeTexture(); if (!waiting_updates.empty()) { assert(texture.get()); // cerr << "updating textureAtlas " << texture.getTextureId() << ": " << waiting_updates.size() << endl; // auto & data = waiting_updates.front(); for (auto & data : waiting_updates) { assert(data.image.get()); // cerr << "updating texture " << texture.getTextureId() << ": " << data.x << ", " << data.y << ", " << data.image->getHeight() << ", " << data.image->getHeight() << endl; texture.updateData(*(data.image), data.x, data.y); } waiting_updates.clear(); texture.generateMipmaps(); } } canvas::InternalFormat TextureAtlas::getCanvasImageFormat() const { switch (internal_format) { case canvas::R8: case canvas::RG8: case canvas::RGB_ETC1: case canvas::RGB_DXT1: return canvas::RGB8; case canvas::RGB565: return canvas::RGB565; // return canvas::ImageFormat::RGB32; case canvas::RGBA4: case canvas::RGBA8: case canvas::LUMINANCE_ALPHA: default: return canvas::RGBA8; } } int TextureAtlas::addProfileImage(std::shared_ptr<canvas::Image> & img) { assert(img.get()); const unsigned int w = getBlockSize(), h = getBlockSize(); if (img->getWidth() != w || img->getHeight() != h || img->getLevels() != getLevels()) { cerr << "wrong dimensions, image: (w = " << img->getWidth() << ", h = " << img->getHeight() << ", l = " << img->getLevels() << "), atlas: (" << getBlockSize() << ", " << getLevels() << ")\n"; assert(0); } if (num_textures >= texture_width / w * texture_height / h) { cerr << "atlas full (w = " << texture_width << ", h = " << texture_height << ")" << endl; // assert(0); return 0; // return default texture } int index = int(num_textures++); int textures_per_row = texture_width / w; unsigned int xx0 = (index % textures_per_row) * w; unsigned int yy0 = index / textures_per_row * h; waiting_updates.push_back({xx0, yy0, img}); return index; } int TextureAtlas::addImage(std::shared_ptr<canvas::Image> & img, unsigned int actual_width, unsigned int actual_height) { assert(img); if (!actual_width) actual_width = img->getWidth(); if (!actual_height) actual_height = img->getHeight(); int index = int(num_textures++); assert(type == FREE); if (type == FREE) index++; unsigned int aligned_width = img->getWidth(), aligned_height = img->getHeight(); if (row_positions.empty()) { row_positions.push_back(0); current_row_height = aligned_height; } else if (row_positions.back() + aligned_width > texture_width || current_row_height != aligned_height) { row_positions.push_back(0); current_row_y += current_row_height; current_row_height = aligned_height; } unsigned int xx0 = row_positions.back(); unsigned int yy0 = current_row_y; row_positions.back() += aligned_width; assert(!row_positions.empty()); if (yy0 + aligned_height > getHeight()) { cerr << "atlas full\n"; row_positions.pop_back(); return -1; } if (internal_format == canvas::RG_RGTC2) { img = img->convert(internal_format); } else if (internal_format == canvas::LA44 && 0) { img = img->convert(internal_format); } waiting_updates.push_back({ xx0, yy0, img }); texture_positions.push_back(texture_pos_s(xx0, yy0, actual_width, actual_height)); return index; } int TextureAtlas::renderLabelToTexture(canvas::ContextFactory & factory, const std::string & text, const std::string & tag, canvas::Image * symbol, LabelStyle style) { auto context = factory.createContext(0, 0, getCanvasImageFormat(), true); float tag_width = 0; if (!tag.empty()) { context->font.size = 9; tag_width = context->measureText(tag).width; } float font_size = style == LABEL_GROUP_TITLE ? 15 : 11; float h_margin = style == LABEL_DARK_BOX ? 18 : 1; float v_margin = style == LABEL_DARK_BOX ? 9 : 0; context->font.size = font_size; context->font.weight = style == LABEL_GROUP_TITLE ? canvas::Font::BOLD : canvas::Font::NORMAL; context->textBaseline = "middle"; canvas::TextMetrics size = context->measureText(text); bool has_symbol = symbol != 0; double x = 0, y = 0, w = round(size.width + tag_width) + h_margin + (has_symbol ? 19 : 0), h = font_size + v_margin; unsigned int aligned_width = (int(w * context->getDisplayScale()) + 3) & ~3; unsigned int aligned_height = (int(h * context->getDisplayScale()) + 3) & ~3; context->resize(int(aligned_width / context->getDisplayScale()), int(aligned_height / context->getDisplayScale())); if (style == LABEL_DARK_BOX) { float r = 5; context->fillStyle = canvas::Color(0.1f, 0.075f, 0.05f, 0.75f); context->beginPath(); context->moveTo(x+r, y); context->arcTo(x+w, y, x+w, y+h, r); context->arcTo(x+w, y+h, x, y+h, r); context->arcTo(x, y+h, x, y, r); context->arcTo(x, y, x+w, y, r); context->fill(); context->fillStyle = "#fff"; } else if (style == LABEL_GROUP_TITLE) { context->shadowColor = canvas::Color(1.0f, 1.0f, 1.0f, 1.0f); context->shadowBlur = 2.0f; context->fillStyle = "#000"; } else { context->shadowColor = canvas::Color(1.0f, 1.0f, 1.0f, 1.0f); context->shadowBlur = 2.0f; context->fillStyle = "#000"; } int pos = h_margin / 3; if (has_symbol) { // context->globalAlpha = 0.75f; context->drawImage(*symbol, pos, h / 2 - 8, 16, 16); pos += 19; // context->globalAlpha = 1.0f; } context->fillText(text, pos, h / 2.0); pos += size.width + 5; if (!tag.empty()) { x += pos; float w2 = tag_width + 8; float r = 3; y += 3; float h2 = h - 6; context->fillStyle = canvas::Color(0.0f, 0.0f, 0.0f, 0.5f); context->beginPath(); context->moveTo(x+r, y); context->arcTo(x+w2, y, x+w2, y+h2, r); context->arcTo(x+w2, y+h2, x, y+h2, r); context->arcTo(x, y+h2, x, y, r); context->arcTo(x, y, x+w2, y, r); context->fill(); context->fillStyle = "#bdf"; context->fillText(tag, pos + 2, h / 2.0); } // cerr << "created label: " << w << " " << h << " => " << context->getActualWidth() << " " << context->getActualHeight() << endl; std::shared_ptr<canvas::Image> img = context->getDefaultSurface().createImage(); return addImage(img, (unsigned int)(w * context->getDisplayScale()), (unsigned int)(h * context->getDisplayScale())); } <commit_msg>set font weight as text<commit_after>#include "GL.h" #include "TextureAtlas.h" #include <Context.h> #include <OpenGLTexture.h> #include <Image.h> #include <cmath> #include <iostream> #include <cassert> using namespace std; TextureAtlas::TextureAtlas(AtlasType _type, unsigned int _block_size, unsigned int _texture_width, unsigned int _texture_height, unsigned int _texture_levels, canvas::InternalFormat _internal_format) : type(_type), block_size(_block_size), texture_width(_texture_width), texture_height(_texture_height), texture_levels(_texture_levels), internal_format(_internal_format) { } void TextureAtlas::initializeTexture() { if (!texture.get()) { cerr << "creating texture for atlas, w = " << texture_width << ", h = " << texture_height << ", l = " << texture_levels << endl; canvas::FilterMode min_filter2 = min_filter; if (min_filter2 == canvas::LINEAR_MIPMAP_LINEAR && texture_levels <= 1) min_filter2 = canvas::LINEAR; texture = canvas::OpenGLTexture::createTexture(texture_width, texture_height, texture_width, texture_height, min_filter2, mag_filter, internal_format, texture_levels); } } void TextureAtlas::updateTexture() { initializeTexture(); if (!waiting_updates.empty()) { assert(texture.get()); // cerr << "updating textureAtlas " << texture.getTextureId() << ": " << waiting_updates.size() << endl; // auto & data = waiting_updates.front(); for (auto & data : waiting_updates) { assert(data.image.get()); // cerr << "updating texture " << texture.getTextureId() << ": " << data.x << ", " << data.y << ", " << data.image->getHeight() << ", " << data.image->getHeight() << endl; texture.updateData(*(data.image), data.x, data.y); } waiting_updates.clear(); texture.generateMipmaps(); } } canvas::InternalFormat TextureAtlas::getCanvasImageFormat() const { switch (internal_format) { case canvas::R8: case canvas::RG8: case canvas::RGB_ETC1: case canvas::RGB_DXT1: return canvas::RGB8; case canvas::RGB565: return canvas::RGB565; // return canvas::ImageFormat::RGB32; case canvas::RGBA4: case canvas::RGBA8: case canvas::LUMINANCE_ALPHA: default: return canvas::RGBA8; } } int TextureAtlas::addProfileImage(std::shared_ptr<canvas::Image> & img) { assert(img.get()); const unsigned int w = getBlockSize(), h = getBlockSize(); if (img->getWidth() != w || img->getHeight() != h || img->getLevels() != getLevels()) { cerr << "wrong dimensions, image: (w = " << img->getWidth() << ", h = " << img->getHeight() << ", l = " << img->getLevels() << "), atlas: (" << getBlockSize() << ", " << getLevels() << ")\n"; assert(0); } if (num_textures >= texture_width / w * texture_height / h) { cerr << "atlas full (w = " << texture_width << ", h = " << texture_height << ")" << endl; // assert(0); return 0; // return default texture } int index = int(num_textures++); int textures_per_row = texture_width / w; unsigned int xx0 = (index % textures_per_row) * w; unsigned int yy0 = index / textures_per_row * h; waiting_updates.push_back({xx0, yy0, img}); return index; } int TextureAtlas::addImage(std::shared_ptr<canvas::Image> & img, unsigned int actual_width, unsigned int actual_height) { assert(img); if (!actual_width) actual_width = img->getWidth(); if (!actual_height) actual_height = img->getHeight(); int index = int(num_textures++); assert(type == FREE); if (type == FREE) index++; unsigned int aligned_width = img->getWidth(), aligned_height = img->getHeight(); if (row_positions.empty()) { row_positions.push_back(0); current_row_height = aligned_height; } else if (row_positions.back() + aligned_width > texture_width || current_row_height != aligned_height) { row_positions.push_back(0); current_row_y += current_row_height; current_row_height = aligned_height; } unsigned int xx0 = row_positions.back(); unsigned int yy0 = current_row_y; row_positions.back() += aligned_width; assert(!row_positions.empty()); if (yy0 + aligned_height > getHeight()) { cerr << "atlas full\n"; row_positions.pop_back(); return -1; } if (internal_format == canvas::RG_RGTC2) { img = img->convert(internal_format); } else if (internal_format == canvas::LA44 && 0) { img = img->convert(internal_format); } waiting_updates.push_back({ xx0, yy0, img }); texture_positions.push_back(texture_pos_s(xx0, yy0, actual_width, actual_height)); return index; } int TextureAtlas::renderLabelToTexture(canvas::ContextFactory & factory, const std::string & text, const std::string & tag, canvas::Image * symbol, LabelStyle style) { auto context = factory.createContext(0, 0, getCanvasImageFormat(), true); float tag_width = 0; if (!tag.empty()) { context->font.size = 9; tag_width = context->measureText(tag).width; } float font_size = style == LABEL_GROUP_TITLE ? 15 : 11; float h_margin = style == LABEL_DARK_BOX ? 18 : 1; float v_margin = style == LABEL_DARK_BOX ? 9 : 0; context->font.size = font_size; context->font.weight = style == LABEL_GROUP_TITLE ? "bold" : "normal"; context->textBaseline = "middle"; canvas::TextMetrics size = context->measureText(text); bool has_symbol = symbol != 0; double x = 0, y = 0, w = round(size.width + tag_width) + h_margin + (has_symbol ? 19 : 0), h = font_size + v_margin; unsigned int aligned_width = (int(w * context->getDisplayScale()) + 3) & ~3; unsigned int aligned_height = (int(h * context->getDisplayScale()) + 3) & ~3; context->resize(int(aligned_width / context->getDisplayScale()), int(aligned_height / context->getDisplayScale())); if (style == LABEL_DARK_BOX) { float r = 5; context->fillStyle = canvas::Color(0.1f, 0.075f, 0.05f, 0.75f); context->beginPath(); context->moveTo(x+r, y); context->arcTo(x+w, y, x+w, y+h, r); context->arcTo(x+w, y+h, x, y+h, r); context->arcTo(x, y+h, x, y, r); context->arcTo(x, y, x+w, y, r); context->fill(); context->fillStyle = "#fff"; } else if (style == LABEL_GROUP_TITLE) { context->shadowColor = canvas::Color(1.0f, 1.0f, 1.0f, 1.0f); context->shadowBlur = 2.0f; context->fillStyle = "#000"; } else { context->shadowColor = canvas::Color(1.0f, 1.0f, 1.0f, 1.0f); context->shadowBlur = 2.0f; context->fillStyle = "#000"; } int pos = h_margin / 3; if (has_symbol) { // context->globalAlpha = 0.75f; context->drawImage(*symbol, pos, h / 2 - 8, 16, 16); pos += 19; // context->globalAlpha = 1.0f; } context->fillText(text, pos, h / 2.0); pos += size.width + 5; if (!tag.empty()) { x += pos; float w2 = tag_width + 8; float r = 3; y += 3; float h2 = h - 6; context->fillStyle = canvas::Color(0.0f, 0.0f, 0.0f, 0.5f); context->beginPath(); context->moveTo(x+r, y); context->arcTo(x+w2, y, x+w2, y+h2, r); context->arcTo(x+w2, y+h2, x, y+h2, r); context->arcTo(x, y+h2, x, y, r); context->arcTo(x, y, x+w2, y, r); context->fill(); context->fillStyle = "#bdf"; context->fillText(tag, pos + 2, h / 2.0); } // cerr << "created label: " << w << " " << h << " => " << context->getActualWidth() << " " << context->getActualHeight() << endl; std::shared_ptr<canvas::Image> img = context->getDefaultSurface().createImage(); return addImage(img, (unsigned int)(w * context->getDisplayScale()), (unsigned int)(h * context->getDisplayScale())); } <|endoftext|>
<commit_before>#ifndef NATIVE_CHAT_TIMELINE_VIEW_HPP_ #define NATIVE_CHAT_TIMELINE_VIEW_HPP_ #include <deque> #include <chrono> #include <vector> #include <unordered_map> #include <unordered_set> #include <experimental/optional> #include <QAbstractScrollArea> #include <QTextLayout> #include <QIcon> #include "matrix/Event.hpp" #include "matrix/Room.hpp" #include "matrix/Content.hpp" #include "QStringHash.hpp" class QShortcut; class TimelineView : public QAbstractScrollArea { Q_OBJECT public: TimelineView(matrix::Room &room, QWidget *parent = nullptr); void end_batch(const QString &token); // Call upon receiving a new batch, with that batch's prev_batch token. void push_back(const matrix::RoomState &state, const matrix::proto::Event &e); void reset(); // Call if a gap arises in events QSize sizeHint() const override; QSize minimumSizeHint() const override; protected: void paintEvent(QPaintEvent *event) override; void resizeEvent(QResizeEvent *event) override; void showEvent(QShowEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void focusOutEvent(QFocusEvent *event) override; private: struct Event { bool system; std::vector<QTextLayout> layouts; const std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> time; Event(const TimelineView &, const matrix::RoomState &, const matrix::proto::Event &); QRectF bounding_rect() const; void update_layout(const TimelineView &); }; class Block { public: Block(TimelineView &, const matrix::RoomState &, const matrix::proto::Event &, Event &); void update_header(TimelineView &view, const matrix::RoomState &state); void update_layout(const TimelineView &); void draw(const TimelineView &view, QPainter &p, QPointF offset, bool select_all, std::experimental::optional<QPointF> select_start, std::experimental::optional<QPointF> select_end) const; QRectF bounding_rect(const TimelineView &view) const; QString selection_text(const QFontMetrics &, bool select_all, std::experimental::optional<QPointF> select_start, std::experimental::optional<QPointF> select_end) const; const QString &sender_id() const { return sender_id_; } size_t size() const; const std::experimental::optional<matrix::Content> &avatar() const { return avatar_; } const Event *event_at(const QFontMetrics &, const QPointF &) const; std::deque<Event *> &events() { return events_; } const std::deque<Event *> &events() const { return events_; } private: const QString event_id_; const QString sender_id_; std::experimental::optional<matrix::Content> avatar_; QTextLayout name_layout_, timestamp_layout_; std::deque<Event *> events_; // deque so we can add events to either end }; struct Batch { std::deque<Event> events; // deque purely so we don't try to copy/move QTextLayout QString token; size_t size() const; }; struct Avatar { size_t references = 0; QPixmap pixmap; }; struct Selection { Block *start; // Point where selection began QPointF start_pos; // relative to start origin Block *end; // Point where selection completed QPointF end_pos; // relative to end origin }; struct VisibleBlock { Block *block; QRectF bounds; // relative to view }; class SelectionScanner { public: SelectionScanner(const std::experimental::optional<Selection> &s) : s_(s) {} void advance(const Block *b) { inside_selection_ &= !ending_selection(); starting_ = false; ending_ = false; check_starting(b); } bool on_selection_edge(const Block *b) const { return s_ && (b == s_->start || b == s_->end); } bool starting_selection() const { return starting_; } bool ending_selection() const { return ending_; } bool fully_selected(const Block *b) const { return inside_selection_ && !on_selection_edge(b); } std::experimental::optional<QPointF> start_point() const { return starting_selection() ? std::experimental::optional<QPointF>(selection_starts_at_start_ ? s_->start_pos : s_->end_pos) : std::experimental::optional<QPointF>(); } std::experimental::optional<QPointF> end_point() const { return ending_selection() ? std::experimental::optional<QPointF>(selection_starts_at_start_ ? s_->end_pos : s_->start_pos) : std::experimental::optional<QPointF>(); } private: const std::experimental::optional<Selection> &s_; bool inside_selection_ = false; bool selection_starts_at_start_; bool starting_ = false; bool ending_ = false; void check_starting(const Block *b) { starting_ = !inside_selection_ && on_selection_edge(b); ending_ = on_selection_edge(b) && (inside_selection_ || s_->start == s_->end); inside_selection_ |= starting_; if(starting_) selection_starts_at_start_ = b == s_->start; } }; matrix::Room &room_; matrix::RoomState initial_state_; std::deque<Batch> batches_; // deque so we can add/remote batches from either end std::deque<Block> blocks_; // what actually gets drawn size_t total_events_; bool head_color_alternate_; bool backlog_growing_; bool backlog_growable_; // false iff we've found the room create message bool backlog_grow_cancelled_; // true iff we reset since backlog started growing size_t min_backlog_size_; qreal content_height_; QString prev_batch_; // Token for the batch immediately prior to the first message std::unordered_map<matrix::Content, Avatar> avatars_; QIcon avatar_missing_, avatar_loading_; std::experimental::optional<Selection> selection_; QShortcut *copy_; std::vector<VisibleBlock> visible_blocks_; void update_scrollbar(); int visible_width() const; int block_spacing() const; int block_margin() const; int avatar_size() const; int block_body_start() const; int block_body_width() const; void grow_backlog(); void prepend_batch(QString start, QString end, gsl::span<const matrix::proto::Event> events); void backlog_grow_error(); int scrollback_trigger_size() const; int scrollback_status_size() const; void set_avatar(const matrix::Content &content, const QString &type, const QString &disposition, const QByteArray &data); void unref_avatar(const matrix::Content &); void copy(); void update_origins(); void pop_front_block(); QString selection_text() const; VisibleBlock *block_near(const QPoint &p); // Point relative to view void prune_backlog(); // Removes enough blocks from the backlog that calling for each new event will cause backlog size to approach one // batch size greater than min_backlog_size_. Requires but does not perform scrollbar update! }; #endif <commit_msg>Cleanup<commit_after>#ifndef NATIVE_CHAT_TIMELINE_VIEW_HPP_ #define NATIVE_CHAT_TIMELINE_VIEW_HPP_ #include <deque> #include <chrono> #include <vector> #include <unordered_map> #include <unordered_set> #include <experimental/optional> #include <QAbstractScrollArea> #include <QTextLayout> #include <QIcon> #include "matrix/Event.hpp" #include "matrix/Room.hpp" #include "matrix/Content.hpp" #include "QStringHash.hpp" class QShortcut; class TimelineView : public QAbstractScrollArea { Q_OBJECT public: TimelineView(matrix::Room &room, QWidget *parent = nullptr); void end_batch(const QString &token); // Call upon receiving a new batch, with that batch's prev_batch token. void push_back(const matrix::RoomState &state, const matrix::proto::Event &e); void reset(); // Call if a gap arises in events QSize sizeHint() const override; QSize minimumSizeHint() const override; protected: void paintEvent(QPaintEvent *event) override; void resizeEvent(QResizeEvent *event) override; void showEvent(QShowEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void focusOutEvent(QFocusEvent *event) override; private: struct Event { bool system; std::vector<QTextLayout> layouts; const std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> time; Event(const TimelineView &, const matrix::RoomState &, const matrix::proto::Event &); QRectF bounding_rect() const; void update_layout(const TimelineView &); }; class Block { public: Block(TimelineView &, const matrix::RoomState &, const matrix::proto::Event &, Event &); void update_header(TimelineView &view, const matrix::RoomState &state); void update_layout(const TimelineView &); void draw(const TimelineView &view, QPainter &p, QPointF offset, bool select_all, std::experimental::optional<QPointF> select_start, std::experimental::optional<QPointF> select_end) const; QRectF bounding_rect(const TimelineView &view) const; QString selection_text(const QFontMetrics &, bool select_all, std::experimental::optional<QPointF> select_start, std::experimental::optional<QPointF> select_end) const; const QString &sender_id() const { return sender_id_; } size_t size() const; const std::experimental::optional<matrix::Content> &avatar() const { return avatar_; } const Event *event_at(const QFontMetrics &, const QPointF &) const; std::deque<Event *> &events() { return events_; } const std::deque<Event *> &events() const { return events_; } private: const QString event_id_; const QString sender_id_; std::experimental::optional<matrix::Content> avatar_; QTextLayout name_layout_, timestamp_layout_; std::deque<Event *> events_; // deque so we can add events to either end }; struct Batch { std::deque<Event> events; // deque purely so we don't try to copy/move QTextLayout QString token; size_t size() const; }; struct Avatar { size_t references = 0; QPixmap pixmap; }; struct Selection { Block *start; // Point where selection began QPointF start_pos; // relative to start origin Block *end; // Point where selection completed QPointF end_pos; // relative to end origin }; struct VisibleBlock { Block *block; QRectF bounds; // relative to view }; class SelectionScanner { public: SelectionScanner(const std::experimental::optional<Selection> &s) : s_(s) {} void advance(const Block *b) { inside_selection_ &= !ending_selection(); starting_ = false; ending_ = false; check_starting(b); } bool on_selection_edge(const Block *b) const { return s_ && (b == s_->start || b == s_->end); } bool starting_selection() const { return starting_; } bool ending_selection() const { return ending_; } bool fully_selected(const Block *b) const { return inside_selection_ && !on_selection_edge(b); } std::experimental::optional<QPointF> start_point() const { return starting_selection() ? std::experimental::optional<QPointF>(selection_starts_at_start_ ? s_->start_pos : s_->end_pos) : std::experimental::optional<QPointF>(); } std::experimental::optional<QPointF> end_point() const { return ending_selection() ? std::experimental::optional<QPointF>(selection_starts_at_start_ ? s_->end_pos : s_->start_pos) : std::experimental::optional<QPointF>(); } private: const std::experimental::optional<Selection> &s_; bool inside_selection_ = false; bool selection_starts_at_start_; bool starting_ = false; bool ending_ = false; void check_starting(const Block *b) { starting_ = !inside_selection_ && on_selection_edge(b); ending_ = on_selection_edge(b) && (inside_selection_ || s_->start == s_->end); inside_selection_ |= starting_; if(starting_) selection_starts_at_start_ = b == s_->start; } }; matrix::Room &room_; matrix::RoomState initial_state_; std::deque<Batch> batches_; // deque so we can add/remote batches from either end std::deque<Block> blocks_; // what actually gets drawn size_t total_events_; bool head_color_alternate_; bool backlog_growing_; bool backlog_growable_; // false iff we've found the room create message bool backlog_grow_cancelled_; // true iff we reset since backlog started growing size_t min_backlog_size_; qreal content_height_; QString prev_batch_; // Token for the batch immediately prior to the first message std::unordered_map<matrix::Content, Avatar> avatars_; QIcon avatar_missing_, avatar_loading_; std::experimental::optional<Selection> selection_; QShortcut *copy_; std::vector<VisibleBlock> visible_blocks_; void update_scrollbar(); int visible_width() const; int block_spacing() const; int block_margin() const; int avatar_size() const; int block_body_start() const; int block_body_width() const; void grow_backlog(); void prepend_batch(QString start, QString end, gsl::span<const matrix::proto::Event> events); void backlog_grow_error(); int scrollback_trigger_size() const; int scrollback_status_size() const; void set_avatar(const matrix::Content &content, const QString &type, const QString &disposition, const QByteArray &data); void unref_avatar(const matrix::Content &); void copy(); void pop_front_block(); QString selection_text() const; VisibleBlock *block_near(const QPoint &p); // Point relative to view void prune_backlog(); // Removes enough blocks from the backlog that calling for each new event will cause backlog size to approach one // batch size greater than min_backlog_size_. Requires but does not perform scrollbar update! }; #endif <|endoftext|>
<commit_before><commit_msg>rename all TransposeMatMul nodes to FusedMatMul (#5373)<commit_after><|endoftext|>
<commit_before>/* * HyPerLayer.hpp * * Created on: Aug 3, 2008 * Author: dcoates */ #ifndef HYPERLAYER_HPP_ #define HYPERLAYER_HPP_ #include "../layers/PVLayer.h" #include "../layers/LayerDataInterface.hpp" #include "../layers/LIF2.h" #include "../columns/DataStore.hpp" #include "../columns/HyPerCol.hpp" #include "../columns/InterColComm.hpp" #include "../io/LayerProbe.hpp" #include "../include/pv_types.h" #include "../arch/opencl/CLBuffer.hpp" namespace PV { // HyPerLayer uses C code from PVLayer.{h,c}, and LIF2.{h,c} typedef LIF2_params HyPerLayerParams; /** * OpenCLLayer collects memory objects for sharing data with OpenCL devices */ typedef struct { CLBuffer * V; CLBuffer * G_E; CLBuffer * G_I; CLBuffer * G_IB; CLBuffer * phi; // collects all three phi buffers and hopefully will go away CLBuffer * activity; } OpenCLLayer; class HyPerLayer : public LayerDataInterface { protected: // only subclasses can be constructed directly HyPerLayer(const char * name, HyPerCol * hc); private: int initialize_base(const char * name, HyPerCol * hc); int initializeThreads(); public: virtual ~HyPerLayer() = 0; static int copyToBuffer(pvdata_t * buf, const pvdata_t * data, const PVLayerLoc * loc, bool extended, float scale); static int copyToBuffer(unsigned char * buf, const pvdata_t * data, const PVLayerLoc * loc, bool extended, float scale); static int copyFromBuffer(const pvdata_t * buf, pvdata_t * data, const PVLayerLoc * loc, bool extended, float scale); static int copyFromBuffer(const unsigned char * buf, pvdata_t * data, const PVLayerLoc * loc, bool extended, float scale); // TODO - make protected PVLayer* clayer; HyPerCol* parent; virtual int updateState(float time, float dt) = 0; virtual int recvSynapticInput(HyPerConn * conn, PVLayerCube * cube, int neighbor); virtual int reconstruct(HyPerConn * conn, PVLayerCube * cube); int initialize(PVLayerType type); int initFinish(); PVLayerCube * initBorder(PVLayerCube * border, int borderId); int mirrorInteriorToBorder(int whichBorder, PVLayerCube * cube, PVLayerCube * borderCube); virtual int columnWillAddLayer(InterColComm * comm, int id); virtual int setParams(int numParams, size_t sizeParams, float * params); virtual int getParams(int * numParams, float ** params); virtual int setFuncs(void * initFunc, void * updateFunc); virtual int publish(InterColComm * comm, float time); virtual int outputState(float time, bool last=false); virtual int writeState(const char * name, float time, bool last=false); virtual int writeActivity(const char * filename, float time); virtual int writeActivity(float time); virtual int writeActivitySparse(float time); virtual int readState(const char * name, float * time); virtual int insertProbe(LayerProbe * probe); /** returns the number of neurons in layer (for borderId=0) or a border region **/ virtual int numberOfNeurons(int borderId); virtual int mirrorToNorthWest(PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToNorth (PVLayerCube * dest, PVLayerCube* src); virtual int mirrorToNorthEast(PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToWest (PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToEast (PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToSouthWest(PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToSouth (PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToSouthEast(PVLayerCube * dest, PVLayerCube * src); // Public access functions: const char * getName() {return name;} int numActivity() {return clayer->numExtended;} int getLayerId() {return clayer->layerId;} void setLayerId(int id) {clayer->layerId = id;} PVLayer* getCLayer() {return clayer;} HyPerCol* getParent() {return parent;} void setParent(HyPerCol* parent) {this->parent = parent;} bool useMirrorBCs() {return this->mirrorBCflag;} // implementation of LayerDataInterface interface // const pvdata_t * getLayerData(); const PVLayerLoc * getLayerLoc() { return &clayer->loc; } bool isExtended() { return true; } virtual int gatherToInteriorBuffer(unsigned char * buf); protected: virtual int initGlobal(int colId, int colRow, int colCol, int nRows, int nCols); char * name; // well known name of layer int numProbes; LayerProbe ** probes; bool mirrorBCflag; // true when mirror BC are to be applied int ioAppend; // controls opening of binary files float writeTime; // time of next output float writeStep; // output time interval OpenCLLayer clBuffers; // data shared with OpenCL devices }; } // namespace PV #endif /* HYPERLAYER_HPP_ */ <commit_msg>Added member functions to return clayer->numNeurons, clayer->layerType, clayer->V and clayer->phi[channel]. Also changed the name of numActivity() to getNumNeurons(). It appears that no one is calling numActivity(), but if you are, getNumExtended() is the preferred name.<commit_after>/* * HyPerLayer.hpp * * Created on: Aug 3, 2008 * Author: dcoates */ #ifndef HYPERLAYER_HPP_ #define HYPERLAYER_HPP_ #include "../layers/PVLayer.h" #include "../layers/LayerDataInterface.hpp" #include "../layers/LIF2.h" #include "../columns/DataStore.hpp" #include "../columns/HyPerCol.hpp" #include "../columns/InterColComm.hpp" #include "../io/LayerProbe.hpp" #include "../include/pv_types.h" #include "../arch/opencl/CLBuffer.hpp" namespace PV { // HyPerLayer uses C code from PVLayer.{h,c}, and LIF2.{h,c} typedef LIF2_params HyPerLayerParams; /** * OpenCLLayer collects memory objects for sharing data with OpenCL devices */ typedef struct { CLBuffer * V; CLBuffer * G_E; CLBuffer * G_I; CLBuffer * G_IB; CLBuffer * phi; // collects all three phi buffers and hopefully will go away CLBuffer * activity; } OpenCLLayer; class HyPerLayer : public LayerDataInterface { protected: // only subclasses can be constructed directly HyPerLayer(const char * name, HyPerCol * hc); private: int initialize_base(const char * name, HyPerCol * hc); int initializeThreads(); public: virtual ~HyPerLayer() = 0; static int copyToBuffer(pvdata_t * buf, const pvdata_t * data, const PVLayerLoc * loc, bool extended, float scale); static int copyToBuffer(unsigned char * buf, const pvdata_t * data, const PVLayerLoc * loc, bool extended, float scale); static int copyFromBuffer(const pvdata_t * buf, pvdata_t * data, const PVLayerLoc * loc, bool extended, float scale); static int copyFromBuffer(const unsigned char * buf, pvdata_t * data, const PVLayerLoc * loc, bool extended, float scale); // TODO - make protected PVLayer* clayer; HyPerCol* parent; virtual int updateState(float time, float dt) = 0; virtual int recvSynapticInput(HyPerConn * conn, PVLayerCube * cube, int neighbor); virtual int reconstruct(HyPerConn * conn, PVLayerCube * cube); int initialize(PVLayerType type); int initFinish(); PVLayerCube * initBorder(PVLayerCube * border, int borderId); int mirrorInteriorToBorder(int whichBorder, PVLayerCube * cube, PVLayerCube * borderCube); virtual int columnWillAddLayer(InterColComm * comm, int id); virtual int setParams(int numParams, size_t sizeParams, float * params); virtual int getParams(int * numParams, float ** params); virtual int setFuncs(void * initFunc, void * updateFunc); virtual int publish(InterColComm * comm, float time); virtual int outputState(float time, bool last=false); virtual int writeState(const char * name, float time, bool last=false); virtual int writeActivity(const char * filename, float time); virtual int writeActivity(float time); virtual int writeActivitySparse(float time); virtual int readState(const char * name, float * time); virtual int insertProbe(LayerProbe * probe); /** returns the number of neurons in layer (for borderId=0) or a border region **/ virtual int numberOfNeurons(int borderId); virtual int mirrorToNorthWest(PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToNorth (PVLayerCube * dest, PVLayerCube* src); virtual int mirrorToNorthEast(PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToWest (PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToEast (PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToSouthWest(PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToSouth (PVLayerCube * dest, PVLayerCube * src); virtual int mirrorToSouthEast(PVLayerCube * dest, PVLayerCube * src); // Public access functions: const char * getName() {return name;} int getNumNeurons() {return clayer->numNeurons;} int getNumExtended() {return clayer->numExtended;} int getLayerId() {return clayer->layerId;} PVLayerType getLayerType() {return clayer->layerType;} void setLayerId(int id) {clayer->layerId = id;} PVLayer* getCLayer() {return clayer;} pvdata_t * getV() {return clayer->V;} // name query pvdata_t * getChannel(ChannelType ch) { // name query return ch < clayer->numPhis ? clayer->phi[ch] : NULL; } HyPerCol* getParent() {return parent;} void setParent(HyPerCol* parent) {this->parent = parent;} bool useMirrorBCs() {return this->mirrorBCflag;} // implementation of LayerDataInterface interface // const pvdata_t * getLayerData(); const PVLayerLoc * getLayerLoc() { return &clayer->loc; } bool isExtended() { return true; } virtual int gatherToInteriorBuffer(unsigned char * buf); protected: virtual int initGlobal(int colId, int colRow, int colCol, int nRows, int nCols); char * name; // well known name of layer int numProbes; LayerProbe ** probes; bool mirrorBCflag; // true when mirror BC are to be applied int ioAppend; // controls opening of binary files float writeTime; // time of next output float writeStep; // output time interval OpenCLLayer clBuffers; // data shared with OpenCL devices }; } // namespace PV #endif /* HYPERLAYER_HPP_ */ <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2012-, Open Perception, 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 the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef PCL_FILTERS_IMPL_FRUSTUM_CULLING_HPP_ #define PCL_FILTERS_IMPL_FRUSTUM_CULLING_HPP_ #include <pcl/filters/frustum_culling.h> #include <vector> /////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::FrustumCulling<PointT>::applyFilter (PointCloud& output) { Eigen::Vector4f pl_n; // near plane Eigen::Vector4f pl_f; // far plane Eigen::Vector4f pl_t; // top plane Eigen::Vector4f pl_b; // bottom plane Eigen::Vector4f pl_r; // right plane Eigen::Vector4f pl_l; // left plane Eigen::Vector3f view = camera_pose_.block (0, 0, 3, 1); // view vector for the camera - first column of the rotation matrix Eigen::Vector3f up = camera_pose_.block (0, 1, 3, 1); // up vector for the camera - second column of the rotation matix Eigen::Vector3f right = camera_pose_.block (0, 2, 3, 1); // right vector for the camera - third column of the rotation matrix Eigen::Vector3f T = camera_pose_.block (0, 3, 3, 1); // The (X, Y, Z) position of the camera w.r.t origin vfov_ = float (vfov_ * M_PI / 180); // degrees to radians hfov_ = float (hfov_ * M_PI / 180); // degrees to radians float np_h = float (2 * tan (vfov_ / 2) * np_dist_); // near plane height float np_w = float (2 * tan (hfov_ / 2) * np_dist_); // near plane width float fp_h = float (2 * tan (vfov_ / 2) * fp_dist_); // far plane height float fp_w = float (2 * tan (hfov_ / 2) * fp_dist_); // far plane width Eigen::Vector3f fp_c (T + view * fp_dist_); // far plane center Eigen::Vector3f fp_tl (fp_c + (up * fp_h / 2) - (right * fp_w / 2)); // Top left corner of the far plane Eigen::Vector3f fp_tr (fp_c + (up * fp_h / 2) + (right * fp_w / 2)); // Top right corner of the far plane Eigen::Vector3f fp_bl (fp_c - (up * fp_h / 2) - (right * fp_w / 2)); // Bottom left corner of the far plane Eigen::Vector3f fp_br (fp_c - (up * fp_h / 2) + (right * fp_w / 2)); // Bottom right corner of the far plane Eigen::Vector3f np_c (T + view * np_dist_); // near plane center //Eigen::Vector3f np_tl = np_c + (up * np_h/2) - (right * np_w/2); // Top left corner of the near plane Eigen::Vector3f np_tr (np_c + (up * np_h / 2) + (right * np_w / 2)); // Top right corner of the near plane Eigen::Vector3f np_bl (np_c - (up * np_h / 2) - (right * np_w / 2)); // Bottom left corner of the near plane Eigen::Vector3f np_br (np_c - (up * np_h / 2) + (right * np_w / 2)); // Bottom right corner of the near plane pl_f.block (0, 0, 3, 1).matrix () = (fp_bl - fp_br).cross (fp_tr - fp_br); // Far plane equation - cross product of the pl_f (3) = -fp_c.dot (pl_f.block (0, 0, 3, 1)); // perpendicular edges of the far plane pl_n.block (0, 0, 3, 1).matrix () = (np_tr - np_br).cross (np_bl - np_br); // Near plane equation - cross product of the pl_n (3) = -np_c.dot (pl_n.block (0, 0, 3, 1)); // perpendicular edges of the far plane Eigen::Vector3f a (fp_bl - T); // Vector connecting the camera and far plane bottom left Eigen::Vector3f b (fp_br - T); // Vector connecting the camera and far plane bottom right Eigen::Vector3f c (fp_tr - T); // Vector connecting the camera and far plane top right Eigen::Vector3f d (fp_tl - T); // Vector connecting the camera and far plane top left // Frustum and the vectors a, b, c and d. T is the position of the camera // _________ // /| . | // d / | c . | // / | __._____| // / / . . // a <---/-/ . . // / / . . b // / . // . // T // pl_r.block (0, 0, 3, 1).matrix () = b.cross (c); pl_l.block (0, 0, 3, 1).matrix () = d.cross (a); pl_t.block (0, 0, 3, 1).matrix () = c.cross (d); pl_b.block (0, 0, 3, 1).matrix () = a.cross (b); pl_r (3) = -T.dot (pl_r.block (0, 0, 3, 1)); pl_l (3) = -T.dot (pl_l.block (0, 0, 3, 1)); pl_t (3) = -T.dot (pl_t.block (0, 0, 3, 1)); pl_b (3) = -T.dot (pl_b.block (0, 0, 3, 1)); output.reserve (input_->points.size ()); for (int i = 0; i < int (input_->points.size ()); i++) { Eigen::Vector4f pt (input_->points[i].x, input_->points[i].y, input_->points[i].z, 1.0f); if ( (pt.dot (pl_l) <= 0) && (pt.dot (pl_r) <= 0) && (pt.dot (pl_t) <= 0) && (pt.dot (pl_b) <= 0) && (pt.dot (pl_f) <= 0) && (pt.dot (pl_n) <= 0) ) { output.points.push_back (input_->points[i]); } } output.width = 1; output.height = uint32_t (output.points.size ()); } /////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::FrustumCulling<PointT>::applyFilter (std::vector<int> &indices) { int indices_count = 0; int removed_indices_count = 0; Eigen::Vector4f pl_n; // near plane Eigen::Vector4f pl_f; // far plane Eigen::Vector4f pl_t; // top plane Eigen::Vector4f pl_b; // bottom plane Eigen::Vector4f pl_r; // right plane Eigen::Vector4f pl_l; // left plane Eigen::Vector3f view = camera_pose_.block (0, 0, 3, 1); // view vector for the camera - first column of the rotation matrix Eigen::Vector3f up = camera_pose_.block (0, 1, 3, 1); // up vector for the camera - second column of the rotation matix Eigen::Vector3f right = camera_pose_.block (0, 2, 3, 1); // right vector for the camera - third column of the rotation matrix Eigen::Vector3f T = camera_pose_.block (0, 3, 3, 1); // The (X, Y, Z) position of the camera w.r.t origin vfov_ = float (vfov_ * M_PI / 180); // degrees to radians hfov_ = float (hfov_ * M_PI / 180); // degrees to radians float np_h = float (2 * tan (vfov_ / 2) * np_dist_); // near plane height float np_w = float (2 * tan (hfov_ / 2) * np_dist_); // near plane width float fp_h = float (2 * tan (vfov_ / 2) * fp_dist_); // far plane height float fp_w = float (2 * tan (hfov_ / 2) * fp_dist_); // far plane width Eigen::Vector3f fp_c (T + view * fp_dist_); // far plane center Eigen::Vector3f fp_tl (fp_c + (up * fp_h / 2) - (right * fp_w / 2)); // Top left corner of the far plane Eigen::Vector3f fp_tr (fp_c + (up * fp_h / 2) + (right * fp_w / 2)); // Top right corner of the far plane Eigen::Vector3f fp_bl (fp_c - (up * fp_h / 2) - (right * fp_w / 2)); // Bottom left corner of the far plane Eigen::Vector3f fp_br (fp_c - (up * fp_h / 2) + (right * fp_w / 2)); // Bottom right corner of the far plane Eigen::Vector3f np_c (T + view * np_dist_); // near plane center //Eigen::Vector3f np_tl = np_c + (up * np_h/2) - (right * np_w/2); // Top left corner of the near plane Eigen::Vector3f np_tr (np_c + (up * np_h / 2) + (right * np_w / 2)); // Top right corner of the near plane Eigen::Vector3f np_bl (np_c - (up * np_h / 2) - (right * np_w / 2)); // Bottom left corner of the near plane Eigen::Vector3f np_br (np_c - (up * np_h / 2) + (right * np_w / 2)); // Bottom right corner of the near plane pl_f.block (0, 0, 3, 1).matrix () = (fp_bl - fp_br).cross (fp_tr - fp_br); // Far plane equation - cross product of the pl_f (3) = -fp_c.dot (pl_f.block (0, 0, 3, 1)); // perpendicular edges of the far plane pl_n.block (0, 0, 3, 1).matrix () = (np_tr - np_br).cross (np_bl - np_br); // Near plane equation - cross product of the pl_n (3) = -np_c.dot (pl_n.block (0, 0, 3, 1)); // perpendicular edges of the far plane Eigen::Vector3f a (fp_bl - T); // Vector connecting the camera and far plane bottom left Eigen::Vector3f b (fp_br - T); // Vector connecting the camera and far plane bottom right Eigen::Vector3f c (fp_tr - T); // Vector connecting the camera and far plane top right Eigen::Vector3f d (fp_tl - T); // Vector connecting the camera and far plane top left // Frustum and the vectors a, b, c and d. T is the position of the camera // _________ // /| . | // d / | c . | // / | __._____| // / / . . // a <---/-/ . . // / / . . b // / . // . // T // pl_r.block (0, 0, 3, 1).matrix () = b.cross (c); pl_l.block (0, 0, 3, 1).matrix () = d.cross (a); pl_t.block (0, 0, 3, 1).matrix () = c.cross (d); pl_b.block (0, 0, 3, 1).matrix () = a.cross (b); pl_r (3) = -T.dot (pl_r.block (0, 0, 3, 1)); pl_l (3) = -T.dot (pl_l.block (0, 0, 3, 1)); pl_t (3) = -T.dot (pl_t.block (0, 0, 3, 1)); pl_b (3) = -T.dot (pl_b.block (0, 0, 3, 1)); removed_indices_->reserve (indices.size ()); for (int i = 0; i < int (indices.size ()); i++) { Eigen::Vector4f pt (input_->points[indices[i]].x, input_->points[indices[i]].y, input_->points[indices[i]].z, 1.0f); if ( (pt.dot (pl_l) <= 0) && (pt.dot (pl_r) <= 0) && (pt.dot (pl_t) <= 0) && (pt.dot (pl_b) <= 0) && (pt.dot (pl_f) <= 0) && (pt.dot (pl_n) <= 0) ) { if (extract_removed_indices_) { (*removed_indices_)[removed_indices_count++] = static_cast<int> (i); } else { indices[indices_count++] = (*indices_)[i]; } } } indices.resize (indices_count); removed_indices_->resize (removed_indices_count); } #define PCL_INSTANTIATE_FrustumCulling(T) template class PCL_EXPORTS pcl::FrustumCulling<T>; #endif <commit_msg>Fixed a few bugs in @FrustumCulling@<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2012-, Open Perception, 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 the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef PCL_FILTERS_IMPL_FRUSTUM_CULLING_HPP_ #define PCL_FILTERS_IMPL_FRUSTUM_CULLING_HPP_ #include <pcl/filters/frustum_culling.h> #include <vector> /////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::FrustumCulling<PointT>::applyFilter (PointCloud& output) { Eigen::Vector4f pl_n; // near plane Eigen::Vector4f pl_f; // far plane Eigen::Vector4f pl_t; // top plane Eigen::Vector4f pl_b; // bottom plane Eigen::Vector4f pl_r; // right plane Eigen::Vector4f pl_l; // left plane Eigen::Vector3f view = camera_pose_.block (0, 0, 3, 1); // view vector for the camera - first column of the rotation matrix Eigen::Vector3f up = camera_pose_.block (0, 1, 3, 1); // up vector for the camera - second column of the rotation matix Eigen::Vector3f right = camera_pose_.block (0, 2, 3, 1); // right vector for the camera - third column of the rotation matrix Eigen::Vector3f T = camera_pose_.block (0, 3, 3, 1); // The (X, Y, Z) position of the camera w.r.t origin vfov_ = float (vfov_ * M_PI / 180); // degrees to radians hfov_ = float (hfov_ * M_PI / 180); // degrees to radians float np_h = float (2 * tan (vfov_ / 2) * np_dist_); // near plane height float np_w = float (2 * tan (hfov_ / 2) * np_dist_); // near plane width float fp_h = float (2 * tan (vfov_ / 2) * fp_dist_); // far plane height float fp_w = float (2 * tan (hfov_ / 2) * fp_dist_); // far plane width Eigen::Vector3f fp_c (T + view * fp_dist_); // far plane center Eigen::Vector3f fp_tl (fp_c + (up * fp_h / 2) - (right * fp_w / 2)); // Top left corner of the far plane Eigen::Vector3f fp_tr (fp_c + (up * fp_h / 2) + (right * fp_w / 2)); // Top right corner of the far plane Eigen::Vector3f fp_bl (fp_c - (up * fp_h / 2) - (right * fp_w / 2)); // Bottom left corner of the far plane Eigen::Vector3f fp_br (fp_c - (up * fp_h / 2) + (right * fp_w / 2)); // Bottom right corner of the far plane Eigen::Vector3f np_c (T + view * np_dist_); // near plane center //Eigen::Vector3f np_tl = np_c + (up * np_h/2) - (right * np_w/2); // Top left corner of the near plane Eigen::Vector3f np_tr (np_c + (up * np_h / 2) + (right * np_w / 2)); // Top right corner of the near plane Eigen::Vector3f np_bl (np_c - (up * np_h / 2) - (right * np_w / 2)); // Bottom left corner of the near plane Eigen::Vector3f np_br (np_c - (up * np_h / 2) + (right * np_w / 2)); // Bottom right corner of the near plane pl_f.block (0, 0, 3, 1).matrix () = (fp_bl - fp_br).cross (fp_tr - fp_br); // Far plane equation - cross product of the pl_f (3) = -fp_c.dot (pl_f.block (0, 0, 3, 1)); // perpendicular edges of the far plane pl_n.block (0, 0, 3, 1).matrix () = (np_tr - np_br).cross (np_bl - np_br); // Near plane equation - cross product of the pl_n (3) = -np_c.dot (pl_n.block (0, 0, 3, 1)); // perpendicular edges of the far plane Eigen::Vector3f a (fp_bl - T); // Vector connecting the camera and far plane bottom left Eigen::Vector3f b (fp_br - T); // Vector connecting the camera and far plane bottom right Eigen::Vector3f c (fp_tr - T); // Vector connecting the camera and far plane top right Eigen::Vector3f d (fp_tl - T); // Vector connecting the camera and far plane top left // Frustum and the vectors a, b, c and d. T is the position of the camera // _________ // /| . | // d / | c . | // / | __._____| // / / . . // a <---/-/ . . // / / . . b // / . // . // T // pl_r.block (0, 0, 3, 1).matrix () = b.cross (c); pl_l.block (0, 0, 3, 1).matrix () = d.cross (a); pl_t.block (0, 0, 3, 1).matrix () = c.cross (d); pl_b.block (0, 0, 3, 1).matrix () = a.cross (b); pl_r (3) = -T.dot (pl_r.block (0, 0, 3, 1)); pl_l (3) = -T.dot (pl_l.block (0, 0, 3, 1)); pl_t (3) = -T.dot (pl_t.block (0, 0, 3, 1)); pl_b (3) = -T.dot (pl_b.block (0, 0, 3, 1)); output.reserve (input_->points.size ()); for (int i = 0; i < int (input_->points.size ()); i++) { Eigen::Vector4f pt (input_->points[i].x, input_->points[i].y, input_->points[i].z, 1.0f); if ( (pt.dot (pl_l) <= 0) && (pt.dot (pl_r) <= 0) && (pt.dot (pl_t) <= 0) && (pt.dot (pl_b) <= 0) && (pt.dot (pl_f) <= 0) && (pt.dot (pl_n) <= 0) ) { output.points.push_back (input_->points[i]); } } output.width = 1; output.height = uint32_t (output.points.size ()); } /////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::FrustumCulling<PointT>::applyFilter (std::vector<int> &indices) { int indices_count = 0; int removed_indices_count = 0; Eigen::Vector4f pl_n; // near plane Eigen::Vector4f pl_f; // far plane Eigen::Vector4f pl_t; // top plane Eigen::Vector4f pl_b; // bottom plane Eigen::Vector4f pl_r; // right plane Eigen::Vector4f pl_l; // left plane Eigen::Vector3f view = camera_pose_.block (0, 0, 3, 1); // view vector for the camera - first column of the rotation matrix Eigen::Vector3f up = camera_pose_.block (0, 1, 3, 1); // up vector for the camera - second column of the rotation matix Eigen::Vector3f right = camera_pose_.block (0, 2, 3, 1); // right vector for the camera - third column of the rotation matrix Eigen::Vector3f T = camera_pose_.block (0, 3, 3, 1); // The (X, Y, Z) position of the camera w.r.t origin vfov_ = float (vfov_ * M_PI / 180); // degrees to radians hfov_ = float (hfov_ * M_PI / 180); // degrees to radians float np_h = float (2 * tan (vfov_ / 2) * np_dist_); // near plane height float np_w = float (2 * tan (hfov_ / 2) * np_dist_); // near plane width float fp_h = float (2 * tan (vfov_ / 2) * fp_dist_); // far plane height float fp_w = float (2 * tan (hfov_ / 2) * fp_dist_); // far plane width Eigen::Vector3f fp_c (T + view * fp_dist_); // far plane center Eigen::Vector3f fp_tl (fp_c + (up * fp_h / 2) - (right * fp_w / 2)); // Top left corner of the far plane Eigen::Vector3f fp_tr (fp_c + (up * fp_h / 2) + (right * fp_w / 2)); // Top right corner of the far plane Eigen::Vector3f fp_bl (fp_c - (up * fp_h / 2) - (right * fp_w / 2)); // Bottom left corner of the far plane Eigen::Vector3f fp_br (fp_c - (up * fp_h / 2) + (right * fp_w / 2)); // Bottom right corner of the far plane Eigen::Vector3f np_c (T + view * np_dist_); // near plane center //Eigen::Vector3f np_tl = np_c + (up * np_h/2) - (right * np_w/2); // Top left corner of the near plane Eigen::Vector3f np_tr (np_c + (up * np_h / 2) + (right * np_w / 2)); // Top right corner of the near plane Eigen::Vector3f np_bl (np_c - (up * np_h / 2) - (right * np_w / 2)); // Bottom left corner of the near plane Eigen::Vector3f np_br (np_c - (up * np_h / 2) + (right * np_w / 2)); // Bottom right corner of the near plane pl_f.block (0, 0, 3, 1).matrix () = (fp_bl - fp_br).cross (fp_tr - fp_br); // Far plane equation - cross product of the pl_f (3) = -fp_c.dot (pl_f.block (0, 0, 3, 1)); // perpendicular edges of the far plane pl_n.block (0, 0, 3, 1).matrix () = (np_tr - np_br).cross (np_bl - np_br); // Near plane equation - cross product of the pl_n (3) = -np_c.dot (pl_n.block (0, 0, 3, 1)); // perpendicular edges of the far plane Eigen::Vector3f a (fp_bl - T); // Vector connecting the camera and far plane bottom left Eigen::Vector3f b (fp_br - T); // Vector connecting the camera and far plane bottom right Eigen::Vector3f c (fp_tr - T); // Vector connecting the camera and far plane top right Eigen::Vector3f d (fp_tl - T); // Vector connecting the camera and far plane top left // Frustum and the vectors a, b, c and d. T is the position of the camera // _________ // /| . | // d / | c . | // / | __._____| // / / . . // a <---/-/ . . // / / . . b // / . // . // T // pl_r.block (0, 0, 3, 1).matrix () = b.cross (c); pl_l.block (0, 0, 3, 1).matrix () = d.cross (a); pl_t.block (0, 0, 3, 1).matrix () = c.cross (d); pl_b.block (0, 0, 3, 1).matrix () = a.cross (b); pl_r (3) = -T.dot (pl_r.block (0, 0, 3, 1)); pl_l (3) = -T.dot (pl_l.block (0, 0, 3, 1)); pl_t (3) = -T.dot (pl_t.block (0, 0, 3, 1)); pl_b (3) = -T.dot (pl_b.block (0, 0, 3, 1)); removed_indices_->clear (); removed_indices_->reserve (indices_->size ()); indices.clear (); indices.reserve (indices_->size ()); for (size_t i = 0; i < indices_->size (); i++) { int idx = indices_->at (i); Eigen::Vector4f pt (input_->points[idx].x, input_->points[idx].y, input_->points[idx].z, 1.0f); if ( (pt.dot (pl_l) <= 0) && (pt.dot (pl_r) <= 0) && (pt.dot (pl_t) <= 0) && (pt.dot (pl_b) <= 0) && (pt.dot (pl_f) <= 0) && (pt.dot (pl_n) <= 0) ) { if (extract_removed_indices_) { removed_indices_->push_back (idx); } indices.push_back (idx); } } } #define PCL_INSTANTIATE_FrustumCulling(T) template class PCL_EXPORTS pcl::FrustumCulling<T>; #endif <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow 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. ==============================================================================*/ #include "tensorflow/compiler/xla/service/liveness_util.h" #include <algorithm> #include <utility> #include <vector> #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/logical_buffer.h" #include "tensorflow/compiler/xla/service/tuple_points_to_analysis.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" namespace xla { bool DoesNotUseOperandBuffer(const HloInstruction* operand, const ShapeIndex& index, const HloInstruction* user, const TuplePointsToAnalysis& points_to_analysis) { CHECK(user->IsUserOf(operand)) << "user: " << user->ToString() << " operand: " << operand->ToString(); if (user->opcode() == HloOpcode::kGetTupleElement && !index.empty()) { // GetTupleElement instructions only access the top-level buffer of their // operand. return true; } else if (user->opcode() == HloOpcode::kFusion && user->fusion_kind() == HloInstruction::FusionKind::kLoop) { // Find fusion parameter associated with 'operand'. auto it = std::find_if( user->fused_parameters().begin(), user->fused_parameters().end(), [=](HloInstruction* fused_param) { return user->operand(fused_param->parameter_number()) == operand; }); CHECK(it != user->fused_parameters().end()); // Iterate through all users of all buffer aliases of the buffer in the // points-to set of fusion parameter at 'index'. // Return false if any uses are detected at 'index', returns true otherwise. const LogicalBuffer* buffer = points_to_analysis.GetBufferDefinedAt(*it, index).ValueOrDie(); for (const BufferAlias& alias : points_to_analysis.GetBufferAliases(*buffer)) { for (HloInstruction* alias_user : alias.instruction()->users()) { if (DoesNotUseOperandBuffer(alias.instruction(), alias.index(), alias_user, points_to_analysis)) { continue; } // Return false: use detected at 'buffer' -> 'alias' -> 'alias_user'. return false; } } // Return true: found no uses of 'operand' at 'index' in 'user'. return true; } return false; } bool DoesNotUseOperandBuffer(const HloInstruction* operand, const ShapeIndex& index, const HloInstruction* user, const HloDataflowAnalysis& dataflow) { CHECK(user->IsUserOf(operand)) << "user: " << user->ToString() << " operand: " << operand->ToString(); if (user->opcode() == HloOpcode::kFusion && user->fusion_kind() == HloInstruction::FusionKind::kLoop) { // Find fusion parameter associated with 'operand'. HloInstruction* fusion_param = user->fused_parameter(user->operand_index(operand)); // Iterate through all users of all uses of the fusion parameter value. // Return false if any uses are detected, returns true otherwise. const HloValue& value = dataflow.GetValueDefinedAt(fusion_param, index); return value.uses().empty(); } else { // Return false if no value at 'operand' and 'index' is used at 'user'. for (const HloValue* value : dataflow.GetValueSet(operand, index).values()) { for (const HloUse& use : value->uses()) { if (use.instruction == user) { return false; } } } } return true; } namespace { // Returns all uses of all aliases of 'instruction' at 'index' in 'uses'. // Each use in 'uses' is a pair (HloInstruction* user, int64 operand_index) // where 'user' is a user of an alias of 'intruction' at 'index', and // 'operand_index' is the operand index at which the alias appears in the // operand list of 'user'. std::vector<std::pair<HloInstruction*, int64>> GetAllUsesOfInstructionAtIndex( HloInstruction* instruction, const ShapeIndex& index, const TuplePointsToAnalysis& points_to_analysis) { std::vector<std::pair<HloInstruction*, int64>> uses; const PointsToSet::BufferList& points_to = points_to_analysis.GetPointsToSet(instruction).element(index); for (const LogicalBuffer* buffer : points_to) { for (const BufferAlias& alias : points_to_analysis.GetBufferAliases(*buffer)) { for (HloInstruction* alias_user : alias.instruction()->users()) { if (DoesNotUseOperandBuffer(alias.instruction(), alias.index(), alias_user, points_to_analysis)) { continue; } for (int64 op_idx : alias_user->OperandIndices(alias.instruction())) { uses.emplace_back(alias_user, op_idx); } } } } return uses; } // Returns true if there is exactly one use of 'operand' at 'operand_index' // in 'fusion.fused_instructions', where the singleton use is the fused // root at operand index 'use_operand_index'. Returns false otherwise. // // REQUIRES: 'fusion' opcode is a kFusion instruction. bool HasUniqueFusedUseOfOperandAt( HloInstruction* operand, const ShapeIndex& operand_index, HloInstruction* fusion, const int64 use_operand_index, const TuplePointsToAnalysis& points_to_analysis) { CHECK_EQ(HloOpcode::kFusion, fusion->opcode()); // Check that 'operand' is unique in the operand list of 'fusion'. if (fusion->OperandIndices(operand).size() > 1) { return false; } // Find fusion parameter associated with 'operand'. const auto& fused_params = fusion->fused_parameters(); auto fused_param_it = std::find_if( fused_params.begin(), fused_params.end(), [&](HloInstruction* fused_param) { return fusion->operand(fused_param->parameter_number()) == operand; }); if (fused_param_it == fused_params.end()) { return false; } auto* fused_param = *fused_param_it; // Get all uses of 'operand' at 'index' from 'fusion.fused_instructions'. auto fused_param_uses = GetAllUsesOfInstructionAtIndex( fused_param, operand_index, points_to_analysis); // Return true iff there is exactly one use of 'operand' at 'index', and // this singleton use is the fused root (at index in 'use_operand_indices'). return fused_param_uses.size() == 1 && fused_param_uses[0].first == fusion->fused_expression_root() && fused_param_uses[0].second == use_operand_index; } } // namespace // User and operand can share buffers iff both instructions emit the same shape // and layout, and 'user' meets one of the following qualifications: // // (1) Is element-wise. Or... // (2) Is a loop fusion instruction where the only use of 'operand' at 'index' // in the set 'user.fused_instructions' is a DynamicUpdateSlice fused root // at operand 0. Or... // (3) Is a kDot -> kAdd (or fused kTransposeDot -> kAdd) output fusion // instruction where the only use of 'operand' at 'index' in the set // 'user.fused_instructions' is a kAdd fused root at operand 0 or 1. Or... // (4) The 'user' of 'operand' is DynamicUpdateSlice or While at operand index // 0. // // (2) and (3) can only be determined if points-to analysis is available. bool CanShareOperandBufferWithUser( HloInstruction* operand, const ShapeIndex& operand_index, HloInstruction* user, const ShapeIndex& user_index, const TuplePointsToAnalysis& points_to_analysis) { CHECK(user->IsUserOf(operand)) << "user: " << user->ToString() << " operand: " << operand->ToString(); const Shape& operand_subshape = ShapeUtil::GetSubshape(operand->shape(), operand_index); const Shape& user_subshape = ShapeUtil::GetSubshape(user->shape(), user_index); // Check that operand and user emit the same shape and layout. if (!ShapeUtil::Equal(operand_subshape, user_subshape)) { return false; } if (user->opcode() == HloOpcode::kFusion) { if (user->fusion_kind() == HloInstruction::FusionKind::kLoop && user->fused_expression_root()->opcode() == HloOpcode::kDynamicUpdateSlice) { // Loop fusion with kDynamicUpdateSlice fused root. // // Returns true iff there is exactly one use of 'operand' at shape index // 'operand_index', and this singleton use is the fused root at operand // index 0. return HasUniqueFusedUseOfOperandAt(operand, operand_index, user, 0, points_to_analysis); } else if (user->fusion_kind() == HloInstruction::FusionKind::kOutput && user->fused_expression_root()->opcode() == HloOpcode::kAdd) { // Output fusion with kAdd fused root. // Check if one operand of kAdd fused root is either kDot, or nested // kFusion of kind kTransposeDot. auto* add = user->fused_expression_root(); auto add_operand_it = std::find_if(add->operands().begin(), add->operands().end(), [&](HloInstruction* operand) { return operand->opcode() == HloOpcode::kDot || (operand->opcode() == HloOpcode::kFusion && operand->fusion_kind() == HloInstruction::FusionKind::kTransposeDot); }); if (add_operand_it == add->operands().end()) { return false; } auto* matched_add_operand = *add_operand_it; // Calculate operand index of 'add' operand which was not matched above. const int64 other_add_operand_index = matched_add_operand == add->operand(0) ? 1 : 0; // Returns true iff there is exactly one use of 'operand' at shape index // 'operand_index', and this singleton use is the fused root (at operand // index 'other_add_operand_index'). return HasUniqueFusedUseOfOperandAt(operand, operand_index, user, other_add_operand_index, points_to_analysis); } } if (user->opcode() == HloOpcode::kDynamicUpdateSlice || user->opcode() == HloOpcode::kWhile) { // We eliminated other users in BufferLiveness::live_range_strictly_before, // so here we just need to check that the use is at operand index 0. std::vector<int64> operand_indices = user->OperandIndices(operand); return operand_indices.size() == 1 && operand_indices[0] == 0; } // Check if 'user' is element-wise. return user->IsElementwise(); } bool CanShareOperandBufferWithUser(HloInstruction* operand, const ShapeIndex& operand_index, HloInstruction* user, const ShapeIndex& user_index, const HloDataflowAnalysis& dataflow) { CHECK(user->IsUserOf(operand)) << "user: " << user->ToString() << " operand: " << operand->ToString(); const Shape& operand_subshape = ShapeUtil::GetSubshape(operand->shape(), operand_index); const Shape& user_subshape = ShapeUtil::GetSubshape(user->shape(), user_index); // Check that operand and user emit the same shape and layout. if (!ShapeUtil::Equal(operand_subshape, user_subshape)) { return false; } if (user->opcode() == HloOpcode::kFusion) { // Get the parameter associated with 'operand'; HloInstruction* fusion_param = user->fused_parameter(user->operand_index(operand)); const HloValue& value = dataflow.GetValueDefinedAt(fusion_param, operand_index); if (value.uses().size() != 1) { return false; } const HloUse& use = value.uses()[0]; if (user->fusion_kind() == HloInstruction::FusionKind::kLoop && user->fused_expression_root()->opcode() == HloOpcode::kDynamicUpdateSlice) { // Loop fusion with kDynamicUpdateSlice fused root. // // Returns true iff there is exactly one use of 'operand' at shape index // 'operand_index', and this singleton use is the fused root at operand // index 0. return use.instruction == user->fused_expression_root() && use.operand_number == 0; } else if (user->fusion_kind() == HloInstruction::FusionKind::kOutput && user->fused_expression_root()->opcode() == HloOpcode::kAdd) { // Output fusion with kAdd fused root. // Check if one operand of kAdd fused root is either kDot, or nested // kFusion of kind kTransposeDot. auto* add = user->fused_expression_root(); auto add_operand_it = std::find_if(add->operands().begin(), add->operands().end(), [&](HloInstruction* operand) { return operand->opcode() == HloOpcode::kDot || (operand->opcode() == HloOpcode::kFusion && operand->fusion_kind() == HloInstruction::FusionKind::kTransposeDot); }); if (add_operand_it == add->operands().end()) { return false; } auto* matched_add_operand = *add_operand_it; // Calculate operand index of 'add' operand which was not matched above. const int64 other_add_operand_index = matched_add_operand == add->operand(0) ? 1 : 0; // Returns true iff there is exactly one use of 'operand' at shape index // 'operand_index', and this singleton use is the fused root (at operand // index 'other_add_operand_index'). return use.instruction == user->fused_expression_root() && use.operand_number == other_add_operand_index; } } if (user->opcode() == HloOpcode::kDynamicUpdateSlice || user->opcode() == HloOpcode::kWhile) { // We eliminated other users in BufferLiveness::live_range_strictly_before, // so here we just need to check that the use is at operand index 0. std::vector<int64> operand_indices = user->OperandIndices(operand); return operand_indices.size() == 1 && operand_indices[0] == 0; } // Check if 'user' is element-wise. return user->IsElementwise(); } } // namespace xla <commit_msg>[XLA] Include kConvolution in the dot-add liveness optimization<commit_after>/* Copyright 2017 The TensorFlow 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. ==============================================================================*/ #include "tensorflow/compiler/xla/service/liveness_util.h" #include <algorithm> #include <utility> #include <vector> #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/logical_buffer.h" #include "tensorflow/compiler/xla/service/tuple_points_to_analysis.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" namespace xla { bool DoesNotUseOperandBuffer(const HloInstruction* operand, const ShapeIndex& index, const HloInstruction* user, const TuplePointsToAnalysis& points_to_analysis) { CHECK(user->IsUserOf(operand)) << "user: " << user->ToString() << " operand: " << operand->ToString(); if (user->opcode() == HloOpcode::kGetTupleElement && !index.empty()) { // GetTupleElement instructions only access the top-level buffer of their // operand. return true; } else if (user->opcode() == HloOpcode::kFusion && user->fusion_kind() == HloInstruction::FusionKind::kLoop) { // Find fusion parameter associated with 'operand'. auto it = std::find_if( user->fused_parameters().begin(), user->fused_parameters().end(), [=](HloInstruction* fused_param) { return user->operand(fused_param->parameter_number()) == operand; }); CHECK(it != user->fused_parameters().end()); // Iterate through all users of all buffer aliases of the buffer in the // points-to set of fusion parameter at 'index'. // Return false if any uses are detected at 'index', returns true otherwise. const LogicalBuffer* buffer = points_to_analysis.GetBufferDefinedAt(*it, index).ValueOrDie(); for (const BufferAlias& alias : points_to_analysis.GetBufferAliases(*buffer)) { for (HloInstruction* alias_user : alias.instruction()->users()) { if (DoesNotUseOperandBuffer(alias.instruction(), alias.index(), alias_user, points_to_analysis)) { continue; } // Return false: use detected at 'buffer' -> 'alias' -> 'alias_user'. return false; } } // Return true: found no uses of 'operand' at 'index' in 'user'. return true; } return false; } bool DoesNotUseOperandBuffer(const HloInstruction* operand, const ShapeIndex& index, const HloInstruction* user, const HloDataflowAnalysis& dataflow) { CHECK(user->IsUserOf(operand)) << "user: " << user->ToString() << " operand: " << operand->ToString(); if (user->opcode() == HloOpcode::kFusion && user->fusion_kind() == HloInstruction::FusionKind::kLoop) { // Find fusion parameter associated with 'operand'. HloInstruction* fusion_param = user->fused_parameter(user->operand_index(operand)); // Iterate through all users of all uses of the fusion parameter value. // Return false if any uses are detected, returns true otherwise. const HloValue& value = dataflow.GetValueDefinedAt(fusion_param, index); return value.uses().empty(); } else { // Return false if no value at 'operand' and 'index' is used at 'user'. for (const HloValue* value : dataflow.GetValueSet(operand, index).values()) { for (const HloUse& use : value->uses()) { if (use.instruction == user) { return false; } } } } return true; } namespace { // Returns all uses of all aliases of 'instruction' at 'index' in 'uses'. // Each use in 'uses' is a pair (HloInstruction* user, int64 operand_index) // where 'user' is a user of an alias of 'intruction' at 'index', and // 'operand_index' is the operand index at which the alias appears in the // operand list of 'user'. std::vector<std::pair<HloInstruction*, int64>> GetAllUsesOfInstructionAtIndex( HloInstruction* instruction, const ShapeIndex& index, const TuplePointsToAnalysis& points_to_analysis) { std::vector<std::pair<HloInstruction*, int64>> uses; const PointsToSet::BufferList& points_to = points_to_analysis.GetPointsToSet(instruction).element(index); for (const LogicalBuffer* buffer : points_to) { for (const BufferAlias& alias : points_to_analysis.GetBufferAliases(*buffer)) { for (HloInstruction* alias_user : alias.instruction()->users()) { if (DoesNotUseOperandBuffer(alias.instruction(), alias.index(), alias_user, points_to_analysis)) { continue; } for (int64 op_idx : alias_user->OperandIndices(alias.instruction())) { uses.emplace_back(alias_user, op_idx); } } } } return uses; } // Returns true if there is exactly one use of 'operand' at 'operand_index' // in 'fusion.fused_instructions', where the singleton use is the fused // root at operand index 'use_operand_index'. Returns false otherwise. // // REQUIRES: 'fusion' opcode is a kFusion instruction. bool HasUniqueFusedUseOfOperandAt( HloInstruction* operand, const ShapeIndex& operand_index, HloInstruction* fusion, const int64 use_operand_index, const TuplePointsToAnalysis& points_to_analysis) { CHECK_EQ(HloOpcode::kFusion, fusion->opcode()); // Check that 'operand' is unique in the operand list of 'fusion'. if (fusion->OperandIndices(operand).size() > 1) { return false; } // Find fusion parameter associated with 'operand'. const auto& fused_params = fusion->fused_parameters(); auto fused_param_it = std::find_if( fused_params.begin(), fused_params.end(), [&](HloInstruction* fused_param) { return fusion->operand(fused_param->parameter_number()) == operand; }); if (fused_param_it == fused_params.end()) { return false; } auto* fused_param = *fused_param_it; // Get all uses of 'operand' at 'index' from 'fusion.fused_instructions'. auto fused_param_uses = GetAllUsesOfInstructionAtIndex( fused_param, operand_index, points_to_analysis); // Return true iff there is exactly one use of 'operand' at 'index', and // this singleton use is the fused root (at index in 'use_operand_indices'). return fused_param_uses.size() == 1 && fused_param_uses[0].first == fusion->fused_expression_root() && fused_param_uses[0].second == use_operand_index; } } // namespace // User and operand can share buffers iff both instructions emit the same shape // and layout, and 'user' meets one of the following qualifications: // // (1) Is element-wise. Or... // (2) Is a loop fusion instruction where the only use of 'operand' at 'index' // in the set 'user.fused_instructions' is a DynamicUpdateSlice fused root // at operand 0. Or... // (3) Is a kDot -> kAdd (or fused kTransposeDot -> kAdd) output fusion // instruction where the only use of 'operand' at 'index' in the set // 'user.fused_instructions' is a kAdd fused root at operand 0 or 1. Or... // (4) The 'user' of 'operand' is DynamicUpdateSlice or While at operand index // 0. // // (2) and (3) can only be determined if points-to analysis is available. bool CanShareOperandBufferWithUser( HloInstruction* operand, const ShapeIndex& operand_index, HloInstruction* user, const ShapeIndex& user_index, const TuplePointsToAnalysis& points_to_analysis) { CHECK(user->IsUserOf(operand)) << "user: " << user->ToString() << " operand: " << operand->ToString(); const Shape& operand_subshape = ShapeUtil::GetSubshape(operand->shape(), operand_index); const Shape& user_subshape = ShapeUtil::GetSubshape(user->shape(), user_index); // Check that operand and user emit the same shape and layout. if (!ShapeUtil::Equal(operand_subshape, user_subshape)) { return false; } if (user->opcode() == HloOpcode::kFusion) { if (user->fusion_kind() == HloInstruction::FusionKind::kLoop && user->fused_expression_root()->opcode() == HloOpcode::kDynamicUpdateSlice) { // Loop fusion with kDynamicUpdateSlice fused root. // // Returns true iff there is exactly one use of 'operand' at shape index // 'operand_index', and this singleton use is the fused root at operand // index 0. return HasUniqueFusedUseOfOperandAt(operand, operand_index, user, 0, points_to_analysis); } else if (user->fusion_kind() == HloInstruction::FusionKind::kOutput && user->fused_expression_root()->opcode() == HloOpcode::kAdd) { // Output fusion with kAdd fused root. // Check if one operand of kAdd fused root is either kDot, or nested // kFusion of kind kTransposeDot. auto* add = user->fused_expression_root(); auto add_operand_it = std::find_if(add->operands().begin(), add->operands().end(), [&](HloInstruction* operand) { return operand->opcode() == HloOpcode::kConvolution || operand->opcode() == HloOpcode::kDot || (operand->opcode() == HloOpcode::kFusion && operand->fusion_kind() == HloInstruction::FusionKind::kTransposeDot); }); if (add_operand_it == add->operands().end()) { return false; } auto* matched_add_operand = *add_operand_it; // Calculate operand index of 'add' operand which was not matched above. const int64 other_add_operand_index = matched_add_operand == add->operand(0) ? 1 : 0; // Returns true iff there is exactly one use of 'operand' at shape index // 'operand_index', and this singleton use is the fused root (at operand // index 'other_add_operand_index'). return HasUniqueFusedUseOfOperandAt(operand, operand_index, user, other_add_operand_index, points_to_analysis); } } if (user->opcode() == HloOpcode::kDynamicUpdateSlice || user->opcode() == HloOpcode::kWhile) { // We eliminated other users in BufferLiveness::live_range_strictly_before, // so here we just need to check that the use is at operand index 0. std::vector<int64> operand_indices = user->OperandIndices(operand); return operand_indices.size() == 1 && operand_indices[0] == 0; } // Check if 'user' is element-wise. return user->IsElementwise(); } bool CanShareOperandBufferWithUser(HloInstruction* operand, const ShapeIndex& operand_index, HloInstruction* user, const ShapeIndex& user_index, const HloDataflowAnalysis& dataflow) { CHECK(user->IsUserOf(operand)) << "user: " << user->ToString() << " operand: " << operand->ToString(); const Shape& operand_subshape = ShapeUtil::GetSubshape(operand->shape(), operand_index); const Shape& user_subshape = ShapeUtil::GetSubshape(user->shape(), user_index); // Check that operand and user emit the same shape and layout. if (!ShapeUtil::Equal(operand_subshape, user_subshape)) { return false; } if (user->opcode() == HloOpcode::kFusion) { // Get the parameter associated with 'operand'; HloInstruction* fusion_param = user->fused_parameter(user->operand_index(operand)); const HloValue& value = dataflow.GetValueDefinedAt(fusion_param, operand_index); if (value.uses().size() != 1) { return false; } const HloUse& use = value.uses()[0]; if (user->fusion_kind() == HloInstruction::FusionKind::kLoop && user->fused_expression_root()->opcode() == HloOpcode::kDynamicUpdateSlice) { // Loop fusion with kDynamicUpdateSlice fused root. // // Returns true iff there is exactly one use of 'operand' at shape index // 'operand_index', and this singleton use is the fused root at operand // index 0. return use.instruction == user->fused_expression_root() && use.operand_number == 0; } else if (user->fusion_kind() == HloInstruction::FusionKind::kOutput && user->fused_expression_root()->opcode() == HloOpcode::kAdd) { // Output fusion with kAdd fused root. // Check if one operand of kAdd fused root is either kDot, or nested // kFusion of kind kTransposeDot. auto* add = user->fused_expression_root(); auto add_operand_it = std::find_if(add->operands().begin(), add->operands().end(), [&](HloInstruction* operand) { return operand->opcode() == HloOpcode::kConvolution || operand->opcode() == HloOpcode::kDot || (operand->opcode() == HloOpcode::kFusion && operand->fusion_kind() == HloInstruction::FusionKind::kTransposeDot); }); if (add_operand_it == add->operands().end()) { return false; } auto* matched_add_operand = *add_operand_it; // Calculate operand index of 'add' operand which was not matched above. const int64 other_add_operand_index = matched_add_operand == add->operand(0) ? 1 : 0; // Returns true iff there is exactly one use of 'operand' at shape index // 'operand_index', and this singleton use is the fused root (at operand // index 'other_add_operand_index'). return use.instruction == user->fused_expression_root() && use.operand_number == other_add_operand_index; } } if (user->opcode() == HloOpcode::kDynamicUpdateSlice || user->opcode() == HloOpcode::kWhile) { // We eliminated other users in BufferLiveness::live_range_strictly_before, // so here we just need to check that the use is at operand index 0. std::vector<int64> operand_indices = user->OperandIndices(operand); return operand_indices.size() == 1 && operand_indices[0] == 0; } // Check if 'user' is element-wise. return user->IsElementwise(); } } // namespace xla <|endoftext|>
<commit_before>// Copyright (C) 2010, 2011 and 2012 Marcin Arkadiusz Skrobiranda. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 <Protocol/Xml/Cpp/LanguageToProtocolTranslator.hpp> #include <Protocol/Xml/Cpp/MessageFactory.hpp> #include <boost/assert.hpp> namespace TUSProtocol { Message::SingleHandle LanguageToProtocolTranslator::translate( TUSLanguage::ICommand::SingleHandle a_command ) const { MessageFactory message_factory; switch (a_command->getID()) { case TUSLanguage::ID_COMMAND_ECHO_REQUEST: return message_factory.createEchoRequest(); case TUSLanguage::ID_COMMAND_ERROR_REQUEST: return message_factory.createErrorRequest(); case TUSLanguage::ID_COMMAND_CREATE_LAND_REQUEST: return message_factory.createCreateLandRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name"), a_command->getParam("land_name") ); case TUSLanguage::ID_COMMAND_DELETE_LAND_REQUEST: return message_factory.createDeleteLandRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("land_name") ); case TUSLanguage::ID_COMMAND_GET_LAND_REQUEST: return message_factory.createGetLandRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("land_name") ); case TUSLanguage::ID_COMMAND_GET_LANDS_REQUEST: return message_factory.createGetLandsRequest( a_command->getLogin(), a_command->getPassword() ); case TUSLanguage::ID_COMMAND_CREATE_SETTLEMENT_REQUEST: return message_factory.createCreateSettlementRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("land_name"), a_command->getParam("settlement_name") ); case TUSLanguage::ID_COMMAND_DELETE_SETTLEMENT_REQUEST: return message_factory.createDeleteSettlementRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("settlement_name") ); case TUSLanguage::ID_COMMAND_GET_SETTLEMENT_REQUEST: return message_factory.createGetSettlementRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("settlement_name") ); case TUSLanguage::ID_COMMAND_GET_SETTLEMENTS_REQUEST: return message_factory.createGetSettlementsRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("land_name") ); case TUSLanguage::ID_COMMAND_BUILD_BUILDING_REQUEST: return message_factory.createBuildBuildingRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("buildingkey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_DESTROY_BUILDING_REQUEST: return message_factory.createDestroyBuildingRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("buildingkey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_GET_BUILDING_REQUEST: return message_factory.createGetBuildingRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("buildingkey") ); case TUSLanguage::ID_COMMAND_GET_BUILDINGS_REQUEST: return message_factory.createGetBuildingsRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name") ); case TUSLanguage::ID_COMMAND_DISMISS_HUMAN_REQUEST: return message_factory.createDismissHumanRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("humankey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_ENGAGE_HUMAN_REQUEST: return message_factory.createEngageHumanRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("humankey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_GET_HUMAN_REQUEST: return message_factory.createGetHumanRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("humankey") ); case TUSLanguage::ID_COMMAND_GET_HUMANS_REQUEST: return message_factory.createGetHumansRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name") ); case TUSLanguage::ID_COMMAND_GET_RESOURCE_REQUEST: return message_factory.createGetResourceRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("resourcekey") ); case TUSLanguage::ID_COMMAND_GET_RESOURCES_REQUEST: return message_factory.createGetResourcesRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name") ); case TUSLanguage::ID_COMMAND_CREATE_USER_REQUEST: return message_factory.createCreateUserRequest( a_command->getParam("login"), a_command->getParam("password") ); case TUSLanguage::ID_COMMAND_CREATE_WORLD_REQUEST: return message_factory.createCreateWorldRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_CREATE_EPOCH_REQUEST: return message_factory.createCreateEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name"), a_command->getParam("epoch_name") ); case TUSLanguage::ID_COMMAND_DELETE_EPOCH_REQUEST: return message_factory.createDeleteEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_ACTIVATE_EPOCH_REQUEST: return message_factory.createActivateEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_DEACTIVATE_EPOCH_REQUEST: return message_factory.createDeactivateEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_FINISH_EPOCH_REQUEST: return message_factory.createFinishEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_TICK_EPOCH_REQUEST: return message_factory.createTickEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_GET_EPOCH_REQUEST: return message_factory.createGetEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_TRANSPORT_HUMAN_REQUEST: return message_factory.createTransportHumanRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("settlement_name_source"), a_command->getParam("settlement_name_destination"), a_command->getParam("humankey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_TRANSPORT_RESOURCE_REQUEST: return message_factory.createTransportResourceRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("settlement_name_source"), a_command->getParam("settlement_name_destination"), a_command->getParam("resourcekey"), a_command->getParam("volume") ); default: BOOST_ASSERT_MSG(false, "Invalid command ID."); } } } // namespace TUSProtocol <commit_msg>LanguageToProtocolTranslator translate replies now.<commit_after>// Copyright (C) 2010, 2011 and 2012 Marcin Arkadiusz Skrobiranda. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 <Protocol/Xml/Cpp/LanguageToProtocolTranslator.hpp> #include <Protocol/Xml/Cpp/MessageFactory.hpp> #include <boost/assert.hpp> #include <boost/lexical_cast.hpp> namespace TUSProtocol { // TODO: Consider removing lexical cast. Message::SingleHandle LanguageToProtocolTranslator::translate( TUSLanguage::ICommand::SingleHandle a_command ) const { MessageFactory message_factory; switch (a_command->getID()) { case TUSLanguage::ID_COMMAND_ECHO_REQUEST: return message_factory.createEchoRequest(); case TUSLanguage::ID_COMMAND_ERROR_REQUEST: return message_factory.createErrorRequest(); case TUSLanguage::ID_COMMAND_CREATE_LAND_REQUEST: return message_factory.createCreateLandRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name"), a_command->getParam("land_name") ); case TUSLanguage::ID_COMMAND_DELETE_LAND_REQUEST: return message_factory.createDeleteLandRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("land_name") ); case TUSLanguage::ID_COMMAND_GET_LAND_REQUEST: return message_factory.createGetLandRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("land_name") ); case TUSLanguage::ID_COMMAND_GET_LANDS_REQUEST: return message_factory.createGetLandsRequest( a_command->getLogin(), a_command->getPassword() ); case TUSLanguage::ID_COMMAND_CREATE_SETTLEMENT_REQUEST: return message_factory.createCreateSettlementRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("land_name"), a_command->getParam("settlement_name") ); case TUSLanguage::ID_COMMAND_DELETE_SETTLEMENT_REQUEST: return message_factory.createDeleteSettlementRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("settlement_name") ); case TUSLanguage::ID_COMMAND_GET_SETTLEMENT_REQUEST: return message_factory.createGetSettlementRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("settlement_name") ); case TUSLanguage::ID_COMMAND_GET_SETTLEMENTS_REQUEST: return message_factory.createGetSettlementsRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("land_name") ); case TUSLanguage::ID_COMMAND_BUILD_BUILDING_REQUEST: return message_factory.createBuildBuildingRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("buildingkey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_DESTROY_BUILDING_REQUEST: return message_factory.createDestroyBuildingRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("buildingkey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_GET_BUILDING_REQUEST: return message_factory.createGetBuildingRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("buildingkey") ); case TUSLanguage::ID_COMMAND_GET_BUILDINGS_REQUEST: return message_factory.createGetBuildingsRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name") ); case TUSLanguage::ID_COMMAND_DISMISS_HUMAN_REQUEST: return message_factory.createDismissHumanRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("humankey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_ENGAGE_HUMAN_REQUEST: return message_factory.createEngageHumanRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("humankey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_GET_HUMAN_REQUEST: return message_factory.createGetHumanRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("humankey") ); case TUSLanguage::ID_COMMAND_GET_HUMANS_REQUEST: return message_factory.createGetHumansRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name") ); case TUSLanguage::ID_COMMAND_GET_RESOURCE_REQUEST: return message_factory.createGetResourceRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name"), a_command->getParam("resourcekey") ); case TUSLanguage::ID_COMMAND_GET_RESOURCES_REQUEST: return message_factory.createGetResourcesRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("idholderclass"), a_command->getParam("holder_name") ); case TUSLanguage::ID_COMMAND_CREATE_USER_REQUEST: return message_factory.createCreateUserRequest( a_command->getParam("login"), a_command->getParam("password") ); case TUSLanguage::ID_COMMAND_CREATE_WORLD_REQUEST: return message_factory.createCreateWorldRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_CREATE_EPOCH_REQUEST: return message_factory.createCreateEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name"), a_command->getParam("epoch_name") ); case TUSLanguage::ID_COMMAND_DELETE_EPOCH_REQUEST: return message_factory.createDeleteEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_ACTIVATE_EPOCH_REQUEST: return message_factory.createActivateEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_DEACTIVATE_EPOCH_REQUEST: return message_factory.createDeactivateEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_FINISH_EPOCH_REQUEST: return message_factory.createFinishEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_TICK_EPOCH_REQUEST: return message_factory.createTickEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_GET_EPOCH_REQUEST: return message_factory.createGetEpochRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("world_name") ); case TUSLanguage::ID_COMMAND_TRANSPORT_HUMAN_REQUEST: return message_factory.createTransportHumanRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("settlement_name_source"), a_command->getParam("settlement_name_destination"), a_command->getParam("humankey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_TRANSPORT_RESOURCE_REQUEST: return message_factory.createTransportResourceRequest( a_command->getLogin(), a_command->getPassword(), a_command->getParam("settlement_name_source"), a_command->getParam("settlement_name_destination"), a_command->getParam("resourcekey"), a_command->getParam("volume") ); case TUSLanguage::ID_COMMAND_ECHO_REPLY: return message_factory.createEchoReply( boost::lexical_cast<std::string>(a_command->getCode()) ); case TUSLanguage::ID_COMMAND_ERROR_REPLY: return message_factory.createErrorReply( boost::lexical_cast<std::string>(a_command->getCode()) ); case TUSLanguage::ID_COMMAND_CREATE_LAND_REPLY: return message_factory.createCreateLandReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_DELETE_LAND_REPLY: return message_factory.createDeleteLandReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_GET_LAND_REPLY: return message_factory.createGetLandReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects().front() ); case TUSLanguage::ID_COMMAND_GET_LANDS_REPLY: return message_factory.createGetLandsReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects() ); case TUSLanguage::ID_COMMAND_CREATE_SETTLEMENT_REPLY: return message_factory.createCreateSettlementReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_DELETE_SETTLEMENT_REPLY: return message_factory.createDeleteSettlementReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_GET_SETTLEMENT_REPLY: return message_factory.createGetSettlementReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects().front() ); case TUSLanguage::ID_COMMAND_GET_SETTLEMENTS_REPLY: return message_factory.createGetSettlementsReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects() ); case TUSLanguage::ID_COMMAND_BUILD_BUILDING_REPLY: return message_factory.createBuildBuildingReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_DESTROY_BUILDING_REPLY: return message_factory.createDestroyBuildingReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_GET_BUILDING_REPLY: return message_factory.createGetBuildingReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects().front() ); case TUSLanguage::ID_COMMAND_GET_BUILDINGS_REPLY: return message_factory.createGetBuildingsReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects() ); case TUSLanguage::ID_COMMAND_DISMISS_HUMAN_REPLY: return message_factory.createDismissHumanReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_ENGAGE_HUMAN_REPLY: return message_factory.createEngageHumanReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_GET_HUMAN_REPLY: return message_factory.createGetHumanReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects().front() ); case TUSLanguage::ID_COMMAND_GET_HUMANS_REPLY: return message_factory.createGetHumansReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects() ); case TUSLanguage::ID_COMMAND_GET_RESOURCE_REPLY: return message_factory.createGetResourceReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects().front() ); case TUSLanguage::ID_COMMAND_GET_RESOURCES_REPLY: return message_factory.createGetResourcesReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects() ); case TUSLanguage::ID_COMMAND_CREATE_USER_REPLY: return message_factory.createCreateUserReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_CREATE_WORLD_REPLY: return message_factory.createCreateWorldReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_CREATE_EPOCH_REPLY: return message_factory.createCreateEpochReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_DELETE_EPOCH_REPLY: return message_factory.createDeleteEpochReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_ACTIVATE_EPOCH_REPLY: return message_factory.createActivateEpochReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_DEACTIVATE_EPOCH_REPLY: return message_factory.createDeactivateEpochReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_FINISH_EPOCH_REPLY: return message_factory.createFinishEpochReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_TICK_EPOCH_REPLY: return message_factory.createTickEpochReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_GET_EPOCH_REPLY: return message_factory.createGetEpochReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage(), a_command->getObjects().front() ); case TUSLanguage::ID_COMMAND_TRANSPORT_HUMAN_REPLY: return message_factory.createTransportHumanReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); case TUSLanguage::ID_COMMAND_TRANSPORT_RESOURCE_REPLY: return message_factory.createTransportResourceReply( boost::lexical_cast<std::string>(a_command->getCode()), a_command->getMessage() ); default: BOOST_ASSERT_MSG(false, "Invalid command ID."); } } } // namespace TUSProtocol <|endoftext|>
<commit_before>// Copyright 2016 The Bazel 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. #include "src/tools/singlejar/combiners.h" #include <cctype> #include <iostream> #include <iterator> #include <sstream> #include <string> #include "src/tools/singlejar/diag.h" Combiner::~Combiner() {} Concatenator::~Concatenator() {} bool Concatenator::Merge(const CDH *cdh, const LH *lh) { if (insert_newlines_ && buffer_.get() && buffer_->data_size() && '\n' != buffer_->last_byte()) { Append("\n", 1); } CreateBuffer(); if (Z_NO_COMPRESSION == lh->compression_method()) { buffer_->ReadEntryContents(lh); } else if (Z_DEFLATED == lh->compression_method()) { if (!inflater_) { inflater_.reset(new Inflater()); } buffer_->DecompressEntryContents(cdh, lh, inflater_.get()); } else { diag_errx(2, "%s is neither stored nor deflated", filename_.c_str()); } return true; } void *Concatenator::OutputEntry(bool compress) { if (!buffer_) { return nullptr; } // Allocate a contiguous buffer for the local file header and // deflated data. We assume that deflate decreases the size, so if // the deflater reports overflow, we just save original data. size_t deflated_buffer_size = sizeof(LH) + filename_.size() + buffer_->data_size(); // Huge entry (>4GB) needs Zip64 extension field with 64-bit original // and compressed size values. uint8_t zip64_extension_buffer[sizeof(Zip64ExtraField) + 2 * sizeof(uint64_t)]; bool huge_buffer = ziph::zfield_needs_ext64(buffer_->data_size()); if (huge_buffer) { deflated_buffer_size += sizeof(zip64_extension_buffer); } LH *lh = reinterpret_cast<LH *>(malloc(deflated_buffer_size)); if (lh == nullptr) { return nullptr; } lh->signature(); lh->version(20); lh->bit_flag(0x0); lh->last_mod_file_time(1); // 00:00:01 lh->last_mod_file_date(30 << 9 | 1 << 5 | 1); // 2010-01-01 lh->crc32(0x12345678); lh->compressed_file_size32(0); lh->file_name(filename_.c_str(), filename_.size()); if (huge_buffer) { // Add Z64 extension if this is a huge entry. lh->uncompressed_file_size32(0xFFFFFFFF); Zip64ExtraField *z64 = reinterpret_cast<Zip64ExtraField *>(zip64_extension_buffer); z64->signature(); z64->payload_size(2 * sizeof(uint64_t)); z64->attr64(0, buffer_->data_size()); lh->extra_fields(reinterpret_cast<uint8_t *>(z64), z64->size()); } else { lh->uncompressed_file_size32(buffer_->data_size()); lh->extra_fields(nullptr, 0); } uint32_t checksum; uint64_t compressed_size; uint16_t method; if (compress) { method = buffer_->CompressOut(lh->data(), &checksum, &compressed_size); } else { buffer_->CopyOut(lh->data(), &checksum); method = Z_NO_COMPRESSION; compressed_size = buffer_->data_size(); } lh->crc32(checksum); lh->compression_method(method); if (huge_buffer) { lh->compressed_file_size32(ziph::zfield_needs_ext64(compressed_size) ? 0xFFFFFFFF : compressed_size); // Not sure if this has to be written in the small case, but it shouldn't // hurt. const_cast<Zip64ExtraField *>(lh->zip64_extra_field()) ->attr64(1, compressed_size); } else { // If original data is <4GB, the compressed one is, too. lh->compressed_file_size32(compressed_size); } return reinterpret_cast<void *>(lh); } NullCombiner::~NullCombiner() {} bool NullCombiner::Merge(const CDH * /*cdh*/, const LH * /*lh*/) { return true; } void *NullCombiner::OutputEntry(bool /*compress*/) { return nullptr; } XmlCombiner::~XmlCombiner() {} bool XmlCombiner::Merge(const CDH *cdh, const LH *lh) { if (!concatenator_) { concatenator_.reset(new Concatenator(filename_, false)); concatenator_->Append(start_tag_); concatenator_->Append("\n"); } // To ensure xml concatentation is idempotent, read in the entry being added // and remove the start and end tags if they are present. TransientBytes bytes_; if (Z_NO_COMPRESSION == lh->compression_method()) { bytes_.ReadEntryContents(lh); } else if (Z_DEFLATED == lh->compression_method()) { if (!inflater_) { inflater_.reset(new Inflater()); } bytes_.DecompressEntryContents(cdh, lh, inflater_.get()); } else { diag_errx(2, "%s is neither stored nor deflated", filename_.c_str()); } uint32_t checksum; char *buf = reinterpret_cast<char *>(malloc(bytes_.data_size())); // TODO(b/37631490): optimize this to avoid copying the bytes twice bytes_.CopyOut(reinterpret_cast<uint8_t *>(buf), &checksum); int start_offset = 0; if (strncmp(buf, start_tag_.c_str(), start_tag_.length()) == 0) { start_offset = start_tag_.length(); } uint64_t end = bytes_.data_size(); while (end >= end_tag_.length() && std::isspace(buf[end - 1])) end--; if (strncmp(buf + end - end_tag_.length(), end_tag_.c_str(), end_tag_.length()) == 0) { end -= end_tag_.length(); } else { // Leave trailing whitespace alone if we didn't find a match. end = bytes_.data_size(); } concatenator_->Append(buf + start_offset, end - start_offset); free(buf); return true; } void *XmlCombiner::OutputEntry(bool compress) { if (!concatenator_) { return nullptr; } concatenator_->Append(end_tag_); concatenator_->Append("\n"); return concatenator_->OutputEntry(compress); } PropertyCombiner::~PropertyCombiner() {} bool PropertyCombiner::Merge(const CDH * /*cdh*/, const LH * /*lh*/) { return false; // This should not be called. } ManifestCombiner::~ManifestCombiner() {} static const char *MULTI_RELEASE = "Multi-Release: true"; static const size_t MULTI_RELEASE_LENGTH = strlen(MULTI_RELEASE); static const char *MULTI_RELEASE_PREFIX = "Multi-Release: "; static const size_t MULTI_RELEASE_PREFIX_LENGTH = strlen(MULTI_RELEASE_PREFIX); static const char *ADD_EXPORTS_PREFIX = "Add-Exports: "; static const size_t ADD_EXPORTS_PREFIX_LENGTH = strlen(ADD_EXPORTS_PREFIX); static const char *ADD_OPENS_PREFIX = "Add-Opens: "; static const size_t ADD_OPENS_PREFIX_LENGTH = strlen(ADD_OPENS_PREFIX); void ManifestCombiner::EnableMultiRelease() { multi_release_ = true; } void ManifestCombiner::AddExports(const std::vector<std::string> &add_exports) { add_exports_.insert(std::end(add_exports_), std::begin(add_exports), std::end(add_exports)); } void ManifestCombiner::AddOpens(const std::vector<std::string> &add_opens) { add_opens_.insert(std::end(add_opens_), std::begin(add_opens), std::end(add_opens)); } bool ManifestCombiner::HandleModuleFlags(std::vector<std::string> &output, const char *key, size_t key_length, std::string line) { if (line.find(key, 0, key_length) == std::string::npos) { return false; } std::istringstream iss(line.substr(key_length)); std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(output)); return true; } void ManifestCombiner::AppendLine(const std::string &line) { if (line.find(MULTI_RELEASE_PREFIX, 0, MULTI_RELEASE_PREFIX_LENGTH) != std::string::npos) { if (line.find("true", MULTI_RELEASE_PREFIX_LENGTH) != std::string::npos) { multi_release_ = true; } else if (line.find("false", MULTI_RELEASE_PREFIX_LENGTH) != std::string::npos) { multi_release_ = false; } return; } // Handle 'Add-Exports:' and 'Add-Opens:' lines in --deploy_manifest_lines and // merge them with the --add_exports= and --add_opens= flags. if (HandleModuleFlags(add_exports_, ADD_EXPORTS_PREFIX, ADD_EXPORTS_PREFIX_LENGTH, line)) { return; } if (HandleModuleFlags(add_opens_, ADD_OPENS_PREFIX, ADD_OPENS_PREFIX_LENGTH, line)) { return; } concatenator_->Append(line); if (line[line.size() - 1] != '\n') { concatenator_->Append("\r\n"); } } bool ManifestCombiner::Merge(const CDH *cdh, const LH *lh) { // Ignore Multi-Release attributes in inputs: we write the manifest first, // before inputs are processed, so we reply on deploy_manifest_lines to // create Multi-Release jars instead of doing it automatically based on // the inputs. return true; } void ManifestCombiner::OutputModuleFlags(std::vector<std::string> &flags, const char *key) { std::sort(flags.begin(), flags.end()); flags.erase(std::unique(flags.begin(), flags.end()), flags.end()); if (!flags.empty()) { concatenator_->Append(key); bool first = true; for (const auto &flag : flags) { if (!first) { concatenator_->Append("\r\n "); } concatenator_->Append(flag); first = false; } concatenator_->Append("\r\n"); } } void *ManifestCombiner::OutputEntry(bool compress) { if (multi_release_) { concatenator_->Append(MULTI_RELEASE); concatenator_->Append("\r\n"); } OutputModuleFlags(add_exports_, ADD_EXPORTS_PREFIX); OutputModuleFlags(add_opens_, ADD_OPENS_PREFIX); concatenator_->Append("\r\n"); return concatenator_->OutputEntry(compress); } <commit_msg>Remove unused MULTI_RELEASE_LENGTH constant.<commit_after>// Copyright 2016 The Bazel 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. #include "src/tools/singlejar/combiners.h" #include <cctype> #include <iostream> #include <iterator> #include <sstream> #include <string> #include "src/tools/singlejar/diag.h" Combiner::~Combiner() {} Concatenator::~Concatenator() {} bool Concatenator::Merge(const CDH *cdh, const LH *lh) { if (insert_newlines_ && buffer_.get() && buffer_->data_size() && '\n' != buffer_->last_byte()) { Append("\n", 1); } CreateBuffer(); if (Z_NO_COMPRESSION == lh->compression_method()) { buffer_->ReadEntryContents(lh); } else if (Z_DEFLATED == lh->compression_method()) { if (!inflater_) { inflater_.reset(new Inflater()); } buffer_->DecompressEntryContents(cdh, lh, inflater_.get()); } else { diag_errx(2, "%s is neither stored nor deflated", filename_.c_str()); } return true; } void *Concatenator::OutputEntry(bool compress) { if (!buffer_) { return nullptr; } // Allocate a contiguous buffer for the local file header and // deflated data. We assume that deflate decreases the size, so if // the deflater reports overflow, we just save original data. size_t deflated_buffer_size = sizeof(LH) + filename_.size() + buffer_->data_size(); // Huge entry (>4GB) needs Zip64 extension field with 64-bit original // and compressed size values. uint8_t zip64_extension_buffer[sizeof(Zip64ExtraField) + 2 * sizeof(uint64_t)]; bool huge_buffer = ziph::zfield_needs_ext64(buffer_->data_size()); if (huge_buffer) { deflated_buffer_size += sizeof(zip64_extension_buffer); } LH *lh = reinterpret_cast<LH *>(malloc(deflated_buffer_size)); if (lh == nullptr) { return nullptr; } lh->signature(); lh->version(20); lh->bit_flag(0x0); lh->last_mod_file_time(1); // 00:00:01 lh->last_mod_file_date(30 << 9 | 1 << 5 | 1); // 2010-01-01 lh->crc32(0x12345678); lh->compressed_file_size32(0); lh->file_name(filename_.c_str(), filename_.size()); if (huge_buffer) { // Add Z64 extension if this is a huge entry. lh->uncompressed_file_size32(0xFFFFFFFF); Zip64ExtraField *z64 = reinterpret_cast<Zip64ExtraField *>(zip64_extension_buffer); z64->signature(); z64->payload_size(2 * sizeof(uint64_t)); z64->attr64(0, buffer_->data_size()); lh->extra_fields(reinterpret_cast<uint8_t *>(z64), z64->size()); } else { lh->uncompressed_file_size32(buffer_->data_size()); lh->extra_fields(nullptr, 0); } uint32_t checksum; uint64_t compressed_size; uint16_t method; if (compress) { method = buffer_->CompressOut(lh->data(), &checksum, &compressed_size); } else { buffer_->CopyOut(lh->data(), &checksum); method = Z_NO_COMPRESSION; compressed_size = buffer_->data_size(); } lh->crc32(checksum); lh->compression_method(method); if (huge_buffer) { lh->compressed_file_size32(ziph::zfield_needs_ext64(compressed_size) ? 0xFFFFFFFF : compressed_size); // Not sure if this has to be written in the small case, but it shouldn't // hurt. const_cast<Zip64ExtraField *>(lh->zip64_extra_field()) ->attr64(1, compressed_size); } else { // If original data is <4GB, the compressed one is, too. lh->compressed_file_size32(compressed_size); } return reinterpret_cast<void *>(lh); } NullCombiner::~NullCombiner() {} bool NullCombiner::Merge(const CDH * /*cdh*/, const LH * /*lh*/) { return true; } void *NullCombiner::OutputEntry(bool /*compress*/) { return nullptr; } XmlCombiner::~XmlCombiner() {} bool XmlCombiner::Merge(const CDH *cdh, const LH *lh) { if (!concatenator_) { concatenator_.reset(new Concatenator(filename_, false)); concatenator_->Append(start_tag_); concatenator_->Append("\n"); } // To ensure xml concatentation is idempotent, read in the entry being added // and remove the start and end tags if they are present. TransientBytes bytes_; if (Z_NO_COMPRESSION == lh->compression_method()) { bytes_.ReadEntryContents(lh); } else if (Z_DEFLATED == lh->compression_method()) { if (!inflater_) { inflater_.reset(new Inflater()); } bytes_.DecompressEntryContents(cdh, lh, inflater_.get()); } else { diag_errx(2, "%s is neither stored nor deflated", filename_.c_str()); } uint32_t checksum; char *buf = reinterpret_cast<char *>(malloc(bytes_.data_size())); // TODO(b/37631490): optimize this to avoid copying the bytes twice bytes_.CopyOut(reinterpret_cast<uint8_t *>(buf), &checksum); int start_offset = 0; if (strncmp(buf, start_tag_.c_str(), start_tag_.length()) == 0) { start_offset = start_tag_.length(); } uint64_t end = bytes_.data_size(); while (end >= end_tag_.length() && std::isspace(buf[end - 1])) end--; if (strncmp(buf + end - end_tag_.length(), end_tag_.c_str(), end_tag_.length()) == 0) { end -= end_tag_.length(); } else { // Leave trailing whitespace alone if we didn't find a match. end = bytes_.data_size(); } concatenator_->Append(buf + start_offset, end - start_offset); free(buf); return true; } void *XmlCombiner::OutputEntry(bool compress) { if (!concatenator_) { return nullptr; } concatenator_->Append(end_tag_); concatenator_->Append("\n"); return concatenator_->OutputEntry(compress); } PropertyCombiner::~PropertyCombiner() {} bool PropertyCombiner::Merge(const CDH * /*cdh*/, const LH * /*lh*/) { return false; // This should not be called. } ManifestCombiner::~ManifestCombiner() {} static const char *MULTI_RELEASE = "Multi-Release: true"; static const char *MULTI_RELEASE_PREFIX = "Multi-Release: "; static const size_t MULTI_RELEASE_PREFIX_LENGTH = strlen(MULTI_RELEASE_PREFIX); static const char *ADD_EXPORTS_PREFIX = "Add-Exports: "; static const size_t ADD_EXPORTS_PREFIX_LENGTH = strlen(ADD_EXPORTS_PREFIX); static const char *ADD_OPENS_PREFIX = "Add-Opens: "; static const size_t ADD_OPENS_PREFIX_LENGTH = strlen(ADD_OPENS_PREFIX); void ManifestCombiner::EnableMultiRelease() { multi_release_ = true; } void ManifestCombiner::AddExports(const std::vector<std::string> &add_exports) { add_exports_.insert(std::end(add_exports_), std::begin(add_exports), std::end(add_exports)); } void ManifestCombiner::AddOpens(const std::vector<std::string> &add_opens) { add_opens_.insert(std::end(add_opens_), std::begin(add_opens), std::end(add_opens)); } bool ManifestCombiner::HandleModuleFlags(std::vector<std::string> &output, const char *key, size_t key_length, std::string line) { if (line.find(key, 0, key_length) == std::string::npos) { return false; } std::istringstream iss(line.substr(key_length)); std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(output)); return true; } void ManifestCombiner::AppendLine(const std::string &line) { if (line.find(MULTI_RELEASE_PREFIX, 0, MULTI_RELEASE_PREFIX_LENGTH) != std::string::npos) { if (line.find("true", MULTI_RELEASE_PREFIX_LENGTH) != std::string::npos) { multi_release_ = true; } else if (line.find("false", MULTI_RELEASE_PREFIX_LENGTH) != std::string::npos) { multi_release_ = false; } return; } // Handle 'Add-Exports:' and 'Add-Opens:' lines in --deploy_manifest_lines and // merge them with the --add_exports= and --add_opens= flags. if (HandleModuleFlags(add_exports_, ADD_EXPORTS_PREFIX, ADD_EXPORTS_PREFIX_LENGTH, line)) { return; } if (HandleModuleFlags(add_opens_, ADD_OPENS_PREFIX, ADD_OPENS_PREFIX_LENGTH, line)) { return; } concatenator_->Append(line); if (line[line.size() - 1] != '\n') { concatenator_->Append("\r\n"); } } bool ManifestCombiner::Merge(const CDH *cdh, const LH *lh) { // Ignore Multi-Release attributes in inputs: we write the manifest first, // before inputs are processed, so we reply on deploy_manifest_lines to // create Multi-Release jars instead of doing it automatically based on // the inputs. return true; } void ManifestCombiner::OutputModuleFlags(std::vector<std::string> &flags, const char *key) { std::sort(flags.begin(), flags.end()); flags.erase(std::unique(flags.begin(), flags.end()), flags.end()); if (!flags.empty()) { concatenator_->Append(key); bool first = true; for (const auto &flag : flags) { if (!first) { concatenator_->Append("\r\n "); } concatenator_->Append(flag); first = false; } concatenator_->Append("\r\n"); } } void *ManifestCombiner::OutputEntry(bool compress) { if (multi_release_) { concatenator_->Append(MULTI_RELEASE); concatenator_->Append("\r\n"); } OutputModuleFlags(add_exports_, ADD_EXPORTS_PREFIX); OutputModuleFlags(add_opens_, ADD_OPENS_PREFIX); concatenator_->Append("\r\n"); return concatenator_->OutputEntry(compress); } <|endoftext|>
<commit_before>#pragma once #include "type_check.hpp" #include "model_adapter.hpp" #include "matrix_adapter.hpp" #include "vector_adapter.hpp" #include "densitas_error.hpp" #include <vector> #include <algorithm> #include <string> namespace densitas { namespace math { template<typename ModelType, typename ElementType, typename VectorType> VectorType make_classification_target(const VectorType& y, ElementType lower, ElementType upper) { densitas::core::check_element_type<ElementType>(); const auto n_elem = densitas::vector_adapter::n_elements(y); auto target = densitas::vector_adapter::construct_uninitialized<VectorType>(n_elem); for (size_t i=0; i<n_elem; ++i) { const auto value = densitas::vector_adapter::get_element<ElementType>(y, i); const auto cls_result = value<lower || value>upper ? densitas::model_adapter::no<ModelType>() : densitas::model_adapter::yes<ModelType>(); densitas::vector_adapter::set_element<ElementType>(target, i, cls_result); } return target; } template<typename ElementType, typename VectorType> ElementType minimum(const VectorType& vector) { densitas::core::check_element_type<ElementType>(); const auto n_elem = densitas::vector_adapter::n_elements(vector); if (!(n_elem > 0)) throw densitas::densitas_error("vector is of size zero"); auto minimum = std::numeric_limits<ElementType>::max(); for (size_t i=0; i<n_elem; ++i) { const auto value = densitas::vector_adapter::get_element<ElementType>(vector, i); if (value < minimum) minimum = value; } return minimum; } template<typename ElementType> ElementType quantile(std::vector<ElementType>& data, ElementType proba) { densitas::core::check_element_type<ElementType>(); if (!data.size()) throw densitas::densitas_error("vector contains no values"); if (proba < 0 || proba > 1) throw densitas::densitas_error("proba must be between zero and one, not: " + std::to_string(proba)); if (proba < 1.0 / data.size()) return *std::min_element(data.begin(), data.end()); if (proba == 1) return *std::max_element(data.begin(), data.end()); const ElementType pos = data.size() * proba; const size_t ind = static_cast<size_t>(pos); const ElementType delta = pos - ind; std::nth_element(data.begin(), data.begin() + ind - 1, data.end()); const ElementType i1 = *(data.begin() + ind - 1); const ElementType i2 = *std::min_element(data.begin() + ind, data.end()); return i1 * (1. - delta) + i2 * delta; } template<typename ElementType, typename VectorType> VectorType quantiles(const VectorType& vector, const VectorType& probas) { densitas::core::check_element_type<ElementType>(); const auto n_elem = densitas::vector_adapter::n_elements(vector); std::vector<ElementType> data(n_elem); for (size_t i=0; i<n_elem; ++i) { data[i] = densitas::vector_adapter::get_element<ElementType>(vector, i); } const auto n_probas = densitas::vector_adapter::n_elements(probas); auto quantiles = densitas::vector_adapter::construct_uninitialized<VectorType>(n_probas); for (size_t i=0; i<n_probas; ++i) { const auto proba = densitas::vector_adapter::get_element<ElementType>(probas, i); const auto quantile = densitas::math::quantile(data, proba); densitas::vector_adapter::set_element<ElementType>(quantiles, i, quantile); } return quantiles; } template<typename ElementType, typename VectorType> VectorType quantiles_weighted(const VectorType& vector, const VectorType& weights, const VectorType& probas, ElementType accuracy) { densitas::core::check_element_type<ElementType>(); const auto n_elem = densitas::vector_adapter::n_elements(vector); if (n_elem != densitas::vector_adapter::n_elements(weights)) throw densitas::densitas_error("vector and weights must be of equal size"); if (!(accuracy > 0 && accuracy < 1)) throw densitas::densitas_error("quantile accuracy must be between zero and one, not: " + std::to_string(accuracy)); auto min_weight = densitas::math::minimum<ElementType>(weights); if (min_weight < accuracy) min_weight = accuracy; std::vector<size_t> counts(n_elem); for (size_t i=0; i<n_elem; ++i) { const auto weight = densitas::vector_adapter::get_element<ElementType>(weights, i); counts[i] = static_cast<size_t>(weight / min_weight); } const auto n_vals = std::accumulate(counts.begin(), counts.end(), 0); auto extended = n_vals > 0 ? densitas::vector_adapter::construct_uninitialized<VectorType>(n_vals) : vector; if (n_vals > 0) { size_t index = 0; for (size_t i=0; i<counts.size(); ++i) { const auto value = densitas::vector_adapter::get_element<ElementType>(vector, i); for (size_t j=0; j<counts[i]; ++j) { densitas::vector_adapter::set_element<ElementType>(extended, index, value); ++index; } } } return densitas::math::quantiles<ElementType>(extended, probas); } template<typename VectorType, typename ElementType> VectorType linspace(ElementType start, ElementType end, size_t n) { densitas::core::check_element_type<ElementType>(); if (!(end > start)) throw densitas::densitas_error("end is not larger than start"); if (!(n > 1)) throw densitas::densitas_error("n must be larger than one, not: " + std::to_string(n)); const auto delta = (end - start) / (n - 1); auto linspace = densitas::vector_adapter::construct_uninitialized<VectorType>(n); for (size_t i=0; i<n; ++i) { densitas::vector_adapter::set_element<ElementType>(linspace, i, start + i*delta); } return linspace; } template<typename ElementType, typename VectorType> VectorType centers(const VectorType& data, const VectorType& quantiles) { densitas::core::check_element_type<ElementType>(); const auto n_data = densitas::vector_adapter::n_elements(data); const auto n_elem = densitas::vector_adapter::n_elements(quantiles); if (!(n_data > 0)) throw densitas::densitas_error("size of data is zero"); if (!(n_elem > 1)) throw densitas::densitas_error("size of quantiles must be larger than one, not: " + std::to_string(n_elem)); std::vector<size_t> counter(n_elem - 1, 0); std::vector<ElementType> accumulator(n_elem - 1, 0.); for (size_t i=0; i<n_data; ++i) { const auto value = densitas::vector_adapter::get_element<ElementType>(data, i); for (size_t j=0; j<n_elem-1; ++j) { const auto first = densitas::vector_adapter::get_element<ElementType>(quantiles, j); const auto second = densitas::vector_adapter::get_element<ElementType>(quantiles, j + 1); if (value>=first && value<=second) { accumulator[j] += value; ++counter[j]; } } } auto centers = densitas::vector_adapter::construct_uninitialized<VectorType>(n_elem - 1); for (size_t j=0; j<n_elem-1; ++j) { if (counter[j]==0) counter[j] = 1; densitas::vector_adapter::set_element<ElementType>(centers, j, accumulator[j] / counter[j]); } return centers; } } // math } // densitas <commit_msg>more efficient centers function<commit_after>#pragma once #include "type_check.hpp" #include "model_adapter.hpp" #include "matrix_adapter.hpp" #include "vector_adapter.hpp" #include "densitas_error.hpp" #include <vector> #include <algorithm> #include <string> namespace densitas { namespace math { template<typename ModelType, typename ElementType, typename VectorType> VectorType make_classification_target(const VectorType& y, ElementType lower, ElementType upper) { densitas::core::check_element_type<ElementType>(); const auto n_elem = densitas::vector_adapter::n_elements(y); auto target = densitas::vector_adapter::construct_uninitialized<VectorType>(n_elem); for (size_t i=0; i<n_elem; ++i) { const auto value = densitas::vector_adapter::get_element<ElementType>(y, i); const auto cls_result = value<lower || value>upper ? densitas::model_adapter::no<ModelType>() : densitas::model_adapter::yes<ModelType>(); densitas::vector_adapter::set_element<ElementType>(target, i, cls_result); } return target; } template<typename ElementType, typename VectorType> ElementType minimum(const VectorType& vector) { densitas::core::check_element_type<ElementType>(); const auto n_elem = densitas::vector_adapter::n_elements(vector); if (!(n_elem > 0)) throw densitas::densitas_error("vector is of size zero"); auto minimum = std::numeric_limits<ElementType>::max(); for (size_t i=0; i<n_elem; ++i) { const auto value = densitas::vector_adapter::get_element<ElementType>(vector, i); if (value < minimum) minimum = value; } return minimum; } template<typename ElementType> ElementType quantile(std::vector<ElementType>& data, ElementType proba) { densitas::core::check_element_type<ElementType>(); if (!data.size()) throw densitas::densitas_error("vector contains no values"); if (proba < 0 || proba > 1) throw densitas::densitas_error("proba must be between zero and one, not: " + std::to_string(proba)); if (proba < 1.0 / data.size()) return *std::min_element(data.begin(), data.end()); if (proba == 1) return *std::max_element(data.begin(), data.end()); const ElementType pos = data.size() * proba; const size_t ind = static_cast<size_t>(pos); const ElementType delta = pos - ind; std::nth_element(data.begin(), data.begin() + ind - 1, data.end()); const ElementType i1 = *(data.begin() + ind - 1); const ElementType i2 = *std::min_element(data.begin() + ind, data.end()); return i1 * (1. - delta) + i2 * delta; } template<typename ElementType, typename VectorType> VectorType quantiles(const VectorType& vector, const VectorType& probas) { densitas::core::check_element_type<ElementType>(); const auto n_elem = densitas::vector_adapter::n_elements(vector); std::vector<ElementType> data(n_elem); for (size_t i=0; i<n_elem; ++i) { data[i] = densitas::vector_adapter::get_element<ElementType>(vector, i); } const auto n_probas = densitas::vector_adapter::n_elements(probas); auto quantiles = densitas::vector_adapter::construct_uninitialized<VectorType>(n_probas); for (size_t i=0; i<n_probas; ++i) { const auto proba = densitas::vector_adapter::get_element<ElementType>(probas, i); const auto quantile = densitas::math::quantile(data, proba); densitas::vector_adapter::set_element<ElementType>(quantiles, i, quantile); } return quantiles; } template<typename ElementType, typename VectorType> VectorType quantiles_weighted(const VectorType& vector, const VectorType& weights, const VectorType& probas, ElementType accuracy) { densitas::core::check_element_type<ElementType>(); const auto n_elem = densitas::vector_adapter::n_elements(vector); if (n_elem != densitas::vector_adapter::n_elements(weights)) throw densitas::densitas_error("vector and weights must be of equal size"); if (!(accuracy > 0 && accuracy < 1)) throw densitas::densitas_error("quantile accuracy must be between zero and one, not: " + std::to_string(accuracy)); auto min_weight = densitas::math::minimum<ElementType>(weights); if (min_weight < accuracy) min_weight = accuracy; std::vector<size_t> counts(n_elem); for (size_t i=0; i<n_elem; ++i) { const auto weight = densitas::vector_adapter::get_element<ElementType>(weights, i); counts[i] = static_cast<size_t>(weight / min_weight); } const auto n_vals = std::accumulate(counts.begin(), counts.end(), 0); auto extended = n_vals > 0 ? densitas::vector_adapter::construct_uninitialized<VectorType>(n_vals) : vector; if (n_vals > 0) { size_t index = 0; for (size_t i=0; i<counts.size(); ++i) { const auto value = densitas::vector_adapter::get_element<ElementType>(vector, i); for (size_t j=0; j<counts[i]; ++j) { densitas::vector_adapter::set_element<ElementType>(extended, index, value); ++index; } } } return densitas::math::quantiles<ElementType>(extended, probas); } template<typename VectorType, typename ElementType> VectorType linspace(ElementType start, ElementType end, size_t n) { densitas::core::check_element_type<ElementType>(); if (!(end > start)) throw densitas::densitas_error("end is not larger than start"); if (!(n > 1)) throw densitas::densitas_error("n must be larger than one, not: " + std::to_string(n)); const auto delta = (end - start) / (n - 1); auto linspace = densitas::vector_adapter::construct_uninitialized<VectorType>(n); for (size_t i=0; i<n; ++i) { densitas::vector_adapter::set_element<ElementType>(linspace, i, start + i*delta); } return linspace; } template<typename ElementType, typename VectorType> VectorType centers(const VectorType& data, const VectorType& quantiles) { densitas::core::check_element_type<ElementType>(); const auto n_data = densitas::vector_adapter::n_elements(data); if (!(n_data > 0)) throw densitas::densitas_error("size of data is zero"); const auto n_quant = densitas::vector_adapter::n_elements(quantiles); if (!(n_quant > 1)) throw densitas::densitas_error("size of quantiles must be larger than one, not: " + std::to_string(n_quant)); const auto n_elem = n_quant - 1; std::vector<size_t> counter(n_elem, 0); std::vector<ElementType> accumulator(n_elem, 0.); for (size_t i=0; i<n_data; ++i) { int current_j = -1; const auto value = densitas::vector_adapter::get_element<ElementType>(data, i); for (size_t j=0; j<n_elem; ++j) { const auto first = densitas::vector_adapter::get_element<ElementType>(quantiles, j); const auto second = densitas::vector_adapter::get_element<ElementType>(quantiles, j + 1); if (value>=first && value<=second) { accumulator[j] += value; ++counter[j]; current_j = j; } if (current_j>0 && current_j!=j) break; } } auto centers = densitas::vector_adapter::construct_uninitialized<VectorType>(n_elem); for (size_t j=0; j<n_elem; ++j) { if (counter[j]==0) counter[j] = 1; densitas::vector_adapter::set_element<ElementType>(centers, j, accumulator[j] / counter[j]); } return centers; } } // math } // densitas <|endoftext|>
<commit_before>/* * Copyright (c) 2017 OFFIS Institute for Information Technology * Oldenburg, Germany * * 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 timed_object.cpp * \author Philipp A. Hartmann <[email protected]> * \brief timed streaming base classes * \see timed_object.h */ #include "tvs/tracing/timed_object.h" #include "tvs/tracing/timed_stream_base.h" #include "report_msgs.h" #include "tvs/utils/debug.h" #include "tvs/utils/macros.h" #ifdef SYSX_NO_SYSTEMC #include <map> #endif namespace { tracing::host::sync_fn_type sync_fn; #ifdef SYSX_NO_SYSTEMC /// object registry for timed_object instances std::map<std::string, tracing::named_object*> object_registry; #endif // SYSX_NO_SYSTEMC } // anonymous namespace namespace tracing { void register_sync(host::sync_fn_type fn) { if (sync_fn) { SYSX_REPORT_WARNING(sysx::report::plain_msg) << "Overriding already defined synchronisation function."; } sync_fn = fn; } namespace host { void sync_with_model(time_type until) { if (!sync_fn) { #ifndef SYSX_NO_SYSTEMC SYSX_REPORT_WARNING(sysx::report::plain_msg) << "Setting sc_core::wait as the default synchronisation function."; sync_fn = [](time_type const& until) { ::sc_core::wait(until); }; #else SYSX_REPORT_FATAL(sysx::report::plain_msg) << "Cannot synchronise: no sync method specified." << "Please provide a sync callback with " "::tracing::register_sync()."; #endif } sync_fn(until); } /// Apply func on all streams in the current SystemC module scope. /// /// The iteration stops when func returns true. void for_each_stream_in_scope(host::cb_type func) { #ifdef SYSX_NO_SYSTEMC SYSX_REPORT_FATAL(sysx::report::not_implemented) % "native scope traversal"; #else sc_core::sc_object* scope = sc_core::sc_get_current_object(); SYSX_ASSERT(scope != nullptr); scope = scope->get_parent_object(); SYSX_ASSERT(scope != nullptr); for (auto& obj : scope->get_child_objects()) { auto* stream = dynamic_cast<timed_stream_base*>(&(*obj)); if (stream != nullptr) { if (func(stream)) break; } } #endif } const char* gen_unique_name(const char* name) { #ifdef SYSX_NO_SYSTEMC static std::vector<std::string> names_; static int num = 0; auto it = object_registry.find(name); if (it != object_registry.end()) { std::stringstream sstr; sstr << name << "_" << num++; names_.emplace_back(sstr.str()); return names_.back().c_str(); } return name; #else return sc_core::sc_gen_unique_name(name); #endif // SYSX_NO_SYSTEMC } tracing::timed_stream_base* lookup(const char* name) { #ifdef SYSX_NO_SYSTEMC auto it = object_registry.find(name); timed_stream_base* str = nullptr; if (it == object_registry.end()) { SYSX_REPORT_ERROR(report::stream_lookup) % name << "object not found in hierarchy"; } else { str = dynamic_cast<timed_stream_base*>(it->second); if (str == nullptr) { SYSX_REPORT_ERROR(report::stream_lookup) % name << "could not cast to timed_stream_base"; } } return str; #else auto str = dynamic_cast<timed_stream_base*>(sc_core::sc_find_object(name)); if (!str) { auto scope = sc_core::sc_get_current_object(); if (scope) { std::stringstream lname; lname << scope->name() << sc_core::SC_HIERARCHY_CHAR << name; str = host::lookup(lname.str().c_str()); } if (!str) { SYSX_REPORT_ERROR(report::stream_lookup) % name << "object not found " << "(scope: " << (scope ? scope->name() : "<top>") << ")"; return nullptr; } } return str; #endif // SYSX_NO_SYSTEMC } } // namespace host /* ----------------------------- sync --------------------------- */ time_type sync() { time_type max_time; host::for_each_stream_in_scope([&max_time](timed_stream_base* stream) { max_time = std::max(max_time, stream->end_time()); return false; }); sync(max_time); return max_time; } void sync(time_type const& until) { host::for_each_stream_in_scope([&until](timed_stream_base* stream) { stream->commit(until); return false; }); } /* ----------------------------- timed_base --------------------------- */ timed_base::timed_base() : time_() { } void timed_base::commit() { time_ += time_type(do_commit(timed_duration::zero_time)); } void timed_base::commit(time_type const& until) { if (until > time_) { commit(duration_type(until - time_)); } else { // TODO: add warning? commit(); } } void timed_base::commit(duration_type const& duration) { time_ += time_type(do_commit(duration)); } timed_base::duration_type timed_base::do_commit(duration_type duration) { return duration; } /* ---------------------------- named_object -------------------------- */ #ifdef SYSX_NO_SYSTEMC named_object::named_object(const char* name) : name_(name) { if (object_registry.find(name) != object_registry.end()) { SYSX_REPORT_FATAL(sysx::report::plain_msg) << "timed_object " << name << " already defined."; } object_registry[name] = this; std::cout << "registered " << name << "\n"; } named_object::~named_object() { object_registry.erase(name()); } const char* named_object::name() const { return name_.c_str(); } const char* named_object::kind() const { return "object"; } #endif // SYSX_NO_SYSTEMC } // namespace tracing /* Taf! */ <commit_msg>remove debug output<commit_after>/* * Copyright (c) 2017 OFFIS Institute for Information Technology * Oldenburg, Germany * * 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 timed_object.cpp * \author Philipp A. Hartmann <[email protected]> * \brief timed streaming base classes * \see timed_object.h */ #include "tvs/tracing/timed_object.h" #include "tvs/tracing/timed_stream_base.h" #include "report_msgs.h" #include "tvs/utils/debug.h" #include "tvs/utils/macros.h" #ifdef SYSX_NO_SYSTEMC #include <map> #endif namespace { tracing::host::sync_fn_type sync_fn; #ifdef SYSX_NO_SYSTEMC /// object registry for timed_object instances std::map<std::string, tracing::named_object*> object_registry; #endif // SYSX_NO_SYSTEMC } // anonymous namespace namespace tracing { void register_sync(host::sync_fn_type fn) { if (sync_fn) { SYSX_REPORT_WARNING(sysx::report::plain_msg) << "Overriding already defined synchronisation function."; } sync_fn = fn; } namespace host { void sync_with_model(time_type until) { if (!sync_fn) { #ifndef SYSX_NO_SYSTEMC SYSX_REPORT_WARNING(sysx::report::plain_msg) << "Setting sc_core::wait as the default synchronisation function."; sync_fn = [](time_type const& until) { ::sc_core::wait(until); }; #else SYSX_REPORT_FATAL(sysx::report::plain_msg) << "Cannot synchronise: no sync method specified." << "Please provide a sync callback with " "::tracing::register_sync()."; #endif } sync_fn(until); } /// Apply func on all streams in the current SystemC module scope. /// /// The iteration stops when func returns true. void for_each_stream_in_scope(host::cb_type func) { #ifdef SYSX_NO_SYSTEMC SYSX_REPORT_FATAL(sysx::report::not_implemented) % "native scope traversal"; #else sc_core::sc_object* scope = sc_core::sc_get_current_object(); SYSX_ASSERT(scope != nullptr); scope = scope->get_parent_object(); SYSX_ASSERT(scope != nullptr); for (auto& obj : scope->get_child_objects()) { auto* stream = dynamic_cast<timed_stream_base*>(&(*obj)); if (stream != nullptr) { if (func(stream)) break; } } #endif } const char* gen_unique_name(const char* name) { #ifdef SYSX_NO_SYSTEMC static std::vector<std::string> names_; static int num = 0; auto it = object_registry.find(name); if (it != object_registry.end()) { std::stringstream sstr; sstr << name << "_" << num++; names_.emplace_back(sstr.str()); return names_.back().c_str(); } return name; #else return sc_core::sc_gen_unique_name(name); #endif // SYSX_NO_SYSTEMC } tracing::timed_stream_base* lookup(const char* name) { #ifdef SYSX_NO_SYSTEMC auto it = object_registry.find(name); timed_stream_base* str = nullptr; if (it == object_registry.end()) { SYSX_REPORT_ERROR(report::stream_lookup) % name << "object not found in hierarchy"; } else { str = dynamic_cast<timed_stream_base*>(it->second); if (str == nullptr) { SYSX_REPORT_ERROR(report::stream_lookup) % name << "could not cast to timed_stream_base"; } } return str; #else auto str = dynamic_cast<timed_stream_base*>(sc_core::sc_find_object(name)); if (!str) { auto scope = sc_core::sc_get_current_object(); if (scope) { std::stringstream lname; lname << scope->name() << sc_core::SC_HIERARCHY_CHAR << name; str = host::lookup(lname.str().c_str()); } if (!str) { SYSX_REPORT_ERROR(report::stream_lookup) % name << "object not found " << "(scope: " << (scope ? scope->name() : "<top>") << ")"; return nullptr; } } return str; #endif // SYSX_NO_SYSTEMC } } // namespace host /* ----------------------------- sync --------------------------- */ time_type sync() { time_type max_time; host::for_each_stream_in_scope([&max_time](timed_stream_base* stream) { max_time = std::max(max_time, stream->end_time()); return false; }); sync(max_time); return max_time; } void sync(time_type const& until) { host::for_each_stream_in_scope([&until](timed_stream_base* stream) { stream->commit(until); return false; }); } /* ----------------------------- timed_base --------------------------- */ timed_base::timed_base() : time_() { } void timed_base::commit() { time_ += time_type(do_commit(timed_duration::zero_time)); } void timed_base::commit(time_type const& until) { if (until > time_) { commit(duration_type(until - time_)); } else { // TODO: add warning? commit(); } } void timed_base::commit(duration_type const& duration) { time_ += time_type(do_commit(duration)); } timed_base::duration_type timed_base::do_commit(duration_type duration) { return duration; } /* ---------------------------- named_object -------------------------- */ #ifdef SYSX_NO_SYSTEMC named_object::named_object(const char* name) : name_(name) { if (object_registry.find(name) != object_registry.end()) { SYSX_REPORT_FATAL(sysx::report::plain_msg) << "timed_object " << name << " already defined."; } object_registry[name] = this; } named_object::~named_object() { object_registry.erase(name()); } const char* named_object::name() const { return name_.c_str(); } const char* named_object::kind() const { return "object"; } #endif // SYSX_NO_SYSTEMC } // namespace tracing /* Taf! */ <|endoftext|>
<commit_before>// Copyright 2019 Intel Corporation. #include "pmlc/dialect/tile/gradient.h" // TODO: Clean includes #include "llvm/ADT/SetVector.h" #include "llvm/Support/FormatVariadic.h" #include "mlir/Support/DebugStringHelper.h" #include "base/util/logging.h" #include "pmlc/dialect/tile/builder.h" #include "pmlc/dialect/tile/ops.h" #include "pmlc/util/slice.h" namespace pmlc::dialect::tile { Gradient::Gradient(mlir::Value* loss, TileBuilder* builder) : builder_(builder) { IVLOG(3, "Gradient::Gradient> loss: " << mlir::debugString(*loss)); grads_[loss] = builder_->MakeScalarConstantOp(1.0); llvm::SetVector<mlir::Value*> loss_setvec; loss_setvec.insert(loss); auto defs = util::getBackwardSlice(loss_setvec, false, std::function<bool(mlir::Value*)>{[](mlir::Value* val) { auto op = val->getDefiningOp(); // TODO: This is an ad hoc list of what to filter out; make it principled return !mlir::isa<AffineConstraintsOp>(op) && !mlir::isa<AffineMapOp>(op) && !mlir::isa<AffineIndexOp>(op) && !mlir::isa<DimOp>(op) && !mlir::isa<AffineConstantOp>(op) && !mlir::isa<AffineAddOp>(op) && !mlir::isa<AffineDivOp>(op) && !mlir::isa<AffineMulOp>(op) && !mlir::isa<AffineNegOp>(op) && !mlir::isa<AffineSubOp>(op) && !mlir::isa<AffineMaxOp>(op) && !mlir::isa<AffineMinOp>(op) && !mlir::isa<eltwise::ScalarConstantOp>(op); }}); for (auto def = defs.rbegin(); def != defs.rend(); def++) { ComputeOperandDerivs(*def); } if (VLOG_IS_ON(5)) { IVLOG(5, "Gradient::Gradient> Computed the following gradients: "); for (auto [key, value] : grads_) { IVLOG(5, " key is " << mlir::debugString(*key) << "\n for val " << mlir::debugString(*value)); } } } void Gradient::AddToGradient(Value* source_op, Value* deriv) { // Adds the gradient `deriv` computed for one use of `source_op` to the overall gradient of `source_op` if (!grads_.count(source_op)) { grads_[source_op] = deriv; } else { grads_[source_op] = builder_->MakePrimitiveOp("add", {grads_[source_op], deriv}); } } void Gradient::ComputeOperandDerivs(mlir::Value* val) { IVLOG(4, "Gradient::ComputeDerivative> " << mlir::debugString(*val)); // TODO: Throw on ops with multiple results? auto op = val->getDefiningOp(); if (mlir::isa<AffineConstraintsOp>(op) || mlir::isa<AffineMapOp>(op) || mlir::isa<AffineIndexOp>(op) || mlir::isa<PrngOp>(op) || mlir::isa<ShapeOp>(op)) { // TODO: Make the list of which ops these are more principled. Also, should these all be caught in the backwards // slice filter? If so, probably throw here. IVLOG(6, "Gradient::ComputeDerivative> Skipping computing derivatives for op " << mlir::debugString(*op) << ", as it is not a type of op for which gradients apply"); return; } if (!grads_.count(val)) { IVLOG(1, "Gradient::ComputeOperandDerivs> Called on Value which has not itself been differentiated: " << mlir::debugString(*val)); throw std::runtime_error("Unexpected missing derivative in ComputeOperandDerivs"); } if (mlir::isa<eltwise::EltwiseOp>(op)) { size_t idx = 0; // Need to track which operand we're at for (const auto& operand : op->getOperands()) { auto dop = DeriveEltwise(grads_[val], val, idx); AddToGradient(operand, dop); idx++; } // TODO: if grads_[operand] has rank > 0, call a simple_reduce } else if (auto cion_op = mlir::dyn_cast<SymbolicContractionOp>(op)) { { // TODO: Do `init` deriv right: we should passthrough on plus, conditional against result on max/min, throw on // product // TODO: This is a temporary hack! AddToGradient(cion_op.init(), grads_[val]); } size_t idx = 0; // Need to track which operand we're at for (auto src : cion_op.srcs()) { auto dop = DeriveContraction(grads_[val], val, idx); AddToGradient(src, dop); idx++; } } else if (auto gather_op = mlir::dyn_cast<GatherOp>(op)) { auto tensor_input = gather_op.tensor(); auto dims_input = gather_op.dims(); auto dop = builder_->MakePrimitiveOp("scatter", {grads_[val], dims_input, tensor_input}); auto zero_op = builder_->MakeScalarConstantOp(0.); AddToGradient(tensor_input, dop); AddToGradient(dims_input, zero_op); } else if (mlir::isa<ScatterOp>(op)) { // TODO throw std::runtime_error("TODO: Derivs of Scatter not yet implemented"); } else if (mlir::isa<ReshapeOp>(op)) { // TODO throw std::runtime_error("TODO: Derivs of Reshape not yet implemented"); } else if (mlir::isa<SpecialOp>(op)) { throw std::runtime_error("Unrecognized special operation, unable to differentiate"); } else if (mlir::isa<DimOp>(op) || mlir::isa<eltwise::ScalarConstantOp>(op)) { // TODO: If it turns out one of these matters, be sure to split it off from the ones that don't matter // TODO: Or otherwise skip? These shouldn't matter... // TODO: See if int/float matters... auto dop = builder_->MakeScalarConstantOp(0.); for (const auto& operand : op->getOperands()) { AddToGradient(operand, dop); } } else if (auto tmap_op = mlir::dyn_cast<AffineTensorMapOp>(op)) { // Just forward the gradient in a tmap to the tensor AddToGradient(tmap_op.tensor(), grads_[val]); } else { if (op->getNumOperands()) { throw std::runtime_error("Unexpected Operation type in ComputeOperandDerivs! Operation is " + mlir::debugString(*op)); } // If it has no operands, it doesn't matter whether we can differentiate it, so we do nothing } } mlir::Value* Gradient::GetDerivative(mlir::Value* val) { IVLOG(5, "Gradient::GetDerivative> " << mlir::debugString(*val)); auto it = grads_.find(val); if (it != grads_.end()) { IVLOG(6, " Gradient::GetDerivative> Derivative retrieved: " << mlir::debugString(*it->second)); return it->second; } // TODO: // In the long run, this should probably just return 0 or otherwise indicate a continuation // For now, I want to know if we hit this (as we shouldn't in most cases) IVLOG(1, "Gradient::GetDerivative> The requested derivative of " << mlir::debugString(*val) << " was not computed!"); throw std::runtime_error("TODO: requested derivative not from getBackwardSlice"); } mlir::Value* Gradient::DeriveEltwise(mlir::Value* dout, mlir::Value* out, size_t idx) { auto op = out->getDefiningOp(); IVLOG(5, "Gradient::DeriveEltwise> dout=" << mlir::debugString(*dout) << ", op=" << mlir::debugString(*op) << ", idx=" << idx); // TODO: Handle reshape specially. AST code for that follows // if (op->fn == "reshape") { // std::vector<ExprPtr> args = {dout}; // auto in = op->args[0]; // auto dim_exprs = in->shape.dims_as_exprs(); // for (size_t i = 0; i < in->shape.dims.size(); ++i) { // args.push_back(std::make_shared<DimExprExpr>(dim_exprs[i])); // } // return MakeCall("reshape", args); // } auto deriv = DerivRegistry::Instance()->Resolve(op->getName().getStringRef()); llvm::SmallVector<mlir::Value*, 3> operands{op->getOperands()}; // TODO: Size return deriv.fn(out, dout, operands, deriv.user_fn, deriv.user_ctx)[idx]; } mlir::Value* Gradient::DeriveContraction(mlir::Value* dout, mlir::Value* out, size_t idx) { IVLOG(5, "Gradient::DeriveContraction> dout=" << mlir::debugString(*dout) << ", out=" << mlir::debugString(*out) << ", idx=" << idx); auto op = llvm::dyn_cast_or_null<SymbolicContractionOp>(out->getDefiningOp()); if (!op) { throw std::runtime_error("DeriveContraction called on non-contraction"); } if (op.combo() == util::CombinationKind::eq) { // TODO: What type should this 0 be? return builder_->MakeScalarConstantOp(0.); } auto combo_kind = util::CombinationKind::none; // This may be reset later if necessary std::vector<Value*> new_srcs; Value* target_src = nullptr; switch (op.agg()) { case util::AggregationKind::max: case util::AggregationKind::min: { size_t i = 0; // TODO: Is there a better option to do "Get the unique src (or throw if not unique)"? for (auto src : op.srcs()) { if (i == idx) { combo_kind = util::CombinationKind::cond; auto src_op = mlir::dyn_cast_or_null<AffineTensorMapOp>( src->getDefiningOp()); // TODO: Track that this is target_src_op if (!src_op) { throw std::runtime_error("src_op as cast is null"); } new_srcs.push_back(src_op); std::vector<Value*> dout_idxs; for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) { dout_idxs.push_back(dim); } new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(op, dout_idxs)); new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs)); // Also track that this is the differentiated source for later use target_src = src; } else { throw std::runtime_error("Cannot differentiate max/min contractions with multiple input tensors"); } i++; } } break; case util::AggregationKind::add: case util::AggregationKind::assign: { size_t i = 0; for (auto src : op.srcs()) { if (i == idx) { // This is the differentiated input; so swap in dout here to create the new op std::vector<Value*> dout_idxs; for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) { dout_idxs.push_back(dim); } new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs)); // Also track that this is the differentiated source for later use target_src = src; } else { // This is the non-differentiated input; behavior depends on combo op switch (op.combo()) { case util::CombinationKind::none: IVLOG(1, "About to fail on a NONE combo, with idx==" << idx << ", and i==" << i); throw std::runtime_error( "Unexpected multiple inputs found when differentiating contraction with NONE combination op"); break; case util::CombinationKind::add: // For +, we ignore the non-differentiated input combo_kind = util::CombinationKind::none; break; case util::CombinationKind::cond: throw std::runtime_error("Gradient of sum of conditionals not supported"); break; case util::CombinationKind::eq: throw std::logic_error("Gradient unexpectedly failed to detect combo op as equality"); break; case util::CombinationKind::mul: // For *, we multiply by the non-differentiated input new_srcs.push_back(src); combo_kind = util::CombinationKind::mul; break; default: throw std::runtime_error("Failed to recognize combination op during differentiation"); } } i++; } } break; case util::AggregationKind::mul: throw std::runtime_error("Cannot differentiate multiplication aggregations"); break; default: throw std::runtime_error("Did not recognize aggregation operation when differentiating " + mlir::debugString(*out)); } if (!target_src) { throw std::runtime_error( llvm::formatv("Trying to derive contraction at out of range index (requested source operand {0})", idx).str()); } auto target_src_op = llvm::cast<AffineTensorMapOp>(target_src->getDefiningOp()); std::vector<mlir::Value*> sizes; for (size_t i = 0; i < target_src_op.tensor()->getType().dyn_cast<RankedTensorType>().getRank(); ++i) { sizes.push_back(builder_->MakeDimOp(target_src_op.tensor(), i)); } std::vector<mlir::Value*> dsrc_idxs; for (const auto& dim : target_src_op.dims()) { dsrc_idxs.push_back(dim); } std::string new_name; // TODO: Currently names are broken // auto src_name = op.name(); // if (src_name) { // new_name = llvm::formatv("d{0}", op.name()).str(); // } // else use the empty string (already initialized by default ctor) auto dop_val = builder_->MakeContractionOp( // util::AggregationKind::add, // combo_kind, // new_srcs, // builder_->MakeAffineSinkIndexMapOp(dsrc_idxs), // builder_->MakeAffineSizeMapOp(sizes), // new_name); // Copy the constraints from the forward pass contraction auto src_cons = llvm::dyn_cast<AffineConstraintsOp>(op.cons()->getDefiningOp()); auto dop = llvm::dyn_cast<SymbolicContractionOp>(dop_val->getDefiningOp()); auto dst_cons = llvm::dyn_cast<AffineConstraintsOp>(dop.cons()->getDefiningOp()); mlir::SmallVector<mlir::Value*, 6> pairs{src_cons.pairs()}; for (const auto& pair : src_cons.pairs()) { pairs.emplace_back(pair); } dst_cons.getOperation()->setOperands(pairs); return dop_val; } mlir::Value* Gradient::DeriveSpecial(const mlir::Value* dout, SpecialOp* op, size_t idx) { throw std::runtime_error("Made it to DeriveSpecial!"); } } // namespace pmlc::dialect::tile <commit_msg>Add Reshape deriv<commit_after>// Copyright 2019 Intel Corporation. #include "pmlc/dialect/tile/gradient.h" // TODO: Clean includes #include "llvm/ADT/SetVector.h" #include "llvm/Support/FormatVariadic.h" #include "mlir/Support/DebugStringHelper.h" #include "base/util/logging.h" #include "pmlc/dialect/tile/builder.h" #include "pmlc/dialect/tile/ops.h" #include "pmlc/util/slice.h" namespace pmlc::dialect::tile { Gradient::Gradient(mlir::Value* loss, TileBuilder* builder) : builder_(builder) { IVLOG(3, "Gradient::Gradient> loss: " << mlir::debugString(*loss)); grads_[loss] = builder_->MakeScalarConstantOp(1.0); llvm::SetVector<mlir::Value*> loss_setvec; loss_setvec.insert(loss); auto defs = util::getBackwardSlice(loss_setvec, false, std::function<bool(mlir::Value*)>{[](mlir::Value* val) { auto op = val->getDefiningOp(); // TODO: This is an ad hoc list of what to filter out; make it principled return !mlir::isa<AffineConstraintsOp>(op) && !mlir::isa<AffineMapOp>(op) && !mlir::isa<AffineIndexOp>(op) && !mlir::isa<DimOp>(op) && !mlir::isa<AffineConstantOp>(op) && !mlir::isa<AffineAddOp>(op) && !mlir::isa<AffineDivOp>(op) && !mlir::isa<AffineMulOp>(op) && !mlir::isa<AffineNegOp>(op) && !mlir::isa<AffineSubOp>(op) && !mlir::isa<AffineMaxOp>(op) && !mlir::isa<AffineMinOp>(op) && !mlir::isa<eltwise::ScalarConstantOp>(op); }}); for (auto def = defs.rbegin(); def != defs.rend(); def++) { ComputeOperandDerivs(*def); } if (VLOG_IS_ON(5)) { IVLOG(5, "Gradient::Gradient> Computed the following gradients: "); for (auto [key, value] : grads_) { IVLOG(5, " key is " << mlir::debugString(*key) << "\n for val " << mlir::debugString(*value)); } } } void Gradient::AddToGradient(Value* source_op, Value* deriv) { // Adds the gradient `deriv` computed for one use of `source_op` to the overall gradient of `source_op` if (!grads_.count(source_op)) { grads_[source_op] = deriv; } else { grads_[source_op] = builder_->MakePrimitiveOp("add", {grads_[source_op], deriv}); } } void Gradient::ComputeOperandDerivs(mlir::Value* val) { IVLOG(4, "Gradient::ComputeDerivative> " << mlir::debugString(*val)); // TODO: Throw on ops with multiple results? auto op = val->getDefiningOp(); if (mlir::isa<AffineConstraintsOp>(op) || mlir::isa<AffineMapOp>(op) || mlir::isa<AffineIndexOp>(op) || mlir::isa<PrngOp>(op) || mlir::isa<ShapeOp>(op)) { // TODO: Make the list of which ops these are more principled. Also, should these all be caught in the backwards // slice filter? If so, probably throw here. IVLOG(6, "Gradient::ComputeDerivative> Skipping computing derivatives for op " << mlir::debugString(*op) << ", as it is not a type of op for which gradients apply"); return; } if (!grads_.count(val)) { IVLOG(1, "Gradient::ComputeOperandDerivs> Called on Value which has not itself been differentiated: " << mlir::debugString(*val)); throw std::runtime_error("Unexpected missing derivative in ComputeOperandDerivs"); } if (mlir::isa<eltwise::EltwiseOp>(op)) { size_t idx = 0; // Need to track which operand we're at for (const auto& operand : op->getOperands()) { auto dop = DeriveEltwise(grads_[val], val, idx); AddToGradient(operand, dop); idx++; } // TODO: if grads_[operand] has rank > 0, call a simple_reduce } else if (auto cion_op = mlir::dyn_cast<SymbolicContractionOp>(op)) { { // TODO: Do `init` deriv right: we should passthrough on plus, conditional against result on max/min, throw on // product // TODO: This is a temporary hack! AddToGradient(cion_op.init(), grads_[val]); } size_t idx = 0; // Need to track which operand we're at for (auto src : cion_op.srcs()) { auto dop = DeriveContraction(grads_[val], val, idx); AddToGradient(src, dop); idx++; } } else if (auto gather_op = mlir::dyn_cast<GatherOp>(op)) { auto tensor_input = gather_op.tensor(); auto dims_input = gather_op.dims(); auto dop = builder_->MakePrimitiveOp("scatter", {grads_[val], dims_input, tensor_input}); auto zero_op = builder_->MakeScalarConstantOp(0.); AddToGradient(tensor_input, dop); AddToGradient(dims_input, zero_op); } else if (mlir::isa<ScatterOp>(op)) { // TODO throw std::runtime_error("TODO: Derivs of Scatter not yet implemented"); } else if (auto reshape_op = mlir::dyn_cast<ReshapeOp>(op)) { auto tensor_input = reshape_op.tensor(); std::vector<mlir::Value*> args{grads_[val]}; for (size_t i = 0; i < tensor_input->getType().dyn_cast<RankedTensorType>().getRank(); ++i) { args.push_back(builder_->MakeDimOp(tensor_input, i)); } auto dop = builder_->MakePrimitiveOp("reshape", args); AddToGradient(tensor_input, dop); } else if (mlir::isa<SpecialOp>(op)) { throw std::runtime_error("Unrecognized special operation, unable to differentiate"); } else if (mlir::isa<DimOp>(op) || mlir::isa<eltwise::ScalarConstantOp>(op)) { // TODO: If it turns out one of these matters, be sure to split it off from the ones that don't matter // TODO: Or otherwise skip? These shouldn't matter... // TODO: See if int/float matters... auto dop = builder_->MakeScalarConstantOp(0.); for (const auto& operand : op->getOperands()) { AddToGradient(operand, dop); } } else if (auto tmap_op = mlir::dyn_cast<AffineTensorMapOp>(op)) { // Just forward the gradient in a tmap to the tensor AddToGradient(tmap_op.tensor(), grads_[val]); } else { if (op->getNumOperands()) { throw std::runtime_error("Unexpected Operation type in ComputeOperandDerivs! Operation is " + mlir::debugString(*op)); } // If it has no operands, it doesn't matter whether we can differentiate it, so we do nothing } } mlir::Value* Gradient::GetDerivative(mlir::Value* val) { IVLOG(5, "Gradient::GetDerivative> " << mlir::debugString(*val)); auto it = grads_.find(val); if (it != grads_.end()) { IVLOG(6, " Gradient::GetDerivative> Derivative retrieved: " << mlir::debugString(*it->second)); return it->second; } // TODO: // In the long run, this should probably just return 0 or otherwise indicate a continuation // For now, I want to know if we hit this (as we shouldn't in most cases) IVLOG(1, "Gradient::GetDerivative> The requested derivative of " << mlir::debugString(*val) << " was not computed!"); throw std::runtime_error("TODO: requested derivative not from getBackwardSlice"); } mlir::Value* Gradient::DeriveEltwise(mlir::Value* dout, mlir::Value* out, size_t idx) { auto op = out->getDefiningOp(); IVLOG(5, "Gradient::DeriveEltwise> dout=" << mlir::debugString(*dout) << ", op=" << mlir::debugString(*op) << ", idx=" << idx); // TODO: Handle reshape specially. AST code for that follows // if (op->fn == "reshape") { // std::vector<ExprPtr> args = {dout}; // auto in = op->args[0]; // auto dim_exprs = in->shape.dims_as_exprs(); // for (size_t i = 0; i < in->shape.dims.size(); ++i) { // args.push_back(std::make_shared<DimExprExpr>(dim_exprs[i])); // } // return MakeCall("reshape", args); // } auto deriv = DerivRegistry::Instance()->Resolve(op->getName().getStringRef()); llvm::SmallVector<mlir::Value*, 3> operands{op->getOperands()}; // TODO: Size return deriv.fn(out, dout, operands, deriv.user_fn, deriv.user_ctx)[idx]; } mlir::Value* Gradient::DeriveContraction(mlir::Value* dout, mlir::Value* out, size_t idx) { IVLOG(5, "Gradient::DeriveContraction> dout=" << mlir::debugString(*dout) << ", out=" << mlir::debugString(*out) << ", idx=" << idx); auto op = llvm::dyn_cast_or_null<SymbolicContractionOp>(out->getDefiningOp()); if (!op) { throw std::runtime_error("DeriveContraction called on non-contraction"); } if (op.combo() == util::CombinationKind::eq) { // TODO: What type should this 0 be? return builder_->MakeScalarConstantOp(0.); } auto combo_kind = util::CombinationKind::none; // This may be reset later if necessary std::vector<Value*> new_srcs; Value* target_src = nullptr; switch (op.agg()) { case util::AggregationKind::max: case util::AggregationKind::min: { size_t i = 0; // TODO: Is there a better option to do "Get the unique src (or throw if not unique)"? for (auto src : op.srcs()) { if (i == idx) { combo_kind = util::CombinationKind::cond; auto src_op = mlir::dyn_cast_or_null<AffineTensorMapOp>( src->getDefiningOp()); // TODO: Track that this is target_src_op if (!src_op) { throw std::runtime_error("src_op as cast is null"); } new_srcs.push_back(src_op); std::vector<Value*> dout_idxs; for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) { dout_idxs.push_back(dim); } new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(op, dout_idxs)); new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs)); // Also track that this is the differentiated source for later use target_src = src; } else { throw std::runtime_error("Cannot differentiate max/min contractions with multiple input tensors"); } i++; } } break; case util::AggregationKind::add: case util::AggregationKind::assign: { size_t i = 0; for (auto src : op.srcs()) { if (i == idx) { // This is the differentiated input; so swap in dout here to create the new op std::vector<Value*> dout_idxs; for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) { dout_idxs.push_back(dim); } new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs)); // Also track that this is the differentiated source for later use target_src = src; } else { // This is the non-differentiated input; behavior depends on combo op switch (op.combo()) { case util::CombinationKind::none: IVLOG(1, "About to fail on a NONE combo, with idx==" << idx << ", and i==" << i); throw std::runtime_error( "Unexpected multiple inputs found when differentiating contraction with NONE combination op"); break; case util::CombinationKind::add: // For +, we ignore the non-differentiated input combo_kind = util::CombinationKind::none; break; case util::CombinationKind::cond: throw std::runtime_error("Gradient of sum of conditionals not supported"); break; case util::CombinationKind::eq: throw std::logic_error("Gradient unexpectedly failed to detect combo op as equality"); break; case util::CombinationKind::mul: // For *, we multiply by the non-differentiated input new_srcs.push_back(src); combo_kind = util::CombinationKind::mul; break; default: throw std::runtime_error("Failed to recognize combination op during differentiation"); } } i++; } } break; case util::AggregationKind::mul: throw std::runtime_error("Cannot differentiate multiplication aggregations"); break; default: throw std::runtime_error("Did not recognize aggregation operation when differentiating " + mlir::debugString(*out)); } if (!target_src) { throw std::runtime_error( llvm::formatv("Trying to derive contraction at out of range index (requested source operand {0})", idx).str()); } auto target_src_op = llvm::cast<AffineTensorMapOp>(target_src->getDefiningOp()); std::vector<mlir::Value*> sizes; for (size_t i = 0; i < target_src_op.tensor()->getType().dyn_cast<RankedTensorType>().getRank(); ++i) { sizes.push_back(builder_->MakeDimOp(target_src_op.tensor(), i)); } std::vector<mlir::Value*> dsrc_idxs; for (const auto& dim : target_src_op.dims()) { dsrc_idxs.push_back(dim); } std::string new_name; // TODO: Currently names are broken // auto src_name = op.name(); // if (src_name) { // new_name = llvm::formatv("d{0}", op.name()).str(); // } // else use the empty string (already initialized by default ctor) auto dop_val = builder_->MakeContractionOp( // util::AggregationKind::add, // combo_kind, // new_srcs, // builder_->MakeAffineSinkIndexMapOp(dsrc_idxs), // builder_->MakeAffineSizeMapOp(sizes), // new_name); // Copy the constraints from the forward pass contraction auto src_cons = llvm::dyn_cast<AffineConstraintsOp>(op.cons()->getDefiningOp()); auto dop = llvm::dyn_cast<SymbolicContractionOp>(dop_val->getDefiningOp()); auto dst_cons = llvm::dyn_cast<AffineConstraintsOp>(dop.cons()->getDefiningOp()); mlir::SmallVector<mlir::Value*, 6> pairs{src_cons.pairs()}; for (const auto& pair : src_cons.pairs()) { pairs.emplace_back(pair); } dst_cons.getOperation()->setOperands(pairs); return dop_val; } mlir::Value* Gradient::DeriveSpecial(const mlir::Value* dout, SpecialOp* op, size_t idx) { throw std::runtime_error("Made it to DeriveSpecial!"); } } // namespace pmlc::dialect::tile <|endoftext|>
<commit_before>/* @file Animation.hpp @brief Class that manages animated game behavior, such as game behavior and picture frames. @copyright LGPL. MIT License. */ #ifndef __ANIMATION__ #define __ANIMATION__ #include "Engine/Component.hpp" #include "Engine/Frame.hpp" #include "Engine/Image.hpp" #include "Engine/sdl2include.hpp" #include <string> #include <vector> /** @file Animation.hpp @brief Class that represents the entire game and manages the main screens. @copyright LGPL. MIT License. */ class Animation : public Component { public: Animation(GameObject *owner, Image *image, bool playOnStart = false); inline void SetHasExitTime(bool condition) { m_hasExitTime = condition; }; inline void SetFramesPerSecond(int frames) { m_framesPerSecond = frames; }; inline Frame *GetCurrentFrame() { return m_frames[m_currentFrame]; }; void ComponentUpdate() override; void Start() override; void SetPlaying(bool condition); void SetLoop(bool condition); void SetFlip(bool horizontal, bool vertical); void AddFrame(Frame *frame); void DrawCurrentFrame(); std::string GetComponentName() override { return "Animation"; }; bool IsPlaying(){ return m_isPlaying; } private: int m_framesQuantity = 0; int m_currentFrame = 0; int m_framesPerSecond = 12; bool m_isPlaying = false; bool m_hasExitTime = false; bool m_loop = false; bool m_verticalFlip = false; bool m_horizontalFlip = false; Uint32 m_lastDraw = 0; std::vector<Frame *> m_frames; Image *m_image = nullptr; }; #endif <commit_msg>Fourth Application: Animation.hpp<commit_after>/* @file Animation.hpp @brief Class that manages animated game behavior, such as game behavior and picture frames. @copyright LGPL. MIT License. */ #ifndef __ANIMATION__ #define __ANIMATION__ #include "Engine/Component.hpp" #include "Engine/Frame.hpp" #include "Engine/Image.hpp" #include "Engine/sdl2include.hpp" #include <string> #include <vector> class Animation : public Component { public: Animation(GameObject *owner, Image *image, bool playOnStart = false); inline void SetHasExitTime(bool condition) { m_hasExitTime = condition; }; inline void SetFramesPerSecond(int frames) { m_framesPerSecond = frames; }; inline Frame *GetCurrentFrame() { return m_frames[m_currentFrame]; }; void ComponentUpdate() override; void Start() override; void SetPlaying(bool condition); void SetLoop(bool condition); void SetFlip(bool horizontal, bool vertical); void AddFrame(Frame *frame); void DrawCurrentFrame(); std::string GetComponentName() override { return "Animation"; }; bool IsPlaying(){ return m_isPlaying; } private: // Represents the quantity of the frames of the animation. int m_framesQuantity = 0; // Represents the current frame of the animation. int m_currentFrame = 0; // Represents the frames per second of the animation. int m_framesPerSecond = 12; // Represents if someone is playing. bool m_isPlaying = false; bool m_hasExitTime = false; bool m_loop = false; // Represents the vertical flip of the animation. bool m_verticalFlip = false; // Represents the horizontal flip of the animation. bool m_horizontalFlip = false; Uint32 m_lastDraw = 0; std::vector<Frame *> m_frames; Image *m_image = nullptr; }; #endif <|endoftext|>
<commit_before>#include <bts/blockchain/chain_interface.hpp> #include <bts/blockchain/fork_blocks.hpp> #include <bts/blockchain/operation_factory.hpp> #include <bts/blockchain/transaction_evaluation_state.hpp> namespace bts { namespace blockchain { transaction_evaluation_state::transaction_evaluation_state( const chain_interface_ptr& current_state, digest_type chain_id ) :_current_state( current_state ),_chain_id(chain_id),_skip_signature_check(false) { } transaction_evaluation_state::~transaction_evaluation_state() { } void transaction_evaluation_state::reset() { signed_keys.clear(); balance.clear(); deposits.clear(); withdraws.clear(); net_delegate_votes.clear(); required_deposits.clear(); validation_error.reset(); } bool transaction_evaluation_state::check_signature( const address& a )const { return _skip_signature_check || signed_keys.find( a ) != signed_keys.end(); } void transaction_evaluation_state::verify_delegate_id( account_id_type id )const { auto current_account = _current_state->get_account_record( id ); if( !current_account ) FC_CAPTURE_AND_THROW( unknown_account_id, (id) ); if( !current_account->is_delegate() ) FC_CAPTURE_AND_THROW( not_a_delegate, (id) ); } void transaction_evaluation_state::add_required_deposit( const address& owner_key, const asset& amount ) { FC_ASSERT( trx.delegate_slate_id ); balance_id_type balance_id = withdraw_condition( withdraw_with_signature( owner_key ), amount.asset_id, *trx.delegate_slate_id ).get_address(); auto itr = required_deposits.find( balance_id ); if( itr == required_deposits.end() ) { required_deposits[balance_id] = amount; } else { required_deposits[balance_id] += amount; } } void transaction_evaluation_state::update_delegate_votes() { auto asset_rec = _current_state->get_asset_record( asset_id_type() ); for( const auto& del_vote : net_delegate_votes ) { auto del_rec = _current_state->get_account_record( del_vote.first ); FC_ASSERT( !!del_rec ); del_rec->adjust_votes_for( del_vote.second.votes_for ); _current_state->store_account_record( *del_rec ); } } void transaction_evaluation_state::validate_required_fee() { try { asset xts_fees; auto fee_itr = balance.find( 0 ); if( fee_itr != balance.end() ) xts_fees += asset( fee_itr->second, 0); xts_fees += alt_fees_paid; if( required_fees > xts_fees ) { FC_CAPTURE_AND_THROW( insufficient_fee, (required_fees)(alt_fees_paid)(xts_fees) ); } } FC_RETHROW_EXCEPTIONS( warn, "" ) } /** * Process all fees and update the asset records. */ void transaction_evaluation_state::post_evaluate() { try { // Should this be here? We may not have fees in XTS now... balance[0]; // make sure we have something for this. for( const auto& fee : balance ) { if( fee.second < 0 ) FC_CAPTURE_AND_THROW( negative_fee, (fee) ); // if the fee is already in XTS or the fee balance is zero, move along... if( fee.first == 0 || fee.second == 0 ) continue; auto asset_record = _current_state->get_asset_record( fee.first ); if( !asset_record.valid() ) FC_CAPTURE_AND_THROW( unknown_asset_id, (fee.first) ); if( !asset_record->is_market_issued() ) continue; // lowest ask is someone with XTS offered at a price of USD / XTS, fee.first // is an amount of USD which can be converted to price*USD XTS provided we // send lowest_ask.index.owner the USD oprice median_price = _current_state->get_median_delegate_price( fee.first ); if( median_price ) { // fees paid in something other than XTS are discounted 50% alt_fees_paid += asset( (fee.second*2)/3, fee.first ) * *median_price; } } for( const auto& fee : balance ) { if( fee.second < 0 ) FC_CAPTURE_AND_THROW( negative_fee, (fee) ); if( fee.second > 0 ) // if a fee was paid... { auto asset_record = _current_state->get_asset_record( fee.first ); if( !asset_record ) FC_CAPTURE_AND_THROW( unknown_asset_id, (fee.first) ); asset_record->collected_fees += fee.second; _current_state->store_asset_record( *asset_record ); } } for( const auto& required_deposit : required_deposits ) { auto provided_itr = provided_deposits.find( required_deposit.first ); if( provided_itr->second < required_deposit.second ) FC_CAPTURE_AND_THROW( missing_deposit, (required_deposit) ); } } FC_RETHROW_EXCEPTIONS( warn, "" ) } void transaction_evaluation_state::evaluate( const signed_transaction& trx_arg, bool skip_signature_check ) { try { reset(); _skip_signature_check = skip_signature_check; try { if( _current_state->now() >= trx_arg.expiration ) { if( _current_state->now() > trx_arg.expiration || _current_state->get_head_block_num() >= BTSX_MARKET_FORK_11_BLOCK_NUM ) { const auto expired_by_sec = (_current_state->now() - trx_arg.expiration).to_seconds(); FC_CAPTURE_AND_THROW( expired_transaction, (trx_arg)(_current_state->now())(expired_by_sec) ); } } if( (_current_state->now() + BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC) < trx_arg.expiration ) FC_CAPTURE_AND_THROW( invalid_transaction_expiration, (trx_arg)(_current_state->now()) ); auto trx_id = trx_arg.id(); if( _current_state->is_known_transaction( trx_id ) ) FC_CAPTURE_AND_THROW( duplicate_transaction, (trx_id) ); trx = trx_arg; if( !_skip_signature_check ) { auto digest = trx_arg.digest( _chain_id ); for( const auto& sig : trx.signatures ) { auto key = fc::ecc::public_key( sig, digest ).serialize(); signed_keys.insert( address(key) ); signed_keys.insert( address(pts_address(key,false,56) ) ); signed_keys.insert( address(pts_address(key,true,56) ) ); signed_keys.insert( address(pts_address(key,false,0) ) ); signed_keys.insert( address(pts_address(key,true,0) ) ); } } _current_op_index = 0; for( const auto& op : trx.operations ) { evaluate_operation( op ); ++_current_op_index; } post_evaluate(); validate_required_fee(); update_delegate_votes(); } catch ( const fc::exception& e ) { validation_error = e; throw; } } FC_RETHROW_EXCEPTIONS( warn, "", ("trx",trx_arg) ) } void transaction_evaluation_state::evaluate_operation( const operation& op ) { operation_factory::instance().evaluate( *this, op ); } void transaction_evaluation_state::adjust_vote( slate_id_type slate_id, share_type amount ) { if( slate_id ) { auto slate = _current_state->get_delegate_slate( slate_id ); if( !slate ) FC_CAPTURE_AND_THROW( unknown_delegate_slate, (slate_id) ); for( const auto& delegate_id : slate->supported_delegates ) { if( BTS_BLOCKCHAIN_ENABLE_NEGATIVE_VOTES && delegate_id < signed_int(0) ) net_delegate_votes[abs(delegate_id)].votes_for -= amount; else net_delegate_votes[abs(delegate_id)].votes_for += amount; } } } share_type transaction_evaluation_state::get_fees( asset_id_type id )const { auto itr = balance.find(id); if( itr != balance.end() ) return itr->second; return 0; } /** * */ void transaction_evaluation_state::sub_balance( const balance_id_type& balance_id, const asset& amount ) { try { if( balance_id != balance_id_type() ) { auto provided_deposit_itr = provided_deposits.find( balance_id ); if( provided_deposit_itr == provided_deposits.end() ) { provided_deposits[balance_id] = amount; } else { provided_deposit_itr->second += amount; } } auto deposit_itr = deposits.find(amount.asset_id); if( deposit_itr == deposits.end() ) { deposits[amount.asset_id] = amount; } else { deposit_itr->second += amount; } auto balance_itr = balance.find(amount.asset_id); if( balance_itr != balance.end() ) { balance_itr->second -= amount.amount; } else { balance[amount.asset_id] = -amount.amount; } deltas[ _current_op_index ] = amount; } FC_CAPTURE_AND_RETHROW( (balance_id)(amount) ) } void transaction_evaluation_state::add_balance( const asset& amount ) { try { auto withdraw_itr = withdraws.find( amount.asset_id ); if( withdraw_itr == withdraws.end() ) withdraws[amount.asset_id] = amount; else withdraw_itr->second += amount; auto balance_itr = balance.find( amount.asset_id ); if( balance_itr == balance.end() ) balance[amount.asset_id] = amount.amount; else balance_itr->second += amount.amount; deltas[ _current_op_index ] = -amount; } FC_CAPTURE_AND_RETHROW( (amount) ) } /** * Throws if the asset is not known to the blockchain. */ void transaction_evaluation_state::validate_asset( const asset& asset_to_validate )const { auto asset_rec = _current_state->get_asset_record( asset_to_validate.asset_id ); if( NOT asset_rec ) FC_CAPTURE_AND_THROW( unknown_asset_id, (asset_to_validate) ); } } } // bts::blockchain <commit_msg>Handle upstream softfork<commit_after>#include <bts/blockchain/chain_interface.hpp> #include <bts/blockchain/operation_factory.hpp> #include <bts/blockchain/transaction_evaluation_state.hpp> #include <bts/blockchain/fork_blocks.hpp> namespace bts { namespace blockchain { transaction_evaluation_state::transaction_evaluation_state( const chain_interface_ptr& current_state, digest_type chain_id ) :_current_state( current_state ),_chain_id(chain_id),_skip_signature_check(false) { } transaction_evaluation_state::~transaction_evaluation_state() { } void transaction_evaluation_state::reset() { signed_keys.clear(); balance.clear(); deposits.clear(); withdraws.clear(); net_delegate_votes.clear(); required_deposits.clear(); validation_error.reset(); } bool transaction_evaluation_state::check_signature( const address& a )const { return _skip_signature_check || signed_keys.find( a ) != signed_keys.end(); } void transaction_evaluation_state::verify_delegate_id( account_id_type id )const { auto current_account = _current_state->get_account_record( id ); if( !current_account ) FC_CAPTURE_AND_THROW( unknown_account_id, (id) ); if( !current_account->is_delegate() ) FC_CAPTURE_AND_THROW( not_a_delegate, (id) ); } void transaction_evaluation_state::add_required_deposit( const address& owner_key, const asset& amount ) { FC_ASSERT( trx.delegate_slate_id ); balance_id_type balance_id = withdraw_condition( withdraw_with_signature( owner_key ), amount.asset_id, *trx.delegate_slate_id ).get_address(); auto itr = required_deposits.find( balance_id ); if( itr == required_deposits.end() ) { required_deposits[balance_id] = amount; } else { required_deposits[balance_id] += amount; } } void transaction_evaluation_state::update_delegate_votes() { auto asset_rec = _current_state->get_asset_record( asset_id_type() ); for( const auto& del_vote : net_delegate_votes ) { auto del_rec = _current_state->get_account_record( del_vote.first ); FC_ASSERT( !!del_rec ); del_rec->adjust_votes_for( del_vote.second.votes_for ); _current_state->store_account_record( *del_rec ); } } void transaction_evaluation_state::validate_required_fee() { try { asset xts_fees; auto fee_itr = balance.find( 0 ); if( fee_itr != balance.end() ) xts_fees += asset( fee_itr->second, 0); xts_fees += alt_fees_paid; if( required_fees > xts_fees ) { FC_CAPTURE_AND_THROW( insufficient_fee, (required_fees)(alt_fees_paid)(xts_fees) ); } } FC_RETHROW_EXCEPTIONS( warn, "" ) } /** * Process all fees and update the asset records. */ void transaction_evaluation_state::post_evaluate() { try { // Should this be here? We may not have fees in XTS now... balance[0]; // make sure we have something for this. for( const auto& fee : balance ) { if( fee.second < 0 ) FC_CAPTURE_AND_THROW( negative_fee, (fee) ); // if the fee is already in XTS or the fee balance is zero, move along... if( fee.first == 0 || fee.second == 0 ) continue; auto asset_record = _current_state->get_asset_record( fee.first ); if( !asset_record.valid() ) FC_CAPTURE_AND_THROW( unknown_asset_id, (fee.first) ); if( !asset_record->is_market_issued() ) continue; // lowest ask is someone with XTS offered at a price of USD / XTS, fee.first // is an amount of USD which can be converted to price*USD XTS provided we // send lowest_ask.index.owner the USD oprice median_price = _current_state->get_median_delegate_price( fee.first ); if( median_price ) { // fees paid in something other than XTS are discounted 50% alt_fees_paid += asset( (fee.second*2)/3, fee.first ) * *median_price; } } for( const auto& fee : balance ) { if( fee.second < 0 ) FC_CAPTURE_AND_THROW( negative_fee, (fee) ); if( fee.second > 0 ) // if a fee was paid... { auto asset_record = _current_state->get_asset_record( fee.first ); if( !asset_record ) FC_CAPTURE_AND_THROW( unknown_asset_id, (fee.first) ); asset_record->collected_fees += fee.second; _current_state->store_asset_record( *asset_record ); } } for( const auto& required_deposit : required_deposits ) { auto provided_itr = provided_deposits.find( required_deposit.first ); if( provided_itr->second < required_deposit.second ) FC_CAPTURE_AND_THROW( missing_deposit, (required_deposit) ); } } FC_RETHROW_EXCEPTIONS( warn, "" ) } void transaction_evaluation_state::evaluate( const signed_transaction& trx_arg, bool skip_signature_check ) { try { reset(); _skip_signature_check = skip_signature_check; try { if( _current_state->now() >= trx_arg.expiration ) { if( _current_state->now() > trx_arg.expiration || _current_state->get_head_block_num() >= BTSX_MARKET_FORK_11_BLOCK_NUM ) { const auto expired_by_sec = (_current_state->now() - trx_arg.expiration).to_seconds(); FC_CAPTURE_AND_THROW( expired_transaction, (trx_arg)(_current_state->now())(expired_by_sec) ); } } if( (_current_state->now() + BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC) < trx_arg.expiration ) FC_CAPTURE_AND_THROW( invalid_transaction_expiration, (trx_arg)(_current_state->now()) ); auto trx_id = trx_arg.id(); if( _current_state->is_known_transaction( trx_id ) ) FC_CAPTURE_AND_THROW( duplicate_transaction, (trx_id) ); trx = trx_arg; if( !_skip_signature_check ) { auto digest = trx_arg.digest( _chain_id ); for( const auto& sig : trx.signatures ) { auto key = fc::ecc::public_key( sig, digest ).serialize(); signed_keys.insert( address(key) ); signed_keys.insert( address(pts_address(key,false,56) ) ); signed_keys.insert( address(pts_address(key,true,56) ) ); signed_keys.insert( address(pts_address(key,false,0) ) ); signed_keys.insert( address(pts_address(key,true,0) ) ); } } _current_op_index = 0; for( const auto& op : trx.operations ) { evaluate_operation( op ); ++_current_op_index; } post_evaluate(); validate_required_fee(); update_delegate_votes(); } catch ( const fc::exception& e ) { validation_error = e; throw; } } FC_RETHROW_EXCEPTIONS( warn, "", ("trx",trx_arg) ) } void transaction_evaluation_state::evaluate_operation( const operation& op ) { operation_factory::instance().evaluate( *this, op ); } void transaction_evaluation_state::adjust_vote( slate_id_type slate_id, share_type amount ) { if( slate_id ) { auto slate = _current_state->get_delegate_slate( slate_id ); if( !slate ) FC_CAPTURE_AND_THROW( unknown_delegate_slate, (slate_id) ); for( const auto& delegate_id : slate->supported_delegates ) { if( BTS_BLOCKCHAIN_ENABLE_NEGATIVE_VOTES && delegate_id < signed_int(0) ) net_delegate_votes[abs(delegate_id)].votes_for -= amount; else net_delegate_votes[abs(delegate_id)].votes_for += amount; } } } share_type transaction_evaluation_state::get_fees( asset_id_type id )const { auto itr = balance.find(id); if( itr != balance.end() ) return itr->second; return 0; } /** * */ void transaction_evaluation_state::sub_balance( const balance_id_type& balance_id, const asset& amount ) { try { #ifndef WIN32 #warning [SOFTFORK] This check can be removed after BTSX_MARKET_FORK_12_BLOCK_NUM has passed #endif if( balance_id != balance_id_type() || _current_state->get_head_block_num() < BTSX_MARKET_FORK_12_BLOCK_NUM ) { auto provided_deposit_itr = provided_deposits.find( balance_id ); if( provided_deposit_itr == provided_deposits.end() ) { provided_deposits[balance_id] = amount; } else { provided_deposit_itr->second += amount; } } auto deposit_itr = deposits.find(amount.asset_id); if( deposit_itr == deposits.end() ) { deposits[amount.asset_id] = amount; } else { deposit_itr->second += amount; } auto balance_itr = balance.find(amount.asset_id); if( balance_itr != balance.end() ) { balance_itr->second -= amount.amount; } else { balance[amount.asset_id] = -amount.amount; } deltas[ _current_op_index ] = amount; } FC_CAPTURE_AND_RETHROW( (balance_id)(amount) ) } void transaction_evaluation_state::add_balance( const asset& amount ) { try { auto withdraw_itr = withdraws.find( amount.asset_id ); if( withdraw_itr == withdraws.end() ) withdraws[amount.asset_id] = amount; else withdraw_itr->second += amount; auto balance_itr = balance.find( amount.asset_id ); if( balance_itr == balance.end() ) balance[amount.asset_id] = amount.amount; else balance_itr->second += amount.amount; deltas[ _current_op_index ] = -amount; } FC_CAPTURE_AND_RETHROW( (amount) ) } /** * Throws if the asset is not known to the blockchain. */ void transaction_evaluation_state::validate_asset( const asset& asset_to_validate )const { auto asset_rec = _current_state->get_asset_record( asset_to_validate.asset_id ); if( NOT asset_rec ) FC_CAPTURE_AND_THROW( unknown_asset_id, (asset_to_validate) ); } } } // bts::blockchain <|endoftext|>
<commit_before>/* * LibIPACA.hpp * * Copyright (c) 2011,2012 Mathias Wilhelm * Copyright (c) 2011,2012 Marc Kirchner * */ #ifndef __LIBAAS_INCLUDE_AAS_LIBIPACA_HPP__ #define __LIBAAS_INCLUDE_AAS_LIBIPACA_HPP__ #include "aas/Stoichiometry.hpp" #include "aas/Element.hpp" #include <ipaca/Spectrum.hpp> #include <ipaca/Stoichiometry.hpp> #include <ipaca/Traits.hpp> #include <ipaca/Types.hpp> #include <vector> namespace aas { namespace adapter { typedef ipaca::detail::Spectrum LibaasSpectrum; typedef aas::Stoichiometry LibaasStoichiometry; struct SpectrumConverter { void operator()(const ipaca::detail::Spectrum& lhs, LibaasSpectrum& rhs) { rhs = lhs; } }; struct ElementConverter { void operator()(const aas::elements::Element& lhs, ipaca::detail::Element& rhs) { rhs.count = 0.0; rhs.isotopes.clear(); typedef std::vector<aas::elements::Isotope> AASIsotopeList; const AASIsotopeList& eis = lhs.get().getIsotopes(); // TODO make sure isotopes are added sorted by mass! for (AASIsotopeList::const_iterator it = eis.begin(); it != eis.end(); ++it) { ipaca::detail::Isotope i; i.ab = it->getFrequency(); i.mz = it->getMass(); rhs.isotopes.push_back(i); } } }; struct StoichiometryConverter { void operator()(const LibaasStoichiometry& lhs, ipaca::detail::Stoichiometry& rhs) { typedef LibaasStoichiometry::const_iterator SIT; typedef std::vector<aas::elements::Isotope>::const_iterator IIT; ElementConverter ec; for (SIT it = lhs.begin(); it != lhs.end(); ++it) { ipaca::detail::Element e; ec(it->first, e); e.count = it->second; rhs.push_back(e); } } }; } // namespace adapter } // namespace aas namespace ipaca { template<> struct Traits<aas::adapter::LibaasStoichiometry, aas::adapter::LibaasSpectrum> { typedef aas::adapter::SpectrumConverter spectrum_converter; typedef aas::adapter::StoichiometryConverter stoichiometry_converter; static ipaca::detail::Element getHydrogens(const ipaca::Size n); static ipaca::Bool isHydrogen(const ipaca::detail::Element&); static ipaca::Double getElectronMass(); }; ipaca::detail::Element Traits<aas::adapter::LibaasStoichiometry, aas::adapter::LibaasSpectrum>::getHydrogens(const ipaca::Size n) { ipaca::detail::Element h; aas::adapter::ElementConverter ec; ec(aas::elements::Element(1), h); h.count = static_cast<Double>(n); return h; } ipaca::Bool Traits<aas::adapter::LibaasStoichiometry, aas::adapter::LibaasSpectrum>::isHydrogen( const ipaca::detail::Element& e) { ipaca::detail::Element h; aas::adapter::ElementConverter ec; ec(aas::elements::Element(1), h); typedef std::vector<ipaca::detail::Isotope>::const_iterator IT; for (IT et = e.isotopes.begin(), ht = h.isotopes.begin(); et != e.isotopes.end() && ht != h.isotopes.end(); ++et, ++ht) { if (et->ab != ht->ab || et->mz != ht->mz) { return false; } } return true; } ipaca::Double Traits<aas::adapter::LibaasStoichiometry, aas::adapter::LibaasSpectrum>::getElectronMass() { return ipaca::detail::getElectronMass(); } } // namespace ipaca #endif /* __LIBAAS_INCLUDE_AAS_LIBIPACA_HPP__ */ <commit_msg>fixed adapter<commit_after>/* * LibIPACA.hpp * * Copyright (c) 2011,2012 Mathias Wilhelm * Copyright (c) 2011,2012 Marc Kirchner * */ #ifndef __LIBAAS_INCLUDE_AAS_LIBIPACA_HPP__ #define __LIBAAS_INCLUDE_AAS_LIBIPACA_HPP__ #include "aas/Stoichiometry.hpp" #include "aas/Element.hpp" #include <ipaca/Spectrum.hpp> #include <ipaca/Stoichiometry.hpp> #include <ipaca/Traits.hpp> #include <ipaca/Types.hpp> #include <vector> namespace aas { namespace adapter { typedef ipaca::detail::Spectrum LibaasSpectrum; typedef aas::stoichiometries::Stoichiometry LibaasStoichiometry; struct SpectrumConverter { void operator()(const ipaca::detail::Spectrum& lhs, LibaasSpectrum& rhs) { rhs = lhs; } }; struct ElementConverter { void operator()(const aas::elements::Element& lhs, ipaca::detail::Element& rhs) { rhs.count = 0.0; rhs.isotopes.clear(); typedef std::vector<aas::elements::Isotope> AASIsotopeList; const AASIsotopeList& eis = lhs.get().getIsotopes(); // TODO make sure isotopes are added sorted by mass! for (AASIsotopeList::const_iterator it = eis.begin(); it != eis.end(); ++it) { ipaca::detail::Isotope i; i.ab = it->getFrequency(); i.mz = it->getMass(); rhs.isotopes.push_back(i); } } }; struct StoichiometryConverter { void operator()(const LibaasStoichiometry& lhs, ipaca::detail::Stoichiometry& rhs) { typedef LibaasStoichiometry::const_iterator SIT; typedef std::vector<aas::elements::Isotope>::const_iterator IIT; ElementConverter ec; for (SIT it = lhs.begin(); it != lhs.end(); ++it) { ipaca::detail::Element e; ec(it->first, e); e.count = it->second; rhs.push_back(e); } } }; } // namespace adapter } // namespace aas namespace ipaca { template<> struct Traits<aas::adapter::LibaasStoichiometry, aas::adapter::LibaasSpectrum> { typedef aas::adapter::SpectrumConverter spectrum_converter; typedef aas::adapter::StoichiometryConverter stoichiometry_converter; static ipaca::detail::Element getHydrogens(const ipaca::Size n); static ipaca::Bool isHydrogen(const ipaca::detail::Element&); static ipaca::Double getElectronMass(); }; ipaca::detail::Element Traits<aas::adapter::LibaasStoichiometry, aas::adapter::LibaasSpectrum>::getHydrogens(const ipaca::Size n) { ipaca::detail::Element h; aas::adapter::ElementConverter ec; ec(aas::elements::Element(1), h); h.count = static_cast<Double>(n); return h; } ipaca::Bool Traits<aas::adapter::LibaasStoichiometry, aas::adapter::LibaasSpectrum>::isHydrogen( const ipaca::detail::Element& e) { ipaca::detail::Element h; aas::adapter::ElementConverter ec; ec(aas::elements::Element(1), h); typedef std::vector<ipaca::detail::Isotope>::const_iterator IT; for (IT et = e.isotopes.begin(), ht = h.isotopes.begin(); et != e.isotopes.end() && ht != h.isotopes.end(); ++et, ++ht) { if (et->ab != ht->ab || et->mz != ht->mz) { return false; } } return true; } ipaca::Double Traits<aas::adapter::LibaasStoichiometry, aas::adapter::LibaasSpectrum>::getElectronMass() { return ipaca::detail::getElectronMass(); } } // namespace ipaca #endif /* __LIBAAS_INCLUDE_AAS_LIBIPACA_HPP__ */ <|endoftext|>
<commit_before>/** * @file main.cpp * @author Volodymyr Shymanskyy * @license This project is released under the MIT License (MIT) * @copyright Copyright (c) 2015 Volodymyr Shymanskyy * @date Mar 2015 * @brief */ //#define BLYNK_DEBUG #define BLYNK_PRINT stdout #ifdef RASPBERRY #include <BlynkApiWiringPi.h> #else #include <BlynkApiLinux.h> #endif #include <BlynkSocket.h> #include <BlynkOptionsParser.h> static BlynkTransportSocket _blynkTransport; BlynkSocket Blynk(_blynkTransport); #include <BlynkWidgets.h> BLYNK_WRITE(V1) { printf("Got a value: %s\n", param[0].asStr()); } void setup() { } void loop() { Blynk.run(); } int main(int argc, char* argv[]) { const char *auth, *serv; uint16_t port; parse_options(argc, argv, auth, serv, port); Blynk.begin(auth, serv, port); setup(); while(true) { loop(); } return 0; } <commit_msg>Update linux main<commit_after>/** * @file main.cpp * @author Volodymyr Shymanskyy * @license This project is released under the MIT License (MIT) * @copyright Copyright (c) 2015 Volodymyr Shymanskyy * @date Mar 2015 * @brief */ //#define BLYNK_DEBUG #define BLYNK_PRINT stdout #ifdef RASPBERRY #include <BlynkApiWiringPi.h> #else #include <BlynkApiLinux.h> #endif #include <BlynkSocket.h> #include <BlynkOptionsParser.h> static BlynkTransportSocket _blynkTransport; BlynkSocket Blynk(_blynkTransport); static const char *auth, *serv; static uint16_t port; #include <BlynkWidgets.h> BLYNK_WRITE(V1) { printf("Got a value: %s\n", param[0].asStr()); } void setup() { Blynk.begin(auth, serv, port); } void loop() { Blynk.run(); } int main(int argc, char* argv[]) { parse_options(argc, argv, auth, serv, port); setup(); while(true) { loop(); } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 libczmq++ developers (see AUTHORS) * * This file is part of libczmq++. * * libczmq++ is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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/>. */ #ifndef LIBCZMQPP_AUTHENTICATOR_HPP #define LIBCZMQPP_AUTHENTICATOR_HPP #include <string> #include <czmq++/context.hpp> #include <czmq++/define.hpp> namespace czmqpp { class CZMQPP_EXPORT authenticator { public: authenticator(context& ctx); authenticator(const authenticator&) = delete; ~authenticator(); zauth_t* self(); void allow(const std::string& address); void deny(const std::string& address); void configure_plain( const std::string& domain, const std::string& filename); void configure_curve( const std::string& domain, const std::string& location); void set_verbose(bool verbose); private: // Travis default gcc build: // error: constexpr needed for in-class initialization of static data // member self_ of non-integral type. initialize on construct. zauth_t* self_; }; } // namespace czmqpp #endif <commit_msg>Comments.<commit_after>/* * Copyright (c) 2011-2013 libczmq++ developers (see AUTHORS) * * This file is part of libczmq++. * * libczmq++ is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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/>. */ #ifndef LIBCZMQPP_AUTHENTICATOR_HPP #define LIBCZMQPP_AUTHENTICATOR_HPP #include <string> #include <czmq++/context.hpp> #include <czmq++/define.hpp> namespace czmqpp { class CZMQPP_EXPORT authenticator { public: authenticator(context& ctx); authenticator(const authenticator&) = delete; ~authenticator(); zauth_t* self(); void allow(const std::string& address); void deny(const std::string& address); void configure_plain( const std::string& domain, const std::string& filename); void configure_curve( const std::string& domain, const std::string& location); void set_verbose(bool verbose); private: zauth_t* self_; }; } // namespace czmqpp #endif <|endoftext|>
<commit_before>/** * \file * \brief IntegerSequence template class header * * \author Copyright (C) 2015 Kamil Szczygiel https://distortec.com https://freddiechopin.info * * \par License * 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 https://mozilla.org/MPL/2.0/. */ #ifndef ESTD_INTEGERSEQUENCE_HPP_ #define ESTD_INTEGERSEQUENCE_HPP_ #include <type_traits> namespace estd { /** * \brief Compile-time sequence of integers * * Similar to std::integer_sequence from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * \tparam T is an integer type to use for the elements of the sequence * \tparam Integers is a non-type parameter pack representing the sequence */ template<typename T, T... Integers> class IntegerSequence { public: /// integer type used for the elements of the sequence using value_type = T; /** * \return number of elements in the sequence */ constexpr static std::size_t size() noexcept { return sizeof...(Integers); }; }; /** * \brief Compile-time sequence of std::size_t elements * * Similar to std::index_sequence from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * \tparam Indexes is a non-type parameter pack representing the sequence */ template<std::size_t... Indexes> using IndexSequence = IntegerSequence<std::size_t, Indexes...>; namespace internal { /** * \brief IntegerSequence with two internal type aliases. * * \tparam T is an integer type to use for the elements of the sequence * \tparam Integers is a non-type parameter pack representing the sequence */ template<typename T, T... Integers> struct TypedSequence : IntegerSequence<T, Integers...> { /// type of base class using base = IntegerSequence<T, Integers...>; /// type of class using type = TypedSequence; }; /** * \brief TypedSequence with doubled number of elements * * \tparam Sequence is the type of sequence that will be doubled */ template<typename Sequence> struct DoubledIntegerSequence; /** * \brief TypedSequence with doubled number of elements * * Specialization for TypedSequence. * * \tparam T is an integer type to use for the elements of the sequence * \tparam Integers is a non-type parameter pack representing the sequence */ template<typename T, T... Integers> struct DoubledIntegerSequence<TypedSequence<T, Integers...>> { /// TypedSequence with doubled number of elements - TypedSequence<T, 0, 1, ..., N - 1> is turned into /// TypedSequence<T, 0, 1, ..., N - 1, N, N + 1, ..., 2 * N - 1> using type = TypedSequence<T, Integers..., (sizeof...(Integers) + Integers)...>; }; /** * \brief TypedSequence optionally extended by one element * * \tparam Extend selects whether the sequence will be extended by one element (true) or not (false) * \tparam Sequence is the type of sequence that will optionally be extended */ template<bool Extend, typename Sequence> struct ExtendedIntegerSequence { /// same as \a Sequence using type = Sequence; }; /** * \brief TypedSequence optionally extended by one element * * Specialization for the case with extending. * * \tparam T is an integer type to use for the elements of the sequence * \tparam Integers is a non-type parameter pack representing the sequence */ template<typename T, T... Integers> struct ExtendedIntegerSequence<true, TypedSequence<T, Integers...>> { /// sequence extended by one element - TypedSequence<T, 0, 1, ..., N - 1> is turned into /// TypedSequence<T, 0, 1, ..., N - 1, N> using type = TypedSequence<T, Integers..., sizeof...(Integers)>; }; /** * \brief Implementation of generator of IntegerSequence types * * Generates TypedSequence<T, 0, 1, ..., N - 1> type. * * \tparam T is an integer type to use for the elements of the sequence * \tparam N is the requested number of elements in the sequence */ template<typename T, std::size_t N> struct MakeIntegerSequenceImplementation : ExtendedIntegerSequence<N % 2 != 0, typename DoubledIntegerSequence<typename MakeIntegerSequenceImplementation<T, N / 2>::type>::type> { }; /** * \brief Implementation of generator of IntegerSequence types * * Specialization for terminal case - 0 elements - generates TypedSequence<T> type. * * \tparam T is an integer type to use for the elements of the sequence */ template<typename T> struct MakeIntegerSequenceImplementation<T, 0> { /// empty TypedSequence<T> type using type = TypedSequence<T>; }; /** * \brief Wrapper for MakeIntegerSequenceImplementation that ensures \a N is non-negative * * Generates TypedSequence<T, 0, 1, ..., N - 1> type. * * \tparam T is an integer type to use for the elements of the sequence * \tparam N is the requested number of elements in the sequence, must be non-negative */ template<typename T, T N> struct MakeIntegerSequenceImplementationWrapper : std::enable_if<N >= 0, MakeIntegerSequenceImplementation<T, static_cast<std::size_t>(N)>>::type { static_assert(N >= 0, "Number of elements in the sequence must be non-negative!"); }; } // namespace internal /** * \brief Generator of IntegerSequence types * * Similar to std::make_integer_sequence from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * Whole implementation is based on code from http://stackoverflow.com/a/20101039/157344 * * Generates IntegerSequence<T, 0, 1, ..., N - 1> type. * * \tparam T is an integer type to use for the elements of the sequence * \tparam N is the requested number of elements in the sequence */ template<typename T, T N> using MakeIntegerSequence = typename internal::MakeIntegerSequenceImplementationWrapper<T, N>::type::base; /** * \brief Generator of IndexSequence types * * Similar to std::make_index_sequence from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * Generates IndexSequence<0, 1, ..., N - 1> type. * * \tparam N is the requested number of elements in the sequence */ template<std::size_t N> using MakeIndexSequence = MakeIntegerSequence<std::size_t, N>; /** * \brief Generator of IndexSequence types * * Similar to std::index_sequence_for from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * Generates IndexSequence<0, 1, ..., sizeof...(T) - 1> type. * * \tparam T is the type parameter pack for which an index sequence of the same length will be generated */ template<typename... T> using IndexSequenceFor = MakeIndexSequence<sizeof...(T)>; } // namespace estd #endif // ESTD_INTEGERSEQUENCE_HPP_ <commit_msg>http://stackoverflow.com -> https://stackoverflow.com<commit_after>/** * \file * \brief IntegerSequence template class header * * \author Copyright (C) 2015 Kamil Szczygiel https://distortec.com https://freddiechopin.info * * \par License * 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 https://mozilla.org/MPL/2.0/. */ #ifndef ESTD_INTEGERSEQUENCE_HPP_ #define ESTD_INTEGERSEQUENCE_HPP_ #include <type_traits> namespace estd { /** * \brief Compile-time sequence of integers * * Similar to std::integer_sequence from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * \tparam T is an integer type to use for the elements of the sequence * \tparam Integers is a non-type parameter pack representing the sequence */ template<typename T, T... Integers> class IntegerSequence { public: /// integer type used for the elements of the sequence using value_type = T; /** * \return number of elements in the sequence */ constexpr static std::size_t size() noexcept { return sizeof...(Integers); }; }; /** * \brief Compile-time sequence of std::size_t elements * * Similar to std::index_sequence from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * \tparam Indexes is a non-type parameter pack representing the sequence */ template<std::size_t... Indexes> using IndexSequence = IntegerSequence<std::size_t, Indexes...>; namespace internal { /** * \brief IntegerSequence with two internal type aliases. * * \tparam T is an integer type to use for the elements of the sequence * \tparam Integers is a non-type parameter pack representing the sequence */ template<typename T, T... Integers> struct TypedSequence : IntegerSequence<T, Integers...> { /// type of base class using base = IntegerSequence<T, Integers...>; /// type of class using type = TypedSequence; }; /** * \brief TypedSequence with doubled number of elements * * \tparam Sequence is the type of sequence that will be doubled */ template<typename Sequence> struct DoubledIntegerSequence; /** * \brief TypedSequence with doubled number of elements * * Specialization for TypedSequence. * * \tparam T is an integer type to use for the elements of the sequence * \tparam Integers is a non-type parameter pack representing the sequence */ template<typename T, T... Integers> struct DoubledIntegerSequence<TypedSequence<T, Integers...>> { /// TypedSequence with doubled number of elements - TypedSequence<T, 0, 1, ..., N - 1> is turned into /// TypedSequence<T, 0, 1, ..., N - 1, N, N + 1, ..., 2 * N - 1> using type = TypedSequence<T, Integers..., (sizeof...(Integers) + Integers)...>; }; /** * \brief TypedSequence optionally extended by one element * * \tparam Extend selects whether the sequence will be extended by one element (true) or not (false) * \tparam Sequence is the type of sequence that will optionally be extended */ template<bool Extend, typename Sequence> struct ExtendedIntegerSequence { /// same as \a Sequence using type = Sequence; }; /** * \brief TypedSequence optionally extended by one element * * Specialization for the case with extending. * * \tparam T is an integer type to use for the elements of the sequence * \tparam Integers is a non-type parameter pack representing the sequence */ template<typename T, T... Integers> struct ExtendedIntegerSequence<true, TypedSequence<T, Integers...>> { /// sequence extended by one element - TypedSequence<T, 0, 1, ..., N - 1> is turned into /// TypedSequence<T, 0, 1, ..., N - 1, N> using type = TypedSequence<T, Integers..., sizeof...(Integers)>; }; /** * \brief Implementation of generator of IntegerSequence types * * Generates TypedSequence<T, 0, 1, ..., N - 1> type. * * \tparam T is an integer type to use for the elements of the sequence * \tparam N is the requested number of elements in the sequence */ template<typename T, std::size_t N> struct MakeIntegerSequenceImplementation : ExtendedIntegerSequence<N % 2 != 0, typename DoubledIntegerSequence<typename MakeIntegerSequenceImplementation<T, N / 2>::type>::type> { }; /** * \brief Implementation of generator of IntegerSequence types * * Specialization for terminal case - 0 elements - generates TypedSequence<T> type. * * \tparam T is an integer type to use for the elements of the sequence */ template<typename T> struct MakeIntegerSequenceImplementation<T, 0> { /// empty TypedSequence<T> type using type = TypedSequence<T>; }; /** * \brief Wrapper for MakeIntegerSequenceImplementation that ensures \a N is non-negative * * Generates TypedSequence<T, 0, 1, ..., N - 1> type. * * \tparam T is an integer type to use for the elements of the sequence * \tparam N is the requested number of elements in the sequence, must be non-negative */ template<typename T, T N> struct MakeIntegerSequenceImplementationWrapper : std::enable_if<N >= 0, MakeIntegerSequenceImplementation<T, static_cast<std::size_t>(N)>>::type { static_assert(N >= 0, "Number of elements in the sequence must be non-negative!"); }; } // namespace internal /** * \brief Generator of IntegerSequence types * * Similar to std::make_integer_sequence from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * Whole implementation is based on code from https://stackoverflow.com/a/20101039/157344 * * Generates IntegerSequence<T, 0, 1, ..., N - 1> type. * * \tparam T is an integer type to use for the elements of the sequence * \tparam N is the requested number of elements in the sequence */ template<typename T, T N> using MakeIntegerSequence = typename internal::MakeIntegerSequenceImplementationWrapper<T, N>::type::base; /** * \brief Generator of IndexSequence types * * Similar to std::make_index_sequence from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * Generates IndexSequence<0, 1, ..., N - 1> type. * * \tparam N is the requested number of elements in the sequence */ template<std::size_t N> using MakeIndexSequence = MakeIntegerSequence<std::size_t, N>; /** * \brief Generator of IndexSequence types * * Similar to std::index_sequence_for from C++14 - https://en.cppreference.com/w/cpp/utility/integer_sequence * * Generates IndexSequence<0, 1, ..., sizeof...(T) - 1> type. * * \tparam T is the type parameter pack for which an index sequence of the same length will be generated */ template<typename... T> using IndexSequenceFor = MakeIndexSequence<sizeof...(T)>; } // namespace estd #endif // ESTD_INTEGERSEQUENCE_HPP_ <|endoftext|>
<commit_before>/* * File: OHMComm.cpp * Author: daniel, jonas * * Created on March 29, 2015, 1:49 PM */ #include <cstdlib> #include <string> #include <sstream> #include <iostream> #include <stdio.h> #include "UserInput.h" //dependencies for rtaudio #include "RtAudio.h" #include "AudioHandlerFactory.h" #include "UDPWrapper.h" #include "ProcessorRTP.h" #include "RTPListener.h" #include "Tests.h" //Declare Configurations NetworkConfiguration networkConfiguration; AudioConfiguration audioConfiguration; using namespace std; // method for printing vectors used in configureAudioDevices void printVector(std::vector<unsigned int> v) { for (unsigned int i = 0; i < v.size(); i++) { std::cout << v[i] << " "; } } /*! * Lets the user choose a supported audio-format */ RtAudioFormat selectAudioFormat(RtAudioFormat supportedFormats) { vector<string> formatNames; vector<RtAudioFormat> audioFormats; //preallocate vectors formatNames.reserve(8); audioFormats.reserve(8); //fill options if((supportedFormats & RTAUDIO_SINT8) == RTAUDIO_SINT8) { formatNames.push_back("8 bit signed integer"); audioFormats.push_back(RTAUDIO_SINT8); } if((supportedFormats & RTAUDIO_SINT16) == RTAUDIO_SINT16) { formatNames.push_back("16 bit signed integer"); audioFormats.push_back(RTAUDIO_SINT16); } if((supportedFormats & RTAUDIO_SINT24) == RTAUDIO_SINT24) { formatNames.push_back("24 bit signed integer"); audioFormats.push_back(RTAUDIO_SINT24); } if((supportedFormats & RTAUDIO_SINT32) == RTAUDIO_SINT32) { formatNames.push_back("32 bit signed integer"); audioFormats.push_back(RTAUDIO_SINT32); } if((supportedFormats & RTAUDIO_FLOAT32) == RTAUDIO_FLOAT32) { formatNames.push_back("32 bit float (normalized between +/- 1)"); audioFormats.push_back(RTAUDIO_SINT16); //TODO temporary change, dont forget to changeback to RTAUDIO_FLOAT32 } if((supportedFormats & RTAUDIO_FLOAT64) == RTAUDIO_FLOAT64) { formatNames.push_back("64 bit float (normalized between +/- 1)"); audioFormats.push_back(RTAUDIO_FLOAT64); } int formatIndex = selectOptionIndex("Choose audio format", formatNames, 0); //return selected option return audioFormats[formatIndex]; } void configureNetwork() { cout << "Network configuration" << endl; //1. remote address string ipString = inputString("1. Input destination IP address"); networkConfiguration.addressOutgoing = ipString; networkConfiguration.addressIncoming = "127.0.0.1"; //2. remote and local ports int destPort = inputNumber("2. Input destination port", false, false); int localPort = inputNumber("3. Input local port", false, false); networkConfiguration.portOutgoing = destPort; networkConfiguration.portIncoming = localPort; vector<string> protocols {"TCP", "UDP"}; string protocolString = selectOption("4. Choose protocol", protocols, "UDP"); networkConfiguration.connectionType = protocolString == "TCP" ? NetworkConfiguration::ConnectionType::TCP : NetworkConfiguration::ConnectionType::UDP; // Connection type is not relevant for the network configuration // If there is an TCP connection needed, then pass the config to a TCP-Wrapper // otherwise pass the config cout << "Networkconfiguration set." << endl; } void configureAudioDevices() { cout << endl; cout << "+++Audio Device configuration+++" << endl; cout << endl; RtAudio AudioDevices; // Determine the number of available Audio Devices unsigned int availableAudioDevices = AudioDevices.getDeviceCount(); cout << "Available Audio Devices: " << endl; cout << endl; // printing available Audio Devices RtAudio::DeviceInfo DeviceInfo; unsigned int DefaultOutputDeviceID; unsigned int DefaultInputDeviceID; for (unsigned int i = 0 ; i < availableAudioDevices ; i++) { DeviceInfo = AudioDevices.getDeviceInfo(i); if (DeviceInfo.probed == true) //Audio Device successfully probed { cout << "Device ID: " << i << endl; cout << "Device Name = " << DeviceInfo.name << endl; cout << "Maximum output channels = " << DeviceInfo.outputChannels << endl; cout << "Maximum input channels = " << DeviceInfo.inputChannels << endl; cout << "Maximum duplex channels = " << DeviceInfo.duplexChannels << endl; cout << "Default output: "; if (DeviceInfo.isDefaultOutput == true) { cout << "Yes" << endl; DefaultOutputDeviceID = i; } else { cout << "No" << endl; } cout << "Default input: "; if (DeviceInfo.isDefaultInput == true) { cout << "Yes" << endl; DefaultInputDeviceID = i; } else { cout << "No" << endl; } cout << "Supported Sample Rates: "; printVector(DeviceInfo.sampleRates); cout << endl; cout << "Audio Format = " << DeviceInfo.nativeFormats << endl; cout << endl; } } unsigned int OutputDeviceID; //Choose output Device cout << "Choose output Device ID [default is " << DefaultOutputDeviceID << " ]: "; cin >> OutputDeviceID; RtAudio::DeviceInfo OutputDeviceInfo = AudioDevices.getDeviceInfo(OutputDeviceID); //Configure ID of the Output Audio Device audioConfiguration.outputDeviceID = OutputDeviceID; cout << "-> Using output Device ID: " << audioConfiguration.outputDeviceID << endl; //Configure Name of the Output Audio Device audioConfiguration.outputDeviceName = OutputDeviceInfo.name; cout << "-> Using output Device Name: " << audioConfiguration.outputDeviceName << endl; //Configure Number of Maximum output Channels (we always use stereo) audioConfiguration.outputDeviceChannels = 2; cout << "-> Number of maximum duplex Channels supported from this Device: " << audioConfiguration.outputDeviceChannels << endl; unsigned int OutputSampleRate; //Configure Output Sample Rate cout << "-> Supported Sample Rates from this Device: "; printVector(OutputDeviceInfo.sampleRates); cout << endl << "Choose your Sample Rate: "; cin >> OutputSampleRate; audioConfiguration.sampleRate = OutputSampleRate; cout << "-> Using Sample Rate: " << audioConfiguration.sampleRate << endl; //Configure Output Audio Format audioConfiguration.audioFormat = selectAudioFormat(OutputDeviceInfo.nativeFormats); cout << "-> Output Audio Format: " << audioConfiguration.audioFormat << endl; unsigned int InputDeviceID; //Choose input Device cout << "Choose input Device ID [default is " << DefaultInputDeviceID << " ]: "; cin >> InputDeviceID; RtAudio::DeviceInfo InputDeviceInfo = AudioDevices.getDeviceInfo(InputDeviceID); //Configure ID of the Input Audio Device audioConfiguration.inputDeviceID = InputDeviceID; cout << "-> Using input Device ID " << audioConfiguration.inputDeviceID << endl; //Configure Name of the Input Audio Device audioConfiguration.inputDeviceName = InputDeviceInfo.name; cout << "-> Using input Device Name: " << audioConfiguration.inputDeviceName << endl; //Configure Number of Maximum output Channels (we always use stereo) audioConfiguration.inputDeviceChannels = 2; cout << "-> Number of maximum duplex Channels supported from this Device: " << audioConfiguration.inputDeviceChannels << endl; unsigned int InputSampleRate; //TODO sampleRate and audioFormat are overridden! //Configure Input Sample Rate cout << "-> Supported Sample Rates from this Device: "; printVector(InputDeviceInfo.sampleRates); cout << endl << "Choose your Sample Rate: "; cin >> InputSampleRate; audioConfiguration.sampleRate = InputSampleRate; cout << "-> Using Sample Rate: " << audioConfiguration.sampleRate << endl; //Configure Input Audio Format audioConfiguration.audioFormat = selectAudioFormat(InputDeviceInfo.nativeFormats); cout << "-> Input Audio Format: " << audioConfiguration.audioFormat << endl; //Buffer size audioConfiguration.bufferFrames = inputNumber("Input the number of frames to buffer (around 128 - 2048, 256 is recommended)", false, false); } /*! * RtAudio Error Handler */ void errorHandler( RtAudioError::Type type, const std::string &errorText ) { cerr << "An error occurred!" << endl; switch(type) { case RtAudioError::Type::WARNING: case RtAudioError::Type::DEBUG_WARNING: cerr << "WARNING: "; case RtAudioError::Type::MEMORY_ERROR: case RtAudioError::Type::DRIVER_ERROR: case RtAudioError::Type::SYSTEM_ERROR: case RtAudioError::Type::THREAD_ERROR: cerr << "ERROR: "; case RtAudioError::Type::NO_DEVICES_FOUND: case RtAudioError::Type::INVALID_DEVICE: cerr << "Device Error: "; case RtAudioError::Type::INVALID_PARAMETER: case RtAudioError::Type::INVALID_USE: cerr << "Invalid Function-call: "; case RtAudioError::Type::UNSPECIFIED: cerr << "Unspecified Error: "; } cerr << errorText << endl; } int main(int argc, char** argv) { Test::TextOutput output(Test::TextOutput::Verbose); TestAudioIO testaudio; testaudio.run(output); try { std::unique_ptr<AudioHandler> audioObject; char input; /* Audio-Config */ cout << "Load default audio config? Yes (y), No (n)?" << endl; cin >> input; if (input == 'N' || input == 'n') { configureAudioDevices(); audioObject = AudioHandlerFactory::getAudioHandler("RTAudioWrapper", audioConfiguration); } else { audioObject = AudioHandlerFactory::getAudioHandler("RTAudioWrapper"); } /* Network-Config */ NetworkWrapper *network; cout << "Load default network config? Yes (y), No (n)?" << endl; cin >> input; if (input == 'N' || input == 'n') { configureNetwork(); //XXX make the buffers configurable?? networkConfiguration.inputBufferSize = 4096; networkConfiguration.outputBufferSize = 4096; network = new UDPWrapper(networkConfiguration); } else { networkConfiguration.addressIncoming = "127.0.0.1"; networkConfiguration.addressOutgoing = "127.0.0.1"; networkConfiguration.connectionType = NetworkConfiguration::ConnectionType::UDP; networkConfiguration.inputBufferSize = 4096; networkConfiguration.outputBufferSize = 4096; //the port should be a number greater than 1024 networkConfiguration.portIncoming = 12345; networkConfiguration.portOutgoing = 12345; network = new UDPWrapper(networkConfiguration); } //initialize RTPBuffer and -Listener std::unique_ptr<RTPBuffer> *rtpBuffer = new std::unique_ptr<RTPBuffer>(new RTPBuffer(256, 1000)); RTPListener listener(network, rtpBuffer, networkConfiguration.inputBufferSize); // add a processor to the process chain ProcessorRTP rtp("RTP-Processor", network, rtpBuffer); audioObject->addProcessor((AudioProcessor*)&rtp); //configure all processors audioObject->configureAudioProcessors(); // start audio processing listener.startUp(); audioObject->startDuplexMode(); // wait for exit cout << "Type Enter to exit" << endl; cin >> input; audioObject->stop(); return 0; } catch (RtAudioError exception) { cout << "Ausnahme: " << exception.getMessage() << endl; } } <commit_msg>Added user-input whether to run tests Signed-off-by:doe300 <[email protected]><commit_after>/* * File: OHMComm.cpp * Author: daniel, jonas * * Created on March 29, 2015, 1:49 PM */ #include <cstdlib> #include <string> #include <sstream> #include <iostream> #include <stdio.h> #include "UserInput.h" //dependencies for rtaudio #include "RtAudio.h" #include "AudioHandlerFactory.h" #include "UDPWrapper.h" #include "ProcessorRTP.h" #include "RTPListener.h" #include "Tests.h" //Declare Configurations NetworkConfiguration networkConfiguration; AudioConfiguration audioConfiguration; using namespace std; // method for printing vectors used in configureAudioDevices void printVector(std::vector<unsigned int> v) { for (unsigned int i = 0; i < v.size(); i++) { std::cout << v[i] << " "; } } /*! * Lets the user choose a supported audio-format */ RtAudioFormat selectAudioFormat(RtAudioFormat supportedFormats) { vector<string> formatNames; vector<RtAudioFormat> audioFormats; //preallocate vectors formatNames.reserve(8); audioFormats.reserve(8); //fill options if((supportedFormats & RTAUDIO_SINT8) == RTAUDIO_SINT8) { formatNames.push_back("8 bit signed integer"); audioFormats.push_back(RTAUDIO_SINT8); } if((supportedFormats & RTAUDIO_SINT16) == RTAUDIO_SINT16) { formatNames.push_back("16 bit signed integer"); audioFormats.push_back(RTAUDIO_SINT16); } if((supportedFormats & RTAUDIO_SINT24) == RTAUDIO_SINT24) { formatNames.push_back("24 bit signed integer"); audioFormats.push_back(RTAUDIO_SINT24); } if((supportedFormats & RTAUDIO_SINT32) == RTAUDIO_SINT32) { formatNames.push_back("32 bit signed integer"); audioFormats.push_back(RTAUDIO_SINT32); } if((supportedFormats & RTAUDIO_FLOAT32) == RTAUDIO_FLOAT32) { formatNames.push_back("32 bit float (normalized between +/- 1)"); audioFormats.push_back(RTAUDIO_SINT16); //TODO temporary change, dont forget to changeback to RTAUDIO_FLOAT32 } if((supportedFormats & RTAUDIO_FLOAT64) == RTAUDIO_FLOAT64) { formatNames.push_back("64 bit float (normalized between +/- 1)"); audioFormats.push_back(RTAUDIO_FLOAT64); } int formatIndex = selectOptionIndex("Choose audio format", formatNames, 0); //return selected option return audioFormats[formatIndex]; } void configureNetwork() { cout << "Network configuration" << endl; //1. remote address string ipString = inputString("1. Input destination IP address"); networkConfiguration.addressOutgoing = ipString; networkConfiguration.addressIncoming = "127.0.0.1"; //2. remote and local ports int destPort = inputNumber("2. Input destination port", false, false); int localPort = inputNumber("3. Input local port", false, false); networkConfiguration.portOutgoing = destPort; networkConfiguration.portIncoming = localPort; vector<string> protocols {"TCP", "UDP"}; string protocolString = selectOption("4. Choose protocol", protocols, "UDP"); networkConfiguration.connectionType = protocolString == "TCP" ? NetworkConfiguration::ConnectionType::TCP : NetworkConfiguration::ConnectionType::UDP; // Connection type is not relevant for the network configuration // If there is an TCP connection needed, then pass the config to a TCP-Wrapper // otherwise pass the config cout << "Networkconfiguration set." << endl; } void configureAudioDevices() { cout << endl; cout << "+++Audio Device configuration+++" << endl; cout << endl; RtAudio AudioDevices; // Determine the number of available Audio Devices unsigned int availableAudioDevices = AudioDevices.getDeviceCount(); cout << "Available Audio Devices: " << endl; cout << endl; // printing available Audio Devices RtAudio::DeviceInfo DeviceInfo; unsigned int DefaultOutputDeviceID; unsigned int DefaultInputDeviceID; for (unsigned int i = 0 ; i < availableAudioDevices ; i++) { DeviceInfo = AudioDevices.getDeviceInfo(i); if (DeviceInfo.probed == true) //Audio Device successfully probed { cout << "Device ID: " << i << endl; cout << "Device Name = " << DeviceInfo.name << endl; cout << "Maximum output channels = " << DeviceInfo.outputChannels << endl; cout << "Maximum input channels = " << DeviceInfo.inputChannels << endl; cout << "Maximum duplex channels = " << DeviceInfo.duplexChannels << endl; cout << "Default output: "; if (DeviceInfo.isDefaultOutput == true) { cout << "Yes" << endl; DefaultOutputDeviceID = i; } else { cout << "No" << endl; } cout << "Default input: "; if (DeviceInfo.isDefaultInput == true) { cout << "Yes" << endl; DefaultInputDeviceID = i; } else { cout << "No" << endl; } cout << "Supported Sample Rates: "; printVector(DeviceInfo.sampleRates); cout << endl; cout << "Audio Format = " << DeviceInfo.nativeFormats << endl; cout << endl; } } unsigned int OutputDeviceID; //Choose output Device cout << "Choose output Device ID [default is " << DefaultOutputDeviceID << " ]: "; cin >> OutputDeviceID; RtAudio::DeviceInfo OutputDeviceInfo = AudioDevices.getDeviceInfo(OutputDeviceID); //Configure ID of the Output Audio Device audioConfiguration.outputDeviceID = OutputDeviceID; cout << "-> Using output Device ID: " << audioConfiguration.outputDeviceID << endl; //Configure Name of the Output Audio Device audioConfiguration.outputDeviceName = OutputDeviceInfo.name; cout << "-> Using output Device Name: " << audioConfiguration.outputDeviceName << endl; //Configure Number of Maximum output Channels (we always use stereo) audioConfiguration.outputDeviceChannels = 2; cout << "-> Number of maximum duplex Channels supported from this Device: " << audioConfiguration.outputDeviceChannels << endl; unsigned int OutputSampleRate; //Configure Output Sample Rate cout << "-> Supported Sample Rates from this Device: "; printVector(OutputDeviceInfo.sampleRates); cout << endl << "Choose your Sample Rate: "; cin >> OutputSampleRate; audioConfiguration.sampleRate = OutputSampleRate; cout << "-> Using Sample Rate: " << audioConfiguration.sampleRate << endl; //Configure Output Audio Format audioConfiguration.audioFormat = selectAudioFormat(OutputDeviceInfo.nativeFormats); cout << "-> Output Audio Format: " << audioConfiguration.audioFormat << endl; unsigned int InputDeviceID; //Choose input Device cout << "Choose input Device ID [default is " << DefaultInputDeviceID << " ]: "; cin >> InputDeviceID; RtAudio::DeviceInfo InputDeviceInfo = AudioDevices.getDeviceInfo(InputDeviceID); //Configure ID of the Input Audio Device audioConfiguration.inputDeviceID = InputDeviceID; cout << "-> Using input Device ID " << audioConfiguration.inputDeviceID << endl; //Configure Name of the Input Audio Device audioConfiguration.inputDeviceName = InputDeviceInfo.name; cout << "-> Using input Device Name: " << audioConfiguration.inputDeviceName << endl; //Configure Number of Maximum output Channels (we always use stereo) audioConfiguration.inputDeviceChannels = 2; cout << "-> Number of maximum duplex Channels supported from this Device: " << audioConfiguration.inputDeviceChannels << endl; unsigned int InputSampleRate; //TODO sampleRate and audioFormat are overridden! //Configure Input Sample Rate cout << "-> Supported Sample Rates from this Device: "; printVector(InputDeviceInfo.sampleRates); cout << endl << "Choose your Sample Rate: "; cin >> InputSampleRate; audioConfiguration.sampleRate = InputSampleRate; cout << "-> Using Sample Rate: " << audioConfiguration.sampleRate << endl; //Configure Input Audio Format audioConfiguration.audioFormat = selectAudioFormat(InputDeviceInfo.nativeFormats); cout << "-> Input Audio Format: " << audioConfiguration.audioFormat << endl; //Buffer size audioConfiguration.bufferFrames = inputNumber("Input the number of frames to buffer (around 128 - 2048, 256 is recommended)", false, false); } /*! * RtAudio Error Handler */ void errorHandler( RtAudioError::Type type, const std::string &errorText ) { cerr << "An error occurred!" << endl; switch(type) { case RtAudioError::Type::WARNING: case RtAudioError::Type::DEBUG_WARNING: cerr << "WARNING: "; case RtAudioError::Type::MEMORY_ERROR: case RtAudioError::Type::DRIVER_ERROR: case RtAudioError::Type::SYSTEM_ERROR: case RtAudioError::Type::THREAD_ERROR: cerr << "ERROR: "; case RtAudioError::Type::NO_DEVICES_FOUND: case RtAudioError::Type::INVALID_DEVICE: cerr << "Device Error: "; case RtAudioError::Type::INVALID_PARAMETER: case RtAudioError::Type::INVALID_USE: cerr << "Invalid Function-call: "; case RtAudioError::Type::UNSPECIFIED: cerr << "Unspecified Error: "; } cerr << errorText << endl; } int main(int argc, char** argv) { char input; /* Run Tests */ cout << "Run test cases? Yes (y), No (n)?" << endl; cin >> input; if(input == 'Y' || input == 'y') { Test::TextOutput output(Test::TextOutput::Verbose); TestAudioIO testaudio; testaudio.run(output); } try { std::unique_ptr<AudioHandler> audioObject; /* Audio-Config */ cout << "Load default audio config? Yes (y), No (n)?" << endl; cin >> input; if (input == 'N' || input == 'n') { configureAudioDevices(); audioObject = AudioHandlerFactory::getAudioHandler("RTAudioWrapper", audioConfiguration); } else { audioObject = AudioHandlerFactory::getAudioHandler("RTAudioWrapper"); } /* Network-Config */ NetworkWrapper *network; cout << "Load default network config? Yes (y), No (n)?" << endl; cin >> input; if (input == 'N' || input == 'n') { configureNetwork(); //XXX make the buffers configurable?? networkConfiguration.inputBufferSize = 4096; networkConfiguration.outputBufferSize = 4096; network = new UDPWrapper(networkConfiguration); } else { networkConfiguration.addressIncoming = "127.0.0.1"; networkConfiguration.addressOutgoing = "127.0.0.1"; networkConfiguration.connectionType = NetworkConfiguration::ConnectionType::UDP; networkConfiguration.inputBufferSize = 4096; networkConfiguration.outputBufferSize = 4096; //the port should be a number greater than 1024 networkConfiguration.portIncoming = 12345; networkConfiguration.portOutgoing = 12345; network = new UDPWrapper(networkConfiguration); } //initialize RTPBuffer and -Listener std::unique_ptr<RTPBuffer> *rtpBuffer = new std::unique_ptr<RTPBuffer>(new RTPBuffer(256, 1000)); RTPListener listener(network, rtpBuffer, networkConfiguration.inputBufferSize); // add a processor to the process chain ProcessorRTP rtp("RTP-Processor", network, rtpBuffer); audioObject->addProcessor((AudioProcessor*)&rtp); //configure all processors audioObject->configureAudioProcessors(); // start audio processing listener.startUp(); audioObject->startDuplexMode(); // wait for exit cout << "Type Enter to exit" << endl; cin >> input; audioObject->stop(); return 0; } catch (RtAudioError exception) { cout << "Ausnahme: " << exception.getMessage() << endl; } } <|endoftext|>
<commit_before>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstddef> #ifndef TORRENT_ALLOCATOR_HPP_INCLUDED #define TORRENT_ALLOCATOR_HPP_INCLUDED namespace libtorrent { struct page_aligned_allocator { typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; static char* malloc(const size_type bytes); static void free(char* const block); }; } #endif <commit_msg>add dllexport interface to page_aligned_allocator<commit_after>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ALLOCATOR_HPP_INCLUDED #define TORRENT_ALLOCATOR_HPP_INCLUDED #include <cstddef> #include "libtorrent/config.hpp" namespace libtorrent { struct TORRENT_EXPORT page_aligned_allocator { typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; static char* malloc(const size_type bytes); static void free(char* const block); }; } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_XML_PARSE_HPP #define TORRENT_XML_PARSE_HPP #include <cctype> namespace libtorrent { enum { xml_start_tag, xml_end_tag, xml_empty_tag, xml_declaration_tag, xml_string, xml_attribute, xml_comment, xml_parse_error }; // callback(int type, char const* name, char const* val) // str2 is only used for attributes. name is element or attribute // name and val is attribute value template <class CallbackType> void xml_parse(char* p, char* end, CallbackType callback) { for(;p != end; ++p) { char const* start = p; char const* val_start = 0; int token; // look for tag start for(; *p != '<' && p != end; ++p); if (p != start) { if (p != end) { TORRENT_ASSERT(*p == '<'); *p = 0; } token = xml_string; callback(token, start, val_start); if (p != end) *p = '<'; } if (p == end) break; // skip '<' ++p; // parse the name of the tag. for (start = p; p != end && *p != '>' && !std::isspace(*p); ++p); char* tag_name_end = p; // skip the attributes for now for (; p != end && *p != '>'; ++p); // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } TORRENT_ASSERT(*p == '>'); // save the character that terminated the tag name // it could be both '>' and ' '. char save = *tag_name_end; *tag_name_end = 0; char* tag_end = p; if (*start == '/') { ++start; token = xml_end_tag; callback(token, start, val_start); } else if (*(p-1) == '/') { *(p-1) = 0; token = xml_empty_tag; callback(token, start, val_start); *(p-1) = '/'; tag_end = p - 1; } else if (*start == '?' && *(p-1) == '?') { *(p-1) = 0; ++start; token = xml_declaration_tag; callback(token, start, val_start); *(p-1) = '?'; tag_end = p - 1; } else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0) { start += 3; *(p-2) = 0; token = xml_comment; callback(token, start, val_start); *(p-2) = '-'; tag_end = p - 2; } else { token = xml_start_tag; callback(token, start, val_start); } *tag_name_end = save; // parse attributes for (char* i = tag_name_end; i < tag_end; ++i) { // find start of attribute name for (; i != tag_end && std::isspace(*i); ++i); if (i == tag_end) break; start = i; // find end of attribute name for (; i != tag_end && *i != '=' && !std::isspace(*i); ++i); char* name_end = i; // look for equality sign for (; i != tag_end && *i != '='; ++i); if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "garbage inside element brackets"; callback(token, start, val_start); break; } ++i; for (; i != tag_end && std::isspace(*i); ++i); // check for parse error (values must be quoted) if (i == tag_end || (*i != '\'' && *i != '\"')) { token = xml_parse_error; val_start = 0; start = "unquoted attribute value"; callback(token, start, val_start); break; } char quote = *i; ++i; val_start = i; for (; i != tag_end && *i != quote; ++i); // parse error (missing end quote) if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "missing end quote on attribute"; callback(token, start, val_start); break; } save = *i; *i = 0; *name_end = 0; token = xml_attribute; callback(token, start, val_start); *name_end = '='; *i = save; } } } } #endif <commit_msg>replaced dependency on locale dependent isspace<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_XML_PARSE_HPP #define TORRENT_XML_PARSE_HPP #include <cctype> #include <cstring> namespace libtorrent { enum { xml_start_tag, xml_end_tag, xml_empty_tag, xml_declaration_tag, xml_string, xml_attribute, xml_comment, xml_parse_error }; inline bool isspace(char c) { const static char* ws = " \t\n\r\f\v"; return std::strchr(ws, c); } // callback(int type, char const* name, char const* val) // str2 is only used for attributes. name is element or attribute // name and val is attribute value template <class CallbackType> void xml_parse(char* p, char* end, CallbackType callback) { for(;p != end; ++p) { char const* start = p; char const* val_start = 0; int token; // look for tag start for(; *p != '<' && p != end; ++p); if (p != start) { if (p != end) { TORRENT_ASSERT(*p == '<'); *p = 0; } token = xml_string; callback(token, start, val_start); if (p != end) *p = '<'; } if (p == end) break; // skip '<' ++p; // parse the name of the tag. for (start = p; p != end && *p != '>' && !isspace(*p); ++p); char* tag_name_end = p; // skip the attributes for now for (; p != end && *p != '>'; ++p); // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } TORRENT_ASSERT(*p == '>'); // save the character that terminated the tag name // it could be both '>' and ' '. char save = *tag_name_end; *tag_name_end = 0; char* tag_end = p; if (*start == '/') { ++start; token = xml_end_tag; callback(token, start, val_start); } else if (*(p-1) == '/') { *(p-1) = 0; token = xml_empty_tag; callback(token, start, val_start); *(p-1) = '/'; tag_end = p - 1; } else if (*start == '?' && *(p-1) == '?') { *(p-1) = 0; ++start; token = xml_declaration_tag; callback(token, start, val_start); *(p-1) = '?'; tag_end = p - 1; } else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0) { start += 3; *(p-2) = 0; token = xml_comment; callback(token, start, val_start); *(p-2) = '-'; tag_end = p - 2; } else { token = xml_start_tag; callback(token, start, val_start); } *tag_name_end = save; // parse attributes for (char* i = tag_name_end; i < tag_end; ++i) { // find start of attribute name for (; i != tag_end && isspace(*i); ++i); if (i == tag_end) break; start = i; // find end of attribute name for (; i != tag_end && *i != '=' && !isspace(*i); ++i); char* name_end = i; // look for equality sign for (; i != tag_end && *i != '='; ++i); if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "garbage inside element brackets"; callback(token, start, val_start); break; } ++i; for (; i != tag_end && isspace(*i); ++i); // check for parse error (values must be quoted) if (i == tag_end || (*i != '\'' && *i != '\"')) { token = xml_parse_error; val_start = 0; start = "unquoted attribute value"; callback(token, start, val_start); break; } char quote = *i; ++i; val_start = i; for (; i != tag_end && *i != quote; ++i); // parse error (missing end quote) if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "missing end quote on attribute"; callback(token, start, val_start); break; } save = *i; *i = 0; *name_end = 0; token = xml_attribute; callback(token, start, val_start); *name_end = '='; *i = save; } } } } #endif <|endoftext|>
<commit_before>/* ******************************************************************************* * * Copyright (C) 1999-2003, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * file name: scrptrun.h * * created on: 10/17/2001 * created by: Eric R. Mader * * NOTE: This file is copied from ICU. * http://source.icu-project.org/repos/icu/icu/trunk/license.html */ #ifndef __SCRPTRUN_H #define __SCRPTRUN_H #include "unicode/utypes.h" #include "unicode/uobject.h" #include "unicode/uscript.h" struct ScriptRecord { UChar32 startChar = 0; UChar32 endChar = 0; UScriptCode scriptCode = USCRIPT_INVALID_CODE; }; struct ParenStackEntry { int32_t pairIndex = 0; UScriptCode scriptCode = USCRIPT_INVALID_CODE; }; class ScriptRun : public UObject { public: ScriptRun(); ScriptRun(const UChar chars[], int32_t length); ScriptRun(const UChar chars[], int32_t start, int32_t length); void reset(); void reset(int32_t start, int32_t count); void reset(const UChar chars[], int32_t start, int32_t length); int32_t getScriptStart(); int32_t getScriptEnd(); UScriptCode getScriptCode(); UBool next(); /** * ICU "poor man's RTTI", returns a UClassID for the actual class. * * @stable ICU 2.2 */ virtual inline UClassID getDynamicClassID() const { return getStaticClassID(); } /** * ICU "poor man's RTTI", returns a UClassID for this class. * * @stable ICU 2.2 */ static inline UClassID getStaticClassID() { return (UClassID)&fgClassID; } private: static UBool sameScript(int32_t scriptOne, int32_t scriptTwo); int32_t charStart; int32_t charLimit; const UChar *charArray; int32_t scriptStart; int32_t scriptEnd; UScriptCode scriptCode; ParenStackEntry parenStack[128]; int32_t parenSP; static int8_t highBit(int32_t value); static int32_t getPairIndex(UChar32 ch); static UChar32 pairedChars[]; static const int32_t pairedCharCount; static const int32_t pairedCharPower; static const int32_t pairedCharExtra; /** * The address of this static class variable serves as this class's ID * for ICU "poor man's RTTI". */ static const char fgClassID; }; inline ScriptRun::ScriptRun() { reset(NULL, 0, 0); } inline ScriptRun::ScriptRun(const UChar chars[], int32_t length) { reset(chars, 0, length); } inline ScriptRun::ScriptRun(const UChar chars[], int32_t start, int32_t length) { reset(chars, start, length); } inline int32_t ScriptRun::getScriptStart() { return scriptStart; } inline int32_t ScriptRun::getScriptEnd() { return scriptEnd; } inline UScriptCode ScriptRun::getScriptCode() { return scriptCode; } inline void ScriptRun::reset() { scriptStart = charStart; scriptEnd = charStart; scriptCode = USCRIPT_INVALID_CODE; parenSP = -1; } inline void ScriptRun::reset(int32_t start, int32_t length) { charStart = start; charLimit = start + length; reset(); } inline void ScriptRun::reset(const UChar chars[], int32_t start, int32_t length) { charArray = chars; reset(start, length); } #endif <commit_msg>use correct include type in scrptrun.hpp<commit_after>/* ******************************************************************************* * * Copyright (C) 1999-2003, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * file name: scrptrun.h * * created on: 10/17/2001 * created by: Eric R. Mader * * NOTE: This file is copied from ICU. * http://source.icu-project.org/repos/icu/icu/trunk/license.html */ #ifndef __SCRPTRUN_H #define __SCRPTRUN_H #include <unicode/utypes.h> #include <unicode/uobject.h> #include <unicode/uscript.h> struct ScriptRecord { UChar32 startChar = 0; UChar32 endChar = 0; UScriptCode scriptCode = USCRIPT_INVALID_CODE; }; struct ParenStackEntry { int32_t pairIndex = 0; UScriptCode scriptCode = USCRIPT_INVALID_CODE; }; class ScriptRun : public UObject { public: ScriptRun(); ScriptRun(const UChar chars[], int32_t length); ScriptRun(const UChar chars[], int32_t start, int32_t length); void reset(); void reset(int32_t start, int32_t count); void reset(const UChar chars[], int32_t start, int32_t length); int32_t getScriptStart(); int32_t getScriptEnd(); UScriptCode getScriptCode(); UBool next(); /** * ICU "poor man's RTTI", returns a UClassID for the actual class. * * @stable ICU 2.2 */ virtual inline UClassID getDynamicClassID() const { return getStaticClassID(); } /** * ICU "poor man's RTTI", returns a UClassID for this class. * * @stable ICU 2.2 */ static inline UClassID getStaticClassID() { return (UClassID)&fgClassID; } private: static UBool sameScript(int32_t scriptOne, int32_t scriptTwo); int32_t charStart; int32_t charLimit; const UChar *charArray; int32_t scriptStart; int32_t scriptEnd; UScriptCode scriptCode; ParenStackEntry parenStack[128]; int32_t parenSP; static int8_t highBit(int32_t value); static int32_t getPairIndex(UChar32 ch); static UChar32 pairedChars[]; static const int32_t pairedCharCount; static const int32_t pairedCharPower; static const int32_t pairedCharExtra; /** * The address of this static class variable serves as this class's ID * for ICU "poor man's RTTI". */ static const char fgClassID; }; inline ScriptRun::ScriptRun() { reset(NULL, 0, 0); } inline ScriptRun::ScriptRun(const UChar chars[], int32_t length) { reset(chars, 0, length); } inline ScriptRun::ScriptRun(const UChar chars[], int32_t start, int32_t length) { reset(chars, start, length); } inline int32_t ScriptRun::getScriptStart() { return scriptStart; } inline int32_t ScriptRun::getScriptEnd() { return scriptEnd; } inline UScriptCode ScriptRun::getScriptCode() { return scriptCode; } inline void ScriptRun::reset() { scriptStart = charStart; scriptEnd = charStart; scriptCode = USCRIPT_INVALID_CODE; parenSP = -1; } inline void ScriptRun::reset(int32_t start, int32_t length) { charStart = start; charLimit = start + length; reset(); } inline void ScriptRun::reset(const UChar chars[], int32_t start, int32_t length) { charArray = chars; reset(start, length); } #endif <|endoftext|>
<commit_before>#ifndef QRW_RENDERABLE_HPP #define QRW_RENDERABLE_HPP #include <SFML/System/Vector2.hpp> namespace sf { class RenderTarget; } namespace qrw { typedef int Layer; class Renderable { public: Renderable(Layer layer); virtual ~Renderable(); virtual void render(sf::RenderTarget& renderTarget) = 0; Layer getLayer(); inline bool isVisible() const { return m_visible; } void setVisible(bool visible) { m_visible = visible; } virtual void setPosition(const sf::Vector2f& position) = 0; virtual const sf::Vector2f& getPosition() const = 0; private: unsigned char m_layer; bool m_visible; }; } // namespace qrw #endif // QRW_RENDERABLE_HPP <commit_msg>Uniform type for renderable layers<commit_after>#ifndef QRW_RENDERABLE_HPP #define QRW_RENDERABLE_HPP #include <SFML/System/Vector2.hpp> namespace sf { class RenderTarget; } namespace qrw { typedef unsigned int Layer; class Renderable { public: Renderable(Layer layer); virtual ~Renderable(); virtual void render(sf::RenderTarget& renderTarget) = 0; Layer getLayer(); inline bool isVisible() const { return m_visible; } void setVisible(bool visible) { m_visible = visible; } virtual void setPosition(const sf::Vector2f& position) = 0; virtual const sf::Vector2f& getPosition() const = 0; private: Layer m_layer; bool m_visible; }; } // namespace qrw #endif // QRW_RENDERABLE_HPP <|endoftext|>
<commit_before>#pragma once #include "Function.hpp" #include "Error.hpp" #include "types/Boolean.hpp" #include "types/Number.hpp" #include "types/String.hpp" #include <cassert> namespace slim { inline bool try_unpack_arg(const ObjectPtr &arg, std::string *out) { auto str = dynamic_cast<String*>(arg.get()); if (str) { *out = str->get_value(); return true; } else return false; } inline bool try_unpack_arg(const ObjectPtr &arg, double *out) { auto n = dynamic_cast<Number*>(arg.get()); if (n) { *out = n->get_value(); return true; } else return false; } inline bool try_unpack_arg(const ObjectPtr &arg, int *out) { auto n = dynamic_cast<Number*>(arg.get()); if (n) { *out = (int)n->get_value(); return true; } else return false; } inline bool try_unpack_arg(const ObjectPtr &arg, bool *out) { auto n = dynamic_cast<Boolean*>(arg.get()); if (n) { *out = n->is_true(); return true; } else return false; } template<class T> bool try_unpack_arg(const ObjectPtr &arg, T **out) { auto ptr = dynamic_cast<T*>(arg.get()); if (ptr) { *out = ptr; return true; } else return false; } inline bool try_unpack_inner(FunctionArgs::const_iterator begin, FunctionArgs::const_iterator end) { assert(begin == end); return true; } template<class NEXT, class... ARGS> bool try_unpack_inner( FunctionArgs::const_iterator begin, FunctionArgs::const_iterator end, NEXT *out, ARGS && ...args) { if (begin == end) return true; NEXT tmp; //dont overwrite *out until sure of success if (!try_unpack_arg(*begin, &tmp)) return false; if (!try_unpack_inner(begin + 1, end, std::forward<ARGS>(args)...)) return false; *out = std::move(tmp); return true; } template<size_t required, class... ARGS> bool try_unpack(const FunctionArgs &args, ARGS && ...out) { if (required > args.size() || args.size() > sizeof...(ARGS)) return false; return try_unpack_inner(args.begin(), args.end(), std::forward<ARGS>(out)...); } template<class... ARGS> bool try_unpack(const FunctionArgs &args, ARGS && ...out) { return try_unpack<sizeof...(ARGS)>(args, std::forward<ARGS>(out)...); } /**Unpack an argument list into provided objects. * Optional parameters will be left with their initial values if there is no * corresponding argument. * @param required The minimun number of arguments that are required. * @param args The argument array. * @param out Pointers to objects to unpack the array elements into. */ template<size_t required, class... ARGS> void unpack(const FunctionArgs &args, ARGS && ...out) { if (required > args.size() || args.size() > sizeof...(ARGS)) throw InvalidArgumentCount(args.size(), required, sizeof...(ARGS)); if (!try_unpack_inner(args.begin(), args.end(), std::forward<ARGS>(out)...)) throw InvalidArgument(); } template<class... ARGS> void unpack(const FunctionArgs &args, ARGS && ...out) { return unpack<sizeof...(ARGS)>(args, std::forward<ARGS>(out)...); } } <commit_msg>Added try_unpack_arg overload for std::shared_ptr<commit_after>#pragma once #include "Function.hpp" #include "Error.hpp" #include "types/Boolean.hpp" #include "types/Number.hpp" #include "types/String.hpp" #include <cassert> namespace slim { inline bool try_unpack_arg(const ObjectPtr &arg, std::string *out) { auto str = dynamic_cast<String*>(arg.get()); if (str) { *out = str->get_value(); return true; } else return false; } inline bool try_unpack_arg(const ObjectPtr &arg, double *out) { auto n = dynamic_cast<Number*>(arg.get()); if (n) { *out = n->get_value(); return true; } else return false; } inline bool try_unpack_arg(const ObjectPtr &arg, int *out) { auto n = dynamic_cast<Number*>(arg.get()); if (n) { *out = (int)n->get_value(); return true; } else return false; } inline bool try_unpack_arg(const ObjectPtr &arg, bool *out) { auto n = dynamic_cast<Boolean*>(arg.get()); if (n) { *out = n->is_true(); return true; } else return false; } template<class T> bool try_unpack_arg(const ObjectPtr &arg, T **out) { auto ptr = dynamic_cast<T*>(arg.get()); if (ptr) { *out = ptr; return true; } else return false; } template<class T> bool try_unpack_arg(const ObjectPtr &arg, std::shared_ptr<T> *out) { auto ptr = std::dynamic_pointer_cast<T>(arg); if (ptr) { *out = std::move(ptr); return true; } else return false; } inline bool try_unpack_inner(FunctionArgs::const_iterator begin, FunctionArgs::const_iterator end) { assert(begin == end); return true; } template<class NEXT, class... ARGS> bool try_unpack_inner( FunctionArgs::const_iterator begin, FunctionArgs::const_iterator end, NEXT *out, ARGS && ...args) { if (begin == end) return true; NEXT tmp; //dont overwrite *out until sure of success if (!try_unpack_arg(*begin, &tmp)) return false; if (!try_unpack_inner(begin + 1, end, std::forward<ARGS>(args)...)) return false; *out = std::move(tmp); return true; } template<size_t required, class... ARGS> bool try_unpack(const FunctionArgs &args, ARGS && ...out) { if (required > args.size() || args.size() > sizeof...(ARGS)) return false; return try_unpack_inner(args.begin(), args.end(), std::forward<ARGS>(out)...); } template<class... ARGS> bool try_unpack(const FunctionArgs &args, ARGS && ...out) { return try_unpack<sizeof...(ARGS)>(args, std::forward<ARGS>(out)...); } /**Unpack an argument list into provided objects. * Optional parameters will be left with their initial values if there is no * corresponding argument. * @param required The minimun number of arguments that are required. * @param args The argument array. * @param out Pointers to objects to unpack the array elements into. */ template<size_t required, class... ARGS> void unpack(const FunctionArgs &args, ARGS && ...out) { if (required > args.size() || args.size() > sizeof...(ARGS)) throw InvalidArgumentCount(args.size(), required, sizeof...(ARGS)); if (!try_unpack_inner(args.begin(), args.end(), std::forward<ARGS>(out)...)) throw InvalidArgument(); } template<class... ARGS> void unpack(const FunctionArgs &args, ARGS && ...out) { return unpack<sizeof...(ARGS)>(args, std::forward<ARGS>(out)...); } } <|endoftext|>
<commit_before>#ifndef LIBTEN_HTTP_MESSAGE_HH #define LIBTEN_HTTP_MESSAGE_HH #include <string> #include <vector> #include <stdexcept> #include <mutex> #include <stdarg.h> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/predicate.hpp> #include "http_parser.h" #include "ten/task.hh" #include "ten/error.hh" #include "ten/optional.hh" namespace ten { // TODO: define exceptions typedef std::pair<std::string, std::string> header_pair; typedef std::vector<header_pair> header_list; // only a limited set of versions are supported enum http_version { http_0_9, http_1_0, http_1_1, default_http_version = http_1_1 }; const std::string &version_string(http_version ver); namespace hs { //! common strings for HTTP extern const std::string GET, HEAD, POST, PUT, DELETE, Connection, close, keep_alive, Host, Date, Content_Type, Content_Length; } //! http headers struct http_headers { header_list headers; http_headers() {} template <typename ...Args> http_headers(Args&& ...args) { static_assert((sizeof...(args) % 2) == 0, "mismatched header name/value pairs"); headers.reserve(sizeof...(args) / 2); init(std::forward<Args>(args)...); } void init() {} template <typename ValueT, typename ...Args> void init(const std::string &field, ValueT &&header_value, Args&& ...args) { append(field, std::forward<ValueT>(header_value)); init(std::forward<Args>(args)...); } void set(const std::string &field, const std::string &value); template <typename ValueT> void set(const std::string &field, const ValueT &value) { set(field, boost::lexical_cast<std::string>(value)); } void append(const std::string &field, const std::string &value); template <typename ValueT> void append(const std::string &field, const ValueT &value) { append(field, boost::lexical_cast<std::string>(value)); } bool contains(const std::string &field) const; bool remove(const std::string &field); optional<std::string> get(const std::string &field) const; template <typename ValueT> optional<ValueT> get(const std::string &field) const { const auto i = find(field); return (i == end(headers)) ? nullopt : optional<ValueT>{boost::lexical_cast<ValueT>(i->second)}; } #ifdef CHIP_UNSURE bool is(const std::string &field, const std::string &value) const; bool is_nocase(const std::string &field, const std::string &value) const; template <typename ValueT> bool is(const std::string &field, const ValueT &value) const { const auto i = find(field); return (i != end(headers)) && (boost::lexical_cast<ValueT>(i->second) == value); } #endif // CHIP_UNSURE protected: // iterator-based access requires knowledge of value_type, so not public header_list::iterator find(const std::string &field); header_list::const_iterator find(const std::string &field) const; }; //! base class for http request and response struct http_base : http_headers { http_version version {default_http_version}; std::string body; size_t body_length {}; bool complete {}; explicit http_base(http_headers headers_ = {}, http_version version_ = default_http_version) : http_headers(std::move(headers_)), version{version_} {} void clear() { headers.clear(); version = default_http_version; body.clear(); body_length = {}; complete = {}; } void set_body(std::string body_, const std::string &content_type_ = std::string()) { body = std::move(body_); body_length = body.size(); set(hs::Content_Length, body_length); remove(hs::Content_Type); if (!content_type_.empty()) { append(hs::Content_Type, content_type_); } } bool close_after() const { const auto conn = get(hs::Connection); return version <= http_1_0 ? (!conn || !boost::iequals(*conn, hs::keep_alive)) : (conn && boost::iequals(*conn, hs::close)); } // strftime can be quite expensive, so don't do it more than once per second static std::string rfc822_date() { static std::mutex last_mut; static time_t last_time = -1; static std::string last_date; time_t now = std::chrono::system_clock::to_time_t(procnow()); std::unique_lock<std::mutex> lk(last_mut); if (now == last_time) { char buf[128]; struct tm tm; strftime(buf, sizeof(buf)-1, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r(&now, &tm)); last_time = now; last_date = buf; } return last_date; } }; //! http request struct http_request : http_base { std::string method; std::string uri; http_request() : http_base() {} http_request(std::string method_, std::string uri_, http_headers headers_ = {}, http_version version_ = default_http_version) : http_base(std::move(headers_), version_), method{std::move(method_)}, uri{std::move(uri_)} {} http_request(std::string method_, std::string uri_, http_headers headers_, std::string body_, std::string content_type_ = std::string()) : http_base(std::move(headers_)), method{std::move(method_)}, uri{std::move(uri_)} { set_body(std::move(body_), std::move(content_type_)); } void clear() { http_base::clear(); method.clear(); uri.clear(); } void parser_init(struct http_parser *p); void parse(struct http_parser *p, const char *data, size_t &len); std::string data() const; std::string path() const { std::string p = uri; size_t pos = p.find_first_of("?#"); if (pos != std::string::npos) { p = p.substr(0, pos); } return p; } }; //! http response struct http_response : http_base { using status_t = uint16_t; status_t status_code {}; bool guillotine {}; // return only the head http_response(status_t status_code_ = 200, http_headers headers_ = {}, http_version version_ = default_http_version) : http_base(std::move(headers_), version_), status_code{status_code_} {} http_response(status_t status_code_, http_headers headers_, std::string body_, std::string content_type_ = std::string()) : http_base(std::move(headers_)), status_code{status_code_} { set_body(std::move(body_), std::move(content_type_)); } // TODO: remove this special case http_response(http_request *req_) : http_base(), guillotine{req_ && req_->method == hs::HEAD} {} void clear() { http_base::clear(); status_code = {}; guillotine = {}; } const std::string &reason() const; void parser_init(struct http_parser *p); void parse(struct http_parser *p, const char *data, size_t &len); std::string data() const; }; } // end namespace ten #endif // LIBTEN_HTTP_MESSAGE_HH <commit_msg>fix reversed test on http date; unique_lock -> lock_guard<commit_after>#ifndef LIBTEN_HTTP_MESSAGE_HH #define LIBTEN_HTTP_MESSAGE_HH #include <string> #include <vector> #include <stdexcept> #include <mutex> #include <stdarg.h> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/predicate.hpp> #include "http_parser.h" #include "ten/task.hh" #include "ten/error.hh" #include "ten/optional.hh" namespace ten { // TODO: define exceptions typedef std::pair<std::string, std::string> header_pair; typedef std::vector<header_pair> header_list; // only a limited set of versions are supported enum http_version { http_0_9, http_1_0, http_1_1, default_http_version = http_1_1 }; const std::string &version_string(http_version ver); namespace hs { //! common strings for HTTP extern const std::string GET, HEAD, POST, PUT, DELETE, Connection, close, keep_alive, Host, Date, Content_Type, Content_Length; } //! http headers struct http_headers { header_list headers; http_headers() {} template <typename ...Args> http_headers(Args&& ...args) { static_assert((sizeof...(args) % 2) == 0, "mismatched header name/value pairs"); headers.reserve(sizeof...(args) / 2); init(std::forward<Args>(args)...); } void init() {} template <typename ValueT, typename ...Args> void init(const std::string &field, ValueT &&header_value, Args&& ...args) { append(field, std::forward<ValueT>(header_value)); init(std::forward<Args>(args)...); } void set(const std::string &field, const std::string &value); template <typename ValueT> void set(const std::string &field, const ValueT &value) { set(field, boost::lexical_cast<std::string>(value)); } void append(const std::string &field, const std::string &value); template <typename ValueT> void append(const std::string &field, const ValueT &value) { append(field, boost::lexical_cast<std::string>(value)); } bool contains(const std::string &field) const; bool remove(const std::string &field); optional<std::string> get(const std::string &field) const; template <typename ValueT> optional<ValueT> get(const std::string &field) const { const auto i = find(field); return (i == end(headers)) ? nullopt : optional<ValueT>{boost::lexical_cast<ValueT>(i->second)}; } #ifdef CHIP_UNSURE bool is(const std::string &field, const std::string &value) const; bool is_nocase(const std::string &field, const std::string &value) const; template <typename ValueT> bool is(const std::string &field, const ValueT &value) const { const auto i = find(field); return (i != end(headers)) && (boost::lexical_cast<ValueT>(i->second) == value); } #endif // CHIP_UNSURE protected: // iterator-based access requires knowledge of value_type, so not public header_list::iterator find(const std::string &field); header_list::const_iterator find(const std::string &field) const; }; //! base class for http request and response struct http_base : http_headers { http_version version {default_http_version}; std::string body; size_t body_length {}; bool complete {}; explicit http_base(http_headers headers_ = {}, http_version version_ = default_http_version) : http_headers(std::move(headers_)), version{version_} {} void clear() { headers.clear(); version = default_http_version; body.clear(); body_length = {}; complete = {}; } void set_body(std::string body_, const std::string &content_type_ = std::string()) { body = std::move(body_); body_length = body.size(); set(hs::Content_Length, body_length); remove(hs::Content_Type); if (!content_type_.empty()) { append(hs::Content_Type, content_type_); } } bool close_after() const { const auto conn = get(hs::Connection); return version <= http_1_0 ? (!conn || !boost::iequals(*conn, hs::keep_alive)) : (conn && boost::iequals(*conn, hs::close)); } // strftime can be quite expensive, so don't do it more than once per second static std::string rfc822_date() { static std::mutex last_mut; static time_t last_time = -1; static std::string last_date; time_t now = std::chrono::system_clock::to_time_t(procnow()); std::lock_guard<std::mutex> lk(last_mut); if (last_time != now) { char buf[128]; struct tm tm; strftime(buf, sizeof(buf)-1, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r(&now, &tm)); last_time = now; last_date = buf; } return last_date; } }; //! http request struct http_request : http_base { std::string method; std::string uri; http_request() : http_base() {} http_request(std::string method_, std::string uri_, http_headers headers_ = {}, http_version version_ = default_http_version) : http_base(std::move(headers_), version_), method{std::move(method_)}, uri{std::move(uri_)} {} http_request(std::string method_, std::string uri_, http_headers headers_, std::string body_, std::string content_type_ = std::string()) : http_base(std::move(headers_)), method{std::move(method_)}, uri{std::move(uri_)} { set_body(std::move(body_), std::move(content_type_)); } void clear() { http_base::clear(); method.clear(); uri.clear(); } void parser_init(struct http_parser *p); void parse(struct http_parser *p, const char *data, size_t &len); std::string data() const; std::string path() const { std::string p = uri; size_t pos = p.find_first_of("?#"); if (pos != std::string::npos) { p = p.substr(0, pos); } return p; } }; //! http response struct http_response : http_base { using status_t = uint16_t; status_t status_code {}; bool guillotine {}; // return only the head http_response(status_t status_code_ = 200, http_headers headers_ = {}, http_version version_ = default_http_version) : http_base(std::move(headers_), version_), status_code{status_code_} {} http_response(status_t status_code_, http_headers headers_, std::string body_, std::string content_type_ = std::string()) : http_base(std::move(headers_)), status_code{status_code_} { set_body(std::move(body_), std::move(content_type_)); } // TODO: remove this special case http_response(http_request *req_) : http_base(), guillotine{req_ && req_->method == hs::HEAD} {} void clear() { http_base::clear(); status_code = {}; guillotine = {}; } const std::string &reason() const; void parser_init(struct http_parser *p); void parse(struct http_parser *p, const char *data, size_t &len); std::string data() const; }; } // end namespace ten #endif // LIBTEN_HTTP_MESSAGE_HH <|endoftext|>
<commit_before>#pragma once #include <sys/types.h> #include <unistd.h> #include <array> namespace the { namespace net { template < typename Owner > class ClientSocket : public Socket { public: ClientSocket( int socket, Owner& owner ) : Socket( socket ) , m_owner( owner ) { } void handle_event() override { ssize_t length( 0 ); while ( 0 < ( length = ::read( fd, &m_buffer[ 0 ], messagebuffer_size ) ) ) { m_owner.on_data_available( *this, &m_buffer[ 0 ], length ); } const bool connection_lost( !length ); if ( connection_lost ) { m_owner.on_socket_lost( *this ); return; } } private: Owner& m_owner; static const int messagebuffer_size{ 1000 }; std::array< char, messagebuffer_size > m_buffer; }; } } <commit_msg>add socket include dependency to client socket<commit_after>#pragma once #include <thenet/socket.hpp> #include <sys/types.h> #include <unistd.h> #include <array> namespace the { namespace net { template < typename Owner > class ClientSocket : public Socket { public: ClientSocket( int socket, Owner& owner ) : Socket( socket ) , m_owner( owner ) { } void handle_event() override { ssize_t length( 0 ); while ( 0 < ( length = ::read( fd, &m_buffer[ 0 ], messagebuffer_size ) ) ) { m_owner.on_data_available( *this, &m_buffer[ 0 ], length ); } const bool connection_lost( !length ); if ( connection_lost ) { m_owner.on_socket_lost( *this ); return; } } private: Owner& m_owner; static const int messagebuffer_size{ 1000 }; std::array< char, messagebuffer_size > m_buffer; }; } } <|endoftext|>
<commit_before>/// /// @file string.hpp /// @brief Contains ulility functions for string operations /// /// @author Lyrex <[email protected]> /// @version 1.0 2017/09/04 /// #pragma once #ifndef thunder_utils_string_hpp__ #define thunder_utils_string_hpp__ #include <algorithm> #include <vector> #if _HAS_CXX17 && __has_include(<string_view>) #include <string_view> #else #include <string> #endif #include "string/trim.hpp" /// @namespace thunder namespace thunder { /// @namespace utils namespace utils { /// @namespace string namespace string { #if _HAS_CXX17 && __has_include(<string_view>) using String_type = std::string_view; #else using String_type = std::string; #endif /// @brief Finds strings that lie between <tt>start_marker</tt> and <tt>end_marker</tt> /// /// @param s input string that gets searched /// @param start_marker string that defines the start marker of the search /// @param start_marker string that defines the end marker of the search /// @param ignore_case set to true if the start and end marker case should be ignored (default: false) /// @param keep_empty set to true if empty results should still be keeped and returned in the result vector (default: false) /// /// @returns A vector containing <tt>String_type</tt> with all found results. The vector is empty if there are no results. static inline auto between(const String_type& s, std::string start_marker, std::string end_marker, const bool ignore_case = false, const bool keep_empty = false) { std::vector<String_type> result; if (start_marker.empty() || end_marker.empty()) return std::vector<String_type>(); if (ignore_case) { std::transform(start_marker.begin(), start_marker.end(), start_marker.begin(), ::tolower); std::transform(end_marker.begin(), end_marker.end(), end_marker.begin(), ::tolower); } // pre-allocate some memory result.resize(s.length() / 8); result.reserve(s.length() / 8); String_type::size_type start_found = s.find(start_marker, 0); String_type::size_type end_found = s.find(end_marker, start_found + 1); while ((start_found != String_type::npos) && (end_found != String_type::npos)) { if (keep_empty || (end_found - start_found) > 1) result.push_back(s.substr(start_found + start_marker.length(), end_found - start_found - start_marker.length())); start_found = s.find(start_marker, end_found + 1); end_found = s.find(end_marker, start_found + 1); } return result; } /// @brief Splits a string by a delimiter. /// /// @param s input string that gets splitted /// @param delimiter string that defines the delmited by which the string gets splitted /// /// @returns A vector containing <tt>String_type</tt> with all found results. The vector is empty if there are no results. static inline auto split(const String_type& s, const char* delimiter) { std::vector<String_type> result; String_type::size_type pos = 0; String_type::size_type last_pos = 0; if (s.empty()) return result; // count substring occurences size_t count = 0; pos = s.find(delimiter, 0); while (pos != std::string::npos) { ++count; pos = s.find(delimiter, pos + 1); } // pre-reserve vector size result.resize(count * 4); result.reserve(count * 4); // split string pos = s.find_first_of(delimiter, last_pos); while (pos != String_type::npos) { if (pos != last_pos) result.push_back(s.substr(last_pos, pos - last_pos)); last_pos = pos + 1; pos = s.find_first_of(delimiter, last_pos); } if (last_pos < s.length()) result.push_back(s.substr(last_pos, s.length() - last_pos)); return result; } /// @brief Removes all occurences of <tt>character</tt> in a string in place. <b>Attention: The input is modified.</b> /// /// @param s input string that gets modified /// @param character character that gets removed from the string static inline void remove_all_inplace(std::string* s, const char character) { s->erase(std::remove(s->begin(), s->end(), character), s->end()); } /// @brief Removes all occurences of <tt>character</tt> in a string /// /// @param s input string that gets searched /// @param character character that gets removed from the string /// /// @returns The string without all <tt>character</tt> occurences. static inline auto remove_all(std::string copy, const char character) { remove_all_inplace(&copy, character); return copy; } #if _HAS_CXX17 && __has_include(<string_view>) /// @brief Removes all occurences of <tt>character</tt> in a string /// /// @param sv input string view that gets searched /// @param character character that gets removed from the string /// /// @returns The string without all <tt>character</tt> occurences. static inline auto remove_all(const std::string_view& sv, const char character) { std::string result{ sv }; remove_all_inplace(result, character); return result; } #endif }; // namespace string }; // namespace utils }; // namespace thunder #endif // thunder_utils_string_hpp__ <commit_msg>Fix a compilation error in utils/string.hpp<commit_after>/// /// @file string.hpp /// @brief Contains ulility functions for string operations /// /// @author Lyrex <[email protected]> /// @version 1.0 2017/09/04 /// #pragma once #ifndef thunder_utils_string_hpp__ #define thunder_utils_string_hpp__ #include <algorithm> #include <vector> #if _HAS_CXX17 && __has_include(<string_view>) #include <string_view> #else #include <string> #endif #include "string/trim.hpp" /// @namespace thunder namespace thunder { /// @namespace utils namespace utils { /// @namespace string namespace string { #if _HAS_CXX17 && __has_include(<string_view>) using String_type = std::string_view; #else using String_type = std::string; #endif /// @brief Finds strings that lie between <tt>start_marker</tt> and <tt>end_marker</tt> /// /// @param s input string that gets searched /// @param start_marker string that defines the start marker of the search /// @param start_marker string that defines the end marker of the search /// @param ignore_case set to true if the start and end marker case should be ignored (default: false) /// @param keep_empty set to true if empty results should still be keeped and returned in the result vector (default: false) /// /// @returns A vector containing <tt>String_type</tt> with all found results. The vector is empty if there are no results. static inline auto between(const String_type& s, std::string start_marker, std::string end_marker, const bool ignore_case = false, const bool keep_empty = false) { std::vector<String_type> result; if (start_marker.empty() || end_marker.empty()) return std::vector<String_type>(); if (ignore_case) { std::transform(start_marker.begin(), start_marker.end(), start_marker.begin(), ::tolower); std::transform(end_marker.begin(), end_marker.end(), end_marker.begin(), ::tolower); } // pre-allocate some memory result.resize(s.length() / 8); result.reserve(s.length() / 8); String_type::size_type start_found = s.find(start_marker, 0); String_type::size_type end_found = s.find(end_marker, start_found + 1); while ((start_found != String_type::npos) && (end_found != String_type::npos)) { if (keep_empty || (end_found - start_found) > 1) result.push_back(s.substr(start_found + start_marker.length(), end_found - start_found - start_marker.length())); start_found = s.find(start_marker, end_found + 1); end_found = s.find(end_marker, start_found + 1); } return result; } /// @brief Splits a string by a delimiter. /// /// @param s input string that gets splitted /// @param delimiter string that defines the delmited by which the string gets splitted /// /// @returns A vector containing <tt>String_type</tt> with all found results. The vector is empty if there are no results. static inline auto split(const String_type& s, const char* delimiter) { std::vector<String_type> result; String_type::size_type pos = 0; String_type::size_type last_pos = 0; if (s.empty()) return result; // count substring occurences size_t count = 0; pos = s.find(delimiter, 0); while (pos != std::string::npos) { ++count; pos = s.find(delimiter, pos + 1); } // pre-reserve vector size result.resize(count * 4); result.reserve(count * 4); // split string pos = s.find_first_of(delimiter, last_pos); while (pos != String_type::npos) { if (pos != last_pos) result.push_back(s.substr(last_pos, pos - last_pos)); last_pos = pos + 1; pos = s.find_first_of(delimiter, last_pos); } if (last_pos < s.length()) result.push_back(s.substr(last_pos, s.length() - last_pos)); return result; } /// @brief Removes all occurences of <tt>character</tt> in a string in place. <b>Attention: The input is modified.</b> /// /// @param s input string that gets modified /// @param character character that gets removed from the string static inline void remove_all_inplace(std::string* s, const char character) { s->erase(std::remove(s->begin(), s->end(), character), s->end()); } /// @brief Removes all occurences of <tt>character</tt> in a string /// /// @param s input string that gets searched /// @param character character that gets removed from the string /// /// @returns The string without all <tt>character</tt> occurences. static inline auto remove_all(std::string copy, const char character) { remove_all_inplace(&copy, character); return copy; } #if _HAS_CXX17 && __has_include(<string_view>) /// @brief Removes all occurences of <tt>character</tt> in a string /// /// @param sv input string view that gets searched /// @param character character that gets removed from the string /// /// @returns The string without all <tt>character</tt> occurences. static inline auto remove_all(const std::string_view& sv, const char character) { std::string result{ sv }; remove_all_inplace(&result, character); return result; } #endif }; // namespace string }; // namespace utils }; // namespace thunder #endif // thunder_utils_string_hpp__ <|endoftext|>
<commit_before>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "library/constants.h" #include "library/vm/vm.h" namespace lean { // ======================================= // Builtin nat operations vm_obj mk_vm_nat(unsigned n) { if (n < LEAN_MAX_SMALL_NAT) return mk_vm_simple(n); else return mk_vm_mpz(mpz(n)); } vm_obj mk_vm_nat(mpz const & n) { if (n < LEAN_MAX_SMALL_NAT) return mk_vm_simple(n.get_unsigned_int()); else return mk_vm_mpz(n); } MK_THREAD_LOCAL_GET_DEF(mpz, get_mpz1); MK_THREAD_LOCAL_GET_DEF(mpz, get_mpz2); static mpz const & to_mpz1(vm_obj const & o) { if (is_simple(o)) { mpz & r = get_mpz1(); r = cidx(o); return r; } else { return to_mpz(o); } } static mpz const & to_mpz2(vm_obj const & o) { if (is_simple(o)) { mpz & r = get_mpz2(); r = cidx(o); return r; } else { return to_mpz(o); } } static void nat_succ(vm_state & s) { vm_obj const & a = s.get(0); if (is_simple(a)) { s.push(mk_vm_nat(cidx(a) + 1)); } else { s.push(mk_vm_mpz(to_mpz1(a) + 1)); } } static void nat_add(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { s.push(mk_vm_nat(cidx(a1) + cidx(a2))); } else { s.push(mk_vm_mpz(to_mpz1(a1) + to_mpz2(a2))); } } static void nat_mul(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { unsigned long long r = static_cast<unsigned long long>(cidx(a1)) + static_cast<unsigned long long>(cidx(a2)); if (r < LEAN_MAX_SMALL_NAT) { s.push(mk_vm_simple(r)); return; } } s.push(mk_vm_mpz(to_mpz1(a1) * to_mpz2(a2))); } static void nat_sub(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 > v1) s.push(mk_vm_simple(0)); else s.push(mk_vm_nat(v1 - v2)); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 > v1) s.push(mk_vm_simple(0)); else s.push(mk_vm_nat(v1 - v2)); } } static void nat_div(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 == 0) s.push(mk_vm_simple(0)); else s.push(mk_vm_nat(v1 / v2)); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 == 0) s.push(mk_vm_simple(0)); else s.push(mk_vm_nat(v1 / v2)); } } static void nat_mod(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 == 0) s.push(a1); else s.push(mk_vm_nat(v1 % v2)); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 == 0) s.push(a1); else s.push(mk_vm_nat(v1 % v2)); } } static void nat_gcd(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); mpz r; gcd(r, to_mpz1(a1), to_mpz2(a2)); s.push(mk_vm_nat(r)); } static void nat_has_decidable_eq(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { return s.push(mk_vm_bool(cidx(a1) == cidx(a2))); } else { return s.push(mk_vm_bool(to_mpz1(a1) == to_mpz2(a2))); } } static void nat_decidable_le(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { return s.push(mk_vm_bool(cidx(a1) <= cidx(a2))); } else { return s.push(mk_vm_bool(to_mpz1(a1) <= to_mpz2(a2))); } } static void nat_decidable_lt(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { return s.push(mk_vm_bool(cidx(a1) < cidx(a2))); } else { return s.push(mk_vm_bool(to_mpz1(a1) < to_mpz2(a2))); } } void initialize_vm_nat() { declare_vm_builtin(get_nat_succ_name(), 1, nat_succ); declare_vm_builtin(get_nat_add_name(), 2, nat_add); declare_vm_builtin(get_nat_mul_name(), 2, nat_mul); declare_vm_builtin(get_nat_sub_name(), 2, nat_sub); declare_vm_builtin(get_nat_div_name(), 2, nat_div); declare_vm_builtin(get_nat_mod_name(), 2, nat_mod); declare_vm_builtin(get_nat_gcd_name(), 2, nat_gcd); declare_vm_builtin(get_nat_has_decidable_eq_name(), 2, nat_has_decidable_eq); declare_vm_builtin(get_nat_decidable_le_name(), 2, nat_decidable_le); declare_vm_builtin(get_nat_decidable_lt_name(), 2, nat_decidable_lt); } void finalize_vm_nat() { } } <commit_msg>fix(library/vm/vm_nat): typo<commit_after>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "library/constants.h" #include "library/vm/vm.h" namespace lean { // ======================================= // Builtin nat operations vm_obj mk_vm_nat(unsigned n) { if (n < LEAN_MAX_SMALL_NAT) return mk_vm_simple(n); else return mk_vm_mpz(mpz(n)); } vm_obj mk_vm_nat(mpz const & n) { if (n < LEAN_MAX_SMALL_NAT) return mk_vm_simple(n.get_unsigned_int()); else return mk_vm_mpz(n); } MK_THREAD_LOCAL_GET_DEF(mpz, get_mpz1); MK_THREAD_LOCAL_GET_DEF(mpz, get_mpz2); static mpz const & to_mpz1(vm_obj const & o) { if (is_simple(o)) { mpz & r = get_mpz1(); r = cidx(o); return r; } else { return to_mpz(o); } } static mpz const & to_mpz2(vm_obj const & o) { if (is_simple(o)) { mpz & r = get_mpz2(); r = cidx(o); return r; } else { return to_mpz(o); } } static void nat_succ(vm_state & s) { vm_obj const & a = s.get(0); if (is_simple(a)) { s.push(mk_vm_nat(cidx(a) + 1)); } else { s.push(mk_vm_mpz(to_mpz1(a) + 1)); } } static void nat_add(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { s.push(mk_vm_nat(cidx(a1) + cidx(a2))); } else { s.push(mk_vm_mpz(to_mpz1(a1) + to_mpz2(a2))); } } static void nat_mul(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { unsigned long long r = static_cast<unsigned long long>(cidx(a1)) * static_cast<unsigned long long>(cidx(a2)); if (r < LEAN_MAX_SMALL_NAT) { s.push(mk_vm_simple(r)); return; } } s.push(mk_vm_mpz(to_mpz1(a1) * to_mpz2(a2))); } static void nat_sub(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 > v1) s.push(mk_vm_simple(0)); else s.push(mk_vm_nat(v1 - v2)); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 > v1) s.push(mk_vm_simple(0)); else s.push(mk_vm_nat(v1 - v2)); } } static void nat_div(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 == 0) s.push(mk_vm_simple(0)); else s.push(mk_vm_nat(v1 / v2)); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 == 0) s.push(mk_vm_simple(0)); else s.push(mk_vm_nat(v1 / v2)); } } static void nat_mod(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 == 0) s.push(a1); else s.push(mk_vm_nat(v1 % v2)); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 == 0) s.push(a1); else s.push(mk_vm_nat(v1 % v2)); } } static void nat_gcd(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); mpz r; gcd(r, to_mpz1(a1), to_mpz2(a2)); s.push(mk_vm_nat(r)); } static void nat_has_decidable_eq(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { return s.push(mk_vm_bool(cidx(a1) == cidx(a2))); } else { return s.push(mk_vm_bool(to_mpz1(a1) == to_mpz2(a2))); } } static void nat_decidable_le(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { return s.push(mk_vm_bool(cidx(a1) <= cidx(a2))); } else { return s.push(mk_vm_bool(to_mpz1(a1) <= to_mpz2(a2))); } } static void nat_decidable_lt(vm_state & s) { vm_obj const & a1 = s.get(0); vm_obj const & a2 = s.get(1); if (is_simple(a1) && is_simple(a2)) { return s.push(mk_vm_bool(cidx(a1) < cidx(a2))); } else { return s.push(mk_vm_bool(to_mpz1(a1) < to_mpz2(a2))); } } void initialize_vm_nat() { declare_vm_builtin(get_nat_succ_name(), 1, nat_succ); declare_vm_builtin(get_nat_add_name(), 2, nat_add); declare_vm_builtin(get_nat_mul_name(), 2, nat_mul); declare_vm_builtin(get_nat_sub_name(), 2, nat_sub); declare_vm_builtin(get_nat_div_name(), 2, nat_div); declare_vm_builtin(get_nat_mod_name(), 2, nat_mod); declare_vm_builtin(get_nat_gcd_name(), 2, nat_gcd); declare_vm_builtin(get_nat_has_decidable_eq_name(), 2, nat_has_decidable_eq); declare_vm_builtin(get_nat_decidable_le_name(), 2, nat_decidable_le); declare_vm_builtin(get_nat_decidable_lt_name(), 2, nat_decidable_lt); } void finalize_vm_nat() { } } <|endoftext|>
<commit_before>/************************************************************************/ /* */ /* Copyright 2015 by Thorsten Beier */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://hci.iwr.uni-heidelberg.de/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* [email protected] or */ /* [email protected] */ /* */ /* 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. */ /* */ /************************************************************************/ #ifndef VIGRA_MULTI_BLOCKING_HXX #define VIGRA_MULTI_BLOCKING_HXX #include "vigra/tinyvector.hxx" #include "vigra/box.hxx" #include "vigra/multi_iterator.hxx" #include "vigra/multi_convolution.hxx" #include "vigra/transform_iterator.hxx" namespace vigra{ // forward declaration template<unsigned int DIM, class C> class MultiBlocking; /// \cond namespace detail_multi_blocking{ template<unsigned int DIM, class C> class BlockWithBorder{ public: typedef C PointValue; typedef TinyVector<PointValue, DIM> Point; typedef Point Shape; typedef Box<PointValue, DIM> Block; typedef MultiCoordinateIterator< DIM> MultiCoordIter; BlockWithBorder(const Block & core = Block(), const Block & border = Block()) : core_(core), border_(border){ } /// get the core block const Block & core()const{ return core_; } Block localCore()const{ return core_-border_.begin(); } const Block & border()const{ return border_; } bool operator == (const BlockWithBorder & rhs) const{ return core_ == rhs.core_ && border_ == rhs.border_; } bool operator != (const BlockWithBorder & rhs) const{ return core_ != rhs.core_ || border_ != rhs.border_; } private: Block core_; Block border_; }; template<class VALUETYPE, unsigned int DIMENSION> std::ostream& operator<< (std::ostream& stream, const BlockWithBorder<DIMENSION,VALUETYPE> & bwb) { stream<<"["<<bwb.core()<<", "<<bwb.border()<<" ]"; return stream; } template<class MB> class MultiCoordToBlockWithBoarder{ public: typedef typename MB::Shape Shape; typedef typename MB::BlockDesc BlockDesc; typedef typename MB::BlockWithBorder result_type; MultiCoordToBlockWithBoarder() : mb_(NULL), width_(){ } MultiCoordToBlockWithBoarder(const MB & mb, const Shape & width) : mb_(&mb), width_(width){ } result_type operator()(const BlockDesc & blockDesc)const{ return mb_->getBlockWithBorder(blockDesc, width_); } private: const MB * mb_; Shape width_; }; template<class MB> class MultiCoordToBlock{ public: typedef typename MB::Shape Shape; typedef typename MB::BlockDesc BlockDesc; typedef typename MB::Block result_type; MultiCoordToBlock() : mb_(NULL){ } MultiCoordToBlock(const MB & mb) : mb_(&mb){ } result_type operator()(const BlockDesc & blockDesc)const{ return mb_->getBlock(blockDesc); } private: const MB * mb_; }; } /// \endcond /** MultiBlocking is used to split a image / volume / multiarray into non-overlapping blocks. These non overlapping blocks are called cores. A border can be added to the core boxes. These 'core+border' blocks are just called border. The core block within the coordinate system of the border block is called local core. */ template<unsigned int DIM, class C = MultiArrayIndex> class MultiBlocking{ public: typedef MultiBlocking<DIM, C> SelfType; friend class detail_multi_blocking::MultiCoordToBlock<SelfType>; friend class detail_multi_blocking::MultiCoordToBlockWithBoarder<SelfType>; typedef C PointValue; typedef TinyVector<PointValue, DIM> Point; typedef Point Shape; typedef Point BlockDesc; typedef Box<PointValue, DIM> Block; typedef MultiCoordinateIterator< DIM> MultiCoordIter; typedef detail_multi_blocking::BlockWithBorder<DIM, PointValue> BlockWithBorder; // iterators typedef detail_multi_blocking::MultiCoordToBlockWithBoarder<SelfType> CoordToBwb; typedef detail_multi_blocking::MultiCoordToBlock<SelfType> CoordToB; typedef EndAwareTransformIterator<CoordToBwb, MultiCoordIter> BlockWithBorderIter; typedef EndAwareTransformIterator<CoordToB, MultiCoordIter> BlockIter; MultiBlocking(const Shape & shape, const Shape & blockShape, const Shape & roiBegin = Shape(0), const Shape & roiEnd = Shape(0) ) : shape_(shape), roiBlock_(roiBegin,roiEnd == Shape(0) ? shape : roiEnd), blockShape_(blockShape), blocksPerAxis_(vigra::SkipInitialization), numBlocks_(1) { const Shape roiShape = roiBlock_.size(); blocksPerAxis_ = roiShape / blockShape_; // blocking for(size_t d=0; d<DIM; ++d){ if(blocksPerAxis_[d]*blockShape_[d] < roiShape[d] ){ ++blocksPerAxis_[d]; } numBlocks_ *= blocksPerAxis_[d]; } // total image border blocks Shape beginCA(0),endCB(shape); for(size_t d=0; d<DIM; ++d){ { // fix coordinate d to zero Shape endCA(shape); endCA[d] = 1; volumeBorderBlocks_.push_back(Block(beginCA,endCA)); } { // fix coordinate d to shape[dim]-1 Shape beginCB(shape); beginCB[d] -= 1; volumeBorderBlocks_.push_back(Block(beginCB,endCB)); } } insideVolBlock_.setBegin(Shape(1)); Shape insideVolBlockShapeEnd(shape); insideVolBlockShapeEnd -= Shape(1); insideVolBlock_.setEnd(insideVolBlockShapeEnd); } /// total number of blocks size_t numBlocks()const{ return numBlocks_; } BlockWithBorderIter blockWithBorderBegin(const Shape & width)const{ return BlockWithBorderIter(MultiCoordIter(blocksPerAxis_), CoordToBwb(*this, width)); } BlockWithBorderIter blockWithBorderEnd(const Shape & width)const{ const MultiCoordIter beginIter(blocksPerAxis_); return BlockWithBorderIter(beginIter.getEndIterator(), CoordToBwb(*this, width)); } Block blockDescToBlock(const BlockDesc & desc){ MultiCoordIter beginIter(blocksPerAxis_); beginIter+=desc; return *BlockIter(beginIter,CoordToB(*this)); } BlockIter blockBegin()const{ return BlockIter(MultiCoordIter(blocksPerAxis_),CoordToB(*this)); } BlockIter blockEnd()const{ const MultiCoordIter beginIter(blocksPerAxis_); return BlockIter(beginIter.getEndIterator(),CoordToB(*this)); } Block blockDescToBlock(const BlockDesc & blockDesc)const{ MultiCoordIter iter(blocksPerAxis_); iter+=blockDesc; return *BlockIter(iter,CoordToB(*this)); } /// does this block intersect with the volume border bool containsVolumeBorder(const Block & block) const { return !insideVolBlock_.contains(block); } const Shape & roiBegin()const{ return roiBlock_.begin(); } const Shape & roiEnd()const{ return roiBlock_.end(); } const Shape & shape()const{ return shape_; } const Shape & blockShape()const{ return blockShape_; } const Shape & blocksPerAxis()const{ return blocksPerAxis_; } const std::vector<Block> & volumeBorderBlocks()const{ return volumeBorderBlocks_; } std::vector<UInt32> intersectingBlocks( const Shape roiBegin, const Shape roiEnd )const{ size_t i=0; std::vector<UInt32> iBlocks; const Block testBlock(roiBegin, roiEnd); for(BlockIter iter=blockBegin(); iter!=blockEnd(); ++iter){ if(testBlock.intersects(*iter)){ iBlocks.push_back(i); } ++i; } return std::move(iBlocks); } private: /// get a block with border BlockWithBorder getBlockWithBorder(const BlockDesc & blockDesc, const Shape & width )const{ const Point blockStart(blockDesc * blockShape_ + roiBlock_.begin()); const Point blockEnd(blockStart + blockShape_); const Block core = Block(blockStart, blockEnd) & roiBlock_ ; Block border = core; border.addBorder(width); border &= Block(shape_); return BlockWithBorder( core, border ); } /// get a block (without any overlap) Block getBlock(const BlockDesc & blockDesc)const{ const Point blockStart(blockDesc * blockShape_ + roiBlock_.begin()); const Point blockEnd(blockStart + blockShape_); return Block(blockStart, blockEnd) & roiBlock_; } Shape shape_; // total shape of the input volume Block roiBlock_; // ROI in which to compute filters/algorithms Shape blockShape_; // shape sub-block for each thread (without border pixels) Shape blocksPerAxis_; // how many blocks are on each axis size_t numBlocks_; // total number of blocks std::vector<Block> volumeBorderBlocks_; Block insideVolBlock_; }; } #endif // VIGRA_MULTI_BLOCKING_HXX <commit_msg>multi_blocking: fix pessimization spotted by clang.<commit_after>/************************************************************************/ /* */ /* Copyright 2015 by Thorsten Beier */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://hci.iwr.uni-heidelberg.de/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* [email protected] or */ /* [email protected] */ /* */ /* 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. */ /* */ /************************************************************************/ #ifndef VIGRA_MULTI_BLOCKING_HXX #define VIGRA_MULTI_BLOCKING_HXX #include "vigra/tinyvector.hxx" #include "vigra/box.hxx" #include "vigra/multi_iterator.hxx" #include "vigra/multi_convolution.hxx" #include "vigra/transform_iterator.hxx" namespace vigra{ // forward declaration template<unsigned int DIM, class C> class MultiBlocking; /// \cond namespace detail_multi_blocking{ template<unsigned int DIM, class C> class BlockWithBorder{ public: typedef C PointValue; typedef TinyVector<PointValue, DIM> Point; typedef Point Shape; typedef Box<PointValue, DIM> Block; typedef MultiCoordinateIterator< DIM> MultiCoordIter; BlockWithBorder(const Block & core = Block(), const Block & border = Block()) : core_(core), border_(border){ } /// get the core block const Block & core()const{ return core_; } Block localCore()const{ return core_-border_.begin(); } const Block & border()const{ return border_; } bool operator == (const BlockWithBorder & rhs) const{ return core_ == rhs.core_ && border_ == rhs.border_; } bool operator != (const BlockWithBorder & rhs) const{ return core_ != rhs.core_ || border_ != rhs.border_; } private: Block core_; Block border_; }; template<class VALUETYPE, unsigned int DIMENSION> std::ostream& operator<< (std::ostream& stream, const BlockWithBorder<DIMENSION,VALUETYPE> & bwb) { stream<<"["<<bwb.core()<<", "<<bwb.border()<<" ]"; return stream; } template<class MB> class MultiCoordToBlockWithBoarder{ public: typedef typename MB::Shape Shape; typedef typename MB::BlockDesc BlockDesc; typedef typename MB::BlockWithBorder result_type; MultiCoordToBlockWithBoarder() : mb_(NULL), width_(){ } MultiCoordToBlockWithBoarder(const MB & mb, const Shape & width) : mb_(&mb), width_(width){ } result_type operator()(const BlockDesc & blockDesc)const{ return mb_->getBlockWithBorder(blockDesc, width_); } private: const MB * mb_; Shape width_; }; template<class MB> class MultiCoordToBlock{ public: typedef typename MB::Shape Shape; typedef typename MB::BlockDesc BlockDesc; typedef typename MB::Block result_type; MultiCoordToBlock() : mb_(NULL){ } MultiCoordToBlock(const MB & mb) : mb_(&mb){ } result_type operator()(const BlockDesc & blockDesc)const{ return mb_->getBlock(blockDesc); } private: const MB * mb_; }; } /// \endcond /** MultiBlocking is used to split a image / volume / multiarray into non-overlapping blocks. These non overlapping blocks are called cores. A border can be added to the core boxes. These 'core+border' blocks are just called border. The core block within the coordinate system of the border block is called local core. */ template<unsigned int DIM, class C = MultiArrayIndex> class MultiBlocking{ public: typedef MultiBlocking<DIM, C> SelfType; friend class detail_multi_blocking::MultiCoordToBlock<SelfType>; friend class detail_multi_blocking::MultiCoordToBlockWithBoarder<SelfType>; typedef C PointValue; typedef TinyVector<PointValue, DIM> Point; typedef Point Shape; typedef Point BlockDesc; typedef Box<PointValue, DIM> Block; typedef MultiCoordinateIterator< DIM> MultiCoordIter; typedef detail_multi_blocking::BlockWithBorder<DIM, PointValue> BlockWithBorder; // iterators typedef detail_multi_blocking::MultiCoordToBlockWithBoarder<SelfType> CoordToBwb; typedef detail_multi_blocking::MultiCoordToBlock<SelfType> CoordToB; typedef EndAwareTransformIterator<CoordToBwb, MultiCoordIter> BlockWithBorderIter; typedef EndAwareTransformIterator<CoordToB, MultiCoordIter> BlockIter; MultiBlocking(const Shape & shape, const Shape & blockShape, const Shape & roiBegin = Shape(0), const Shape & roiEnd = Shape(0) ) : shape_(shape), roiBlock_(roiBegin,roiEnd == Shape(0) ? shape : roiEnd), blockShape_(blockShape), blocksPerAxis_(vigra::SkipInitialization), numBlocks_(1) { const Shape roiShape = roiBlock_.size(); blocksPerAxis_ = roiShape / blockShape_; // blocking for(size_t d=0; d<DIM; ++d){ if(blocksPerAxis_[d]*blockShape_[d] < roiShape[d] ){ ++blocksPerAxis_[d]; } numBlocks_ *= blocksPerAxis_[d]; } // total image border blocks Shape beginCA(0),endCB(shape); for(size_t d=0; d<DIM; ++d){ { // fix coordinate d to zero Shape endCA(shape); endCA[d] = 1; volumeBorderBlocks_.push_back(Block(beginCA,endCA)); } { // fix coordinate d to shape[dim]-1 Shape beginCB(shape); beginCB[d] -= 1; volumeBorderBlocks_.push_back(Block(beginCB,endCB)); } } insideVolBlock_.setBegin(Shape(1)); Shape insideVolBlockShapeEnd(shape); insideVolBlockShapeEnd -= Shape(1); insideVolBlock_.setEnd(insideVolBlockShapeEnd); } /// total number of blocks size_t numBlocks()const{ return numBlocks_; } BlockWithBorderIter blockWithBorderBegin(const Shape & width)const{ return BlockWithBorderIter(MultiCoordIter(blocksPerAxis_), CoordToBwb(*this, width)); } BlockWithBorderIter blockWithBorderEnd(const Shape & width)const{ const MultiCoordIter beginIter(blocksPerAxis_); return BlockWithBorderIter(beginIter.getEndIterator(), CoordToBwb(*this, width)); } Block blockDescToBlock(const BlockDesc & desc){ MultiCoordIter beginIter(blocksPerAxis_); beginIter+=desc; return *BlockIter(beginIter,CoordToB(*this)); } BlockIter blockBegin()const{ return BlockIter(MultiCoordIter(blocksPerAxis_),CoordToB(*this)); } BlockIter blockEnd()const{ const MultiCoordIter beginIter(blocksPerAxis_); return BlockIter(beginIter.getEndIterator(),CoordToB(*this)); } Block blockDescToBlock(const BlockDesc & blockDesc)const{ MultiCoordIter iter(blocksPerAxis_); iter+=blockDesc; return *BlockIter(iter,CoordToB(*this)); } /// does this block intersect with the volume border bool containsVolumeBorder(const Block & block) const { return !insideVolBlock_.contains(block); } const Shape & roiBegin()const{ return roiBlock_.begin(); } const Shape & roiEnd()const{ return roiBlock_.end(); } const Shape & shape()const{ return shape_; } const Shape & blockShape()const{ return blockShape_; } const Shape & blocksPerAxis()const{ return blocksPerAxis_; } const std::vector<Block> & volumeBorderBlocks()const{ return volumeBorderBlocks_; } std::vector<UInt32> intersectingBlocks( const Shape roiBegin, const Shape roiEnd )const{ size_t i=0; std::vector<UInt32> iBlocks; const Block testBlock(roiBegin, roiEnd); for(BlockIter iter=blockBegin(); iter!=blockEnd(); ++iter){ if(testBlock.intersects(*iter)){ iBlocks.push_back(i); } ++i; } return iBlocks; } private: /// get a block with border BlockWithBorder getBlockWithBorder(const BlockDesc & blockDesc, const Shape & width )const{ const Point blockStart(blockDesc * blockShape_ + roiBlock_.begin()); const Point blockEnd(blockStart + blockShape_); const Block core = Block(blockStart, blockEnd) & roiBlock_ ; Block border = core; border.addBorder(width); border &= Block(shape_); return BlockWithBorder( core, border ); } /// get a block (without any overlap) Block getBlock(const BlockDesc & blockDesc)const{ const Point blockStart(blockDesc * blockShape_ + roiBlock_.begin()); const Point blockEnd(blockStart + blockShape_); return Block(blockStart, blockEnd) & roiBlock_; } Shape shape_; // total shape of the input volume Block roiBlock_; // ROI in which to compute filters/algorithms Shape blockShape_; // shape sub-block for each thread (without border pixels) Shape blocksPerAxis_; // how many blocks are on each axis size_t numBlocks_; // total number of blocks std::vector<Block> volumeBorderBlocks_; Block insideVolBlock_; }; } #endif // VIGRA_MULTI_BLOCKING_HXX <|endoftext|>
<commit_before>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include "library/vm/vm.h" #include "library/vm/vm_string.h" namespace lean { // ======================================= // Builtin nat operations vm_obj mk_vm_nat(unsigned n) { if (LEAN_LIKELY(n < LEAN_MAX_SMALL_NAT)) return mk_vm_simple(n); else return mk_vm_mpz(mpz(n)); } vm_obj mk_vm_nat(mpz const & n) { if (LEAN_LIKELY(n < LEAN_MAX_SMALL_NAT)) return mk_vm_simple(n.get_unsigned_int()); else return mk_vm_mpz(n); } unsigned to_unsigned(vm_obj const & o) { if (LEAN_LIKELY(is_simple(o))) return cidx(o); else return to_mpz(o).get_unsigned_int(); } optional<unsigned> try_to_unsigned(vm_obj const & o) { if (LEAN_LIKELY(is_simple(o))) { return optional<unsigned>(cidx(o)); } else { mpz const & v = to_mpz(o); if (v.is_unsigned_int()) return optional<unsigned>(v.get_unsigned_int()); else return optional<unsigned>(); } } unsigned force_to_unsigned(vm_obj const & o, unsigned def) { if (auto r = try_to_unsigned(o)) return *r; else return def; } MK_THREAD_LOCAL_GET_DEF(mpz, get_mpz1); MK_THREAD_LOCAL_GET_DEF(mpz, get_mpz2); static mpz const & to_mpz1(vm_obj const & o) { if (is_simple(o)) { mpz & r = get_mpz1(); r = cidx(o); return r; } else { return to_mpz(o); } } static mpz const & to_mpz2(vm_obj const & o) { if (is_simple(o)) { mpz & r = get_mpz2(); r = cidx(o); return r; } else { return to_mpz(o); } } vm_obj nat_succ(vm_obj const & a) { if (LEAN_LIKELY(is_simple(a))) { return mk_vm_nat(cidx(a) + 1); } else { return mk_vm_mpz(to_mpz1(a) + 1); } } vm_obj nat_add(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) + cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) + to_mpz2(a2)); } } vm_obj nat_mul(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned long long r = static_cast<unsigned long long>(cidx(a1)) * static_cast<unsigned long long>(cidx(a2)); if (LEAN_LIKELY(r < LEAN_MAX_SMALL_NAT)) { return mk_vm_simple(r); } } return mk_vm_mpz(to_mpz1(a1) * to_mpz2(a2)); } vm_obj nat_sub(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 > v1) return mk_vm_simple(0); else return mk_vm_nat(v1 - v2); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 > v1) return mk_vm_simple(0); else return mk_vm_nat(v1 - v2); } } vm_obj nat_div(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 == 0) return mk_vm_simple(0); else return mk_vm_nat(v1 / v2); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 == 0) return mk_vm_simple(0); else return mk_vm_nat(v1 / v2); } } vm_obj nat_mod(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 == 0) return a1; else return mk_vm_nat(v1 % v2); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 == 0) return a1; else return mk_vm_nat(v1 % v2); } } vm_obj nat_gcd(vm_obj const & a1, vm_obj const & a2) { mpz r; gcd(r, to_mpz1(a1), to_mpz2(a2)); return mk_vm_nat(r); } vm_obj nat_shiftl(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v1 >> (31 - v2) == 0) // LEAN_MAX_SMALL_NAT = 1 >> 31 return mk_vm_nat(v1 << v2); } mpz const & v1 = to_mpz1(a1); return mk_vm_mpz(mul2k(v1, v1, to_unsigned(a2))); } vm_obj nat_shiftr(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) >> cidx(a2)); } else { mpz const & v1 = to_mpz1(a1); return mk_vm_mpz(div2k(v1, v1, to_unsigned(a2))); } } vm_obj nat_land(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) & cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) & to_mpz2(a2)); } } vm_obj nat_lor(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) | cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) | to_mpz2(a2)); } } vm_obj nat_lxor(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) ^ cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) ^ to_mpz2(a2)); } } vm_obj nat_ldiff(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) & ~cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) & ~to_mpz2(a2)); } } vm_obj nat_test_bit(vm_obj const & a1, vm_obj const & a2) { unsigned n2; if (LEAN_LIKELY(is_simple(a2))) { n2 = cidx(a2); if (n2 >= 31) return mk_vm_bool(false); } else { mpz const & v2 = to_mpz2(a2); if (v2 >= 31) return mk_vm_bool(false); n2 = v2.to_unsigned(); } if (LEAN_LIKELY(is_simple(a1))) { return mk_vm_bool((cidx(a1) & (1 << n2)) != 0); } else { // return mk_vm_bool(to_mpz1(a1).test_bit(to_mpz1(a2))); // TODO return mk_vm_bool((to_mpz1(a1) & (1 << n2)) != 0); } } vm_obj nat_decidable_eq(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_bool(cidx(a1) == cidx(a2)); } else { return mk_vm_bool(to_mpz1(a1) == to_mpz2(a2)); } } vm_obj nat_decidable_le(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_bool(cidx(a1) <= cidx(a2)); } else { return mk_vm_bool(to_mpz1(a1) <= to_mpz2(a2)); } } vm_obj nat_decidable_lt(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_bool(cidx(a1) < cidx(a2)); } else { return mk_vm_bool(to_mpz1(a1) < to_mpz2(a2)); } } void nat_rec(vm_state &) { /* recursors are implemented by the compiler */ lean_unreachable(); } void nat_no_confusion(vm_state &) { /* no_confusion is implemented by the compiler */ lean_unreachable(); } vm_obj nat_to_string(vm_obj const & a) { std::ostringstream out; if (is_simple(a)) { out << cidx(a); } else { out << to_mpz(a); } return to_obj(out.str()); } vm_obj nat_repeat(vm_obj const &, vm_obj const & f, vm_obj const & n, vm_obj const & a) { if (LEAN_LIKELY(is_simple(n))) { unsigned _n = cidx(n); vm_obj r = a; for (unsigned i = 0; i < _n ; i++) { r = invoke(f, mk_vm_simple(i), r); } return r; } else { mpz _n = to_mpz(n); mpz i(0); vm_obj r = a; while (i < _n) { r = invoke(f, mk_vm_nat(i), r); i++; } return r; } } void initialize_vm_nat() { DECLARE_VM_BUILTIN(name({"nat", "succ"}), nat_succ); DECLARE_VM_BUILTIN(name({"nat", "add"}), nat_add); DECLARE_VM_BUILTIN(name({"nat", "mul"}), nat_mul); DECLARE_VM_BUILTIN(name({"nat", "sub"}), nat_sub); DECLARE_VM_BUILTIN(name({"nat", "div"}), nat_div); DECLARE_VM_BUILTIN(name({"nat", "mod"}), nat_mod); DECLARE_VM_BUILTIN(name({"nat", "gcd"}), nat_gcd); DECLARE_VM_BUILTIN(name({"nat", "decidable_eq"}), nat_decidable_eq); DECLARE_VM_BUILTIN(name({"nat", "decidable_le"}), nat_decidable_le); DECLARE_VM_BUILTIN(name({"nat", "decidable_lt"}), nat_decidable_lt); DECLARE_VM_BUILTIN(name({"nat", "to_string"}), nat_to_string); DECLARE_VM_BUILTIN(name({"nat", "repeat"}), nat_repeat); DECLARE_VM_BUILTIN(name({"nat", "shiftl"}), nat_shiftl); DECLARE_VM_BUILTIN(name({"nat", "shiftr"}), nat_shiftr); DECLARE_VM_BUILTIN(name({"nat", "lor"}), nat_lor); DECLARE_VM_BUILTIN(name({"nat", "land"}), nat_land); DECLARE_VM_BUILTIN(name({"nat", "ldiff"}), nat_ldiff); DECLARE_VM_BUILTIN(name({"nat", "lxor"}), nat_lxor); declare_vm_builtin(name({"nat", "cases_on"}), "nat_rec", 4, nat_rec); declare_vm_builtin(name({"nat", "rec_on"}), "nat_rec", 4, nat_rec); declare_vm_builtin(name({"nat", "no_confusion"}), "nat_no_confusion", 5, nat_no_confusion); declare_vm_builtin(name({"nat", "no_confusion_type"}), "nat_no_confusion", 3, nat_no_confusion); } void finalize_vm_nat() { } } <commit_msg>fix(library/vm/vm_nat): bitwise operators<commit_after>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include "library/vm/vm.h" #include "library/vm/vm_string.h" namespace lean { // ======================================= // Builtin nat operations vm_obj mk_vm_nat(unsigned n) { if (LEAN_LIKELY(n < LEAN_MAX_SMALL_NAT)) return mk_vm_simple(n); else return mk_vm_mpz(mpz(n)); } vm_obj mk_vm_nat(mpz const & n) { if (LEAN_LIKELY(n < LEAN_MAX_SMALL_NAT)) return mk_vm_simple(n.get_unsigned_int()); else return mk_vm_mpz(n); } unsigned to_unsigned(vm_obj const & o) { if (LEAN_LIKELY(is_simple(o))) return cidx(o); else return to_mpz(o).get_unsigned_int(); } optional<unsigned> try_to_unsigned(vm_obj const & o) { if (LEAN_LIKELY(is_simple(o))) { return optional<unsigned>(cidx(o)); } else { mpz const & v = to_mpz(o); if (v.is_unsigned_int()) return optional<unsigned>(v.get_unsigned_int()); else return optional<unsigned>(); } } unsigned force_to_unsigned(vm_obj const & o, unsigned def) { if (auto r = try_to_unsigned(o)) return *r; else return def; } MK_THREAD_LOCAL_GET_DEF(mpz, get_mpz1); MK_THREAD_LOCAL_GET_DEF(mpz, get_mpz2); static mpz const & to_mpz1(vm_obj const & o) { if (is_simple(o)) { mpz & r = get_mpz1(); r = cidx(o); return r; } else { return to_mpz(o); } } static mpz const & to_mpz2(vm_obj const & o) { if (is_simple(o)) { mpz & r = get_mpz2(); r = cidx(o); return r; } else { return to_mpz(o); } } vm_obj nat_succ(vm_obj const & a) { if (LEAN_LIKELY(is_simple(a))) { return mk_vm_nat(cidx(a) + 1); } else { return mk_vm_mpz(to_mpz1(a) + 1); } } vm_obj nat_add(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) + cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) + to_mpz2(a2)); } } vm_obj nat_mul(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned long long r = static_cast<unsigned long long>(cidx(a1)) * static_cast<unsigned long long>(cidx(a2)); if (LEAN_LIKELY(r < LEAN_MAX_SMALL_NAT)) { return mk_vm_simple(r); } } return mk_vm_mpz(to_mpz1(a1) * to_mpz2(a2)); } vm_obj nat_sub(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 > v1) return mk_vm_simple(0); else return mk_vm_nat(v1 - v2); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 > v1) return mk_vm_simple(0); else return mk_vm_nat(v1 - v2); } } vm_obj nat_div(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 == 0) return mk_vm_simple(0); else return mk_vm_nat(v1 / v2); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 == 0) return mk_vm_simple(0); else return mk_vm_nat(v1 / v2); } } vm_obj nat_mod(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v2 == 0) return a1; else return mk_vm_nat(v1 % v2); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2 == 0) return a1; else return mk_vm_nat(v1 % v2); } } vm_obj nat_gcd(vm_obj const & a1, vm_obj const & a2) { mpz r; gcd(r, to_mpz1(a1), to_mpz2(a2)); return mk_vm_nat(r); } vm_obj nat_shiftl(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { unsigned v1 = cidx(a1); unsigned v2 = cidx(a2); if (v1 >> (31 - v2) == 0) // LEAN_MAX_SMALL_NAT = 1 >> 31 return mk_vm_nat(v1 << v2); } mpz v1 = to_mpz1(a1); mul2k(v1, v1, to_unsigned(a2)); return mk_vm_mpz(v1); } vm_obj nat_shiftr(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) >> cidx(a2)); } else { mpz v1 = to_mpz1(a1); div2k(v1, v1, to_unsigned(a2)); return mk_vm_mpz(v1); } } vm_obj nat_land(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) & cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) & to_mpz2(a2)); } } vm_obj nat_lor(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) | cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) | to_mpz2(a2)); } } vm_obj nat_lxor(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) ^ cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) ^ to_mpz2(a2)); } } vm_obj nat_ldiff(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_nat(cidx(a1) & ~cidx(a2)); } else { return mk_vm_mpz(to_mpz1(a1) & ~to_mpz2(a2)); } } vm_obj nat_test_bit(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_bool((cidx(a1) & (1u << cidx(a2))) != 0); } else { mpz const & v1 = to_mpz1(a1); mpz const & v2 = to_mpz2(a2); if (v2.is_unsigned_long_int()) return mk_vm_bool(v1.test_bit(v2.get_unsigned_long_int())); else return mk_vm_bool(false); } } vm_obj nat_decidable_eq(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_bool(cidx(a1) == cidx(a2)); } else { return mk_vm_bool(to_mpz1(a1) == to_mpz2(a2)); } } vm_obj nat_decidable_le(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_bool(cidx(a1) <= cidx(a2)); } else { return mk_vm_bool(to_mpz1(a1) <= to_mpz2(a2)); } } vm_obj nat_decidable_lt(vm_obj const & a1, vm_obj const & a2) { if (LEAN_LIKELY(is_simple(a1) && is_simple(a2))) { return mk_vm_bool(cidx(a1) < cidx(a2)); } else { return mk_vm_bool(to_mpz1(a1) < to_mpz2(a2)); } } void nat_rec(vm_state &) { /* recursors are implemented by the compiler */ lean_unreachable(); } void nat_no_confusion(vm_state &) { /* no_confusion is implemented by the compiler */ lean_unreachable(); } vm_obj nat_to_string(vm_obj const & a) { std::ostringstream out; if (is_simple(a)) { out << cidx(a); } else { out << to_mpz(a); } return to_obj(out.str()); } vm_obj nat_repeat(vm_obj const &, vm_obj const & f, vm_obj const & n, vm_obj const & a) { if (LEAN_LIKELY(is_simple(n))) { unsigned _n = cidx(n); vm_obj r = a; for (unsigned i = 0; i < _n ; i++) { r = invoke(f, mk_vm_simple(i), r); } return r; } else { mpz _n = to_mpz(n); mpz i(0); vm_obj r = a; while (i < _n) { r = invoke(f, mk_vm_nat(i), r); i++; } return r; } } void initialize_vm_nat() { DECLARE_VM_BUILTIN(name({"nat", "succ"}), nat_succ); DECLARE_VM_BUILTIN(name({"nat", "add"}), nat_add); DECLARE_VM_BUILTIN(name({"nat", "mul"}), nat_mul); DECLARE_VM_BUILTIN(name({"nat", "sub"}), nat_sub); DECLARE_VM_BUILTIN(name({"nat", "div"}), nat_div); DECLARE_VM_BUILTIN(name({"nat", "mod"}), nat_mod); DECLARE_VM_BUILTIN(name({"nat", "gcd"}), nat_gcd); DECLARE_VM_BUILTIN(name({"nat", "decidable_eq"}), nat_decidable_eq); DECLARE_VM_BUILTIN(name({"nat", "decidable_le"}), nat_decidable_le); DECLARE_VM_BUILTIN(name({"nat", "decidable_lt"}), nat_decidable_lt); DECLARE_VM_BUILTIN(name({"nat", "to_string"}), nat_to_string); DECLARE_VM_BUILTIN(name({"nat", "repeat"}), nat_repeat); DECLARE_VM_BUILTIN(name({"nat", "shiftl"}), nat_shiftl); DECLARE_VM_BUILTIN(name({"nat", "shiftr"}), nat_shiftr); DECLARE_VM_BUILTIN(name({"nat", "lor"}), nat_lor); DECLARE_VM_BUILTIN(name({"nat", "land"}), nat_land); DECLARE_VM_BUILTIN(name({"nat", "ldiff"}), nat_ldiff); DECLARE_VM_BUILTIN(name({"nat", "lxor"}), nat_lxor); DECLARE_VM_BUILTIN(name({"nat", "test_bit"}), nat_test_bit); declare_vm_builtin(name({"nat", "cases_on"}), "nat_rec", 4, nat_rec); declare_vm_builtin(name({"nat", "rec_on"}), "nat_rec", 4, nat_rec); declare_vm_builtin(name({"nat", "no_confusion"}), "nat_no_confusion", 5, nat_no_confusion); declare_vm_builtin(name({"nat", "no_confusion_type"}), "nat_no_confusion", 3, nat_no_confusion); } void finalize_vm_nat() { } } <|endoftext|>
<commit_before>#include <iostream> using namespace std; #include <fstream> #include "Lecture.h" #include <cstring> #include <locale> bool isnumber(wchar_t ch) { if(ch >= L'0' && ch <= L'9') return true; return false; } int tonumber(wchar_t ch) { return int(ch) - int(L'0'); } int tonumber(wchar_t ch, wchar_t ch2) { return (int(ch) - int(L'0')) * 10 + (int(ch2) - int(L'0')); } int LECTURE::Open_Lecture(const wchar_t* const Filename, LECTURE *Lecture) { LECTURE *Loop_Lecture; wchar_t ch; wchar_t ch2; wchar_t ch3; wchar_t dummy; wchar_t* temp; int i; int j; int to; int tmp; wifstream fin(Filename); if(!fin.is_open()) return false; fin.imbue(locale("kor")); Loop_Lecture = Lecture; do { // ڵ for(i = 0; i < BUFFER_LENGTH; i++) { fin.get(ch); if(ch == L'\n' || ch == L'\t') fin.get(ch); Loop_Lecture->code[i] = ch; } Loop_Lecture->code[BUFFER_LENGTH] = L'\0'; fin.get(ch); // \t remover temp = new wchar_t[TEMP_CHAR_SIZE]; // ̸ fin.get(ch); i = 0; do { temp[i] = ch; i++; fin.get(ch); }while(ch != L'\t'); temp[i] = L'\0'; int lectureNameLen = wcslen(temp) + 1; Loop_Lecture->name = new wchar_t[lectureNameLen]; wcscpy_s(Loop_Lecture->name, lectureNameLen, temp); Loop_Lecture->name[i] = L'\0'; delete[] temp; // fin >> Loop_Lecture->pou_srt; // ǽð fin >> Loop_Lecture->lecture; // ð fin >> Loop_Lecture->exp; // fin >> Loop_Lecture->plan_point; // й fin >> Loop_Lecture->div_class; fin.get(ch); // TAB REMOVER fin.get(ch); if(ch != '\t') //  Loop_Lecture->target_eng = ch; fin.get(ch); // TAB REMOVER // for(i = 0; i < MAJOR_COUNT; i++) { fin.get(ch); if(ch != L'\t') { fin.get(ch2); if(ch2 != L'\t') { fin.get(ch3); if(ch3 != L'\t') { fin.get(dummy); if(dummy != L'\t') { fin.get(dummy); if(dummy != L'\t') fin.get(dummy); } } else dummy = L'\t'; } else ch3 = L'\t'; } else { ch2 = L'\t'; ch3 = L'\t'; } if(ch != L'\t') { if(ch2 != L'\t') { if(isnumber(ch2)) { Loop_Lecture->major[i] = tonumber(ch, ch2); if(Loop_Lecture->major[i] == CT_norm_dummy) Loop_Lecture->major[i] = CT_norm_sel; if(ch3 != L'\t') { if(ch3 == L'S') { Loop_Lecture->major[i] = Loop_Lecture->major[i] | CT_MULTI_UNMAJOR; ch3 = dummy; } if(ch3 == L'T') { Loop_Lecture->major[i] = Loop_Lecture->major[i] | CT_MDTEACHER_LECTURE; if(ch3 == dummy) fin.get(dummy); } } } else { Loop_Lecture->major[i] = tonumber(ch); if(ch2 == L'S') { Loop_Lecture->major[i] = Loop_Lecture->major[i] | CT_MULTI_UNMAJOR; ch2 = ch3; } if(ch2 == L'T') { Loop_Lecture->major[i] = Loop_Lecture->major[i] | CT_MDTEACHER_LECTURE; } } } else { Loop_Lecture->major[i] = tonumber(ch); } } else { Loop_Lecture->major[i] = 0; } } // а/г temp = new wchar_t[200]; fin.get(ch); while(ch == L'\t' || ch == L'"') fin.get(ch); i = 0; while(ch != L'\t' && ch != L'"') { temp[i] = ch; i++; fin.get(ch); } temp[i] = L'\0'; int targetDepYearLen = wcslen(temp) + 1; Loop_Lecture->target_dep_year = new wchar_t[targetDepYearLen]; wcscpy_s(Loop_Lecture->target_dep_year, targetDepYearLen, temp); Loop_Lecture->target_dep_year[i] = L'\0'; delete[] temp; if(ch == L'"') fin.get(ch); // tab remover // 米 temp = new wchar_t[20]; fin.get(ch); if(ch == L'"') fin.get(ch); // " remover i = 0; while(ch != L'\t' && ch != L'"') { temp[i] = ch; i++; fin.get(ch); } temp[i] = L'\0'; if(ch == L'"') fin.get(ch); // tab remover int teacherNameLen = wcslen(temp) + 1; Loop_Lecture->teacher = new wchar_t[teacherNameLen]; wcscpy_s(Loop_Lecture->teacher, teacherNameLen, temp); Loop_Lecture->teacher[i] = L'\0'; delete[] temp; // ðǥ for (int i = 0; i < MAX_TIME_COUNT; i++) Loop_Lecture->time_info[i] = 0; while(true) { if(!fin.get(ch)) break; if(ch == L'\t') continue; if(ch == L'/') continue; if(ch == L' ') continue; if(ch != L'\n') { fin.get(dummy); for(j = 0; j < DAY_COUNT; j++) { if(ch == day_inf[j][0]) { break; } } if(j == DAY_COUNT) { cout << "Reading Failed.. (ðǥ:)"; return 0; } if(!IS_DAY_VALIED(Loop_Lecture->time_info[0])) { Loop_Lecture->time_info[0] = MON >> j; to = 0; } else if(Loop_Lecture->time_info[0] & (MON >> j)) { to = 0; } else if(!IS_DAY_VALIED(Loop_Lecture->time_info[1])) { Loop_Lecture->time_info[1] = MON >> j; to = 1; } else if(Loop_Lecture->time_info[1] & (MON >> j)) { to = 1; } else if(!IS_DAY_VALIED(Loop_Lecture->time_info[2])) { Loop_Lecture->time_info[2] = MON >> j; to = 2; } else if(Loop_Lecture->time_info[2] & (MON >> j)) { to = 2; } else { cout << "Reading Failed.. (ðǥ:ð)"; return 0; } fin.get(ch); fin.get(ch2); fin.get(ch3); fin.get(dummy); tmp = tonumber(ch, ch2) - 1; tmp *= 2; if(ch3 == 'B') tmp++; if(tmp >= 24) tmp = 24; // 13A ̻ ð tovr Loop_Lecture->time_info[to] = Loop_Lecture->time_info[to] | tt_inf[tmp]; if(dummy == L'\n') break; } else break; } Loop_Lecture->valid = 1; if(Loop_Lecture->next == NULL) { Loop_Lecture->next = new LECTURE; if(Loop_Lecture->next == NULL) { cout << "Reading Failed.. (Memory Overflow)"; return false; } Loop_Lecture = Loop_Lecture->next; } else Loop_Lecture = Loop_Lecture->next; if(fin.eof()) break; }while(1); fin.close(); return true; } int SameList::AddList(wchar_t cd[CODE_LENGTH]) { if(next != NULL) { int i = 0; for(i = 0; i < CODE_LENGTH; i++) { if(next->code[i] != cd[i]) break; } if(i != CODE_LENGTH) return next->AddList(cd); else return 0; } else { next = new SameList(cd); return 1; } } SameList::SameList(wchar_t cd[]) { wcscpy_s(code, cd); next= NULL; } void SameList::GetCode(int n, wchar_t cd[]) { if(n == 0) { if(next != NULL) wcscpy_s(cd, CODE_LENGTH, next->code); else cd[0] = '\0'; } else next->GetCode(n-1, cd); } MyLecture::MyLecture(LECTURE *lc) { Lecture = lc; next = NULL; } int MyLecture::AddLecture(LECTURE *lc) { if(next != NULL) { if(Check_TT_Duplicate(next->Lecture, lc) == 1) return next->AddLecture(lc); else return 0; } else { next = new MyLecture(lc); return 1; } } void MyLecture::DelLecture(LECTURE *lc) { if(next != NULL) { if(next->Lecture == lc) { MyLecture* temp; temp = next; next = next->next; temp->next = NULL; delete temp; } else next->DelLecture(lc); } } int MyLecture::CheckLecture(LECTURE *lc) { if(next != NULL) { if(next->Lecture == lc) return 1; else return next->CheckLecture(lc); } else return 0; } MyLecture::~MyLecture() { Lecture = NULL; if(next != NULL) delete next; } int Check_TT_Duplicate(LECTURE *a, LECTURE *b) { for(int i = 0; i < MAX_TIME_COUNT * MAX_TIME_COUNT; i++) { if(IS_DAY_VALIED(a->time_info[i / MAX_TIME_COUNT] & b->time_info[i % MAX_TIME_COUNT])) { if(GET_ONLY_TIME(a->time_info[i / MAX_TIME_COUNT] & b->time_info[i % MAX_TIME_COUNT])) return 0; } } return 1; } LECTURE* MyLecture::GetLecture() { return Lecture; } MyLecture* MyLecture::GetNext() { return next; }<commit_msg>tonumber() 함수에 비정상 입력값이 있은 경우 _ASSERT() 발생<commit_after>#include <iostream> using namespace std; #include <fstream> #include "Lecture.h" #include <cstring> #include <locale> bool isnumber(wchar_t ch) { if(ch >= L'0' && ch <= L'9') return true; return false; } int tonumber(wchar_t ch) { if (ch < L'0' || ch > L'9') _ASSERT(false); return int(ch) - int(L'0'); } int tonumber(wchar_t ch, wchar_t ch2) { if (ch < L'0' || ch > L'9' || ch2 < L'0' || ch2 > L'9') _ASSERT(false); return (int(ch) - int(L'0')) * 10 + (int(ch2) - int(L'0')); } int LECTURE::Open_Lecture(const wchar_t* const Filename, LECTURE *Lecture) { LECTURE *Loop_Lecture; wchar_t ch; wchar_t ch2; wchar_t ch3; wchar_t dummy; wchar_t* temp; int i; int j; int to; int tmp; wifstream fin(Filename); if(!fin.is_open()) return false; fin.imbue(locale("kor")); Loop_Lecture = Lecture; do { // ڵ for(i = 0; i < BUFFER_LENGTH; i++) { fin.get(ch); if(ch == L'\n' || ch == L'\t') fin.get(ch); Loop_Lecture->code[i] = ch; } Loop_Lecture->code[BUFFER_LENGTH] = L'\0'; fin.get(ch); // \t remover temp = new wchar_t[TEMP_CHAR_SIZE]; // ̸ fin.get(ch); i = 0; do { temp[i] = ch; i++; fin.get(ch); }while(ch != L'\t'); temp[i] = L'\0'; int lectureNameLen = wcslen(temp) + 1; Loop_Lecture->name = new wchar_t[lectureNameLen]; wcscpy_s(Loop_Lecture->name, lectureNameLen, temp); Loop_Lecture->name[i] = L'\0'; delete[] temp; // fin >> Loop_Lecture->pou_srt; // ǽð fin >> Loop_Lecture->lecture; // ð fin >> Loop_Lecture->exp; // fin >> Loop_Lecture->plan_point; // й fin >> Loop_Lecture->div_class; fin.get(ch); // TAB REMOVER fin.get(ch); if(ch != '\t') //  Loop_Lecture->target_eng = ch; fin.get(ch); // TAB REMOVER // for(i = 0; i < MAJOR_COUNT; i++) { fin.get(ch); if(ch != L'\t') { fin.get(ch2); if(ch2 != L'\t') { fin.get(ch3); if(ch3 != L'\t') { fin.get(dummy); if(dummy != L'\t') { fin.get(dummy); if(dummy != L'\t') fin.get(dummy); } } else dummy = L'\t'; } else ch3 = L'\t'; } else { ch2 = L'\t'; ch3 = L'\t'; } if(ch != L'\t') { if(ch2 != L'\t') { if(isnumber(ch2)) { Loop_Lecture->major[i] = tonumber(ch, ch2); if(Loop_Lecture->major[i] == CT_norm_dummy) Loop_Lecture->major[i] = CT_norm_sel; if(ch3 != L'\t') { if(ch3 == L'S') { Loop_Lecture->major[i] = Loop_Lecture->major[i] | CT_MULTI_UNMAJOR; ch3 = dummy; } if(ch3 == L'T') { Loop_Lecture->major[i] = Loop_Lecture->major[i] | CT_MDTEACHER_LECTURE; if(ch3 == dummy) fin.get(dummy); } } } else { Loop_Lecture->major[i] = tonumber(ch); if(ch2 == L'S') { Loop_Lecture->major[i] = Loop_Lecture->major[i] | CT_MULTI_UNMAJOR; ch2 = ch3; } if(ch2 == L'T') { Loop_Lecture->major[i] = Loop_Lecture->major[i] | CT_MDTEACHER_LECTURE; } } } else { Loop_Lecture->major[i] = tonumber(ch); } } else { Loop_Lecture->major[i] = 0; } } // а/г temp = new wchar_t[200]; fin.get(ch); while(ch == L'\t' || ch == L'"') fin.get(ch); i = 0; while(ch != L'\t' && ch != L'"') { temp[i] = ch; i++; fin.get(ch); } temp[i] = L'\0'; int targetDepYearLen = wcslen(temp) + 1; Loop_Lecture->target_dep_year = new wchar_t[targetDepYearLen]; wcscpy_s(Loop_Lecture->target_dep_year, targetDepYearLen, temp); Loop_Lecture->target_dep_year[i] = L'\0'; delete[] temp; if(ch == L'"') fin.get(ch); // tab remover // 米 temp = new wchar_t[20]; fin.get(ch); if(ch == L'"') fin.get(ch); // " remover i = 0; while(ch != L'\t' && ch != L'"') { temp[i] = ch; i++; fin.get(ch); } temp[i] = L'\0'; if(ch == L'"') fin.get(ch); // tab remover int teacherNameLen = wcslen(temp) + 1; Loop_Lecture->teacher = new wchar_t[teacherNameLen]; wcscpy_s(Loop_Lecture->teacher, teacherNameLen, temp); Loop_Lecture->teacher[i] = L'\0'; delete[] temp; // ðǥ for (int i = 0; i < MAX_TIME_COUNT; i++) Loop_Lecture->time_info[i] = 0; while(true) { if(!fin.get(ch)) break; if(ch == L'\t') continue; if(ch == L'/') continue; if(ch == L' ') continue; if(ch != L'\n') { fin.get(dummy); for(j = 0; j < DAY_COUNT; j++) { if(ch == day_inf[j][0]) { break; } } if(j == DAY_COUNT) { cout << "Reading Failed.. (ðǥ:)"; return 0; } if(!IS_DAY_VALIED(Loop_Lecture->time_info[0])) { Loop_Lecture->time_info[0] = MON >> j; to = 0; } else if(Loop_Lecture->time_info[0] & (MON >> j)) { to = 0; } else if(!IS_DAY_VALIED(Loop_Lecture->time_info[1])) { Loop_Lecture->time_info[1] = MON >> j; to = 1; } else if(Loop_Lecture->time_info[1] & (MON >> j)) { to = 1; } else if(!IS_DAY_VALIED(Loop_Lecture->time_info[2])) { Loop_Lecture->time_info[2] = MON >> j; to = 2; } else if(Loop_Lecture->time_info[2] & (MON >> j)) { to = 2; } else { cout << "Reading Failed.. (ðǥ:ð)"; return 0; } fin.get(ch); fin.get(ch2); fin.get(ch3); fin.get(dummy); if (ch != L'\t' && ch2 != L'\t') { tmp = tonumber(ch, ch2) - 1; tmp *= 2; if (ch3 == 'B') tmp++; if (tmp >= 24) tmp = 24; // 13A ̻ ð tovr Loop_Lecture->time_info[to] = Loop_Lecture->time_info[to] | tt_inf[tmp]; } if(dummy == L'\n') break; } else break; } Loop_Lecture->valid = 1; if(Loop_Lecture->next == NULL) { Loop_Lecture->next = new LECTURE; if(Loop_Lecture->next == NULL) { cout << "Reading Failed.. (Memory Overflow)"; return false; } Loop_Lecture = Loop_Lecture->next; } else Loop_Lecture = Loop_Lecture->next; if(fin.eof()) break; }while(1); fin.close(); return true; } int SameList::AddList(wchar_t cd[CODE_LENGTH]) { if(next != NULL) { int i = 0; for(i = 0; i < CODE_LENGTH; i++) { if(next->code[i] != cd[i]) break; } if(i != CODE_LENGTH) return next->AddList(cd); else return 0; } else { next = new SameList(cd); return 1; } } SameList::SameList(wchar_t cd[]) { wcscpy_s(code, cd); next= NULL; } void SameList::GetCode(int n, wchar_t cd[]) { if(n == 0) { if(next != NULL) wcscpy_s(cd, CODE_LENGTH, next->code); else cd[0] = '\0'; } else next->GetCode(n-1, cd); } MyLecture::MyLecture(LECTURE *lc) { Lecture = lc; next = NULL; } int MyLecture::AddLecture(LECTURE *lc) { if(next != NULL) { if(Check_TT_Duplicate(next->Lecture, lc) == 1) return next->AddLecture(lc); else return 0; } else { next = new MyLecture(lc); return 1; } } void MyLecture::DelLecture(LECTURE *lc) { if(next != NULL) { if(next->Lecture == lc) { MyLecture* temp; temp = next; next = next->next; temp->next = NULL; delete temp; } else next->DelLecture(lc); } } int MyLecture::CheckLecture(LECTURE *lc) { if(next != NULL) { if(next->Lecture == lc) return 1; else return next->CheckLecture(lc); } else return 0; } MyLecture::~MyLecture() { Lecture = NULL; if(next != NULL) delete next; } int Check_TT_Duplicate(LECTURE *a, LECTURE *b) { for(int i = 0; i < MAX_TIME_COUNT * MAX_TIME_COUNT; i++) { if(IS_DAY_VALIED(a->time_info[i / MAX_TIME_COUNT] & b->time_info[i % MAX_TIME_COUNT])) { if(GET_ONLY_TIME(a->time_info[i / MAX_TIME_COUNT] & b->time_info[i % MAX_TIME_COUNT])) return 0; } } return 1; } LECTURE* MyLecture::GetLecture() { return Lecture; } MyLecture* MyLecture::GetNext() { return next; }<|endoftext|>
<commit_before>#include <QNetworkInterface> #include <QJsonObject> #include <QJsonDocument> #include <QCoreApplication> #include <QSettings> #include "DiscoveryServer.h" #include "Data.h" #include "Database.h" /* TODO: implement a security process based on activation * Client send Discovery process with an UUID, EMS check if * this UUID is known, if it's the case, we accept the request * and send back the DISCOVERY answer. * If it's not the case, we need to find a way to display a popup * on the screen to ask the user to accept the connection request * for this new UUID. * How to do that ? Creating a pipe for Inter process communication * between EMS and the UI, only for connexion inside the same machine ? * Have the connection between EMS and the UI on the same device * through a simple TCPSocket instead through websocket ? And let the * websockets connexion for the UI outside machine ? */ DiscoveryServer::DiscoveryServer(quint16 port, QObject *parent) : QObject(parent) { m_socket = new QUdpSocket(this); m_socket->bind(QHostAddress::AnyIPv4, port); qDebug() << "Udp Discovery server listening on port " << port; connect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead())); } DiscoveryServer::~DiscoveryServer() { delete m_socket; } void DiscoveryServer::readyRead() { QByteArray buffer; buffer.resize(m_socket->pendingDatagramSize()); ClientConnectionParam sender_param; bool isLocalGUI = false; bool isClientAlreadyAccepted = false; Database *db = Database::instance(); QHostAddress loopback_addr = QHostAddress::LocalHost; // Read data received m_socket->readDatagram(buffer.data(), buffer.size(), &sender_param.ip, &sender_param.port); QJsonParseError err; QJsonDocument j = QJsonDocument::fromJson(buffer, &err); // Error reading Json if (err.error!= QJsonParseError::NoError) { return; } qDebug() << "UUID :" << j.object()["uuid"].toString(); QHostAddress local_address; // Get the local address foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) { local_address = address; } } if ((sender_param.ip == local_address) || (sender_param.ip == QHostAddress::LocalHost)) { isLocalGUI = true; } // Build the EMSClient data EMSClient client; client.uuid = j.object()["uuid"].toString(); if (isLocalGUI) { client.hostname = loopback_addr.toString(); } else { client.hostname = sender_param.ip.toString(); } isClientAlreadyAccepted = db->getAuthorizedClient(client.uuid, &client); qDebug() << "Database: is client already accepted : " << isClientAlreadyAccepted; // Local client usecase: accept the client if (!isClientAlreadyAccepted && isLocalGUI) { db->insertNewAuthorizedClient(&client); this->sendAcceptAnswer(sender_param); } // Already accepted clients usecase else if (isClientAlreadyAccepted) { this->sendAcceptAnswer(sender_param); } // Other unknown clients usecase else{ this->sendAuthenticationRequest(client.uuid, sender_param); } } void DiscoveryServer::sendDiscoveryAnswer(const ClientConnectionParam &client_param, const QString &status) { QSettings settings; // Create object containing the answer QJsonObject jobj; jobj["action"] = "EMS_DISCOVER"; jobj["status"] = status; jobj["ip"] = client_param.ip.toString(); jobj["port"] = settings.value("main/websocket_port").toInt(); qDebug() << "EMS_DISCOVER (status: " << status << ") Client Addr: " << client_param.ip.toString() << ", port: " << settings.value("main/websocket_port").toInt(); QJsonDocument jdoc(jobj); // Convert json object into datagram QByteArray datagram = jdoc.toJson(QJsonDocument::Compact); // Send the data m_socket->writeDatagram(datagram.data(), datagram.size(), client_param.ip, client_param.port); } void DiscoveryServer::sendAcceptAnswer(const ClientConnectionParam &client_param) { this->sendDiscoveryAnswer(client_param, "accepted"); } void DiscoveryServer::sendAuthenticationRequest(const QString &uuid, const ClientConnectionParam &client_param) { // First, send the EMS_DISCOVER 'pending' answer to the new client this->sendDiscoveryAnswer(client_param, "pending"); // and save the pending client properties m_pending_clients[uuid] = client_param; // Next, start the authentication with the local UI emit authenticationNeeded(uuid); } <commit_msg>Accept client: fix the database access with 'lock()' and 'unlock()'<commit_after>#include <QNetworkInterface> #include <QJsonObject> #include <QJsonDocument> #include <QCoreApplication> #include <QSettings> #include "DiscoveryServer.h" #include "Data.h" #include "Database.h" /* TODO: implement a security process based on activation * Client send Discovery process with an UUID, EMS check if * this UUID is known, if it's the case, we accept the request * and send back the DISCOVERY answer. * If it's not the case, we need to find a way to display a popup * on the screen to ask the user to accept the connection request * for this new UUID. * How to do that ? Creating a pipe for Inter process communication * between EMS and the UI, only for connexion inside the same machine ? * Have the connection between EMS and the UI on the same device * through a simple TCPSocket instead through websocket ? And let the * websockets connexion for the UI outside machine ? */ DiscoveryServer::DiscoveryServer(quint16 port, QObject *parent) : QObject(parent) { m_socket = new QUdpSocket(this); m_socket->bind(QHostAddress::AnyIPv4, port); qDebug() << "Udp Discovery server listening on port " << port; connect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead())); } DiscoveryServer::~DiscoveryServer() { delete m_socket; } void DiscoveryServer::readyRead() { QByteArray buffer; buffer.resize(m_socket->pendingDatagramSize()); ClientConnectionParam sender_param; bool isLocalGUI = false; bool isClientAlreadyAccepted = false; Database *db = Database::instance(); QHostAddress loopback_addr = QHostAddress::LocalHost; // Read data received m_socket->readDatagram(buffer.data(), buffer.size(), &sender_param.ip, &sender_param.port); QJsonParseError err; QJsonDocument j = QJsonDocument::fromJson(buffer, &err); // Error reading Json if (err.error!= QJsonParseError::NoError) { return; } qDebug() << "UUID :" << j.object()["uuid"].toString(); QHostAddress local_address; // Get the local address foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) { local_address = address; } } if ((sender_param.ip == local_address) || (sender_param.ip == QHostAddress::LocalHost)) { isLocalGUI = true; } // Build the EMSClient data EMSClient client; client.uuid = j.object()["uuid"].toString(); if (isLocalGUI) { client.hostname = loopback_addr.toString(); } else { client.hostname = sender_param.ip.toString(); } db->lock(); isClientAlreadyAccepted = db->getAuthorizedClient(client.uuid, &client); db->unlock(); qDebug() << "Database: is client already accepted : " << isClientAlreadyAccepted; // Local client usecase: accept the client if (!isClientAlreadyAccepted && isLocalGUI) { db->lock(); db->insertNewAuthorizedClient(&client); db->unlock(); this->sendAcceptAnswer(sender_param); } // Already accepted clients usecase else if (isClientAlreadyAccepted) { this->sendAcceptAnswer(sender_param); } // Other unknown clients usecase else{ this->sendAuthenticationRequest(client.uuid, sender_param); } } void DiscoveryServer::sendDiscoveryAnswer(const ClientConnectionParam &client_param, const QString &status) { QSettings settings; // Create object containing the answer QJsonObject jobj; jobj["action"] = "EMS_DISCOVER"; jobj["status"] = status; jobj["ip"] = client_param.ip.toString(); jobj["port"] = settings.value("main/websocket_port").toInt(); qDebug() << "EMS_DISCOVER (status: " << status << ") Client Addr: " << client_param.ip.toString() << ", port: " << settings.value("main/websocket_port").toInt(); QJsonDocument jdoc(jobj); // Convert json object into datagram QByteArray datagram = jdoc.toJson(QJsonDocument::Compact); // Send the data m_socket->writeDatagram(datagram.data(), datagram.size(), client_param.ip, client_param.port); } void DiscoveryServer::sendAcceptAnswer(const ClientConnectionParam &client_param) { this->sendDiscoveryAnswer(client_param, "accepted"); } void DiscoveryServer::sendAuthenticationRequest(const QString &uuid, const ClientConnectionParam &client_param) { // First, send the EMS_DISCOVER 'pending' answer to the new client this->sendDiscoveryAnswer(client_param, "pending"); // and save the pending client properties m_pending_clients[uuid] = client_param; // Next, start the authentication with the local UI emit authenticationNeeded(uuid); } <|endoftext|>
<commit_before>#ifndef ENTT_META_CONTAINER_HPP #define ENTT_META_CONTAINER_HPP #include <array> #include <map> #include <set> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> #include "meta.hpp" #include "type_traits.hpp" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename, typename = void> struct is_dynamic_sequence_container: std::false_type {}; template<typename Type> struct is_dynamic_sequence_container<Type, std::void_t<decltype(&Type::reserve)>>: std::true_type {}; template<typename, typename = void> struct is_key_only_meta_associative_container: std::true_type {}; template<typename Type> struct is_key_only_meta_associative_container<Type, std::void_t<typename Type::mapped_type>>: std::false_type {}; template<typename Type> struct basic_meta_sequence_container_traits { using iterator = meta_sequence_container::iterator; using size_type = std::size_t; [[nodiscard]] static size_type size(const any &container) ENTT_NOEXCEPT { return any_cast<const Type &>(container).size(); } [[nodiscard]] static bool resize(any &container, size_type sz) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto * const cont = any_cast<Type>(&container); cont) { cont->resize(sz); return true; } } return false; } [[nodiscard]] static bool clear(any &container) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto * const cont = any_cast<Type>(&container); cont) { cont->clear(); return true; } } return false; } [[nodiscard]] static iterator begin(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::begin(*cont)}; } return iterator{std::begin(any_cast<const Type &>(container))}; } [[nodiscard]] static iterator end(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::end(*cont)}; } return iterator{std::end(any_cast<const Type &>(container))}; } [[nodiscard]] static iterator insert(any &container, iterator it, meta_any &value) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto * const cont = any_cast<Type>(&container); cont) { // this abomination is necessary because only on macos value_type and const_reference are different types for std::vector<bool> if(value.allow_cast<typename Type::const_reference>() || value.allow_cast<typename Type::value_type>()) { const auto *element = value.try_cast<std::remove_reference_t<typename Type::const_reference>>(); return iterator{cont->insert(any_cast<const typename Type::iterator &>(it.base()), element ? *element : value.cast<typename Type::value_type>())}; } } } return {}; } [[nodiscard]] static iterator erase(any &container, iterator it) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{cont->erase(any_cast<const typename Type::iterator &>(it.base()))}; } } return {}; } [[nodiscard]] static meta_any get(any &container, size_type pos) { if(auto * const cont = any_cast<Type>(&container); cont) { return meta_any{std::in_place_type<typename Type::reference>, (*cont)[pos]}; } return meta_any{std::in_place_type<typename Type::const_reference>, any_cast<const Type &>(container)[pos]}; } }; template<typename Type> struct basic_meta_associative_container_traits { using iterator = meta_associative_container::iterator; using size_type = std::size_t; [[nodiscard]] static constexpr bool key_only() ENTT_NOEXCEPT { return is_key_only_meta_associative_container<Type>::value; } [[nodiscard]] static size_type size(const any &container) ENTT_NOEXCEPT { return any_cast<const Type &>(container).size(); } [[nodiscard]] static bool clear(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { cont->clear(); return true; } return false; } [[nodiscard]] static iterator begin(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only()>{}, cont->begin()}; } return iterator{std::integral_constant<bool, key_only()>{}, std::begin(any_cast<const Type &>(container))}; } [[nodiscard]] static iterator end(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only()>{}, cont->end()}; } return iterator{std::integral_constant<bool, key_only()>{}, std::end(any_cast<const Type &>(container))}; } [[nodiscard]] static bool insert(any &container, meta_any &key, meta_any &value) { if(auto * const cont = any_cast<Type>(&container); cont && key.allow_cast<const typename Type::key_type &>()) { if constexpr(is_key_only_meta_associative_container<Type>::value) { return cont->insert(key.cast<const typename Type::key_type &>()).second; } else { if(value.allow_cast<const typename Type::mapped_type &>()) { return cont->emplace(key.cast<const typename Type::key_type &>(), value.cast<const typename Type::mapped_type &>()).second; } } } return false; } [[nodiscard]] static bool erase(any &container, meta_any &key) { if(auto * const cont = any_cast<Type>(&container); cont && key.allow_cast<const typename Type::key_type &>()) { return (cont->erase(key.cast<const typename Type::key_type &>()) != cont->size()); } return false; } [[nodiscard]] static iterator find(any &container, meta_any &key) { if(key.allow_cast<const typename Type::key_type &>()) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only()>{}, cont->find(key.cast<const typename Type::key_type &>())}; } return iterator{std::integral_constant<bool, key_only()>{}, any_cast<const Type &>(container).find(key.cast<const typename Type::key_type &>())}; } return {}; } }; } /** * Internal details not to be documented. * @endcond */ /** * @brief Meta sequence container traits for `std::vector`s of any type. * @tparam Type The type of elements. * @tparam Args Other arguments. */ template<typename Type, typename... Args> struct meta_sequence_container_traits<std::vector<Type, Args...>> : internal::basic_meta_sequence_container_traits<std::vector<Type, Args...>> {}; /** * @brief Meta sequence container traits for `std::array`s of any type. * @tparam Type The type of elements. * @tparam N The number of elements. */ template<typename Type, auto N> struct meta_sequence_container_traits<std::array<Type, N>> : internal::basic_meta_sequence_container_traits<std::array<Type, N>> {}; /** * @brief Meta associative container traits for `std::map`s of any type. * @tparam Key The key type of elements. * @tparam Value The value type of elements. * @tparam Args Other arguments. */ template<typename Key, typename Value, typename... Args> struct meta_associative_container_traits<std::map<Key, Value, Args...>> : internal::basic_meta_associative_container_traits<std::map<Key, Value, Args...>> {}; /** * @brief Meta associative container traits for `std::unordered_map`s of any * type. * @tparam Key The key type of elements. * @tparam Value The value type of elements. * @tparam Args Other arguments. */ template<typename Key, typename Value, typename... Args> struct meta_associative_container_traits<std::unordered_map<Key, Value, Args...>> : internal::basic_meta_associative_container_traits<std::unordered_map<Key, Value, Args...>> {}; /** * @brief Meta associative container traits for `std::set`s of any type. * @tparam Key The type of elements. * @tparam Args Other arguments. */ template<typename Key, typename... Args> struct meta_associative_container_traits<std::set<Key, Args...>> : internal::basic_meta_associative_container_traits<std::set<Key, Args...>> {}; /** * @brief Meta associative container traits for `std::unordered_set`s of any * type. * @tparam Key The type of elements. * @tparam Args Other arguments. */ template<typename Key, typename... Args> struct meta_associative_container_traits<std::unordered_set<Key, Args...>> : internal::basic_meta_associative_container_traits<std::unordered_set<Key, Args...>> {}; } #endif <commit_msg>meta: added missing [[maybe_unused]] to suppress warnings<commit_after>#ifndef ENTT_META_CONTAINER_HPP #define ENTT_META_CONTAINER_HPP #include <array> #include <map> #include <set> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> #include "meta.hpp" #include "type_traits.hpp" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename, typename = void> struct is_dynamic_sequence_container: std::false_type {}; template<typename Type> struct is_dynamic_sequence_container<Type, std::void_t<decltype(&Type::reserve)>>: std::true_type {}; template<typename, typename = void> struct is_key_only_meta_associative_container: std::true_type {}; template<typename Type> struct is_key_only_meta_associative_container<Type, std::void_t<typename Type::mapped_type>>: std::false_type {}; template<typename Type> struct basic_meta_sequence_container_traits { using iterator = meta_sequence_container::iterator; using size_type = std::size_t; [[nodiscard]] static size_type size(const any &container) ENTT_NOEXCEPT { return any_cast<const Type &>(container).size(); } [[nodiscard]] static bool resize([[maybe_unused]] any &container, [[maybe_unused]] size_type sz) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto * const cont = any_cast<Type>(&container); cont) { cont->resize(sz); return true; } } return false; } [[nodiscard]] static bool clear([[maybe_unused]] any &container) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto * const cont = any_cast<Type>(&container); cont) { cont->clear(); return true; } } return false; } [[nodiscard]] static iterator begin(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::begin(*cont)}; } return iterator{std::begin(any_cast<const Type &>(container))}; } [[nodiscard]] static iterator end(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::end(*cont)}; } return iterator{std::end(any_cast<const Type &>(container))}; } [[nodiscard]] static iterator insert([[maybe_unused]] any &container, [[maybe_unused]] iterator it, [[maybe_unused]] meta_any &value) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto * const cont = any_cast<Type>(&container); cont) { // this abomination is necessary because only on macos value_type and const_reference are different types for std::vector<bool> if(value.allow_cast<typename Type::const_reference>() || value.allow_cast<typename Type::value_type>()) { const auto *element = value.try_cast<std::remove_reference_t<typename Type::const_reference>>(); return iterator{cont->insert(any_cast<const typename Type::iterator &>(it.base()), element ? *element : value.cast<typename Type::value_type>())}; } } } return {}; } [[nodiscard]] static iterator erase([[maybe_unused]] any &container, [[maybe_unused]] iterator it) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{cont->erase(any_cast<const typename Type::iterator &>(it.base()))}; } } return {}; } [[nodiscard]] static meta_any get(any &container, size_type pos) { if(auto * const cont = any_cast<Type>(&container); cont) { return meta_any{std::in_place_type<typename Type::reference>, (*cont)[pos]}; } return meta_any{std::in_place_type<typename Type::const_reference>, any_cast<const Type &>(container)[pos]}; } }; template<typename Type> struct basic_meta_associative_container_traits { using iterator = meta_associative_container::iterator; using size_type = std::size_t; [[nodiscard]] static constexpr bool key_only() ENTT_NOEXCEPT { return is_key_only_meta_associative_container<Type>::value; } [[nodiscard]] static size_type size(const any &container) ENTT_NOEXCEPT { return any_cast<const Type &>(container).size(); } [[nodiscard]] static bool clear(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { cont->clear(); return true; } return false; } [[nodiscard]] static iterator begin(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only()>{}, cont->begin()}; } return iterator{std::integral_constant<bool, key_only()>{}, std::begin(any_cast<const Type &>(container))}; } [[nodiscard]] static iterator end(any &container) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only()>{}, cont->end()}; } return iterator{std::integral_constant<bool, key_only()>{}, std::end(any_cast<const Type &>(container))}; } [[nodiscard]] static bool insert(any &container, meta_any &key, [[maybe_unused]] meta_any &value) { if(auto * const cont = any_cast<Type>(&container); cont && key.allow_cast<const typename Type::key_type &>()) { if constexpr(is_key_only_meta_associative_container<Type>::value) { return cont->insert(key.cast<const typename Type::key_type &>()).second; } else { if(value.allow_cast<const typename Type::mapped_type &>()) { return cont->emplace(key.cast<const typename Type::key_type &>(), value.cast<const typename Type::mapped_type &>()).second; } } } return false; } [[nodiscard]] static bool erase(any &container, meta_any &key) { if(auto * const cont = any_cast<Type>(&container); cont && key.allow_cast<const typename Type::key_type &>()) { return (cont->erase(key.cast<const typename Type::key_type &>()) != cont->size()); } return false; } [[nodiscard]] static iterator find(any &container, meta_any &key) { if(key.allow_cast<const typename Type::key_type &>()) { if(auto * const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only()>{}, cont->find(key.cast<const typename Type::key_type &>())}; } return iterator{std::integral_constant<bool, key_only()>{}, any_cast<const Type &>(container).find(key.cast<const typename Type::key_type &>())}; } return {}; } }; } /** * Internal details not to be documented. * @endcond */ /** * @brief Meta sequence container traits for `std::vector`s of any type. * @tparam Type The type of elements. * @tparam Args Other arguments. */ template<typename Type, typename... Args> struct meta_sequence_container_traits<std::vector<Type, Args...>> : internal::basic_meta_sequence_container_traits<std::vector<Type, Args...>> {}; /** * @brief Meta sequence container traits for `std::array`s of any type. * @tparam Type The type of elements. * @tparam N The number of elements. */ template<typename Type, auto N> struct meta_sequence_container_traits<std::array<Type, N>> : internal::basic_meta_sequence_container_traits<std::array<Type, N>> {}; /** * @brief Meta associative container traits for `std::map`s of any type. * @tparam Key The key type of elements. * @tparam Value The value type of elements. * @tparam Args Other arguments. */ template<typename Key, typename Value, typename... Args> struct meta_associative_container_traits<std::map<Key, Value, Args...>> : internal::basic_meta_associative_container_traits<std::map<Key, Value, Args...>> {}; /** * @brief Meta associative container traits for `std::unordered_map`s of any * type. * @tparam Key The key type of elements. * @tparam Value The value type of elements. * @tparam Args Other arguments. */ template<typename Key, typename Value, typename... Args> struct meta_associative_container_traits<std::unordered_map<Key, Value, Args...>> : internal::basic_meta_associative_container_traits<std::unordered_map<Key, Value, Args...>> {}; /** * @brief Meta associative container traits for `std::set`s of any type. * @tparam Key The type of elements. * @tparam Args Other arguments. */ template<typename Key, typename... Args> struct meta_associative_container_traits<std::set<Key, Args...>> : internal::basic_meta_associative_container_traits<std::set<Key, Args...>> {}; /** * @brief Meta associative container traits for `std::unordered_set`s of any * type. * @tparam Key The type of elements. * @tparam Args Other arguments. */ template<typename Key, typename... Args> struct meta_associative_container_traits<std::unordered_set<Key, Args...>> : internal::basic_meta_associative_container_traits<std::unordered_set<Key, Args...>> {}; } #endif <|endoftext|>
<commit_before>#ifndef ENTT_RESOURCE_CACHE_HPP #define ENTT_RESOURCE_CACHE_HPP #include <type_traits> #include <unordered_map> #include <utility> #include "../config/config.h" #include "../core/fwd.hpp" #include "fwd.hpp" #include "handle.hpp" #include "loader.hpp" namespace entt { /** * @brief Simple cache for resources of a given type. * * Minimal implementation of a cache for resources of a given type. It doesn't * offer much functionalities but it's suitable for small or medium sized * applications and can be freely inherited to add targeted functionalities for * large sized applications. * * @tparam Resource Type of resources managed by a cache. */ template<typename Resource> struct resource_cache { /*! @brief Unsigned integer type. */ using size_type = std::size_t; /*! @brief Type of resources managed by a cache. */ using resource_type = Resource; /*! @brief Default constructor. */ resource_cache() = default; /*! @brief Default move constructor. */ resource_cache(resource_cache &&) = default; /*! @brief Default move assignment operator. @return This cache. */ resource_cache &operator=(resource_cache &&) = default; /** * @brief Number of resources managed by a cache. * @return Number of resources currently stored. */ [[nodiscard]] size_type size() const ENTT_NOEXCEPT { return resources.size(); } /** * @brief Returns true if a cache contains no resources, false otherwise. * @return True if the cache contains no resources, false otherwise. */ [[nodiscard]] bool empty() const ENTT_NOEXCEPT { return resources.empty(); } /** * @brief Clears a cache and discards all its resources. * * Handles are not invalidated and the memory used by a resource isn't * freed as long as at least a handle keeps the resource itself alive. */ void clear() ENTT_NOEXCEPT { resources.clear(); } /** * @brief Loads the resource that corresponds to a given identifier. * * In case an identifier isn't already present in the cache, it loads its * resource and stores it aside for future uses. Arguments are forwarded * directly to the loader in order to construct properly the requested * resource. * * @note * If the identifier is already present in the cache, this function does * nothing and the arguments are simply discarded. * * @warning * If the resource cannot be loaded correctly, the returned handle will be * invalid and any use of it will result in undefined behavior. * * @tparam Loader Type of loader to use to load the resource if required. * @tparam Args Types of arguments to use to load the resource if required. * @param id Unique resource identifier. * @param args Arguments to use to load the resource if required. * @return A handle for the given resource. */ template<typename Loader, typename... Args> resource_handle<Resource> load(const id_type id, Args &&...args) { if(auto it = resources.find(id); it == resources.cend()) { if(auto handle = temp<Loader>(std::forward<Args>(args)...); handle) { return (resources[id] = std::move(handle)); } } else { return it->second; } return {}; } /** * @brief Reloads a resource or loads it for the first time if not present. * * Equivalent to the following snippet (pseudocode): * * @code{.cpp} * cache.discard(id); * cache.load(id, args...); * @endcode * * Arguments are forwarded directly to the loader in order to construct * properly the requested resource. * * @warning * If the resource cannot be loaded correctly, the returned handle will be * invalid and any use of it will result in undefined behavior. * * @tparam Loader Type of loader to use to load the resource. * @tparam Args Types of arguments to use to load the resource. * @param id Unique resource identifier. * @param args Arguments to use to load the resource. * @return A handle for the given resource. */ template<typename Loader, typename... Args> resource_handle<Resource> reload(const id_type id, Args &&...args) { return (discard(id), load<Loader>(id, std::forward<Args>(args)...)); } /** * @brief Creates a temporary handle for a resource. * * Arguments are forwarded directly to the loader in order to construct * properly the requested resource. The handle isn't stored aside and the * cache isn't in charge of the lifetime of the resource itself. * * @tparam Loader Type of loader to use to load the resource. * @tparam Args Types of arguments to use to load the resource. * @param args Arguments to use to load the resource. * @return A handle for the given resource. */ template<typename Loader, typename... Args> [[nodiscard]] resource_handle<Resource> temp(Args &&...args) const { return Loader{}.get(std::forward<Args>(args)...); } /** * @brief Creates a handle for a given resource identifier. * * A resource handle can be in a either valid or invalid state. In other * terms, a resource handle is properly initialized with a resource if the * cache contains the resource itself. Otherwise the returned handle is * uninitialized and accessing it results in undefined behavior. * * @sa resource_handle * * @param id Unique resource identifier. * @return A handle for the given resource. */ [[nodiscard]] resource_handle<Resource> handle(const id_type id) const { if(auto it = resources.find(id); it != resources.cend()) { return it->second; } return {}; } /** * @brief Checks if a cache contains a given identifier. * @param id Unique resource identifier. * @return True if the cache contains the resource, false otherwise. */ [[nodiscard]] bool contains(const id_type id) const { return (resources.find(id) != resources.cend()); } /** * @brief Discards the resource that corresponds to a given identifier. * * Handles are not invalidated and the memory used by the resource isn't * freed as long as at least a handle keeps the resource itself alive. * * @param id Unique resource identifier. */ void discard(const id_type id) { if(auto it = resources.find(id); it != resources.end()) { resources.erase(it); } } /** * @brief Iterates all resources. * * The function object is invoked for each element. It is provided with * either the resource identifier, the resource handle or both of them.<br/> * The signature of the function must be equivalent to one of the following * forms: * * @code{.cpp} * void(const entt::id_type); * void(entt::resource_handle<Resource>); * void(const entt::id_type, entt::resource_handle<Resource>); * @endcode * * @tparam Func Type of the function object to invoke. * @param func A valid function object. */ template<typename Func> void each(Func func) const { auto begin = resources.begin(); auto end = resources.end(); while(begin != end) { auto curr = begin++; if constexpr(std::is_invocable_v<Func, id_type>) { func(curr->first); } else if constexpr(std::is_invocable_v<Func, resource_handle<Resource>>) { func(curr->second); } else { func(curr->first, curr->second); } } } private: std::unordered_map<id_type, resource_handle<Resource>> resources; }; } // namespace entt #endif <commit_msg>resource: strict check on resource type for cache<commit_after>#ifndef ENTT_RESOURCE_CACHE_HPP #define ENTT_RESOURCE_CACHE_HPP #include <type_traits> #include <unordered_map> #include <utility> #include "../config/config.h" #include "../core/fwd.hpp" #include "fwd.hpp" #include "handle.hpp" #include "loader.hpp" namespace entt { /** * @brief Simple cache for resources of a given type. * * Minimal implementation of a cache for resources of a given type. It doesn't * offer much functionalities but it's suitable for small or medium sized * applications and can be freely inherited to add targeted functionalities for * large sized applications. * * @tparam Resource Type of resources managed by a cache. */ template<typename Resource> class resource_cache { static_assert(std::is_same_v<Resource, std::remove_const_t<std::remove_reference_t<Resource>>>, "Invalid resource type"); public: /*! @brief Unsigned integer type. */ using size_type = std::size_t; /*! @brief Type of resources managed by a cache. */ using resource_type = Resource; /*! @brief Default constructor. */ resource_cache() = default; /*! @brief Default move constructor. */ resource_cache(resource_cache &&) = default; /*! @brief Default move assignment operator. @return This cache. */ resource_cache &operator=(resource_cache &&) = default; /** * @brief Number of resources managed by a cache. * @return Number of resources currently stored. */ [[nodiscard]] size_type size() const ENTT_NOEXCEPT { return resources.size(); } /** * @brief Returns true if a cache contains no resources, false otherwise. * @return True if the cache contains no resources, false otherwise. */ [[nodiscard]] bool empty() const ENTT_NOEXCEPT { return resources.empty(); } /** * @brief Clears a cache and discards all its resources. * * Handles are not invalidated and the memory used by a resource isn't * freed as long as at least a handle keeps the resource itself alive. */ void clear() ENTT_NOEXCEPT { resources.clear(); } /** * @brief Loads the resource that corresponds to a given identifier. * * In case an identifier isn't already present in the cache, it loads its * resource and stores it aside for future uses. Arguments are forwarded * directly to the loader in order to construct properly the requested * resource. * * @note * If the identifier is already present in the cache, this function does * nothing and the arguments are simply discarded. * * @warning * If the resource cannot be loaded correctly, the returned handle will be * invalid and any use of it will result in undefined behavior. * * @tparam Loader Type of loader to use to load the resource if required. * @tparam Args Types of arguments to use to load the resource if required. * @param id Unique resource identifier. * @param args Arguments to use to load the resource if required. * @return A handle for the given resource. */ template<typename Loader, typename... Args> resource_handle<resource_type> load(const id_type id, Args &&...args) { if(auto it = resources.find(id); it == resources.cend()) { if(auto handle = temp<Loader>(std::forward<Args>(args)...); handle) { return (resources[id] = std::move(handle)); } } else { return it->second; } return {}; } /** * @brief Reloads a resource or loads it for the first time if not present. * * Equivalent to the following snippet (pseudocode): * * @code{.cpp} * cache.discard(id); * cache.load(id, args...); * @endcode * * Arguments are forwarded directly to the loader in order to construct * properly the requested resource. * * @warning * If the resource cannot be loaded correctly, the returned handle will be * invalid and any use of it will result in undefined behavior. * * @tparam Loader Type of loader to use to load the resource. * @tparam Args Types of arguments to use to load the resource. * @param id Unique resource identifier. * @param args Arguments to use to load the resource. * @return A handle for the given resource. */ template<typename Loader, typename... Args> resource_handle<resource_type> reload(const id_type id, Args &&...args) { return (discard(id), load<Loader>(id, std::forward<Args>(args)...)); } /** * @brief Creates a temporary handle for a resource. * * Arguments are forwarded directly to the loader in order to construct * properly the requested resource. The handle isn't stored aside and the * cache isn't in charge of the lifetime of the resource itself. * * @tparam Loader Type of loader to use to load the resource. * @tparam Args Types of arguments to use to load the resource. * @param args Arguments to use to load the resource. * @return A handle for the given resource. */ template<typename Loader, typename... Args> [[nodiscard]] resource_handle<resource_type> temp(Args &&...args) const { return Loader{}.get(std::forward<Args>(args)...); } /** * @brief Creates a handle for a given resource identifier. * * A resource handle can be in a either valid or invalid state. In other * terms, a resource handle is properly initialized with a resource if the * cache contains the resource itself. Otherwise the returned handle is * uninitialized and accessing it results in undefined behavior. * * @sa resource_handle * * @param id Unique resource identifier. * @return A handle for the given resource. */ [[nodiscard]] resource_handle<resource_type> handle(const id_type id) const { if(auto it = resources.find(id); it != resources.cend()) { return it->second; } return {}; } /** * @brief Checks if a cache contains a given identifier. * @param id Unique resource identifier. * @return True if the cache contains the resource, false otherwise. */ [[nodiscard]] bool contains(const id_type id) const { return (resources.find(id) != resources.cend()); } /** * @brief Discards the resource that corresponds to a given identifier. * * Handles are not invalidated and the memory used by the resource isn't * freed as long as at least a handle keeps the resource itself alive. * * @param id Unique resource identifier. */ void discard(const id_type id) { if(auto it = resources.find(id); it != resources.end()) { resources.erase(it); } } /** * @brief Iterates all resources. * * The function object is invoked for each element. It is provided with * either the resource identifier, the resource handle or both of them.<br/> * The signature of the function must be equivalent to one of the following * forms: * * @code{.cpp} * void(const entt::id_type); * void(entt::resource_handle<resource_type>); * void(const entt::id_type, entt::resource_handle<resource_type>); * @endcode * * @tparam Func Type of the function object to invoke. * @param func A valid function object. */ template<typename Func> void each(Func func) const { auto begin = resources.begin(); auto end = resources.end(); while(begin != end) { auto curr = begin++; if constexpr(std::is_invocable_v<Func, id_type>) { func(curr->first); } else if constexpr(std::is_invocable_v<Func, resource_handle<resource_type>>) { func(curr->second); } else { func(curr->first, curr->second); } } } private: std::unordered_map<id_type, resource_handle<resource_type>> resources; }; } // namespace entt #endif <|endoftext|>
<commit_before>// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // #include "ArticyFlowPlayer.h" #include "ArticyRuntimeModule.h" #include "Interfaces/ArticyFlowObject.h" #include "Interfaces/ArticyObjectWithSpeaker.h" #include "ArticyExpressoScripts.h" #include "UObject/ConstructorHelpers.h" #include "Interfaces/ArticyInputPinsProvider.h" #include "Interfaces/ArticyOutputPinsProvider.h" #include "Engine/Texture2D.h" TScriptInterface<IArticyFlowObject> FArticyBranch::GetTarget() const { return Path.Num() > 0 ? Path.Last() : nullptr; } void UArticyFlowPlayer::BeginPlay() { Super::BeginPlay(); //update Cursor to object referenced by StartOn SetCursorToStartNode(); } //---------------------------------------------------------------------------// void UArticyFlowPlayer::SetStartNode(FArticyRef StartNodeId) { StartOn.SetId(StartNodeId.GetId()); SetCursorToStartNode(); } void UArticyFlowPlayer::SetStartNodeWithFlowObject(TScriptInterface<IArticyFlowObject> Node) { FArticyRef ArticyRef; ArticyRef.SetReference(Cast<UArticyObject>(Node.GetObject())); SetStartNode(ArticyRef); } void UArticyFlowPlayer::SetStartNodeById(FArticyId NewId) { StartOn.SetId(NewId); SetCursorToStartNode(); } void UArticyFlowPlayer::SetCursorTo(TScriptInterface<IArticyFlowObject> Node) { if(!Node.GetObject()) { UE_LOG(LogArticyRuntime, Warning, TEXT("Could not set cursor in flow player of actor %s: invalid node"), *this->GetOwner()->GetName()); return; } Cursor = Node; UpdateAvailableBranches(); } void UArticyFlowPlayer::Play(int BranchIndex) { TArray<FArticyBranch> branches; if (IgnoresInvalidBranches()) { for (auto branch : AvailableBranches) if (branch.bIsValid) branches.Add(branch); } else { branches = AvailableBranches; } //check if the specified branch exists if(!branches.IsValidIndex(BranchIndex)) { UE_LOG(LogArticyRuntime, Error, TEXT("Branch with index %d does not exist!"), BranchIndex) return; } PlayBranch(branches[BranchIndex]); } void UArticyFlowPlayer::FinishCurrentPausedObject(int PinIndex) { IArticyOutputPinsProvider* outputPinOwner = Cast<IArticyOutputPinsProvider>(Cursor.GetObject()); if (outputPinOwner) { auto outputPins = outputPinOwner->GetOutputPinsPtr(); if (outputPins->Num() > 0) { if (PinIndex < outputPins->Num()) { (*outputPins)[PinIndex]->Execute(GetGVs(), GetMethodsProvider()); } else UE_LOG(LogArticyRuntime, Warning, TEXT("FinishCurrentPausedObject: The index was out of bounds: Index: %d, PinCount: %d"), PinIndex, outputPins->Num()); } } } bool UArticyFlowPlayer::ShouldPauseOn(IArticyFlowObject* Node) const { return Node && (1 << static_cast<uint8>(Node->GetType()) & PauseOn); } bool UArticyFlowPlayer::ShouldPauseOn(TScriptInterface<IArticyFlowObject> Node) const { return ShouldPauseOn(Cast<IArticyFlowObject>(Node.GetObject())); } UArticyDatabase* UArticyFlowPlayer::GetDB() const { return UArticyDatabase::Get(this); } UArticyGlobalVariables* UArticyFlowPlayer::GetGVs() const { return OverrideGV ? OverrideGV : UArticyGlobalVariables::GetDefault(this); } UObject* UArticyFlowPlayer::GetMethodsProvider() const { auto expressoInstance = GetDB()->GetExpressoInstance(); auto provider = expressoInstance->GetUserMethodsProviderInterface(); if (expressoInstance->UserMethodsProvider != nullptr && UserMethodsProvider == nullptr)//MM_CHANGE UserMethodsProvider = expressoInstance->UserMethodsProvider; if(ensure(provider)) { //check if the set provider implements the required interface if(!UserMethodsProvider || !ensure(UserMethodsProvider->GetClass()->ImplementsInterface(provider))) { //no valid UserMethodsProvider set, search for it //check if the flow player itself implements it if(GetClass()->ImplementsInterface(provider)) UserMethodsProvider = const_cast<UArticyFlowPlayer*>(this); else { auto actor = GetOwner(); if(ensure(actor)) { //check if the flow player's owning actor implements it if(actor->GetClass()->ImplementsInterface(provider)) UserMethodsProvider = actor; else { //check if any other component implements it auto components = actor->GetComponents(); for(auto comp : components) { if(comp->GetClass()->ImplementsInterface(provider)) { UserMethodsProvider = comp; break; } } //and finally we check for a default methods provider, which we can use as fallback auto defaultUserMethodsProvider = expressoInstance->DefaultUserMethodsProvider; if(defaultUserMethodsProvider && ensure(defaultUserMethodsProvider->GetClass()->ImplementsInterface(provider))) UserMethodsProvider = defaultUserMethodsProvider; } } } } } return UserMethodsProvider; } IArticyFlowObject* UArticyFlowPlayer::GetUnshadowedNode(IArticyFlowObject* Node) { auto db = UArticyDatabase::Get(this); auto unshadowedObject = db->GetObjectUnshadowed(Cast<UArticyPrimitive>(Node)->GetId()); // handle pins, because we can not request them directly from the db if (!unshadowedObject) { auto pinOwner = db->GetObjectUnshadowed(Cast<UArticyFlowPin>(Node)->GetOwner()->GetId()); TArray<UArticyFlowPin*> pins; auto inputPinsOwner = Cast<IArticyInputPinsProvider>(pinOwner); pins.Append(*inputPinsOwner->GetInputPins()); auto outputPinsOwner = Cast<IArticyOutputPinsProvider>(pinOwner); pins.Append(*outputPinsOwner->GetOutputPinsPtr()); auto targetId = Cast<UArticyPrimitive>(Node)->GetId(); for (auto pin : pins) { if (pin->GetId() == targetId) { unshadowedObject = pin; break; } } } return Cast<IArticyFlowObject>(unshadowedObject); } //---------------------------------------------------------------------------// TArray<FArticyBranch> UArticyFlowPlayer::Explore(IArticyFlowObject* Node, bool bShadowed, int32 Depth) { TArray<FArticyBranch> OutBranches; //check stop condition if((Depth > ExploreDepthLimit || !Node || (Node != Cursor.GetInterface() && ShouldPauseOn(Node)))) { if(Depth > ExploreDepthLimit) UE_LOG(LogArticyRuntime, Warning, TEXT("ExploreDepthLimit (%d) reached, stopping exploration!"), ExploreDepthLimit); if(!Node) UE_LOG(LogArticyRuntime, Warning, TEXT("Found a nullptr Node when exploring a branch!")); /* TODO where should I put this? if(OutBranches.Num() >= BranchLimit) { UE_LOG(LogArticyRuntime, Warning, TEXT("BranchLimit (%d) reached, cannot add another branch!"), BranchLimit); return; }*/ //target reached, create a branch auto branch = FArticyBranch{}; if(Node) { /* NOTE: This check must not be done, as the last node in a branch never affects * validity of the branch. A branch is only invalidated if it runs THROUGH a node * with invalid condition, instead of just UP TO that node. branch.bIsValid = Node->Execute(this); */ auto unshadowedNode = GetUnshadowedNode(Node); TScriptInterface<IArticyFlowObject> ptr; ptr.SetObject(unshadowedNode->_getUObject()); ptr.SetInterface(unshadowedNode); branch.Path.Add(ptr); } OutBranches.Add(branch); } else { //set speaker on expresso scripts auto xp = GetDB()->GetExpressoInstance(); if(ensure(xp)) { auto obj = Cast<UArticyPrimitive>(Node); if(obj) { xp->SetCurrentObject(obj); IArticyObjectWithSpeaker* speaker; if (auto flowPin = Cast<UArticyFlowPin>(Node)) speaker = Cast<IArticyObjectWithSpeaker>(flowPin->GetOwner()); else speaker = Cast<IArticyObjectWithSpeaker>(obj); if(speaker) xp->SetSpeaker(speaker->GetSpeaker()); } } //if this is the first node, try to submerge bool bSubmerged = false; if(Depth == 0) { auto inputPinProvider = Cast<IArticyInputPinsProvider>(Node); if(inputPinProvider) bSubmerged = inputPinProvider->TrySubmerge(this, OutBranches, Depth + 1, bShadowed); //NOTE: bShadowed will always be true if Depth == 0 } //explore this node if(!bSubmerged) { if(bShadowed) { //explore the node inside a shadowed operation ShadowedOperation([&] { Node->Explore(this, OutBranches, Depth + 1); }); } else { //non-shadowed explore Node->Explore(this, OutBranches, Depth + 1); } } //add this node to the head of all the branches for(auto& branch : OutBranches) { auto unshadowedNode = GetUnshadowedNode(Node); TScriptInterface<IArticyFlowObject> ptr; ptr.SetObject(unshadowedNode->_getUObject()); ptr.SetInterface(unshadowedNode); branch.Path.Insert(ptr, 0); //TODO inserting at front is not ideal performance wise } } return OutBranches; } void UArticyFlowPlayer::SetPauseOn(EArticyPausableType Types) { PauseOn = 1 << uint8(Types & EArticyPausableType::DialogueFragment) | 1 << uint8(Types & EArticyPausableType::Dialogue) | 1 << uint8(Types & EArticyPausableType::FlowFragment) | 1 << uint8(Types & EArticyPausableType::Hub) | 1 << uint8(Types & EArticyPausableType::Jump) | 1 << uint8(Types & EArticyPausableType::Condition) | 1 << uint8(Types & EArticyPausableType::Instruction) | 1 << uint8(Types & EArticyPausableType::Pin); } //---------------------------------------------------------------------------// void UArticyFlowPlayer::UpdateAvailableBranches() { AvailableBranches.Reset(); if(PauseOn == 0) UE_LOG(LogArticyRuntime, Warning, TEXT("PauseOn is not set, not exploring the Flow as it would not pause on any node.")) else if(!Cursor) UE_LOG(LogArticyRuntime, Warning, TEXT("Cannot explore flow, cursor is not set!")) else { const bool bMustBeShadowed = true; AvailableBranches = Explore(&*Cursor, bMustBeShadowed, 0); // NP: Every branch needs the index so that Play() can actually take a branch as input for (int32 i = 0; i < AvailableBranches.Num(); i++) AvailableBranches[i].Index = i; //if the cursor is at the StartOn node, check if we should fast-forward if(Cursor.GetObject() == StartOn.GetObject(this) && FastForwardToPause()) { //fast-forwarding will call UpdateAvailableBranches again, can abort here return; } //broadcast and return result OnPlayerPaused.Broadcast(Cursor); OnBranchesUpdated.Broadcast(AvailableBranches); } } void UArticyFlowPlayer::SetCursorToStartNode() { const auto obj = StartOn.GetObject(this); TScriptInterface<IArticyFlowObject> ptr; ptr.SetObject(obj); ptr.SetInterface(Cast<IArticyFlowObject>(obj)); SetCursorTo(ptr); } bool UArticyFlowPlayer::FastForwardToPause() { checkNoRecursion(); //this cannot recurse! if(AvailableBranches.Num() <= 0) return false; const auto& firstPath = AvailableBranches[0].Path; if(!ensure(firstPath.Num() > 0)) return false; int ffwdIndex; for(ffwdIndex = 0; ffwdIndex < firstPath.Num(); ++ffwdIndex) { const auto node = firstPath[ffwdIndex]; if(ShouldPauseOn(&*node)) { //pause on this node break; } auto bSplitFound = false; for(int b = 1; b < AvailableBranches.Num(); ++b) { const auto path = AvailableBranches[b].Path; //it shouldn't be possible that one path is a subset of the other one //(shorter but all nodes equal to the other path) if(!ensure(path.IsValidIndex(ffwdIndex)) || path[ffwdIndex] != node) { bSplitFound = true; break; } } if(bSplitFound) { //pause on the node BEFORE --ffwdIndex; break; } } if(ffwdIndex <= 0 || ffwdIndex >= firstPath.Num()) { //no need to fast-forward return false; } //create the fast-forward branch auto newBranch = FArticyBranch{}; newBranch.bIsValid = AvailableBranches[0].bIsValid; for(int i = 0; i <= ffwdIndex; ++i) { //add node to branch newBranch.Path.Add(firstPath[i]); } //this also calls UpdateAvailableBranches again PlayBranch(newBranch); return true; } void UArticyFlowPlayer::PlayBranch(const FArticyBranch& Branch) { if(!ensure(ShadowLevel == 0)) { UE_LOG(LogArticyRuntime, Error, TEXT("ArticyFlowPlayer::Traverse was called inside a ShadowedOperation! Aborting Play.")) return; } for(auto node : Branch.Path) node->Execute(GetGVs(), GetMethodsProvider()); Cursor = Branch.Path.Last(); UpdateAvailableBranches(); } AArticyFlowDebugger::AArticyFlowDebugger() { FlowPlayer = CreateDefaultSubobject<UArticyFlowPlayer>(TEXT("Articy Flow Player")); ArticyImporterIcon = CreateDefaultSubobject<UBillboardComponent>(TEXT("Icon")); auto ImporterIconFinder = ConstructorHelpers::FObjectFinder<UTexture2D>(TEXT("Texture2D'/ArticyImporter/Res/ArticyImporter64.ArticyImporter64'")); ArticyImporterIcon->SetSprite(ImporterIconFinder.Object); FlowPlayer->SetIgnoreInvalidBranches(false); }<commit_msg>Compile fix from previous DB return type changes<commit_after>// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // #include "ArticyFlowPlayer.h" #include "ArticyRuntimeModule.h" #include "Interfaces/ArticyFlowObject.h" #include "Interfaces/ArticyObjectWithSpeaker.h" #include "ArticyExpressoScripts.h" #include "UObject/ConstructorHelpers.h" #include "Interfaces/ArticyInputPinsProvider.h" #include "Interfaces/ArticyOutputPinsProvider.h" #include "Engine/Texture2D.h" TScriptInterface<IArticyFlowObject> FArticyBranch::GetTarget() const { return Path.Num() > 0 ? Path.Last() : nullptr; } void UArticyFlowPlayer::BeginPlay() { Super::BeginPlay(); //update Cursor to object referenced by StartOn SetCursorToStartNode(); } //---------------------------------------------------------------------------// void UArticyFlowPlayer::SetStartNode(FArticyRef StartNodeId) { StartOn.SetId(StartNodeId.GetId()); SetCursorToStartNode(); } void UArticyFlowPlayer::SetStartNodeWithFlowObject(TScriptInterface<IArticyFlowObject> Node) { FArticyRef ArticyRef; ArticyRef.SetReference(Cast<UArticyObject>(Node.GetObject())); SetStartNode(ArticyRef); } void UArticyFlowPlayer::SetStartNodeById(FArticyId NewId) { StartOn.SetId(NewId); SetCursorToStartNode(); } void UArticyFlowPlayer::SetCursorTo(TScriptInterface<IArticyFlowObject> Node) { if(!Node.GetObject()) { UE_LOG(LogArticyRuntime, Warning, TEXT("Could not set cursor in flow player of actor %s: invalid node"), *this->GetOwner()->GetName()); return; } Cursor = Node; UpdateAvailableBranches(); } void UArticyFlowPlayer::Play(int BranchIndex) { TArray<FArticyBranch> branches; if (IgnoresInvalidBranches()) { for (auto branch : AvailableBranches) if (branch.bIsValid) branches.Add(branch); } else { branches = AvailableBranches; } //check if the specified branch exists if(!branches.IsValidIndex(BranchIndex)) { UE_LOG(LogArticyRuntime, Error, TEXT("Branch with index %d does not exist!"), BranchIndex) return; } PlayBranch(branches[BranchIndex]); } void UArticyFlowPlayer::FinishCurrentPausedObject(int PinIndex) { IArticyOutputPinsProvider* outputPinOwner = Cast<IArticyOutputPinsProvider>(Cursor.GetObject()); if (outputPinOwner) { auto outputPins = outputPinOwner->GetOutputPinsPtr(); if (outputPins->Num() > 0) { if (PinIndex < outputPins->Num()) { (*outputPins)[PinIndex]->Execute(GetGVs(), GetMethodsProvider()); } else UE_LOG(LogArticyRuntime, Warning, TEXT("FinishCurrentPausedObject: The index was out of bounds: Index: %d, PinCount: %d"), PinIndex, outputPins->Num()); } } } bool UArticyFlowPlayer::ShouldPauseOn(IArticyFlowObject* Node) const { return Node && (1 << static_cast<uint8>(Node->GetType()) & PauseOn); } bool UArticyFlowPlayer::ShouldPauseOn(TScriptInterface<IArticyFlowObject> Node) const { return ShouldPauseOn(Cast<IArticyFlowObject>(Node.GetObject())); } UArticyDatabase* UArticyFlowPlayer::GetDB() const { return UArticyDatabase::Get(this); } UArticyGlobalVariables* UArticyFlowPlayer::GetGVs() const { return OverrideGV ? OverrideGV : UArticyGlobalVariables::GetDefault(this); } UObject* UArticyFlowPlayer::GetMethodsProvider() const { auto expressoInstance = GetDB()->GetExpressoInstance(); auto provider = expressoInstance->GetUserMethodsProviderInterface(); if (expressoInstance->UserMethodsProvider != nullptr && UserMethodsProvider == nullptr)//MM_CHANGE UserMethodsProvider = expressoInstance->UserMethodsProvider; if(ensure(provider)) { //check if the set provider implements the required interface if(!UserMethodsProvider || !ensure(UserMethodsProvider->GetClass()->ImplementsInterface(provider))) { //no valid UserMethodsProvider set, search for it //check if the flow player itself implements it if(GetClass()->ImplementsInterface(provider)) UserMethodsProvider = const_cast<UArticyFlowPlayer*>(this); else { auto actor = GetOwner(); if(ensure(actor)) { //check if the flow player's owning actor implements it if(actor->GetClass()->ImplementsInterface(provider)) UserMethodsProvider = actor; else { //check if any other component implements it auto components = actor->GetComponents(); for(auto comp : components) { if(comp->GetClass()->ImplementsInterface(provider)) { UserMethodsProvider = comp; break; } } //and finally we check for a default methods provider, which we can use as fallback auto defaultUserMethodsProvider = expressoInstance->DefaultUserMethodsProvider; if(defaultUserMethodsProvider && ensure(defaultUserMethodsProvider->GetClass()->ImplementsInterface(provider))) UserMethodsProvider = defaultUserMethodsProvider; } } } } } return UserMethodsProvider; } IArticyFlowObject* UArticyFlowPlayer::GetUnshadowedNode(IArticyFlowObject* Node) { auto db = UArticyDatabase::Get(this); UArticyPrimitive* UnshadowedObject = db->GetObjectUnshadowed(Cast<UArticyPrimitive>(Node)->GetId()); // handle pins, because we can not request them directly from the db if (!UnshadowedObject) { auto pinOwner = db->GetObjectUnshadowed(Cast<UArticyFlowPin>(Node)->GetOwner()->GetId()); TArray<UArticyFlowPin*> pins; auto inputPinsOwner = Cast<IArticyInputPinsProvider>(pinOwner); pins.Append(*inputPinsOwner->GetInputPins()); auto outputPinsOwner = Cast<IArticyOutputPinsProvider>(pinOwner); pins.Append(*outputPinsOwner->GetOutputPinsPtr()); auto targetId = Cast<UArticyPrimitive>(Node)->GetId(); for (auto pin : pins) { if (pin->GetId() == targetId) { UnshadowedObject = pin; break; } } } return Cast<IArticyFlowObject>(UnshadowedObject); } //---------------------------------------------------------------------------// TArray<FArticyBranch> UArticyFlowPlayer::Explore(IArticyFlowObject* Node, bool bShadowed, int32 Depth) { TArray<FArticyBranch> OutBranches; //check stop condition if((Depth > ExploreDepthLimit || !Node || (Node != Cursor.GetInterface() && ShouldPauseOn(Node)))) { if(Depth > ExploreDepthLimit) UE_LOG(LogArticyRuntime, Warning, TEXT("ExploreDepthLimit (%d) reached, stopping exploration!"), ExploreDepthLimit); if(!Node) UE_LOG(LogArticyRuntime, Warning, TEXT("Found a nullptr Node when exploring a branch!")); /* TODO where should I put this? if(OutBranches.Num() >= BranchLimit) { UE_LOG(LogArticyRuntime, Warning, TEXT("BranchLimit (%d) reached, cannot add another branch!"), BranchLimit); return; }*/ //target reached, create a branch auto branch = FArticyBranch{}; if(Node) { /* NOTE: This check must not be done, as the last node in a branch never affects * validity of the branch. A branch is only invalidated if it runs THROUGH a node * with invalid condition, instead of just UP TO that node. branch.bIsValid = Node->Execute(this); */ auto unshadowedNode = GetUnshadowedNode(Node); TScriptInterface<IArticyFlowObject> ptr; ptr.SetObject(unshadowedNode->_getUObject()); ptr.SetInterface(unshadowedNode); branch.Path.Add(ptr); } OutBranches.Add(branch); } else { //set speaker on expresso scripts auto xp = GetDB()->GetExpressoInstance(); if(ensure(xp)) { auto obj = Cast<UArticyPrimitive>(Node); if(obj) { xp->SetCurrentObject(obj); IArticyObjectWithSpeaker* speaker; if (auto flowPin = Cast<UArticyFlowPin>(Node)) speaker = Cast<IArticyObjectWithSpeaker>(flowPin->GetOwner()); else speaker = Cast<IArticyObjectWithSpeaker>(obj); if(speaker) xp->SetSpeaker(speaker->GetSpeaker()); } } //if this is the first node, try to submerge bool bSubmerged = false; if(Depth == 0) { auto inputPinProvider = Cast<IArticyInputPinsProvider>(Node); if(inputPinProvider) bSubmerged = inputPinProvider->TrySubmerge(this, OutBranches, Depth + 1, bShadowed); //NOTE: bShadowed will always be true if Depth == 0 } //explore this node if(!bSubmerged) { if(bShadowed) { //explore the node inside a shadowed operation ShadowedOperation([&] { Node->Explore(this, OutBranches, Depth + 1); }); } else { //non-shadowed explore Node->Explore(this, OutBranches, Depth + 1); } } //add this node to the head of all the branches for(auto& branch : OutBranches) { auto unshadowedNode = GetUnshadowedNode(Node); TScriptInterface<IArticyFlowObject> ptr; ptr.SetObject(unshadowedNode->_getUObject()); ptr.SetInterface(unshadowedNode); branch.Path.Insert(ptr, 0); //TODO inserting at front is not ideal performance wise } } return OutBranches; } void UArticyFlowPlayer::SetPauseOn(EArticyPausableType Types) { PauseOn = 1 << uint8(Types & EArticyPausableType::DialogueFragment) | 1 << uint8(Types & EArticyPausableType::Dialogue) | 1 << uint8(Types & EArticyPausableType::FlowFragment) | 1 << uint8(Types & EArticyPausableType::Hub) | 1 << uint8(Types & EArticyPausableType::Jump) | 1 << uint8(Types & EArticyPausableType::Condition) | 1 << uint8(Types & EArticyPausableType::Instruction) | 1 << uint8(Types & EArticyPausableType::Pin); } //---------------------------------------------------------------------------// void UArticyFlowPlayer::UpdateAvailableBranches() { AvailableBranches.Reset(); if(PauseOn == 0) UE_LOG(LogArticyRuntime, Warning, TEXT("PauseOn is not set, not exploring the Flow as it would not pause on any node.")) else if(!Cursor) UE_LOG(LogArticyRuntime, Warning, TEXT("Cannot explore flow, cursor is not set!")) else { const bool bMustBeShadowed = true; AvailableBranches = Explore(&*Cursor, bMustBeShadowed, 0); // NP: Every branch needs the index so that Play() can actually take a branch as input for (int32 i = 0; i < AvailableBranches.Num(); i++) AvailableBranches[i].Index = i; //if the cursor is at the StartOn node, check if we should fast-forward if(Cursor.GetObject() == StartOn.GetObject(this) && FastForwardToPause()) { //fast-forwarding will call UpdateAvailableBranches again, can abort here return; } //broadcast and return result OnPlayerPaused.Broadcast(Cursor); OnBranchesUpdated.Broadcast(AvailableBranches); } } void UArticyFlowPlayer::SetCursorToStartNode() { const auto obj = StartOn.GetObject(this); TScriptInterface<IArticyFlowObject> ptr; ptr.SetObject(obj); ptr.SetInterface(Cast<IArticyFlowObject>(obj)); SetCursorTo(ptr); } bool UArticyFlowPlayer::FastForwardToPause() { checkNoRecursion(); //this cannot recurse! if(AvailableBranches.Num() <= 0) return false; const auto& firstPath = AvailableBranches[0].Path; if(!ensure(firstPath.Num() > 0)) return false; int ffwdIndex; for(ffwdIndex = 0; ffwdIndex < firstPath.Num(); ++ffwdIndex) { const auto node = firstPath[ffwdIndex]; if(ShouldPauseOn(&*node)) { //pause on this node break; } auto bSplitFound = false; for(int b = 1; b < AvailableBranches.Num(); ++b) { const auto path = AvailableBranches[b].Path; //it shouldn't be possible that one path is a subset of the other one //(shorter but all nodes equal to the other path) if(!ensure(path.IsValidIndex(ffwdIndex)) || path[ffwdIndex] != node) { bSplitFound = true; break; } } if(bSplitFound) { //pause on the node BEFORE --ffwdIndex; break; } } if(ffwdIndex <= 0 || ffwdIndex >= firstPath.Num()) { //no need to fast-forward return false; } //create the fast-forward branch auto newBranch = FArticyBranch{}; newBranch.bIsValid = AvailableBranches[0].bIsValid; for(int i = 0; i <= ffwdIndex; ++i) { //add node to branch newBranch.Path.Add(firstPath[i]); } //this also calls UpdateAvailableBranches again PlayBranch(newBranch); return true; } void UArticyFlowPlayer::PlayBranch(const FArticyBranch& Branch) { if(!ensure(ShadowLevel == 0)) { UE_LOG(LogArticyRuntime, Error, TEXT("ArticyFlowPlayer::Traverse was called inside a ShadowedOperation! Aborting Play.")) return; } for(auto node : Branch.Path) node->Execute(GetGVs(), GetMethodsProvider()); Cursor = Branch.Path.Last(); UpdateAvailableBranches(); } AArticyFlowDebugger::AArticyFlowDebugger() { FlowPlayer = CreateDefaultSubobject<UArticyFlowPlayer>(TEXT("Articy Flow Player")); ArticyImporterIcon = CreateDefaultSubobject<UBillboardComponent>(TEXT("Icon")); auto ImporterIconFinder = ConstructorHelpers::FObjectFinder<UTexture2D>(TEXT("Texture2D'/ArticyImporter/Res/ArticyImporter64.ArticyImporter64'")); ArticyImporterIcon->SetSprite(ImporterIconFinder.Object); FlowPlayer->SetIgnoreInvalidBranches(false); }<|endoftext|>
<commit_before>/*************************************************************************** * This file is part of libmygpo-qt * * Copyright (c) 2010 - 2011 Stefan Derkits <[email protected]> * * Copyright (c) 2010 - 2011 Christian Wagner <[email protected]> * * Copyright (c) 2010 - 2011 Felix Winter <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * * USA * ***************************************************************************/ #include "Podcast.h" #include <parser.h> #include <QDebug> namespace mygpo { class PodcastPrivate : QObject { Q_OBJECT public: PodcastPrivate( Podcast* qq, QNetworkReply* reply ); PodcastPrivate( Podcast* qq, const QVariant& variant ); virtual ~PodcastPrivate(); //Getters QUrl url() const; QString title() const; QString description() const; uint subscribers() const; const uint subscribersLastWeek() const; QUrl logoUrl() const; QUrl website() const; QUrl mygpoUrl() const; private: QNetworkReply* m_reply; Podcast* const q; QUrl m_url; QString m_title; QString m_description; uint m_subscribers; uint m_SubscribersLastWeek; QUrl m_logoUrl; QUrl m_website; QUrl m_mygpoUrl; QNetworkReply::NetworkError m_error; bool parse( const QVariant& data ); bool parse( const QByteArray& data ); private slots: void parseData(); void error( QNetworkReply::NetworkError error ); }; }; using namespace mygpo; PodcastPrivate::PodcastPrivate( Podcast* qq, QNetworkReply* reply ): m_reply( reply ), q( qq ), m_error( QNetworkReply::NoError ) { QObject::connect( m_reply, SIGNAL( finished() ), this, SLOT( parseData() ) ); QObject::connect( m_reply, SIGNAL( error( QNetworkReply::NetworkError ) ), this, SLOT( error( QNetworkReply::NetworkError ) ) ); } PodcastPrivate::PodcastPrivate( Podcast* qq, const QVariant& variant ): m_reply( 0 ), q( qq ), m_error( QNetworkReply::NoError ) { parse( variant ); } PodcastPrivate::~PodcastPrivate() { delete m_reply; } QUrl PodcastPrivate::url() const { return m_url; } QString PodcastPrivate::title() const { return m_title; } QString PodcastPrivate::description() const { return m_description; } uint PodcastPrivate::subscribers() const { return m_subscribers; } const uint PodcastPrivate::subscribersLastWeek() const { return m_SubscribersLastWeek; } QUrl PodcastPrivate::logoUrl() const { return m_logoUrl; } QUrl PodcastPrivate::website() const { return m_website; } QUrl PodcastPrivate::mygpoUrl() const { return m_mygpoUrl; } Podcast::Podcast( QNetworkReply* reply, QObject* parent ) : QObject( parent ), d( new PodcastPrivate( this, reply ) ) { } Podcast::Podcast( const QVariant& variant, QObject* parent ): QObject( parent ), d( new PodcastPrivate( this, variant ) ) { } Podcast::~Podcast() { delete d; } QUrl Podcast::url() const { return d->url(); } QString Podcast::title() const { return d->title(); } QString Podcast::description() const { return d->description(); } uint Podcast::subscribers() const { return d->subscribers(); } uint Podcast::subscribersLastWeek() const { return d->subscribersLastWeek(); } QUrl Podcast::logoUrl() const { return d->logoUrl(); } QUrl Podcast::website() const { return d->website(); } QUrl Podcast::mygpoUrl() const { return d->mygpoUrl(); } bool PodcastPrivate::parse( const QVariant& data ) { if ( !data.canConvert( QVariant::Map ) ) return false; QVariantMap podcastMap = data.toMap(); QVariant v = podcastMap.value( QLatin1String( "url" ) ); if ( !v.canConvert( QVariant::Url ) ) return false; m_url = v.toUrl(); v = podcastMap.value( QLatin1String( "title" ) ); if ( !v.canConvert( QVariant::String ) ) return false; m_title = v.toString(); v = podcastMap.value( QLatin1String( "description" ) ); if ( !v.canConvert( QVariant::String ) ) return false; m_description = v.toString(); v = podcastMap.value( QLatin1String( "subscribers" ) ); if ( !v.canConvert( QVariant::Int ) ) return false; m_subscribers = v.toUInt(); v = podcastMap.value( QLatin1String( "subscribers_last_week" ) ); if ( !v.canConvert( QVariant::Int ) ) return false; m_SubscribersLastWeek = v.toUInt(); v = podcastMap.value( QLatin1String( "logo_url" ) ); if ( !v.canConvert( QVariant::Url ) ) return false; m_logoUrl = v.toUrl(); v = podcastMap.value( QLatin1String( "website" ) ); if ( !v.canConvert( QVariant::Url ) ) return false; m_website = v.toUrl(); v = podcastMap.value( QLatin1String( "mygpo_link" ) ); if ( !v.canConvert( QVariant::Url ) ) return false; m_mygpoUrl = v.toUrl(); return true; } bool PodcastPrivate::parse( const QByteArray& data ) { QJson::Parser parser; bool ok; QVariant variant = parser.parse( data, &ok ); if ( ok ) { if ( !parse( variant ) ) return false; return true; } else { return false; } } void PodcastPrivate::parseData() { //parsen und signal senden QJson::Parser parser; if ( parse( m_reply->readAll( ) ) ) { emit q->finished(); } else { emit q->parseError(); } } void PodcastPrivate::error( QNetworkReply::NetworkError error ) { this->m_error = error; emit q->requestError( error ); } #include "Podcast.moc" <commit_msg>Deleted unnecessary const Qualifier before return Type<commit_after>/*************************************************************************** * This file is part of libmygpo-qt * * Copyright (c) 2010 - 2011 Stefan Derkits <[email protected]> * * Copyright (c) 2010 - 2011 Christian Wagner <[email protected]> * * Copyright (c) 2010 - 2011 Felix Winter <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * * USA * ***************************************************************************/ #include "Podcast.h" #include <parser.h> #include <QDebug> namespace mygpo { class PodcastPrivate : QObject { Q_OBJECT public: PodcastPrivate( Podcast* qq, QNetworkReply* reply ); PodcastPrivate( Podcast* qq, const QVariant& variant ); virtual ~PodcastPrivate(); //Getters QUrl url() const; QString title() const; QString description() const; uint subscribers() const; uint subscribersLastWeek() const; QUrl logoUrl() const; QUrl website() const; QUrl mygpoUrl() const; private: QNetworkReply* m_reply; Podcast* const q; QUrl m_url; QString m_title; QString m_description; uint m_subscribers; uint m_SubscribersLastWeek; QUrl m_logoUrl; QUrl m_website; QUrl m_mygpoUrl; QNetworkReply::NetworkError m_error; bool parse( const QVariant& data ); bool parse( const QByteArray& data ); private slots: void parseData(); void error( QNetworkReply::NetworkError error ); }; }; using namespace mygpo; PodcastPrivate::PodcastPrivate( Podcast* qq, QNetworkReply* reply ): m_reply( reply ), q( qq ), m_error( QNetworkReply::NoError ) { QObject::connect( m_reply, SIGNAL( finished() ), this, SLOT( parseData() ) ); QObject::connect( m_reply, SIGNAL( error( QNetworkReply::NetworkError ) ), this, SLOT( error( QNetworkReply::NetworkError ) ) ); } PodcastPrivate::PodcastPrivate( Podcast* qq, const QVariant& variant ): m_reply( 0 ), q( qq ), m_error( QNetworkReply::NoError ) { parse( variant ); } PodcastPrivate::~PodcastPrivate() { delete m_reply; } QUrl PodcastPrivate::url() const { return m_url; } QString PodcastPrivate::title() const { return m_title; } QString PodcastPrivate::description() const { return m_description; } uint PodcastPrivate::subscribers() const { return m_subscribers; } uint PodcastPrivate::subscribersLastWeek() const { return m_SubscribersLastWeek; } QUrl PodcastPrivate::logoUrl() const { return m_logoUrl; } QUrl PodcastPrivate::website() const { return m_website; } QUrl PodcastPrivate::mygpoUrl() const { return m_mygpoUrl; } Podcast::Podcast( QNetworkReply* reply, QObject* parent ) : QObject( parent ), d( new PodcastPrivate( this, reply ) ) { } Podcast::Podcast( const QVariant& variant, QObject* parent ): QObject( parent ), d( new PodcastPrivate( this, variant ) ) { } Podcast::~Podcast() { delete d; } QUrl Podcast::url() const { return d->url(); } QString Podcast::title() const { return d->title(); } QString Podcast::description() const { return d->description(); } uint Podcast::subscribers() const { return d->subscribers(); } uint Podcast::subscribersLastWeek() const { return d->subscribersLastWeek(); } QUrl Podcast::logoUrl() const { return d->logoUrl(); } QUrl Podcast::website() const { return d->website(); } QUrl Podcast::mygpoUrl() const { return d->mygpoUrl(); } bool PodcastPrivate::parse( const QVariant& data ) { if ( !data.canConvert( QVariant::Map ) ) return false; QVariantMap podcastMap = data.toMap(); QVariant v = podcastMap.value( QLatin1String( "url" ) ); if ( !v.canConvert( QVariant::Url ) ) return false; m_url = v.toUrl(); v = podcastMap.value( QLatin1String( "title" ) ); if ( !v.canConvert( QVariant::String ) ) return false; m_title = v.toString(); v = podcastMap.value( QLatin1String( "description" ) ); if ( !v.canConvert( QVariant::String ) ) return false; m_description = v.toString(); v = podcastMap.value( QLatin1String( "subscribers" ) ); if ( !v.canConvert( QVariant::Int ) ) return false; m_subscribers = v.toUInt(); v = podcastMap.value( QLatin1String( "subscribers_last_week" ) ); if ( !v.canConvert( QVariant::Int ) ) return false; m_SubscribersLastWeek = v.toUInt(); v = podcastMap.value( QLatin1String( "logo_url" ) ); if ( !v.canConvert( QVariant::Url ) ) return false; m_logoUrl = v.toUrl(); v = podcastMap.value( QLatin1String( "website" ) ); if ( !v.canConvert( QVariant::Url ) ) return false; m_website = v.toUrl(); v = podcastMap.value( QLatin1String( "mygpo_link" ) ); if ( !v.canConvert( QVariant::Url ) ) return false; m_mygpoUrl = v.toUrl(); return true; } bool PodcastPrivate::parse( const QByteArray& data ) { QJson::Parser parser; bool ok; QVariant variant = parser.parse( data, &ok ); if ( ok ) { if ( !parse( variant ) ) return false; return true; } else { return false; } } void PodcastPrivate::parseData() { //parsen und signal senden QJson::Parser parser; if ( parse( m_reply->readAll( ) ) ) { emit q->finished(); } else { emit q->parseError(); } } void PodcastPrivate::error( QNetworkReply::NetworkError error ) { this->m_error = error; emit q->requestError( error ); } #include "Podcast.moc" <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Tests common functionality used by the Chrome Extensions webNavigation API // implementation. #include "testing/gtest/include/gtest/gtest.h" #include "base/values.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/extensions/extension_webnavigation_api.h" #include "chrome/browser/renderer_host/test/test_render_view_host.h" #include "chrome/browser/tab_contents/test_tab_contents.h" #include "chrome/common/url_constants.h" #include "chrome/test/testing_profile.h" class FrameNavigationStateTest : public RenderViewHostTestHarness { }; // Test that a frame is correctly tracked, and removed once the tab contents // goes away. TEST_F(FrameNavigationStateTest, TrackFrame) { FrameNavigationState navigation_state; const long long frame_id1 = 23; const long long frame_id2 = 42; const GURL url("http://www.google.com/"); // Create a main frame. EXPECT_FALSE(navigation_state.CanSendEvents(frame_id1)); navigation_state.TrackFrame(frame_id1, url, true, contents()); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); // Add a sub frame. EXPECT_FALSE(navigation_state.CanSendEvents(frame_id2)); navigation_state.TrackFrame(frame_id2, url, false, contents()); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id2)); // Removing the tab contents should also remove all state of its frames. navigation_state.RemoveTabContentsState(contents()); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id1)); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id2)); } // Test that no events can be sent for a frame after an error occurred, but // before a new navigation happened in this frame. TEST_F(FrameNavigationStateTest, ErrorState) { FrameNavigationState navigation_state; TestTabContents* tab_contents = new TestTabContents(profile(), contents()->GetSiteInstance()); const long long frame_id = 42; const GURL url("http://www.google.com/"); navigation_state.TrackFrame(frame_id, url, true, tab_contents); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id)); // After an error occurred, no further events should be sent. navigation_state.ErrorOccurredInFrame(frame_id); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id)); // Navigations to the "unreachable web data" URL should be ignored. navigation_state.TrackFrame( frame_id, GURL(chrome::kUnreachableWebDataURL), true, tab_contents); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id)); // However, when the frame navigates again, it should send events again. navigation_state.TrackFrame(frame_id, url, true, tab_contents); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id)); } // Tests that for a sub frame, no events are send after an error occurred, but // before a new navigation happened in this frame. TEST_F(FrameNavigationStateTest, ErrorStateFrame) { FrameNavigationState navigation_state; TestTabContents* tab_contents = new TestTabContents(profile(), contents()->GetSiteInstance()); const long long frame_id1 = 23; const long long frame_id2 = 42; const GURL url("http://www.google.com/"); navigation_state.TrackFrame(frame_id1, url, true, tab_contents); navigation_state.TrackFrame(frame_id2, url, false, tab_contents); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id2)); // After an error occurred, no further events should be sent. navigation_state.ErrorOccurredInFrame(frame_id2); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id2)); // Navigations to the "unreachable web data" URL should be ignored. navigation_state.TrackFrame( frame_id2, GURL(chrome::kUnreachableWebDataURL), false, tab_contents); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id2)); // However, when the frame navigates again, it should send events again. navigation_state.TrackFrame(frame_id2, url, false, tab_contents); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id2)); } <commit_msg>Do not leak tab contents from test<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Tests common functionality used by the Chrome Extensions webNavigation API // implementation. #include "testing/gtest/include/gtest/gtest.h" #include "base/values.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/extensions/extension_webnavigation_api.h" #include "chrome/browser/renderer_host/test/test_render_view_host.h" #include "chrome/browser/tab_contents/test_tab_contents.h" #include "chrome/common/url_constants.h" #include "chrome/test/testing_profile.h" class FrameNavigationStateTest : public RenderViewHostTestHarness { }; // Test that a frame is correctly tracked, and removed once the tab contents // goes away. TEST_F(FrameNavigationStateTest, TrackFrame) { FrameNavigationState navigation_state; const long long frame_id1 = 23; const long long frame_id2 = 42; const GURL url("http://www.google.com/"); // Create a main frame. EXPECT_FALSE(navigation_state.CanSendEvents(frame_id1)); navigation_state.TrackFrame(frame_id1, url, true, contents()); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); // Add a sub frame. EXPECT_FALSE(navigation_state.CanSendEvents(frame_id2)); navigation_state.TrackFrame(frame_id2, url, false, contents()); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id2)); // Removing the tab contents should also remove all state of its frames. navigation_state.RemoveTabContentsState(contents()); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id1)); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id2)); } // Test that no events can be sent for a frame after an error occurred, but // before a new navigation happened in this frame. TEST_F(FrameNavigationStateTest, ErrorState) { FrameNavigationState navigation_state; const long long frame_id = 42; const GURL url("http://www.google.com/"); navigation_state.TrackFrame(frame_id, url, true, contents()); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id)); // After an error occurred, no further events should be sent. navigation_state.ErrorOccurredInFrame(frame_id); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id)); // Navigations to the "unreachable web data" URL should be ignored. navigation_state.TrackFrame( frame_id, GURL(chrome::kUnreachableWebDataURL), true, contents()); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id)); // However, when the frame navigates again, it should send events again. navigation_state.TrackFrame(frame_id, url, true, contents()); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id)); } // Tests that for a sub frame, no events are send after an error occurred, but // before a new navigation happened in this frame. TEST_F(FrameNavigationStateTest, ErrorStateFrame) { FrameNavigationState navigation_state; const long long frame_id1 = 23; const long long frame_id2 = 42; const GURL url("http://www.google.com/"); navigation_state.TrackFrame(frame_id1, url, true, contents()); navigation_state.TrackFrame(frame_id2, url, false, contents()); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id2)); // After an error occurred, no further events should be sent. navigation_state.ErrorOccurredInFrame(frame_id2); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id2)); // Navigations to the "unreachable web data" URL should be ignored. navigation_state.TrackFrame( frame_id2, GURL(chrome::kUnreachableWebDataURL), false, contents()); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); EXPECT_FALSE(navigation_state.CanSendEvents(frame_id2)); // However, when the frame navigates again, it should send events again. navigation_state.TrackFrame(frame_id2, url, false, contents()); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id1)); EXPECT_TRUE(navigation_state.CanSendEvents(frame_id2)); } <|endoftext|>
<commit_before>/// \file ROOT/RNTupleMetrics.hxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer <[email protected]> /// \date 2019-08-27 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_RNTupleMetrics #define ROOT7_RNTupleMetrics #include <TError.h> #include <atomic> #include <chrono> #include <cstdint> #include <ctime> // for CPU time measurement with clock() #include <memory> #include <ostream> #include <string> #include <vector> #include <utility> namespace ROOT { namespace Experimental { namespace Detail { // clang-format off /** \class ROOT::Experimental::Detail::RNTuplePerfCounter \ingroup NTuple \brief A performance counter with a name and a unit, which can be activated on demand Derived classes decide on the counter type and implement printing of the value. */ // clang-format on class RNTuplePerfCounter { private: std::string fName; std::string fUnit; std::string fDescription; bool fIsEnabled = false; public: RNTuplePerfCounter(const std::string &name, const std::string &unit, const std::string &desc) : fName(name), fUnit(unit), fDescription(desc) {} virtual ~RNTuplePerfCounter(); void Enable() { fIsEnabled = true; } bool IsEnabled() const { return fIsEnabled; } std::string GetName() const { return fName; } std::string GetDescription() const { return fDescription; } std::string GetUnit() const { return fUnit; } virtual std::string ToString() const = 0; }; // clang-format off /** \class ROOT::Experimental::Detail::RNTuplePlainCounter \ingroup NTuple \brief A non thread-safe integral performance counter */ // clang-format on class RNTuplePlainCounter : public RNTuplePerfCounter { private: std::int64_t fCounter = 0; public: RNTuplePlainCounter(const std::string &name, const std::string &unit, const std::string &desc) : RNTuplePerfCounter(name, unit, desc) { } void Inc() { ++fCounter; } void Dec() { --fCounter; } void Add(int64_t delta) { fCounter += delta; } int64_t GetValue() const { return fCounter; } void SetValue(int64_t val) { fCounter = val; } std::string ToString() const override { return std::to_string(fCounter); } }; // clang-format off /** \class ROOT::Experimental::Detail::RNTupleAtomicCounter \ingroup NTuple \brief A thread-safe integral performance counter */ // clang-format on class RNTupleAtomicCounter : public RNTuplePerfCounter { private: std::atomic<std::int64_t> fCounter = 0; public: RNTupleAtomicCounter(const std::string &name, const std::string &unit, const std::string &desc) : RNTuplePerfCounter(name, unit, desc) { } void Inc() { if (IsEnabled()) ++fCounter; } void Dec() { if (IsEnabled()) --fCounter; } void Add(int64_t delta) { if (IsEnabled()) fCounter += delta; } int64_t XAdd(int64_t delta) { if (IsEnabled()) return fCounter.fetch_add(delta); return 0; } int64_t GetValue() const { if (IsEnabled()) return fCounter.load(); return 0; } void SetValue(int64_t val) { if (IsEnabled()) fCounter.store(val); } std::string ToString() const override { return std::to_string(GetValue()); } }; // clang-format off /** \class ROOT::Experimental::Detail::RNTupleTickCounter \ingroup NTuple \brief An either thread-safe or non thread safe counter for CPU ticks On print, the value is converted from ticks to ns. */ // clang-format on template <typename BaseCounterT> class RNTupleTickCounter : public BaseCounterT { public: RNTupleTickCounter(const std::string &name, const std::string &unit, const std::string &desc) : BaseCounterT(name, unit, desc) { R__ASSERT(unit == "ns"); } std::string ToString() const final { auto ticks = BaseCounterT::GetValue(); return std::to_string(std::uint64_t( (double(ticks) / double(CLOCKS_PER_SEC)) * (1000. * 1000. * 1000.))); } }; // clang-format off /** \class ROOT::Experimental::Detail::RNTupleTimer \ingroup NTuple \brief Record wall time and CPU time between construction and destruction Uses RAII as a stop watch. Only the wall time counter is used to determine whether the timer is active. */ // clang-format on template <typename WallTimeT, typename CpuTimeT> class RNTupleTimer { private: using Clock_t = std::chrono::steady_clock; WallTimeT &fCtrWallTime; CpuTimeT &fCtrCpuTicks; /// Wall clock time Clock_t::time_point fStartTime; /// CPU time clock_t fStartTicks; public: RNTupleTimer(WallTimeT &ctrWallTime, CpuTimeT &ctrCpuTicks) : fCtrWallTime(ctrWallTime), fCtrCpuTicks(ctrCpuTicks) { if (!fCtrWallTime.IsEnabled()) return; fStartTime = Clock_t::now(); fStartTicks = clock(); } ~RNTupleTimer() { if (!fCtrWallTime.IsEnabled()) return; auto wallTimeNs = std::chrono::duration_cast<std::chrono::nanoseconds>(Clock_t::now() - fStartTime); fCtrWallTime.Add(wallTimeNs.count()); fCtrCpuTicks.Add(clock() - fStartTicks); } RNTupleTimer(const RNTupleTimer &other) = delete; RNTupleTimer &operator =(const RNTupleTimer &other) = delete; }; using RNTuplePlainTimer = RNTupleTimer<RNTuplePlainCounter, RNTupleTickCounter<RNTuplePlainCounter>>; using RNTupleAtomicTimer = RNTupleTimer<RNTupleAtomicCounter, RNTupleTickCounter<RNTupleAtomicCounter>>; // clang-format off /** \class ROOT::Experimental::Detail::RNTupleMetrics \ingroup NTuple \brief A collection of Counter objects with a name, a unit, and a description. The class owns the counters; on registration of a new */ // clang-format on class RNTupleMetrics { private: std::vector<std::unique_ptr<RNTuplePerfCounter>> fCounters; std::vector<RNTupleMetrics *> fObservedMetrics; std::string fName; bool fIsEnabled = false; bool Contains(const std::string &name) const; public: explicit RNTupleMetrics(const std::string &name) : fName(name) {} RNTupleMetrics(const RNTupleMetrics &other) = delete; RNTupleMetrics & operator=(const RNTupleMetrics &other) = delete; ~RNTupleMetrics() = default; template <typename CounterT> void MakeCounter(const std::string &name, const std::string &unit, const std::string &desc, CounterT *&ptrCounter) { R__ASSERT(!Contains(name)); auto counter = std::make_unique<CounterT>(name, unit, desc); ptrCounter = counter.get(); fCounters.emplace_back(std::move(counter)); } void ObserveMetrics(RNTupleMetrics &observee); void Print(std::ostream &output, const std::string &prefix = "") const; void Enable(); bool IsEnabled() const { return fIsEnabled; } }; } // namespace Detail } // namespace Experimental } // namespace ROOT #endif <commit_msg>[ntuple] use R__Unlikely and R__ALWAYS_INLINE in metrics<commit_after>/// \file ROOT/RNTupleMetrics.hxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer <[email protected]> /// \date 2019-08-27 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_RNTupleMetrics #define ROOT7_RNTupleMetrics #include <ROOT/RConfig.hxx> #include <TError.h> #include <atomic> #include <chrono> #include <cstdint> #include <ctime> // for CPU time measurement with clock() #include <memory> #include <ostream> #include <string> #include <vector> #include <utility> namespace ROOT { namespace Experimental { namespace Detail { // clang-format off /** \class ROOT::Experimental::Detail::RNTuplePerfCounter \ingroup NTuple \brief A performance counter with a name and a unit, which can be activated on demand Derived classes decide on the counter type and implement printing of the value. */ // clang-format on class RNTuplePerfCounter { private: std::string fName; std::string fUnit; std::string fDescription; bool fIsEnabled = false; public: RNTuplePerfCounter(const std::string &name, const std::string &unit, const std::string &desc) : fName(name), fUnit(unit), fDescription(desc) {} virtual ~RNTuplePerfCounter(); void Enable() { fIsEnabled = true; } bool IsEnabled() const { return fIsEnabled; } std::string GetName() const { return fName; } std::string GetDescription() const { return fDescription; } std::string GetUnit() const { return fUnit; } virtual std::string ToString() const = 0; }; // clang-format off /** \class ROOT::Experimental::Detail::RNTuplePlainCounter \ingroup NTuple \brief A non thread-safe integral performance counter */ // clang-format on class RNTuplePlainCounter : public RNTuplePerfCounter { private: std::int64_t fCounter = 0; public: RNTuplePlainCounter(const std::string &name, const std::string &unit, const std::string &desc) : RNTuplePerfCounter(name, unit, desc) { } R__ALWAYS_INLINE void Inc() { ++fCounter; } R__ALWAYS_INLINE void Dec() { --fCounter; } R__ALWAYS_INLINE void Add(int64_t delta) { fCounter += delta; } R__ALWAYS_INLINE int64_t GetValue() const { return fCounter; } R__ALWAYS_INLINE void SetValue(int64_t val) { fCounter = val; } std::string ToString() const override { return std::to_string(fCounter); } }; // clang-format off /** \class ROOT::Experimental::Detail::RNTupleAtomicCounter \ingroup NTuple \brief A thread-safe integral performance counter */ // clang-format on class RNTupleAtomicCounter : public RNTuplePerfCounter { private: std::atomic<std::int64_t> fCounter = 0; public: RNTupleAtomicCounter(const std::string &name, const std::string &unit, const std::string &desc) : RNTuplePerfCounter(name, unit, desc) { } R__ALWAYS_INLINE void Inc() { if (R__unlikely(IsEnabled())) ++fCounter; } R__ALWAYS_INLINE void Dec() { if (R__unlikely(IsEnabled())) --fCounter; } R__ALWAYS_INLINE void Add(int64_t delta) { if (R__unlikely(IsEnabled())) fCounter += delta; } R__ALWAYS_INLINE int64_t XAdd(int64_t delta) { if (R__unlikely(IsEnabled())) return fCounter.fetch_add(delta); return 0; } R__ALWAYS_INLINE int64_t GetValue() const { if (R__unlikely(IsEnabled())) return fCounter.load(); return 0; } R__ALWAYS_INLINE void SetValue(int64_t val) { if (R__unlikely(IsEnabled())) fCounter.store(val); } std::string ToString() const override { return std::to_string(GetValue()); } }; // clang-format off /** \class ROOT::Experimental::Detail::RNTupleTickCounter \ingroup NTuple \brief An either thread-safe or non thread safe counter for CPU ticks On print, the value is converted from ticks to ns. */ // clang-format on template <typename BaseCounterT> class RNTupleTickCounter : public BaseCounterT { public: RNTupleTickCounter(const std::string &name, const std::string &unit, const std::string &desc) : BaseCounterT(name, unit, desc) { R__ASSERT(unit == "ns"); } std::string ToString() const final { auto ticks = BaseCounterT::GetValue(); return std::to_string(std::uint64_t( (double(ticks) / double(CLOCKS_PER_SEC)) * (1000. * 1000. * 1000.))); } }; // clang-format off /** \class ROOT::Experimental::Detail::RNTupleTimer \ingroup NTuple \brief Record wall time and CPU time between construction and destruction Uses RAII as a stop watch. Only the wall time counter is used to determine whether the timer is active. */ // clang-format on template <typename WallTimeT, typename CpuTimeT> class RNTupleTimer { private: using Clock_t = std::chrono::steady_clock; WallTimeT &fCtrWallTime; CpuTimeT &fCtrCpuTicks; /// Wall clock time Clock_t::time_point fStartTime; /// CPU time clock_t fStartTicks; public: RNTupleTimer(WallTimeT &ctrWallTime, CpuTimeT &ctrCpuTicks) : fCtrWallTime(ctrWallTime), fCtrCpuTicks(ctrCpuTicks) { if (!fCtrWallTime.IsEnabled()) return; fStartTime = Clock_t::now(); fStartTicks = clock(); } ~RNTupleTimer() { if (!fCtrWallTime.IsEnabled()) return; auto wallTimeNs = std::chrono::duration_cast<std::chrono::nanoseconds>(Clock_t::now() - fStartTime); fCtrWallTime.Add(wallTimeNs.count()); fCtrCpuTicks.Add(clock() - fStartTicks); } RNTupleTimer(const RNTupleTimer &other) = delete; RNTupleTimer &operator =(const RNTupleTimer &other) = delete; }; using RNTuplePlainTimer = RNTupleTimer<RNTuplePlainCounter, RNTupleTickCounter<RNTuplePlainCounter>>; using RNTupleAtomicTimer = RNTupleTimer<RNTupleAtomicCounter, RNTupleTickCounter<RNTupleAtomicCounter>>; // clang-format off /** \class ROOT::Experimental::Detail::RNTupleMetrics \ingroup NTuple \brief A collection of Counter objects with a name, a unit, and a description. The class owns the counters; on registration of a new */ // clang-format on class RNTupleMetrics { private: std::vector<std::unique_ptr<RNTuplePerfCounter>> fCounters; std::vector<RNTupleMetrics *> fObservedMetrics; std::string fName; bool fIsEnabled = false; bool Contains(const std::string &name) const; public: explicit RNTupleMetrics(const std::string &name) : fName(name) {} RNTupleMetrics(const RNTupleMetrics &other) = delete; RNTupleMetrics & operator=(const RNTupleMetrics &other) = delete; ~RNTupleMetrics() = default; template <typename CounterT> void MakeCounter(const std::string &name, const std::string &unit, const std::string &desc, CounterT *&ptrCounter) { R__ASSERT(!Contains(name)); auto counter = std::make_unique<CounterT>(name, unit, desc); ptrCounter = counter.get(); fCounters.emplace_back(std::move(counter)); } void ObserveMetrics(RNTupleMetrics &observee); void Print(std::ostream &output, const std::string &prefix = "") const; void Enable(); bool IsEnabled() const { return fIsEnabled; } }; } // namespace Detail } // namespace Experimental } // namespace ROOT #endif <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow 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. ==============================================================================*/ #include "tensorflow/lite/string_util.h" #include <gtest/gtest.h> #include "tensorflow/lite/c/c_api_internal.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/testing/util.h" namespace tflite { TEST(StringUtil, TestStringUtil) { Interpreter interpreter; interpreter.AddTensors(3); TfLiteTensor* t0 = interpreter.tensor(0); t0->type = kTfLiteString; t0->allocation_type = kTfLiteDynamic; TfLiteTensor* t1 = interpreter.tensor(1); t1->type = kTfLiteString; t1->allocation_type = kTfLiteDynamic; char data[] = {1, 0, 0, 0, 12, 0, 0, 0, 15, 0, 0, 0, 'X', 'Y', 'Z'}; TfLiteQuantization quant; interpreter.SetTensorParametersReadOnly(2, kTfLiteString, "", {1}, quant, data, 15); TfLiteTensor* t2 = interpreter.tensor(2); interpreter.AllocateTensors(); char s0[] = "ABC"; string s1 = "DEFG"; char s2[] = ""; // Write strings to tensors DynamicBuffer buf0; buf0.AddString(s0, 3); DynamicBuffer buf1; buf1.AddString(s1.data(), s1.length()); buf0.AddString(s2, 0); auto new_shape = TfLiteIntArrayCreate(2); new_shape->data[0] = 2; new_shape->data[1] = 1; buf0.WriteToTensor(t0, new_shape); buf1.WriteToTensorAsVector(t1); // Check tensor shapes. EXPECT_EQ(t0->dims->size, 2); EXPECT_EQ(t0->dims->data[0], 2); EXPECT_EQ(t0->dims->data[1], 1); EXPECT_EQ(t1->dims->size, 1); EXPECT_EQ(t1->dims->data[0], 1); // Read strings from tensors. ASSERT_EQ(GetStringCount(t0), 2); StringRef str_ref; str_ref = GetString(t0, 0); ASSERT_EQ(string(str_ref.str, str_ref.len), "ABC"); str_ref = GetString(t0, 1); ASSERT_EQ(string(str_ref.str, str_ref.len), ""); ASSERT_EQ(t0->bytes, 19); ASSERT_EQ(GetStringCount(t1), 1); str_ref = GetString(t1, 0); ASSERT_EQ(string(str_ref.str, str_ref.len), "DEFG"); ASSERT_EQ(t1->bytes, 16); ASSERT_EQ(GetStringCount(t2), 1); str_ref = GetString(t2, 0); ASSERT_EQ(string(str_ref.str, str_ref.len), "XYZ"); ASSERT_EQ(t2->bytes, 15); } TEST(StringUtil, TestAddJoinedString) { Interpreter interpreter; interpreter.AddTensors(1); TfLiteTensor* t0 = interpreter.tensor(0); t0->type = kTfLiteString; t0->allocation_type = kTfLiteDynamic; char s0[] = "ABC"; char s1[] = "DEFG"; char s2[] = ""; char s3[] = "XYZ"; DynamicBuffer buf; buf.AddJoinedString({{s0, 3}, {s1, 4}, {s2, 0}, {s3, 3}}, ' '); buf.WriteToTensorAsVector(t0); ASSERT_EQ(GetStringCount(t0), 1); StringRef str_ref; str_ref = GetString(t0, 0); ASSERT_EQ(string(str_ref.str, str_ref.len), "ABC DEFG XYZ"); ASSERT_EQ(t0->bytes, 25); } TEST(StringUtil, TestEmptyList) { Interpreter interpreter; interpreter.AddTensors(1); TfLiteTensor* t0 = interpreter.tensor(0); t0->type = kTfLiteString; t0->allocation_type = kTfLiteDynamic; DynamicBuffer buf; buf.WriteToTensorAsVector(t0); ASSERT_EQ(GetStringCount(t0), 0); ASSERT_EQ(t0->bytes, 8); } TEST(StringUtil, TestShapes) { Interpreter interpreter; interpreter.AddTensors(1); TfLiteTensor* t0 = interpreter.tensor(0); t0->type = kTfLiteString; t0->allocation_type = kTfLiteDynamic; t0->dims = TfLiteIntArrayCreate(2); t0->dims->data[0] = 2; t0->dims->data[1] = 1; // Not setting a new shape: number of strings must match DynamicBuffer buf; buf.AddString("ABC", 3); buf.AddString("X", 1); buf.WriteToTensor(t0, nullptr); ASSERT_EQ(t0->dims->size, 2); EXPECT_EQ(t0->dims->data[0], 2); EXPECT_EQ(t0->dims->data[1], 1); auto new_shape = TfLiteIntArrayCreate(2); new_shape->data[0] = 1; new_shape->data[1] = 2; buf.WriteToTensor(t0, new_shape); ASSERT_EQ(t0->dims->size, 2); EXPECT_EQ(t0->dims->data[0], 1); EXPECT_EQ(t0->dims->data[1], 2); } } // namespace tflite int main(int argc, char** argv) { ::tflite::LogToStderr(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Fix unitialized value msan failure.<commit_after>/* Copyright 2017 The TensorFlow 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. ==============================================================================*/ #include "tensorflow/lite/string_util.h" #include <gtest/gtest.h> #include "tensorflow/lite/c/c_api_internal.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/testing/util.h" namespace tflite { TEST(StringUtil, TestStringUtil) { Interpreter interpreter; interpreter.AddTensors(3); TfLiteTensor* t0 = interpreter.tensor(0); t0->type = kTfLiteString; t0->allocation_type = kTfLiteDynamic; TfLiteTensor* t1 = interpreter.tensor(1); t1->type = kTfLiteString; t1->allocation_type = kTfLiteDynamic; char data[] = {1, 0, 0, 0, 12, 0, 0, 0, 15, 0, 0, 0, 'X', 'Y', 'Z'}; TfLiteQuantization quant; quant.type = kTfLiteNoQuantization; quant.params = nullptr; interpreter.SetTensorParametersReadOnly(2, kTfLiteString, "", {1}, quant, data, 15); TfLiteTensor* t2 = interpreter.tensor(2); interpreter.AllocateTensors(); char s0[] = "ABC"; string s1 = "DEFG"; char s2[] = ""; // Write strings to tensors DynamicBuffer buf0; buf0.AddString(s0, 3); DynamicBuffer buf1; buf1.AddString(s1.data(), s1.length()); buf0.AddString(s2, 0); auto new_shape = TfLiteIntArrayCreate(2); new_shape->data[0] = 2; new_shape->data[1] = 1; buf0.WriteToTensor(t0, new_shape); buf1.WriteToTensorAsVector(t1); // Check tensor shapes. EXPECT_EQ(t0->dims->size, 2); EXPECT_EQ(t0->dims->data[0], 2); EXPECT_EQ(t0->dims->data[1], 1); EXPECT_EQ(t1->dims->size, 1); EXPECT_EQ(t1->dims->data[0], 1); // Read strings from tensors. ASSERT_EQ(GetStringCount(t0), 2); StringRef str_ref; str_ref = GetString(t0, 0); ASSERT_EQ(string(str_ref.str, str_ref.len), "ABC"); str_ref = GetString(t0, 1); ASSERT_EQ(string(str_ref.str, str_ref.len), ""); ASSERT_EQ(t0->bytes, 19); ASSERT_EQ(GetStringCount(t1), 1); str_ref = GetString(t1, 0); ASSERT_EQ(string(str_ref.str, str_ref.len), "DEFG"); ASSERT_EQ(t1->bytes, 16); ASSERT_EQ(GetStringCount(t2), 1); str_ref = GetString(t2, 0); ASSERT_EQ(string(str_ref.str, str_ref.len), "XYZ"); ASSERT_EQ(t2->bytes, 15); } TEST(StringUtil, TestAddJoinedString) { Interpreter interpreter; interpreter.AddTensors(1); TfLiteTensor* t0 = interpreter.tensor(0); t0->type = kTfLiteString; t0->allocation_type = kTfLiteDynamic; char s0[] = "ABC"; char s1[] = "DEFG"; char s2[] = ""; char s3[] = "XYZ"; DynamicBuffer buf; buf.AddJoinedString({{s0, 3}, {s1, 4}, {s2, 0}, {s3, 3}}, ' '); buf.WriteToTensorAsVector(t0); ASSERT_EQ(GetStringCount(t0), 1); StringRef str_ref; str_ref = GetString(t0, 0); ASSERT_EQ(string(str_ref.str, str_ref.len), "ABC DEFG XYZ"); ASSERT_EQ(t0->bytes, 25); } TEST(StringUtil, TestEmptyList) { Interpreter interpreter; interpreter.AddTensors(1); TfLiteTensor* t0 = interpreter.tensor(0); t0->type = kTfLiteString; t0->allocation_type = kTfLiteDynamic; DynamicBuffer buf; buf.WriteToTensorAsVector(t0); ASSERT_EQ(GetStringCount(t0), 0); ASSERT_EQ(t0->bytes, 8); } TEST(StringUtil, TestShapes) { Interpreter interpreter; interpreter.AddTensors(1); TfLiteTensor* t0 = interpreter.tensor(0); t0->type = kTfLiteString; t0->allocation_type = kTfLiteDynamic; t0->dims = TfLiteIntArrayCreate(2); t0->dims->data[0] = 2; t0->dims->data[1] = 1; // Not setting a new shape: number of strings must match DynamicBuffer buf; buf.AddString("ABC", 3); buf.AddString("X", 1); buf.WriteToTensor(t0, nullptr); ASSERT_EQ(t0->dims->size, 2); EXPECT_EQ(t0->dims->data[0], 2); EXPECT_EQ(t0->dims->data[1], 1); auto new_shape = TfLiteIntArrayCreate(2); new_shape->data[0] = 1; new_shape->data[1] = 2; buf.WriteToTensor(t0, new_shape); ASSERT_EQ(t0->dims->size, 2); EXPECT_EQ(t0->dims->data[0], 1); EXPECT_EQ(t0->dims->data[1], 2); } } // namespace tflite int main(int argc, char** argv) { ::tflite::LogToStderr(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Copyright 2018 Google LLC // // 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 "google/cloud/storage/internal/logging_client.h" #include "google/cloud/storage/testing/canonical_errors.h" #include "google/cloud/storage/testing/mock_client.h" #include "google/cloud/log.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace storage { inline namespace STORAGE_CLIENT_NS { namespace internal { namespace { using ::google::cloud::storage::testing::canonical_errors::TransientError; using ::testing::_; using ::testing::HasSubstr; using ::testing::Return; class MockLogBackend : public google::cloud::LogBackend { public: void Process(LogRecord const& lr) override { ProcessWithOwnership(lr); } MOCK_METHOD(void, ProcessWithOwnership, (google::cloud::LogRecord), (override)); // For the purposes of testing we just need one of the member functions. }; class LoggingClientTest : public ::testing::Test { protected: void SetUp() override { log_backend_ = std::make_shared<MockLogBackend>(); log_backend_id_ = google::cloud::LogSink::Instance().AddBackend(log_backend_); } void TearDown() override { google::cloud::LogSink::Instance().RemoveBackend(log_backend_id_); log_backend_id_ = 0; log_backend_.reset(); } std::shared_ptr<MockLogBackend> log_backend_ = nullptr; long log_backend_id_ = 0; // NOLINT(google-runtime-int) }; TEST_F(LoggingClientTest, GetBucketMetadata) { std::string text = R"""({ "kind": "storage#bucket", "id": "my-bucket", "location": "US", "name": "my-bucket" })"""; auto mock = std::make_shared<testing::MockClient>(); EXPECT_CALL(*mock, GetBucketMetadata(_)) .WillOnce( Return(internal::BucketMetadataParser::FromString(text).value())); // We want to test that the key elements are logged, but do not want a // "change detection test", so this is intentionally not exhaustive. EXPECT_CALL(*log_backend_, ProcessWithOwnership(_)) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" << ")); EXPECT_THAT(lr.message, HasSubstr("GetBucketMetadataRequest={")); EXPECT_THAT(lr.message, HasSubstr("my-bucket")); }) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" >> ")); EXPECT_THAT(lr.message, HasSubstr("payload={")); EXPECT_THAT(lr.message, HasSubstr("US")); EXPECT_THAT(lr.message, HasSubstr("my-bucket")); }); LoggingClient client(mock); client.GetBucketMetadata(GetBucketMetadataRequest("my-bucket")); } TEST_F(LoggingClientTest, GetBucketMetadataWithError) { auto mock = std::make_shared<testing::MockClient>(); EXPECT_CALL(*mock, GetBucketMetadata(_)) .WillOnce(Return(StatusOr<BucketMetadata>(TransientError()))); // We want to test that the key elements are logged, but do not want a // "change detection test", so this is intentionally not exhaustive. EXPECT_CALL(*log_backend_, ProcessWithOwnership(_)) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" << ")); EXPECT_THAT(lr.message, HasSubstr("GetBucketMetadataRequest={")); EXPECT_THAT(lr.message, HasSubstr("my-bucket")); }) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" >> ")); EXPECT_THAT(lr.message, HasSubstr("status={")); }); LoggingClient client(mock); client.GetBucketMetadata(GetBucketMetadataRequest("my-bucket")); } TEST_F(LoggingClientTest, InsertObjectMedia) { std::string text = R"""({ "bucket": "foo-bar", "metageneration": "4", "name": "baz" })"""; auto mock = std::make_shared<testing::MockClient>(); EXPECT_CALL(*mock, InsertObjectMedia(_)) .WillOnce( Return(internal::ObjectMetadataParser::FromString(text).value())); // We want to test that the key elements are logged, but do not want a // "change detection test", so this is intentionally not exhaustive. EXPECT_CALL(*log_backend_, ProcessWithOwnership(_)) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" << ")); EXPECT_THAT(lr.message, HasSubstr("InsertObjectMediaRequest={")); EXPECT_THAT(lr.message, HasSubstr("foo-bar")); EXPECT_THAT(lr.message, HasSubstr("baz")); EXPECT_THAT(lr.message, HasSubstr("the contents")); }) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" >> ")); EXPECT_THAT(lr.message, HasSubstr("payload={")); EXPECT_THAT(lr.message, HasSubstr("foo-bar")); EXPECT_THAT(lr.message, HasSubstr("baz")); }); LoggingClient client(mock); client.InsertObjectMedia( InsertObjectMediaRequest("foo-bar", "baz", "the contents")); } TEST_F(LoggingClientTest, ListObjects) { std::vector<ObjectMetadata> items = { internal::ObjectMetadataParser::FromString( R""({"name": "response-object-o1"})"") .value(), internal::ObjectMetadataParser::FromString( R""({"name": "response-object-o2"})"") .value(), }; auto mock = std::make_shared<testing::MockClient>(); EXPECT_CALL(*mock, ListObjects(_)) .WillOnce( Return(make_status_or(ListObjectsResponse{"a-token", items, {}}))); // We want to test that the key elements are logged, but do not want a // "change detection test", so this is intentionally not exhaustive. EXPECT_CALL(*log_backend_, ProcessWithOwnership(_)) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" << ")); EXPECT_THAT(lr.message, HasSubstr("ListObjectsRequest={")); EXPECT_THAT(lr.message, HasSubstr("my-bucket")); }) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" >> ")); EXPECT_THAT(lr.message, HasSubstr("payload={")); EXPECT_THAT(lr.message, HasSubstr("ListObjectsResponse={")); EXPECT_THAT(lr.message, HasSubstr("a-token")); EXPECT_THAT(lr.message, HasSubstr("response-object-o1")); EXPECT_THAT(lr.message, HasSubstr("response-object-o2")); }); LoggingClient client(mock); client.ListObjects(ListObjectsRequest("my-bucket")); } } // namespace } // namespace internal } // namespace STORAGE_CLIENT_NS } // namespace storage } // namespace cloud } // namespace google <commit_msg>feat(storage): Add ListBuckets test for storage::internal::LoggingClient (#5170)<commit_after>// Copyright 2018 Google LLC // // 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 "google/cloud/storage/internal/logging_client.h" #include "google/cloud/storage/testing/canonical_errors.h" #include "google/cloud/storage/testing/mock_client.h" #include "google/cloud/log.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace storage { inline namespace STORAGE_CLIENT_NS { namespace internal { namespace { using ::google::cloud::storage::testing::canonical_errors::TransientError; using ::testing::_; using ::testing::HasSubstr; using ::testing::Return; class MockLogBackend : public google::cloud::LogBackend { public: void Process(LogRecord const& lr) override { ProcessWithOwnership(lr); } MOCK_METHOD(void, ProcessWithOwnership, (google::cloud::LogRecord), (override)); // For the purposes of testing we just need one of the member functions. }; class LoggingClientTest : public ::testing::Test { protected: void SetUp() override { log_backend_ = std::make_shared<MockLogBackend>(); log_backend_id_ = google::cloud::LogSink::Instance().AddBackend(log_backend_); } void TearDown() override { google::cloud::LogSink::Instance().RemoveBackend(log_backend_id_); log_backend_id_ = 0; log_backend_.reset(); } std::shared_ptr<MockLogBackend> log_backend_ = nullptr; long log_backend_id_ = 0; // NOLINT(google-runtime-int) }; TEST_F(LoggingClientTest, GetBucketMetadata) { std::string text = R"""({ "kind": "storage#bucket", "id": "my-bucket", "location": "US", "name": "my-bucket" })"""; auto mock = std::make_shared<testing::MockClient>(); EXPECT_CALL(*mock, GetBucketMetadata(_)) .WillOnce( Return(internal::BucketMetadataParser::FromString(text).value())); // We want to test that the key elements are logged, but do not want a // "change detection test", so this is intentionally not exhaustive. EXPECT_CALL(*log_backend_, ProcessWithOwnership(_)) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" << ")); EXPECT_THAT(lr.message, HasSubstr("GetBucketMetadataRequest={")); EXPECT_THAT(lr.message, HasSubstr("my-bucket")); }) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" >> ")); EXPECT_THAT(lr.message, HasSubstr("payload={")); EXPECT_THAT(lr.message, HasSubstr("US")); EXPECT_THAT(lr.message, HasSubstr("my-bucket")); }); LoggingClient client(mock); client.GetBucketMetadata(GetBucketMetadataRequest("my-bucket")); } TEST_F(LoggingClientTest, GetBucketMetadataWithError) { auto mock = std::make_shared<testing::MockClient>(); EXPECT_CALL(*mock, GetBucketMetadata(_)) .WillOnce(Return(StatusOr<BucketMetadata>(TransientError()))); // We want to test that the key elements are logged, but do not want a // "change detection test", so this is intentionally not exhaustive. EXPECT_CALL(*log_backend_, ProcessWithOwnership(_)) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" << ")); EXPECT_THAT(lr.message, HasSubstr("GetBucketMetadataRequest={")); EXPECT_THAT(lr.message, HasSubstr("my-bucket")); }) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" >> ")); EXPECT_THAT(lr.message, HasSubstr("status={")); }); LoggingClient client(mock); client.GetBucketMetadata(GetBucketMetadataRequest("my-bucket")); } TEST_F(LoggingClientTest, InsertObjectMedia) { std::string text = R"""({ "bucket": "foo-bar", "metageneration": "4", "name": "baz" })"""; auto mock = std::make_shared<testing::MockClient>(); EXPECT_CALL(*mock, InsertObjectMedia(_)) .WillOnce( Return(internal::ObjectMetadataParser::FromString(text).value())); // We want to test that the key elements are logged, but do not want a // "change detection test", so this is intentionally not exhaustive. EXPECT_CALL(*log_backend_, ProcessWithOwnership(_)) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" << ")); EXPECT_THAT(lr.message, HasSubstr("InsertObjectMediaRequest={")); EXPECT_THAT(lr.message, HasSubstr("foo-bar")); EXPECT_THAT(lr.message, HasSubstr("baz")); EXPECT_THAT(lr.message, HasSubstr("the contents")); }) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" >> ")); EXPECT_THAT(lr.message, HasSubstr("payload={")); EXPECT_THAT(lr.message, HasSubstr("foo-bar")); EXPECT_THAT(lr.message, HasSubstr("baz")); }); LoggingClient client(mock); client.InsertObjectMedia( InsertObjectMediaRequest("foo-bar", "baz", "the contents")); } TEST_F(LoggingClientTest, ListBuckets) { std::vector<BucketMetadata> items = { internal::BucketMetadataParser::FromString( R"""({ "name": "response-bucket-b1", "id": "response-bucket-b1", "kind": "storage#bucket", "location": "US" })""") .value(), internal::BucketMetadataParser::FromString( R"""({ "name": "response-bucket-b2", "id": "response-bucket-b2", "kind": "storage#bucket", "location": "CN" })""") .value(), }; auto mock = std::make_shared<testing::MockClient>(); EXPECT_CALL(*mock, ListBuckets(_)) .WillOnce(Return(make_status_or(ListBucketsResponse{"a-token", items}))); // We want to test that the key elements are logged, but do not want a // "change detection test", so this is intentionally not exhaustive. EXPECT_CALL(*log_backend_, ProcessWithOwnership(_)) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" << ")); EXPECT_THAT(lr.message, HasSubstr("ListBucketsRequest={")); EXPECT_THAT(lr.message, HasSubstr("my-bucket")); }) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" >> ")); EXPECT_THAT(lr.message, HasSubstr("payload={")); EXPECT_THAT(lr.message, HasSubstr("ListBucketsResponse={")); EXPECT_THAT(lr.message, HasSubstr("a-token")); EXPECT_THAT(lr.message, HasSubstr("response-bucket-b1")); EXPECT_THAT(lr.message, HasSubstr("US")); EXPECT_THAT(lr.message, HasSubstr("response-bucket-b2")); EXPECT_THAT(lr.message, HasSubstr("storage#bucket")); EXPECT_THAT(lr.message, HasSubstr("CN")); }); LoggingClient client(mock); client.ListBuckets(ListBucketsRequest("my-bucket")); } TEST_F(LoggingClientTest, ListObjects) { std::vector<ObjectMetadata> items = { internal::ObjectMetadataParser::FromString( R""({"name": "response-object-o1"})"") .value(), internal::ObjectMetadataParser::FromString( R""({"name": "response-object-o2"})"") .value(), }; auto mock = std::make_shared<testing::MockClient>(); EXPECT_CALL(*mock, ListObjects(_)) .WillOnce( Return(make_status_or(ListObjectsResponse{"a-token", items, {}}))); // We want to test that the key elements are logged, but do not want a // "change detection test", so this is intentionally not exhaustive. EXPECT_CALL(*log_backend_, ProcessWithOwnership(_)) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" << ")); EXPECT_THAT(lr.message, HasSubstr("ListObjectsRequest={")); EXPECT_THAT(lr.message, HasSubstr("my-bucket")); }) .WillOnce([](LogRecord const& lr) { EXPECT_THAT(lr.message, HasSubstr(" >> ")); EXPECT_THAT(lr.message, HasSubstr("payload={")); EXPECT_THAT(lr.message, HasSubstr("ListObjectsResponse={")); EXPECT_THAT(lr.message, HasSubstr("a-token")); EXPECT_THAT(lr.message, HasSubstr("response-object-o1")); EXPECT_THAT(lr.message, HasSubstr("response-object-o2")); }); LoggingClient client(mock); client.ListObjects(ListObjectsRequest("my-bucket")); } } // namespace } // namespace internal } // namespace STORAGE_CLIENT_NS } // namespace storage } // namespace cloud } // namespace google <|endoftext|>
<commit_before><commit_msg>copied color scale formulas also need to listen to the new document<commit_after><|endoftext|>
<commit_before>#include <sstream> #include <algorithm> #include "player.h" #include "board.h" #include "entity.h" using namespace std; Player::Player(ABoard& board, std::string name, bool human) : board(board), name(name), human(human), active(!human), alive(true) { static size_t idCount = 1; id = idCount++; for (int i = 0; i < board.sizeX * board.sizeY; i++) map_visibility.push_back(INVISIBLE); }; vector<shared_ptr<Entity>> Player::entities() { return board.selectEntities( [this](shared_ptr<Entity> e) { return (&(e->owner) == this);}); } void Player::update() { if(alive) { visibilitMutex.lock(); for (auto& v : map_visibility) { if (v == VISIBLE) { v = SEEN; } } vector<shared_ptr<Entity>> entitites = entities(); for (auto& e : entitites) { e->mapVisible([this](r2 pos) { map_visibility[(int)pos.y* board.sizeX + (int)pos.x] = VISIBLE; }); } visibilitMutex.unlock(); } } Visibility Player::getVisibility(Entity& e) { Visibility ret = INVISIBLE; for(int x = 0; x < e.size.x; x++) { for(int y = 0; y < e.size.y; y++) { ret = max(ret, getVisibility(e.getPosition() + r2(x, y))); } } return ret; } Visibility Player::getVisibility(r2 pos) { visibilitMutex.lock(); if (pos.x < 0 || pos.x >= board.sizeX || pos.y < 0 || pos.y >= board.sizeY) { return INVISIBLE; } auto ret = map_visibility[(int)floor(pos.y) * board.sizeX + (int)floor(pos.x)]; visibilitMutex.unlock(); return ret; } Visibility Player::getVisibility2(r2 pos) { //TODO: Nose xq tuve que duplicar este metodo, si uso getVisibility en los lugares donde uso ahora getVisibility2 habia error. //visibilitMutex.lock(); if (pos.x < 0 || pos.x >= board.sizeX || pos.y < 0 || pos.y >= board.sizeY) { return INVISIBLE; } auto ret = map_visibility[(int)floor(pos.y) * board.sizeX + (int)floor(pos.x)]; //visibilitMutex.unlock(); return ret; } std::map<std::string, long> Player::getResources() { return resources; } bool Player::canGrantResources(std::string resource, long r){ auto& res = resources[resource]; return (r <= 0 || -r < res) && r + res <= board.maxResources; } bool Player::grantResources(std::string resource, long r) { if (!canGrantResources(resource, r)) { return false; } resources[resource] += r; setFrame(); return true; } bool Player::setResources(std::string resource, long r) { resources[resource] = r; setFrame(); return true; } void Player::setFrame() { frame = board.getFrame(); } void Player::setActive(bool newActive) { active = newActive; setFrame(); } bool Player::getActive() { return active; } void Player::kill() { alive = false; setFrame(); } bool Player::getAlive() { return alive; } void Player::conquer(Player& p) { for (auto& entity : p.entities()) { entity->conquered(*this); } } <commit_msg>Cuando un jugador muere, sus unidades no conquistadas mueren<commit_after>#include <sstream> #include <algorithm> #include "player.h" #include "board.h" #include "entity.h" using namespace std; Player::Player(ABoard& board, std::string name, bool human) : board(board), name(name), human(human), active(!human), alive(true) { static size_t idCount = 1; id = idCount++; for (int i = 0; i < board.sizeX * board.sizeY; i++) map_visibility.push_back(INVISIBLE); }; vector<shared_ptr<Entity>> Player::entities() { return board.selectEntities( [this](shared_ptr<Entity> e) { return (&(e->owner) == this);}); } void Player::update() { if(alive) { visibilitMutex.lock(); for (auto& v : map_visibility) { if (v == VISIBLE) { v = SEEN; } } vector<shared_ptr<Entity>> entitites = entities(); for (auto& e : entitites) { e->mapVisible([this](r2 pos) { map_visibility[(int)pos.y* board.sizeX + (int)pos.x] = VISIBLE; }); } visibilitMutex.unlock(); } } Visibility Player::getVisibility(Entity& e) { Visibility ret = INVISIBLE; for(int x = 0; x < e.size.x; x++) { for(int y = 0; y < e.size.y; y++) { ret = max(ret, getVisibility(e.getPosition() + r2(x, y))); } } return ret; } Visibility Player::getVisibility(r2 pos) { visibilitMutex.lock(); if (pos.x < 0 || pos.x >= board.sizeX || pos.y < 0 || pos.y >= board.sizeY) { return INVISIBLE; } auto ret = map_visibility[(int)floor(pos.y) * board.sizeX + (int)floor(pos.x)]; visibilitMutex.unlock(); return ret; } Visibility Player::getVisibility2(r2 pos) { //TODO: Nose xq tuve que duplicar este metodo, si uso getVisibility en los lugares donde uso ahora getVisibility2 habia error. //visibilitMutex.lock(); if (pos.x < 0 || pos.x >= board.sizeX || pos.y < 0 || pos.y >= board.sizeY) { return INVISIBLE; } auto ret = map_visibility[(int)floor(pos.y) * board.sizeX + (int)floor(pos.x)]; //visibilitMutex.unlock(); return ret; } std::map<std::string, long> Player::getResources() { return resources; } bool Player::canGrantResources(std::string resource, long r){ auto& res = resources[resource]; return (r <= 0 || -r < res) && r + res <= board.maxResources; } bool Player::grantResources(std::string resource, long r) { if (!canGrantResources(resource, r)) { return false; } resources[resource] += r; setFrame(); return true; } bool Player::setResources(std::string resource, long r) { resources[resource] = r; setFrame(); return true; } void Player::setFrame() { frame = board.getFrame(); } void Player::setActive(bool newActive) { active = newActive; setFrame(); } bool Player::getActive() { return active; } void Player::kill() { alive = false; setFrame(); for (auto& entity : entities()) { if (dynamic_cast<Unit*>(entity.get())) { entity->setDeletable(); } } } bool Player::getAlive() { return alive; } void Player::conquer(Player& p) { for (auto& entity : p.entities()) { entity->conquered(*this); } } <|endoftext|>
<commit_before>/* * Copyright 2021 Google LLC * * 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 "ecclesia/magent/redfish/indus/sleipnir_sensor.h" #include <string> #include <variant> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "ecclesia/magent/lib/ipmi/interface_options.h" #include "ecclesia/magent/lib/ipmi/ipmitool.h" #include "ecclesia/magent/lib/ipmi/sensor.h" #include "ecclesia/magent/redfish/core/json_helper.h" #include "ecclesia/magent/redfish/core/redfish_keywords.h" #include "ecclesia/magent/redfish/core/resource.h" #include "ecclesia/magent/sysmodel/x86/sleipnir_sensor.h" #include "ecclesia/magent/sysmodel/x86/sysmodel.h" #include "single_include/nlohmann/json.hpp" #include "tensorflow_serving/util/net_http/server/public/server_request_interface.h" namespace ecclesia { namespace { constexpr char kMagentConfigPath[] = "/etc/google/magent/config.pb"; template <typename Tval> struct ValStr { const char *str; Tval val; }; #define VALSTR(val, str) \ { str, val } #define VALSTR_END \ { nullptr } template <typename Tval, typename Tkey> const char *ValToStr(const ValStr<Tval> *array, Tkey val, const char *default_string) { for (int i = 0; array[i].str; ++i) { if (array[i].val == val) { return array[i].str; } } return default_string; } const ValStr<SensorType> kSensorTypes[] = { VALSTR(SENSOR_TYPE_THERMAL, "Temperature"), VALSTR(SENSOR_TYPE_VOLTAGE, "Power"), VALSTR(SENSOR_TYPE_FANTACH, "Rotational"), VALSTR(SENSOR_TYPE_CURRENT, "Current"), VALSTR(SENSOR_TYPE_POWER, "Power"), VALSTR(SENSOR_TYPE_DUTYCYCLE, "Rotational"), VALSTR(SENSOR_TYPE_ENERGY, "EnergyJoule"), VALSTR(SENSOR_TYPE_FREQUENCY, "Frequency"), VALSTR(SENSOR_TYPE_OEM_STATE, "state"), VALSTR(SENSOR_TYPE_TIME, "time"), VALSTR(SENSOR_TYPE_PRESENCE, "presence"), VALSTR_END, }; const ValStr<SensorUnit> kSensorUnit[] = { VALSTR(SENSOR_UNIT_UNSPECIFIED, "unspecified"), VALSTR(SENSOR_UNIT_DEGREES, "Cel"), VALSTR(SENSOR_UNIT_MARGIN, "Cel"), VALSTR(SENSOR_UNIT_TCONTROL, "Tcontrol"), VALSTR(SENSOR_UNIT_VOLTS, "volts"), VALSTR(SENSOR_UNIT_RPM, "RPM"), VALSTR(SENSOR_UNIT_AMPS, "amps"), VALSTR(SENSOR_UNIT_WATTS, "watts"), VALSTR(SENSOR_UNIT_PERCENT, "percent"), VALSTR(SENSOR_UNIT_JOULES, "joules"), VALSTR(SENSOR_UNIT_HERTZ, "hertz"), VALSTR(SENSOR_UNIT_SECONDS, "seconds"), VALSTR(SENSOR_UNIT_PRESENCE, "presence"), VALSTR_END, }; absl::flat_hash_map<std::string, std::string> related_item_map{ {"FAN0", "/redfish/v1/Chassis/Sleipnir/Assembly#/Assemblies/9/Oem/Google/" "Components/0"}, {"FAN1", "/redfish/v1/Chassis/Sleipnir/Assembly#/Assemblies/10/Oem/Google/" "Components/0"}, {"FAN2", "/redfish/v1/Chassis/Sleipnir/Assembly#/Assemblies/11/Oem/Google/" "Components/0"}, }; } // namespace void SleipnirIpmiSensor::Get( tensorflow::serving::net_http::ServerRequestInterface *req, const ParamsType &params) { nlohmann::json json; std::string sensor_name = std::get<std::string>(params[0]); auto sleipnir_sensors = system_model_->GetAllIpmiSensors(); for (const auto &sensor : sleipnir_sensors) { auto info = sensor.GetInfo(); if (info.name == sensor_name) { ecclesia::Ipmitool ipmi( ecclesia::GetIpmiCredentialFromPb(kMagentConfigPath)); json[kOdataId] = std::string(req->uri_path()); json[kOdataType] = "#Sensor.v1_2_0.Sensor"; json[kOdataContext] = "/redfish/v1/$metadata#Sensor.Sensor"; json[kId] = sensor_name; json[kName] = sensor_name; json[kReadingType] = ValToStr(kSensorTypes, info.type, "unknown"); json[kReadingUnits] = ValToStr(kSensorUnit, info.unit, "unknown"); auto maybe_value = ipmi.ReadSensor(info.id); double value = 0; if (maybe_value.ok()) { value = maybe_value.value(); } json[kReading] = value; if (absl::StartsWith(sensor_name, "sleipnir_Fan")) { int idx = sensor_name[12] - '0'; nlohmann::json assoc; assoc[kOdataId] = absl::StrCat( "/redfish/v1/Chassis/Sleipnir/Assembly#/Assemblies/", 9 + idx); GetJsonArray(&json, kRelatedItem)->push_back(assoc); } break; } // auto *status = GetJsonObject(&json, kStatus); //(*status)[kState] = "Enabled"; nlohmann::json status; status[kState] = kEnabled; status[kHealth] = "OK"; json[kStatus] = status; } JSONResponseOK(json, req); } } // namespace ecclesia <commit_msg>Internal change<commit_after>/* * Copyright 2021 Google LLC * * 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 "ecclesia/magent/redfish/indus/sleipnir_sensor.h" #include <string> #include <variant> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "ecclesia/magent/lib/ipmi/interface_options.h" #include "ecclesia/magent/lib/ipmi/ipmitool.h" #include "ecclesia/magent/lib/ipmi/sensor.h" #include "ecclesia/magent/redfish/core/json_helper.h" #include "ecclesia/magent/redfish/core/redfish_keywords.h" #include "ecclesia/magent/redfish/core/resource.h" #include "ecclesia/magent/sysmodel/x86/sleipnir_sensor.h" #include "ecclesia/magent/sysmodel/x86/sysmodel.h" #include "single_include/nlohmann/json.hpp" #include "tensorflow_serving/util/net_http/server/public/server_request_interface.h" namespace ecclesia { namespace { constexpr char kMagentConfigPath[] = "/etc/google/magent/config.pb"; template <typename Tval> struct ValStr { const char *str; Tval val; }; #define VALSTR(val, str) \ { str, val } #define VALSTR_END \ { nullptr } template <typename Tval, typename Tkey> const char *ValToStr(const ValStr<Tval> *array, Tkey val, const char *default_string) { for (int i = 0; array[i].str; ++i) { if (array[i].val == val) { return array[i].str; } } return default_string; } const ValStr<SensorType> kSensorTypes[] = { VALSTR(SENSOR_TYPE_THERMAL, "Temperature"), VALSTR(SENSOR_TYPE_VOLTAGE, "Power"), VALSTR(SENSOR_TYPE_FANTACH, "Rotational"), VALSTR(SENSOR_TYPE_CURRENT, "Current"), VALSTR(SENSOR_TYPE_POWER, "Power"), VALSTR(SENSOR_TYPE_DUTYCYCLE, "Rotational"), VALSTR(SENSOR_TYPE_ENERGY, "EnergyJoule"), VALSTR(SENSOR_TYPE_FREQUENCY, "Frequency"), VALSTR(SENSOR_TYPE_OEM_STATE, "state"), VALSTR(SENSOR_TYPE_TIME, "time"), VALSTR(SENSOR_TYPE_PRESENCE, "presence"), VALSTR_END, }; const ValStr<SensorUnit> kSensorUnit[] = { VALSTR(SENSOR_UNIT_UNSPECIFIED, "unspecified"), VALSTR(SENSOR_UNIT_DEGREES, "Cel"), VALSTR(SENSOR_UNIT_MARGIN, "Cel"), VALSTR(SENSOR_UNIT_TCONTROL, "Tcontrol"), VALSTR(SENSOR_UNIT_VOLTS, "volts"), VALSTR(SENSOR_UNIT_RPM, "RPM"), VALSTR(SENSOR_UNIT_AMPS, "amps"), VALSTR(SENSOR_UNIT_WATTS, "watts"), VALSTR(SENSOR_UNIT_PERCENT, "percent"), VALSTR(SENSOR_UNIT_JOULES, "joules"), VALSTR(SENSOR_UNIT_HERTZ, "hertz"), VALSTR(SENSOR_UNIT_SECONDS, "seconds"), VALSTR(SENSOR_UNIT_PRESENCE, "presence"), VALSTR_END, }; absl::flat_hash_map<std::string, std::string> related_item_map{ {"FAN0", "/redfish/v1/Chassis/Sleipnir/Assembly#/Assemblies/9/Oem/Google/" "Components/0"}, {"FAN1", "/redfish/v1/Chassis/Sleipnir/Assembly#/Assemblies/10/Oem/Google/" "Components/0"}, {"FAN2", "/redfish/v1/Chassis/Sleipnir/Assembly#/Assemblies/11/Oem/Google/" "Components/0"}, }; } // namespace void SleipnirIpmiSensor::Get( tensorflow::serving::net_http::ServerRequestInterface *req, const ParamsType &params) { nlohmann::json json; std::string sensor_name = std::get<std::string>(params[0]); auto sleipnir_sensors = system_model_->GetAllIpmiSensors(); for (const auto &sensor : sleipnir_sensors) { auto info = sensor.GetInfo(); if (info.name == sensor_name) { ecclesia::Ipmitool ipmi( ecclesia::GetIpmiCredentialFromPb(kMagentConfigPath)); json[kOdataId] = std::string(req->uri_path()); json[kOdataType] = "#Sensor.v1_2_0.Sensor"; json[kOdataContext] = "/redfish/v1/$metadata#Sensor.Sensor"; json[kId] = sensor_name; json[kName] = sensor_name; json[kReadingType] = ValToStr(kSensorTypes, info.type, "unknown"); json[kReadingUnits] = ValToStr(kSensorUnit, info.unit, "unknown"); auto value = ipmi.ReadSensor(info.id); // Only set the status field and the reading if it succeeds in reading the // sensor via IPMI. if (value.ok()) { nlohmann::json status; status[kState] = kEnabled; status[kHealth] = "OK"; json[kStatus] = status; json[kReading] = *value; } if (absl::StartsWith(sensor_name, "sleipnir_Fan")) { int idx = sensor_name[12] - '0'; nlohmann::json assoc; assoc[kOdataId] = absl::StrCat( "/redfish/v1/Chassis/Sleipnir/Assembly#/Assemblies/", 9 + idx); GetJsonArray(&json, kRelatedItem)->push_back(assoc); } break; } } JSONResponseOK(json, req); } } // namespace ecclesia <|endoftext|>
<commit_before><commit_msg>Output meStringConversion symbolically<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pkgdatasupplier.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2006-09-17 13:59:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucb.hxx" /************************************************************************** TODO ************************************************************************** *************************************************************************/ #include <vector> #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_ #include <com/sun/star/container/XEnumeration.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX #include <ucbhelper/contentidentifier.hxx> #endif #ifndef _UCBHELPER_PROVIDERHELPER_HXX #include <ucbhelper/providerhelper.hxx> #endif #ifndef _PKGDATASUPPLIER_HXX #include "pkgdatasupplier.hxx" #endif #ifndef _PKGCONTENT_HXX #include "pkgcontent.hxx" #endif #ifndef _PKGPROVIDER_HXX #include "pkgprovider.hxx" #endif using namespace com::sun; using namespace com::sun::star; using namespace package_ucp; namespace package_ucp { //========================================================================= // // struct ResultListEntry. // //========================================================================= struct ResultListEntry { rtl::OUString aURL; uno::Reference< star::ucb::XContentIdentifier > xId; uno::Reference< star::ucb::XContent > xContent; uno::Reference< sdbc::XRow > xRow; ResultListEntry( const rtl::OUString& rURL ) : aURL( rURL ) {} }; //========================================================================= // // ResultList. // //========================================================================= typedef std::vector< ResultListEntry* > ResultList; //========================================================================= // // struct DataSupplier_Impl. // //========================================================================= struct DataSupplier_Impl { osl::Mutex m_aMutex; ResultList m_aResults; rtl::Reference< Content > m_xContent; uno::Reference< lang::XMultiServiceFactory > m_xSMgr; uno::Reference< container::XEnumeration > m_xFolderEnum; sal_Int32 m_nOpenMode; sal_Bool m_bCountFinal; sal_Bool m_bThrowException; DataSupplier_Impl( const uno::Reference< lang::XMultiServiceFactory >& rxSMgr, const rtl::Reference< Content >& rContent, sal_Int32 nOpenMode ) : m_xContent( rContent ), m_xSMgr( rxSMgr ), m_xFolderEnum( rContent->getIterator() ), m_nOpenMode( nOpenMode ), m_bCountFinal( !m_xFolderEnum.is() ), m_bThrowException( m_bCountFinal ) {} ~DataSupplier_Impl(); }; //========================================================================= DataSupplier_Impl::~DataSupplier_Impl() { ResultList::const_iterator it = m_aResults.begin(); ResultList::const_iterator end = m_aResults.end(); while ( it != end ) { delete (*it); it++; } } } //========================================================================= //========================================================================= // // DataSupplier Implementation. // //========================================================================= //========================================================================= DataSupplier::DataSupplier( const uno::Reference< lang::XMultiServiceFactory >& rxSMgr, const rtl::Reference< Content >& rContent, sal_Int32 nOpenMode ) : m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) ) { } //========================================================================= // virtual DataSupplier::~DataSupplier() { delete m_pImpl; } //========================================================================= // virtual rtl::OUString DataSupplier::queryContentIdentifierString( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) { rtl::OUString aId = m_pImpl->m_aResults[ nIndex ]->aURL; if ( aId.getLength() ) { // Already cached. return aId; } } if ( getResult( nIndex ) ) { // Note: getResult fills m_pImpl->m_aResults[ nIndex ]->aURL. return m_pImpl->m_aResults[ nIndex ]->aURL; } return rtl::OUString(); } //========================================================================= // virtual uno::Reference< star::ucb::XContentIdentifier > DataSupplier::queryContentIdentifier( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) { uno::Reference< star::ucb::XContentIdentifier > xId = m_pImpl->m_aResults[ nIndex ]->xId; if ( xId.is() ) { // Already cached. return xId; } } rtl::OUString aId = queryContentIdentifierString( nIndex ); if ( aId.getLength() ) { uno::Reference< star::ucb::XContentIdentifier > xId = new ::ucb::ContentIdentifier( aId ); m_pImpl->m_aResults[ nIndex ]->xId = xId; return xId; } return uno::Reference< star::ucb::XContentIdentifier >(); } //========================================================================= // virtual uno::Reference< star::ucb::XContent > DataSupplier::queryContent( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) { uno::Reference< star::ucb::XContent > xContent = m_pImpl->m_aResults[ nIndex ]->xContent; if ( xContent.is() ) { // Already cached. return xContent; } } uno::Reference< star::ucb::XContentIdentifier > xId = queryContentIdentifier( nIndex ); if ( xId.is() ) { try { uno::Reference< star::ucb::XContent > xContent = m_pImpl->m_xContent->getProvider()->queryContent( xId ); m_pImpl->m_aResults[ nIndex ]->xContent = xContent; return xContent; } catch ( star::ucb::IllegalIdentifierException const & ) { } } return uno::Reference< star::ucb::XContent >(); } //========================================================================= // virtual sal_Bool DataSupplier::getResult( sal_Int32 nIndex ) { osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) > nIndex ) { // Result already present. return sal_True; } // Result not (yet) present. if ( m_pImpl->m_bCountFinal ) return sal_False; // Try to obtain result... sal_uInt32 nOldCount = m_pImpl->m_aResults.size(); sal_Bool bFound = sal_False; sal_Int32 nPos = nOldCount; while ( m_pImpl->m_xFolderEnum->hasMoreElements() ) { try { uno::Reference< container::XNamed > xNamed; m_pImpl->m_xFolderEnum->nextElement() >>= xNamed; if ( !xNamed.is() ) { OSL_ENSURE( sal_False, "DataSupplier::getResult - Got no XNamed!" ); break; } rtl::OUString aName = xNamed->getName(); if ( !aName.getLength() ) { OSL_ENSURE( sal_False, "DataSupplier::getResult - Empty name!" ); break; } // Assemble URL for child. rtl::OUString aURL = assembleChildURL( aName ); m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) ); if ( nPos == nIndex ) { // Result obtained. bFound = sal_True; break; } nPos++; } catch ( container::NoSuchElementException const & ) { m_pImpl->m_bThrowException = sal_True; break; } catch ( lang::WrappedTargetException const & ) { m_pImpl->m_bThrowException = sal_True; break; } } if ( !bFound ) m_pImpl->m_bCountFinal = sal_True; rtl::Reference< ::ucb::ResultSet > xResultSet = getResultSet().getBodyPtr(); if ( xResultSet.is() ) { // Callbacks follow! aGuard.clear(); if ( nOldCount < m_pImpl->m_aResults.size() ) xResultSet->rowCountChanged( nOldCount, m_pImpl->m_aResults.size() ); if ( m_pImpl->m_bCountFinal ) xResultSet->rowCountFinal(); } return bFound; } //========================================================================= // virtual sal_Int32 DataSupplier::totalCount() { osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( m_pImpl->m_bCountFinal ) return m_pImpl->m_aResults.size(); sal_uInt32 nOldCount = m_pImpl->m_aResults.size(); while ( m_pImpl->m_xFolderEnum->hasMoreElements() ) { try { uno::Reference< container::XNamed > xNamed; m_pImpl->m_xFolderEnum->nextElement() >>= xNamed; if ( !xNamed.is() ) { OSL_ENSURE( sal_False, "DataSupplier::getResult - Got no XNamed!" ); break; } rtl::OUString aName = xNamed->getName(); if ( !aName.getLength() ) { OSL_ENSURE( sal_False, "DataSupplier::getResult - Empty name!" ); break; } // Assemble URL for child. rtl::OUString aURL = assembleChildURL( aName ); m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) ); } catch ( container::NoSuchElementException const & ) { m_pImpl->m_bThrowException = sal_True; break; } catch ( lang::WrappedTargetException const & ) { m_pImpl->m_bThrowException = sal_True; break; } } m_pImpl->m_bCountFinal = sal_True; rtl::Reference< ::ucb::ResultSet > xResultSet = getResultSet().getBodyPtr(); if ( xResultSet.is() ) { // Callbacks follow! aGuard.clear(); if ( nOldCount < m_pImpl->m_aResults.size() ) xResultSet->rowCountChanged( nOldCount, m_pImpl->m_aResults.size() ); xResultSet->rowCountFinal(); } return m_pImpl->m_aResults.size(); } //========================================================================= // virtual sal_Int32 DataSupplier::currentCount() { return m_pImpl->m_aResults.size(); } //========================================================================= // virtual sal_Bool DataSupplier::isCountFinal() { return m_pImpl->m_bCountFinal; } //========================================================================= // virtual uno::Reference< sdbc::XRow > DataSupplier::queryPropertyValues( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) { uno::Reference< sdbc::XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow; if ( xRow.is() ) { // Already cached. return xRow; } } if ( getResult( nIndex ) ) { uno::Reference< sdbc::XRow > xRow = Content::getPropertyValues( m_pImpl->m_xSMgr, getResultSet()->getProperties(), static_cast< ContentProvider * >( m_pImpl->m_xContent->getProvider().getBodyPtr() ), queryContentIdentifierString( nIndex ) ); m_pImpl->m_aResults[ nIndex ]->xRow = xRow; return xRow; } return uno::Reference< sdbc::XRow >(); } //========================================================================= // virtual void DataSupplier::releasePropertyValues( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) m_pImpl->m_aResults[ nIndex ]->xRow = uno::Reference< sdbc::XRow >(); } //========================================================================= // virtual void DataSupplier::close() { } //========================================================================= // virtual void DataSupplier::validate() throw( star::ucb::ResultSetException ) { if ( m_pImpl->m_bThrowException ) throw star::ucb::ResultSetException(); } //========================================================================= ::rtl::OUString DataSupplier::assembleChildURL( const ::rtl::OUString& aName ) { rtl::OUString aURL; rtl::OUString aContURL = m_pImpl->m_xContent->getIdentifier()->getContentIdentifier(); sal_Int32 nParam = aContURL.indexOf( '?' ); if ( nParam >= 0 ) { aURL = aContURL.copy( 0, nParam ); sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' ); if ( nPackageUrlEnd != aURL.getLength() - 1 ) aURL += rtl::OUString::createFromAscii( "/" ); aURL += PackageUri::encodeSegment( aName ); aURL += aContURL.copy( nParam ); } else { aURL = aContURL; sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' ); if ( nPackageUrlEnd != aURL.getLength() - 1 ) aURL += rtl::OUString::createFromAscii( "/" ); aURL += PackageUri::encodeSegment( aName ); } return aURL; } <commit_msg>INTEGRATION: CWS ucbfixes01 (1.13.38); FILE MERGED 2007/04/23 16:40:13 kso 1.13.38.1: #70959# - Eliminated multiple identical URI helper functionality implementations.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pkgdatasupplier.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: kz $ $Date: 2007-05-10 13:05:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucb.hxx" /************************************************************************** TODO ************************************************************************** *************************************************************************/ #include <vector> #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_ #include <com/sun/star/container/XEnumeration.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX #include <ucbhelper/contentidentifier.hxx> #endif #ifndef _UCBHELPER_PROVIDERHELPER_HXX #include <ucbhelper/providerhelper.hxx> #endif #ifndef _PKGDATASUPPLIER_HXX #include "pkgdatasupplier.hxx" #endif #ifndef _PKGCONTENT_HXX #include "pkgcontent.hxx" #endif #ifndef _PKGPROVIDER_HXX #include "pkgprovider.hxx" #endif #include "../inc/urihelper.hxx" using namespace com::sun; using namespace com::sun::star; using namespace package_ucp; namespace package_ucp { //========================================================================= // // struct ResultListEntry. // //========================================================================= struct ResultListEntry { rtl::OUString aURL; uno::Reference< star::ucb::XContentIdentifier > xId; uno::Reference< star::ucb::XContent > xContent; uno::Reference< sdbc::XRow > xRow; ResultListEntry( const rtl::OUString& rURL ) : aURL( rURL ) {} }; //========================================================================= // // ResultList. // //========================================================================= typedef std::vector< ResultListEntry* > ResultList; //========================================================================= // // struct DataSupplier_Impl. // //========================================================================= struct DataSupplier_Impl { osl::Mutex m_aMutex; ResultList m_aResults; rtl::Reference< Content > m_xContent; uno::Reference< lang::XMultiServiceFactory > m_xSMgr; uno::Reference< container::XEnumeration > m_xFolderEnum; sal_Int32 m_nOpenMode; sal_Bool m_bCountFinal; sal_Bool m_bThrowException; DataSupplier_Impl( const uno::Reference< lang::XMultiServiceFactory >& rxSMgr, const rtl::Reference< Content >& rContent, sal_Int32 nOpenMode ) : m_xContent( rContent ), m_xSMgr( rxSMgr ), m_xFolderEnum( rContent->getIterator() ), m_nOpenMode( nOpenMode ), m_bCountFinal( !m_xFolderEnum.is() ), m_bThrowException( m_bCountFinal ) {} ~DataSupplier_Impl(); }; //========================================================================= DataSupplier_Impl::~DataSupplier_Impl() { ResultList::const_iterator it = m_aResults.begin(); ResultList::const_iterator end = m_aResults.end(); while ( it != end ) { delete (*it); it++; } } } //========================================================================= //========================================================================= // // DataSupplier Implementation. // //========================================================================= //========================================================================= DataSupplier::DataSupplier( const uno::Reference< lang::XMultiServiceFactory >& rxSMgr, const rtl::Reference< Content >& rContent, sal_Int32 nOpenMode ) : m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) ) { } //========================================================================= // virtual DataSupplier::~DataSupplier() { delete m_pImpl; } //========================================================================= // virtual rtl::OUString DataSupplier::queryContentIdentifierString( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) { rtl::OUString aId = m_pImpl->m_aResults[ nIndex ]->aURL; if ( aId.getLength() ) { // Already cached. return aId; } } if ( getResult( nIndex ) ) { // Note: getResult fills m_pImpl->m_aResults[ nIndex ]->aURL. return m_pImpl->m_aResults[ nIndex ]->aURL; } return rtl::OUString(); } //========================================================================= // virtual uno::Reference< star::ucb::XContentIdentifier > DataSupplier::queryContentIdentifier( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) { uno::Reference< star::ucb::XContentIdentifier > xId = m_pImpl->m_aResults[ nIndex ]->xId; if ( xId.is() ) { // Already cached. return xId; } } rtl::OUString aId = queryContentIdentifierString( nIndex ); if ( aId.getLength() ) { uno::Reference< star::ucb::XContentIdentifier > xId = new ::ucb::ContentIdentifier( aId ); m_pImpl->m_aResults[ nIndex ]->xId = xId; return xId; } return uno::Reference< star::ucb::XContentIdentifier >(); } //========================================================================= // virtual uno::Reference< star::ucb::XContent > DataSupplier::queryContent( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) { uno::Reference< star::ucb::XContent > xContent = m_pImpl->m_aResults[ nIndex ]->xContent; if ( xContent.is() ) { // Already cached. return xContent; } } uno::Reference< star::ucb::XContentIdentifier > xId = queryContentIdentifier( nIndex ); if ( xId.is() ) { try { uno::Reference< star::ucb::XContent > xContent = m_pImpl->m_xContent->getProvider()->queryContent( xId ); m_pImpl->m_aResults[ nIndex ]->xContent = xContent; return xContent; } catch ( star::ucb::IllegalIdentifierException const & ) { } } return uno::Reference< star::ucb::XContent >(); } //========================================================================= // virtual sal_Bool DataSupplier::getResult( sal_Int32 nIndex ) { osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) > nIndex ) { // Result already present. return sal_True; } // Result not (yet) present. if ( m_pImpl->m_bCountFinal ) return sal_False; // Try to obtain result... sal_uInt32 nOldCount = m_pImpl->m_aResults.size(); sal_Bool bFound = sal_False; sal_Int32 nPos = nOldCount; while ( m_pImpl->m_xFolderEnum->hasMoreElements() ) { try { uno::Reference< container::XNamed > xNamed; m_pImpl->m_xFolderEnum->nextElement() >>= xNamed; if ( !xNamed.is() ) { OSL_ENSURE( sal_False, "DataSupplier::getResult - Got no XNamed!" ); break; } rtl::OUString aName = xNamed->getName(); if ( !aName.getLength() ) { OSL_ENSURE( sal_False, "DataSupplier::getResult - Empty name!" ); break; } // Assemble URL for child. rtl::OUString aURL = assembleChildURL( aName ); m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) ); if ( nPos == nIndex ) { // Result obtained. bFound = sal_True; break; } nPos++; } catch ( container::NoSuchElementException const & ) { m_pImpl->m_bThrowException = sal_True; break; } catch ( lang::WrappedTargetException const & ) { m_pImpl->m_bThrowException = sal_True; break; } } if ( !bFound ) m_pImpl->m_bCountFinal = sal_True; rtl::Reference< ::ucb::ResultSet > xResultSet = getResultSet().getBodyPtr(); if ( xResultSet.is() ) { // Callbacks follow! aGuard.clear(); if ( nOldCount < m_pImpl->m_aResults.size() ) xResultSet->rowCountChanged( nOldCount, m_pImpl->m_aResults.size() ); if ( m_pImpl->m_bCountFinal ) xResultSet->rowCountFinal(); } return bFound; } //========================================================================= // virtual sal_Int32 DataSupplier::totalCount() { osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( m_pImpl->m_bCountFinal ) return m_pImpl->m_aResults.size(); sal_uInt32 nOldCount = m_pImpl->m_aResults.size(); while ( m_pImpl->m_xFolderEnum->hasMoreElements() ) { try { uno::Reference< container::XNamed > xNamed; m_pImpl->m_xFolderEnum->nextElement() >>= xNamed; if ( !xNamed.is() ) { OSL_ENSURE( sal_False, "DataSupplier::getResult - Got no XNamed!" ); break; } rtl::OUString aName = xNamed->getName(); if ( !aName.getLength() ) { OSL_ENSURE( sal_False, "DataSupplier::getResult - Empty name!" ); break; } // Assemble URL for child. rtl::OUString aURL = assembleChildURL( aName ); m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) ); } catch ( container::NoSuchElementException const & ) { m_pImpl->m_bThrowException = sal_True; break; } catch ( lang::WrappedTargetException const & ) { m_pImpl->m_bThrowException = sal_True; break; } } m_pImpl->m_bCountFinal = sal_True; rtl::Reference< ::ucb::ResultSet > xResultSet = getResultSet().getBodyPtr(); if ( xResultSet.is() ) { // Callbacks follow! aGuard.clear(); if ( nOldCount < m_pImpl->m_aResults.size() ) xResultSet->rowCountChanged( nOldCount, m_pImpl->m_aResults.size() ); xResultSet->rowCountFinal(); } return m_pImpl->m_aResults.size(); } //========================================================================= // virtual sal_Int32 DataSupplier::currentCount() { return m_pImpl->m_aResults.size(); } //========================================================================= // virtual sal_Bool DataSupplier::isCountFinal() { return m_pImpl->m_bCountFinal; } //========================================================================= // virtual uno::Reference< sdbc::XRow > DataSupplier::queryPropertyValues( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) { uno::Reference< sdbc::XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow; if ( xRow.is() ) { // Already cached. return xRow; } } if ( getResult( nIndex ) ) { uno::Reference< sdbc::XRow > xRow = Content::getPropertyValues( m_pImpl->m_xSMgr, getResultSet()->getProperties(), static_cast< ContentProvider * >( m_pImpl->m_xContent->getProvider().getBodyPtr() ), queryContentIdentifierString( nIndex ) ); m_pImpl->m_aResults[ nIndex ]->xRow = xRow; return xRow; } return uno::Reference< sdbc::XRow >(); } //========================================================================= // virtual void DataSupplier::releasePropertyValues( sal_Int32 nIndex ) { osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex ); if ( nIndex < sal::static_int_cast<sal_Int32>(m_pImpl->m_aResults.size()) ) m_pImpl->m_aResults[ nIndex ]->xRow = uno::Reference< sdbc::XRow >(); } //========================================================================= // virtual void DataSupplier::close() { } //========================================================================= // virtual void DataSupplier::validate() throw( star::ucb::ResultSetException ) { if ( m_pImpl->m_bThrowException ) throw star::ucb::ResultSetException(); } //========================================================================= ::rtl::OUString DataSupplier::assembleChildURL( const ::rtl::OUString& aName ) { rtl::OUString aURL; rtl::OUString aContURL = m_pImpl->m_xContent->getIdentifier()->getContentIdentifier(); sal_Int32 nParam = aContURL.indexOf( '?' ); if ( nParam >= 0 ) { aURL = aContURL.copy( 0, nParam ); sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' ); if ( nPackageUrlEnd != aURL.getLength() - 1 ) aURL += rtl::OUString::createFromAscii( "/" ); aURL += ::ucb::urihelper::encodeSegment( aName ); aURL += aContURL.copy( nParam ); } else { aURL = aContURL; sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' ); if ( nPackageUrlEnd != aURL.getLength() - 1 ) aURL += rtl::OUString::createFromAscii( "/" ); aURL += ::ucb::urihelper::encodeSegment( aName ); } return aURL; } <|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 "formel.hxx" _ScRangeListTabs::_ScRangeListTabs() { } _ScRangeListTabs::~_ScRangeListTabs() { } void _ScRangeListTabs::Append( const ScAddress& aSRD, SCTAB nTab, const bool b ) { ScAddress a = aSRD; if( b ) { if (a.Tab() > MAXTAB) a.SetTab(MAXTAB); if (a.Col() > MAXCOL) a.SetCol(MAXCOL); if (a.Row() > MAXROW) a.SetRow(MAXROW); } else { OSL_ENSURE( ValidTab(a.Tab()), "-_ScRangeListTabs::Append(): A lie has no crash!" ); } if( nTab == SCTAB_MAX) return; if( nTab < 0) nTab = a.Tab(); if (nTab < 0 || MAXTAB < nTab) return; TabRangeType::iterator itr = maTabRanges.find(nTab); if (itr == maTabRanges.end()) { // No entry for this table yet. Insert a new one. std::pair<TabRangeType::iterator, bool> r = maTabRanges.insert(nTab, new RangeListType); if (!r.second) // Insertion failed. return; itr = r.first; } itr->second->push_back(ScRange(a.Col(),a.Row(),a.Tab())); } void _ScRangeListTabs::Append( const ScRange& aCRD, SCTAB nTab, bool b ) { ScRange a = aCRD; if( b ) { // ignore 3D ranges if (a.aStart.Tab() != a.aEnd.Tab()) return; if (a.aStart.Tab() > MAXTAB) a.aStart.SetTab(MAXTAB); else if (a.aStart.Tab() < 0) a.aStart.SetTab(0); if (a.aStart.Col() > MAXCOL) a.aStart.SetCol(MAXCOL); else if (a.aStart.Col() < 0) a.aStart.SetCol(0); if (a.aStart.Row() > MAXROW) a.aStart.SetRow(MAXROW); else if (a.aStart.Row() < 0) a.aStart.SetRow(0); if (a.aEnd.Col() > MAXCOL) a.aEnd.SetCol(MAXCOL); else if (a.aEnd.Col() < 0) a.aEnd.SetCol(0); if (a.aEnd.Row() > MAXROW) a.aEnd.SetRow(MAXROW); else if (a.aEnd.Row() < 0) a.aEnd.SetRow(0); } else { OSL_ENSURE( ValidTab(a.Ref1.nTab), "-_ScRangeListTabs::Append(): Luegen haben kurze Abstuerze!" ); OSL_ENSURE( a.Ref1.nTab == a.Ref2.nTab, "+_ScRangeListTabs::Append(): 3D-Ranges werden in SC nicht unterstuetzt!" ); } if( nTab == SCTAB_MAX) return; if( nTab < -1) nTab = a.aStart.Tab(); if (nTab < 0 || MAXTAB < nTab) return; TabRangeType::iterator itr = maTabRanges.find(nTab); if (itr == maTabRanges.end()) { // No entry for this table yet. Insert a new one. std::pair<TabRangeType::iterator, bool> r = maTabRanges.insert(nTab, new RangeListType); if (!r.second) // Insertion failed. return; itr = r.first; } itr->second->push_back(a); } const ScRange* _ScRangeListTabs::First( SCTAB n ) { OSL_ENSURE( ValidTab(n), "-_ScRangeListTabs::First(): Good bye!" ); TabRangeType::iterator itr = maTabRanges.find(n); if (itr == maTabRanges.end()) // No range list exists for this table. return NULL; const RangeListType& rList = *itr->second; maItrCur = rList.begin(); maItrCurEnd = rList.end(); return rList.empty() ? NULL : &(*maItrCur); } const ScRange* _ScRangeListTabs::Next () { ++maItrCur; if (maItrCur == maItrCurEnd) return NULL; return &(*maItrCur); } ConverterBase::ConverterBase( sal_uInt16 nNewBuffer ) : aEingPos( 0, 0, 0 ), eStatus( ConvOK ), nBufferSize( nNewBuffer ) { OSL_ENSURE( nNewBuffer > 0, "ConverterBase::ConverterBase - nNewBuffer == 0!" ); pBuffer = new sal_Char[ nNewBuffer ]; } ConverterBase::~ConverterBase() { delete[] pBuffer; } void ConverterBase::Reset() { eStatus = ConvOK; aPool.Reset(); aStack.Reset(); } ExcelConverterBase::ExcelConverterBase( sal_uInt16 nNewBuffer ) : ConverterBase( nNewBuffer ) { } ExcelConverterBase::~ExcelConverterBase() { } void ExcelConverterBase::Reset( const ScAddress& rEingPos ) { ConverterBase::Reset(); aEingPos = rEingPos; } void ExcelConverterBase::Reset() { ConverterBase::Reset(); aEingPos.Set( 0, 0, 0 ); } LotusConverterBase::LotusConverterBase( SvStream &rStr, sal_uInt16 nNewBuffer ) : ConverterBase( nNewBuffer ), aIn( rStr ), nBytesLeft( 0 ) { } LotusConverterBase::~LotusConverterBase() { } void LotusConverterBase::Reset( const ScAddress& rEingPos ) { ConverterBase::Reset(); nBytesLeft = 0; aEingPos = rEingPos; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fix errors: no members 'Ref1' or 'Ref2' in 'ScRange'<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 "formel.hxx" _ScRangeListTabs::_ScRangeListTabs() { } _ScRangeListTabs::~_ScRangeListTabs() { } void _ScRangeListTabs::Append( const ScAddress& aSRD, SCTAB nTab, const bool b ) { ScAddress a = aSRD; if( b ) { if (a.Tab() > MAXTAB) a.SetTab(MAXTAB); if (a.Col() > MAXCOL) a.SetCol(MAXCOL); if (a.Row() > MAXROW) a.SetRow(MAXROW); } else { OSL_ENSURE( ValidTab(a.Tab()), "-_ScRangeListTabs::Append(): A lie has no crash!" ); } if( nTab == SCTAB_MAX) return; if( nTab < 0) nTab = a.Tab(); if (nTab < 0 || MAXTAB < nTab) return; TabRangeType::iterator itr = maTabRanges.find(nTab); if (itr == maTabRanges.end()) { // No entry for this table yet. Insert a new one. std::pair<TabRangeType::iterator, bool> r = maTabRanges.insert(nTab, new RangeListType); if (!r.second) // Insertion failed. return; itr = r.first; } itr->second->push_back(ScRange(a.Col(),a.Row(),a.Tab())); } void _ScRangeListTabs::Append( const ScRange& aCRD, SCTAB nTab, bool b ) { ScRange a = aCRD; if( b ) { // ignore 3D ranges if (a.aStart.Tab() != a.aEnd.Tab()) return; if (a.aStart.Tab() > MAXTAB) a.aStart.SetTab(MAXTAB); else if (a.aStart.Tab() < 0) a.aStart.SetTab(0); if (a.aStart.Col() > MAXCOL) a.aStart.SetCol(MAXCOL); else if (a.aStart.Col() < 0) a.aStart.SetCol(0); if (a.aStart.Row() > MAXROW) a.aStart.SetRow(MAXROW); else if (a.aStart.Row() < 0) a.aStart.SetRow(0); if (a.aEnd.Col() > MAXCOL) a.aEnd.SetCol(MAXCOL); else if (a.aEnd.Col() < 0) a.aEnd.SetCol(0); if (a.aEnd.Row() > MAXROW) a.aEnd.SetRow(MAXROW); else if (a.aEnd.Row() < 0) a.aEnd.SetRow(0); } else { #if 0 // no members 'Ref1' or 'Ref2' in 'ScRange' OSL_ENSURE( ValidTab(a.Ref1.nTab), "-_ScRangeListTabs::Append(): Luegen haben kurze Abstuerze!" ); OSL_ENSURE( a.Ref1.nTab == a.Ref2.nTab, "+_ScRangeListTabs::Append(): 3D-Ranges werden in SC nicht unterstuetzt!" ); #endif } if( nTab == SCTAB_MAX) return; if( nTab < -1) nTab = a.aStart.Tab(); if (nTab < 0 || MAXTAB < nTab) return; TabRangeType::iterator itr = maTabRanges.find(nTab); if (itr == maTabRanges.end()) { // No entry for this table yet. Insert a new one. std::pair<TabRangeType::iterator, bool> r = maTabRanges.insert(nTab, new RangeListType); if (!r.second) // Insertion failed. return; itr = r.first; } itr->second->push_back(a); } const ScRange* _ScRangeListTabs::First( SCTAB n ) { OSL_ENSURE( ValidTab(n), "-_ScRangeListTabs::First(): Good bye!" ); TabRangeType::iterator itr = maTabRanges.find(n); if (itr == maTabRanges.end()) // No range list exists for this table. return NULL; const RangeListType& rList = *itr->second; maItrCur = rList.begin(); maItrCurEnd = rList.end(); return rList.empty() ? NULL : &(*maItrCur); } const ScRange* _ScRangeListTabs::Next () { ++maItrCur; if (maItrCur == maItrCurEnd) return NULL; return &(*maItrCur); } ConverterBase::ConverterBase( sal_uInt16 nNewBuffer ) : aEingPos( 0, 0, 0 ), eStatus( ConvOK ), nBufferSize( nNewBuffer ) { OSL_ENSURE( nNewBuffer > 0, "ConverterBase::ConverterBase - nNewBuffer == 0!" ); pBuffer = new sal_Char[ nNewBuffer ]; } ConverterBase::~ConverterBase() { delete[] pBuffer; } void ConverterBase::Reset() { eStatus = ConvOK; aPool.Reset(); aStack.Reset(); } ExcelConverterBase::ExcelConverterBase( sal_uInt16 nNewBuffer ) : ConverterBase( nNewBuffer ) { } ExcelConverterBase::~ExcelConverterBase() { } void ExcelConverterBase::Reset( const ScAddress& rEingPos ) { ConverterBase::Reset(); aEingPos = rEingPos; } void ExcelConverterBase::Reset() { ConverterBase::Reset(); aEingPos.Set( 0, 0, 0 ); } LotusConverterBase::LotusConverterBase( SvStream &rStr, sal_uInt16 nNewBuffer ) : ConverterBase( nNewBuffer ), aIn( rStr ), nBytesLeft( 0 ) { } LotusConverterBase::~LotusConverterBase() { } void LotusConverterBase::Reset( const ScAddress& rEingPos ) { ConverterBase::Reset(); nBytesLeft = 0; aEingPos = rEingPos; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before><commit_msg>sc: loplugin:staticmethods<commit_after><|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_CONSTRUCTION_DECL_HPP #define DTK_DETAILS_TREE_CONSTRUCTION_DECL_HPP #include "DTK_ConfigDefs.hpp" #include <DTK_Box.hpp> #include <DTK_DetailsAlgorithms.hpp> // expand #include <DTK_DetailsMortonCode.hpp> // morton3D #include <DTK_DetailsNode.hpp> #include <DTK_DetailsTags.hpp> #include <DTK_KokkosHelpers.hpp> // clz #include <Kokkos_Macros.hpp> #include <Kokkos_Pair.hpp> #include <Kokkos_Parallel.hpp> #include <Kokkos_View.hpp> namespace DataTransferKit { namespace Details { /** * This structure contains all the functions used to build the BVH. All the * functions are static. */ template <typename DeviceType> struct TreeConstruction { public: using ExecutionSpace = typename DeviceType::execution_space; template <typename ConstViewType> static void calculateBoundingBoxOfTheScene( ConstViewType primitives, Box &scene_bounding_box ); // to assign the Morton code for a given object, we use the centroid point // of its bounding box, and express it relative to the bounding box of the // scene. template <typename ConstViewType> static void assignMortonCodes( ConstViewType primitives, Kokkos::View<unsigned int *, DeviceType> morton_codes, Box const &scene_bounding_box ); template <typename ConstViewType> static void initializeLeafNodes( ConstViewType primitives, Kokkos::View<size_t const *, DeviceType> permutation_indices, Kokkos::View<Node *, DeviceType> leaf_nodes ); static Node *generateHierarchy( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, Kokkos::View<Node *, DeviceType> leaf_nodes, Kokkos::View<Node *, DeviceType> internal_nodes, Kokkos::View<int *, DeviceType> parents ); static void calculateInternalNodesBoundingVolumes( Kokkos::View<Node const *, DeviceType> leaf_nodes, Kokkos::View<Node *, DeviceType> internal_nodes, Kokkos::View<int const *, DeviceType> parents ); KOKKOS_INLINE_FUNCTION static int commonPrefix( Kokkos::View<unsigned int *, DeviceType> morton_codes, int i, int j ) { using KokkosHelpers::clz; int const n = morton_codes.extent( 0 ); if ( j < 0 || j > n - 1 ) return -1; // our construction algorithm relies on keys being unique so we handle // explicitly case of duplicate Morton codes by augmenting each key by // a bit representation of its index. if ( morton_codes[i] == morton_codes[j] ) { // clz( k[i] ^ k[j] ) == 32 return 32 + clz( i ^ j ); } return clz( morton_codes[i] ^ morton_codes[j] ); } KOKKOS_FUNCTION static int findSplit( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, int first, int last ); KOKKOS_FUNCTION static Kokkos::pair<int, int> determineRange( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, int i ); }; template <typename ViewType> class CalculateBoundingBoxOfTheSceneFunctor { public: CalculateBoundingBoxOfTheSceneFunctor( typename ViewType::const_type primitives ) : _primitives( primitives ) { } KOKKOS_INLINE_FUNCTION void init( Box &box ) const { box = Box(); } KOKKOS_INLINE_FUNCTION void operator()( int const i, Box &box ) const { expand( box, _primitives( i ) ); } KOKKOS_INLINE_FUNCTION void join( volatile Box &dst, volatile Box const &src ) const { expand( dst, src ); } private: typename ViewType::const_type _primitives; }; template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::calculateBoundingBoxOfTheScene( ConstViewType primitives, Box &scene_bounding_box ) { static_assert( Kokkos::is_view<ConstViewType>::value, "Must pass a view" ); static_assert( std::is_same<typename ConstViewType::traits::device_type, DeviceType>::value, "Wrong device type" ); // TODO static_assert( is_expandable_v<Box, typename // ConstViewType::value_type), ""); auto const n = primitives.extent( 0 ); Kokkos::parallel_reduce( DTK_MARK_REGION( "calculate_bounding_box_of_the_scene" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), CalculateBoundingBoxOfTheSceneFunctor<decltype( primitives )>( primitives ), scene_bounding_box ); Kokkos::fence(); } template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::assignMortonCodes( ConstViewType primitives, Kokkos::View<unsigned int *, DeviceType> morton_codes, Box const &scene_bounding_box ) { auto const n = morton_codes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "assign_morton_codes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { Point xyz; double a, b; centroid( primitives( i ), xyz ); // scale coordinates with respect to bounding box of the scene for ( int d = 0; d < 3; ++d ) { a = scene_bounding_box.minCorner()[d]; b = scene_bounding_box.maxCorner()[d]; xyz[d] = ( a != b ? ( xyz[d] - a ) / ( b - a ) : 0 ); } morton_codes( i ) = morton3D( xyz[0], xyz[1], xyz[2] ); } ); Kokkos::fence(); } template <typename Primitives, typename Indices, typename Nodes> inline void initializeLeafNodesDispatch( BoxTag, Primitives primitives, Indices permutation_indices, Nodes leaf_nodes ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = leaf_nodes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "initialize_leaf_nodes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { leaf_nodes( i ) = { {nullptr, reinterpret_cast<Node *>( permutation_indices( i ) )}, primitives( permutation_indices( i ) )}; } ); Kokkos::fence(); } template <typename Primitives, typename Indices, typename Nodes> inline void initializeLeafNodesDispatch( PointTag, Primitives primitives, Indices permutation_indices, Nodes leaf_nodes ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = leaf_nodes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "initialize_leaf_nodes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { leaf_nodes( i ) = { {nullptr, reinterpret_cast<Node *>( permutation_indices( i ) )}, {primitives( permutation_indices( i ) ), primitives( permutation_indices( i ) )}}; } ); Kokkos::fence(); } template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::initializeLeafNodes( ConstViewType primitives, Kokkos::View<size_t const *, DeviceType> permutation_indices, Kokkos::View<Node *, DeviceType> leaf_nodes ) { auto const n = leaf_nodes.extent( 0 ); DTK_REQUIRE( permutation_indices.extent( 0 ) == n ); DTK_REQUIRE( primitives.extent( 0 ) == n ); static_assert( sizeof( typename decltype( permutation_indices )::value_type ) == sizeof( Node * ), "Encoding leaf index in pointer to child is not safe if the " "index and pointer types do not have the same size" ); using Tag = typename Tag<typename decltype( primitives )::traits::non_const_value_type>::type; initializeLeafNodesDispatch( Tag{}, primitives, permutation_indices, leaf_nodes ); } } // namespace Details } // namespace DataTransferKit #endif <commit_msg>Use tag dispatching in TreeConstruction::assignMortonCodes()<commit_after>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_CONSTRUCTION_DECL_HPP #define DTK_DETAILS_TREE_CONSTRUCTION_DECL_HPP #include "DTK_ConfigDefs.hpp" #include <DTK_Box.hpp> #include <DTK_DetailsAlgorithms.hpp> // expand #include <DTK_DetailsMortonCode.hpp> // morton3D #include <DTK_DetailsNode.hpp> #include <DTK_DetailsTags.hpp> #include <DTK_KokkosHelpers.hpp> // clz #include <Kokkos_Macros.hpp> #include <Kokkos_Pair.hpp> #include <Kokkos_Parallel.hpp> #include <Kokkos_View.hpp> namespace DataTransferKit { namespace Details { /** * This structure contains all the functions used to build the BVH. All the * functions are static. */ template <typename DeviceType> struct TreeConstruction { public: using ExecutionSpace = typename DeviceType::execution_space; template <typename ConstViewType> static void calculateBoundingBoxOfTheScene( ConstViewType primitives, Box &scene_bounding_box ); // to assign the Morton code for a given object, we use the centroid point // of its bounding box, and express it relative to the bounding box of the // scene. template <typename ConstViewType> static void assignMortonCodes( ConstViewType primitives, Kokkos::View<unsigned int *, DeviceType> morton_codes, Box const &scene_bounding_box ); template <typename ConstViewType> static void initializeLeafNodes( ConstViewType primitives, Kokkos::View<size_t const *, DeviceType> permutation_indices, Kokkos::View<Node *, DeviceType> leaf_nodes ); static Node *generateHierarchy( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, Kokkos::View<Node *, DeviceType> leaf_nodes, Kokkos::View<Node *, DeviceType> internal_nodes, Kokkos::View<int *, DeviceType> parents ); static void calculateInternalNodesBoundingVolumes( Kokkos::View<Node const *, DeviceType> leaf_nodes, Kokkos::View<Node *, DeviceType> internal_nodes, Kokkos::View<int const *, DeviceType> parents ); KOKKOS_INLINE_FUNCTION static int commonPrefix( Kokkos::View<unsigned int *, DeviceType> morton_codes, int i, int j ) { using KokkosHelpers::clz; int const n = morton_codes.extent( 0 ); if ( j < 0 || j > n - 1 ) return -1; // our construction algorithm relies on keys being unique so we handle // explicitly case of duplicate Morton codes by augmenting each key by // a bit representation of its index. if ( morton_codes[i] == morton_codes[j] ) { // clz( k[i] ^ k[j] ) == 32 return 32 + clz( i ^ j ); } return clz( morton_codes[i] ^ morton_codes[j] ); } KOKKOS_FUNCTION static int findSplit( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, int first, int last ); KOKKOS_FUNCTION static Kokkos::pair<int, int> determineRange( Kokkos::View<unsigned int *, DeviceType> sorted_morton_codes, int i ); }; template <typename ViewType> class CalculateBoundingBoxOfTheSceneFunctor { public: CalculateBoundingBoxOfTheSceneFunctor( typename ViewType::const_type primitives ) : _primitives( primitives ) { } KOKKOS_INLINE_FUNCTION void init( Box &box ) const { box = Box(); } KOKKOS_INLINE_FUNCTION void operator()( int const i, Box &box ) const { expand( box, _primitives( i ) ); } KOKKOS_INLINE_FUNCTION void join( volatile Box &dst, volatile Box const &src ) const { expand( dst, src ); } private: typename ViewType::const_type _primitives; }; template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::calculateBoundingBoxOfTheScene( ConstViewType primitives, Box &scene_bounding_box ) { static_assert( Kokkos::is_view<ConstViewType>::value, "Must pass a view" ); static_assert( std::is_same<typename ConstViewType::traits::device_type, DeviceType>::value, "Wrong device type" ); // TODO static_assert( is_expandable_v<Box, typename // ConstViewType::value_type), ""); auto const n = primitives.extent( 0 ); Kokkos::parallel_reduce( DTK_MARK_REGION( "calculate_bounding_box_of_the_scene" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), CalculateBoundingBoxOfTheSceneFunctor<decltype( primitives )>( primitives ), scene_bounding_box ); Kokkos::fence(); } template <typename Primitives, typename MortonCodes> inline void assignMortonCodesDispatch( BoxTag, Primitives primitives, MortonCodes morton_codes, Box const &scene_bounding_box ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = morton_codes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "assign_morton_codes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { Point xyz; double a, b; centroid( primitives( i ), xyz ); // scale coordinates with respect to bounding box of the scene for ( int d = 0; d < 3; ++d ) { a = scene_bounding_box.minCorner()[d]; b = scene_bounding_box.maxCorner()[d]; xyz[d] = ( a != b ? ( xyz[d] - a ) / ( b - a ) : 0 ); } morton_codes( i ) = morton3D( xyz[0], xyz[1], xyz[2] ); } ); Kokkos::fence(); } template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::assignMortonCodes( ConstViewType primitives, Kokkos::View<unsigned int *, DeviceType> morton_codes, Box const &scene_bounding_box ) { using Tag = typename Tag<typename decltype( primitives )::traits::non_const_value_type>::type; assignMortonCodesDispatch( Tag{}, primitives, morton_codes, scene_bounding_box ); } template <typename Primitives, typename Indices, typename Nodes> inline void initializeLeafNodesDispatch( BoxTag, Primitives primitives, Indices permutation_indices, Nodes leaf_nodes ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = leaf_nodes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "initialize_leaf_nodes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { leaf_nodes( i ) = { {nullptr, reinterpret_cast<Node *>( permutation_indices( i ) )}, primitives( permutation_indices( i ) )}; } ); Kokkos::fence(); } template <typename Primitives, typename Indices, typename Nodes> inline void initializeLeafNodesDispatch( PointTag, Primitives primitives, Indices permutation_indices, Nodes leaf_nodes ) { using ExecutionSpace = typename decltype( primitives )::traits::execution_space; auto const n = leaf_nodes.extent( 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "initialize_leaf_nodes" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n ), KOKKOS_LAMBDA( int i ) { leaf_nodes( i ) = { {nullptr, reinterpret_cast<Node *>( permutation_indices( i ) )}, {primitives( permutation_indices( i ) ), primitives( permutation_indices( i ) )}}; } ); Kokkos::fence(); } template <typename DeviceType> template <typename ConstViewType> inline void TreeConstruction<DeviceType>::initializeLeafNodes( ConstViewType primitives, Kokkos::View<size_t const *, DeviceType> permutation_indices, Kokkos::View<Node *, DeviceType> leaf_nodes ) { auto const n = leaf_nodes.extent( 0 ); DTK_REQUIRE( permutation_indices.extent( 0 ) == n ); DTK_REQUIRE( primitives.extent( 0 ) == n ); static_assert( sizeof( typename decltype( permutation_indices )::value_type ) == sizeof( Node * ), "Encoding leaf index in pointer to child is not safe if the " "index and pointer types do not have the same size" ); using Tag = typename Tag<typename decltype( primitives )::traits::non_const_value_type>::type; initializeLeafNodesDispatch( Tag{}, primitives, permutation_indices, leaf_nodes ); } } // namespace Details } // namespace DataTransferKit #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuconpol.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2007-07-18 11:12:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" //------------------------------------------------------------------------ // TOOLS #define _BIGINT_HXX #define _SFXMULTISEL_HXX #define _STACK_HXX #define _QUEUE_HXX #define _DYNARR_HXX #define _TREELIST_HXX #define _CACHESTR_HXX #define _NEW_HXX //#define _SHL_HXX //#define _LINK_HXX //#define _ERRCODE_HXX //#define _GEN_HXX //#define _FRACT_HXX //#define _STRING_HXX //#define _MTF_HXX //#define _CONTNR_HXX //#define _LIST_HXX //#define _TABLE_HXX #define _DYNARY_HXX //#define _UNQIDX_HXX #define _SVMEMPOOL_HXX //#define _UNQID_HXX //#define _DEBUG_HXX //#define _DATE_HXX //#define _TIME_HXX //#define _DATETIME_HXX //#define _INTN_HXX //#define _WLDCRD_HXX //#define _FSYS_HXX //#define _STREAM_HXX #define _CACHESTR_HXX #define _SV_MULTISEL_HXX //SV //#define _CLIP_HXX *** #define _CONFIG_HXX #define _CURSOR_HXX #define _FONTDLG_HXX #define _PRVWIN_HXX //#define _COLOR_HXX //#define _PAL_HXX //#define _BITMAP_HXX //#define _GDIOBJ_HXX //#define _POINTR_HXX //#define _ICON_HXX //#define _IMAGE_HXX //#define _KEYCOD_HXX //#define _EVENT_HXX #define _HELP_HXX //#define _APP_HXX //#define _MDIAPP_HXX //#define _TIMER_HXX //#define _METRIC_HXX //#define _REGION_HXX //#define _OUTDEV_HXX //#define _SYSTEM_HXX //#define _VIRDEV_HXX //#define _JOBSET_HXX //#define _PRINT_HXX //#define _WINDOW_HXX //#define _SYSWIN_HXX //#define _WRKWIN_HXX #define _MDIWIN_HXX //#define _FLOATWIN_HXX //#define _DOCKWIN_HXX //#define _CTRL_HXX //#define _SCRBAR_HXX //#define _BUTTON_HXX //#define _IMAGEBTN_HXX //#define _FIXED_HXX //#define _GROUP_HXX //#define _EDIT_HXX //#define _COMBOBOX_HXX //#define _LSTBOX_HXX //#define _SELENG_HXX *** //#define _SPLIT_HXX #define _SPIN_HXX //#define _FIELD_HXX //#define _MOREBTN_HXX *** //#define _TOOLBOX_HXX //#define _STATUS_HXX *** //#define _DIALOG_HXX //#define _MSGBOX_HXX //#define _SYSDLG_HXX //#define _FILDLG_HXX //#define _PRNDLG_HXX #define _COLDLG_HXX //#define _TABDLG_HXX //#define _MENU_HXX //#define _GDIMTF_HXX //#define _POLY_HXX //#define _ACCEL_HXX //#define _GRAPH_HXX #define _SOUND_HXX //------------------------------------------------------------------------ #include <svx/svdview.hxx> #ifndef _SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #include "fuconpol.hxx" #include "tabvwsh.hxx" #include "sc.hrc" // #98185# Create default drawing objects via keyboard #ifndef _SVDOPATH_HXX #include <svx/svdopath.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGON_HXX #include <basegfx/polygon/b2dpolygon.hxx> #endif #ifndef _BGFX_POINT_B2DPOINT_HXX #include <basegfx/point/b2dpoint.hxx> #endif // Pixelabstand zum Schliessen von Freihand-Zeichnungen #ifndef CLOSE_PIXDIST #define CLOSE_PIXDIST 5 #endif //------------------------------------------------------------------------ /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuConstPolygon::FuConstPolygon(ScTabViewShell* pViewSh, Window* pWin, SdrView* pViewP, SdrModel* pDoc, SfxRequest& rReq) : FuConstruct(pViewSh, pWin, pViewP, pDoc, rReq) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuConstPolygon::~FuConstPolygon() { } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL __EXPORT FuConstPolygon::MouseButtonDown(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FuConstruct::MouseButtonDown(rMEvt); SdrViewEvent aVEvt; (void)pView->PickAnything(rMEvt, SDRMOUSEBUTTONDOWN, aVEvt); if (aVEvt.eEvent == SDREVENT_BEGTEXTEDIT) { // Texteingabe hier nicht zulassen aVEvt.eEvent = SDREVENT_BEGDRAGOBJ; pView->EnableExtendedMouseEventDispatcher(FALSE); } else { pView->EnableExtendedMouseEventDispatcher(TRUE); } if ( pView->MouseButtonDown(rMEvt, pWindow) ) bReturn = TRUE; return bReturn; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL __EXPORT FuConstPolygon::MouseMove(const MouseEvent& rMEvt) { pView->MouseMove(rMEvt, pWindow); BOOL bReturn = FuConstruct::MouseMove(rMEvt); return bReturn; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL __EXPORT FuConstPolygon::MouseButtonUp(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FALSE; BOOL bSimple = FALSE; SdrViewEvent aVEvt; (void)pView->PickAnything(rMEvt, SDRMOUSEBUTTONUP, aVEvt); pView->MouseButtonUp(rMEvt, pWindow); if (aVEvt.eEvent == SDREVENT_ENDCREATE) { bReturn = TRUE; bSimple = TRUE; // Doppelklick nicht weiterreichen } BOOL bParent; if (bSimple) bParent = FuConstruct::SimpleMouseButtonUp(rMEvt); else bParent = FuConstruct::MouseButtonUp(rMEvt); return (bParent || bReturn); } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL __EXPORT FuConstPolygon::KeyInput(const KeyEvent& rKEvt) { BOOL bReturn = FuConstruct::KeyInput(rKEvt); return(bReturn); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuConstPolygon::Activate() { pView->EnableExtendedMouseEventDispatcher(TRUE); SdrObjKind eKind; switch (GetSlotID()) { case SID_DRAW_POLYGON_NOFILL: case SID_DRAW_XPOLYGON_NOFILL: { eKind = OBJ_PLIN; } break; case SID_DRAW_POLYGON: case SID_DRAW_XPOLYGON: { eKind = OBJ_POLY; } break; case SID_DRAW_BEZIER_NOFILL: { eKind = OBJ_PATHLINE; } break; case SID_DRAW_BEZIER_FILL: { eKind = OBJ_PATHFILL; } break; case SID_DRAW_FREELINE_NOFILL: { eKind = OBJ_FREELINE; } break; case SID_DRAW_FREELINE: { eKind = OBJ_FREEFILL; } break; default: { eKind = OBJ_PATHLINE; } break; } pView->SetCurrentObj(sal::static_int_cast<UINT16>(eKind)); pView->SetEditMode(SDREDITMODE_CREATE); FuConstruct::Activate(); aNewPointer = Pointer( POINTER_DRAW_POLYGON ); aOldPointer = pWindow->GetPointer(); pViewShell->SetActivePointer( aNewPointer ); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuConstPolygon::Deactivate() { pView->SetEditMode(SDREDITMODE_EDIT); pView->EnableExtendedMouseEventDispatcher(FALSE); FuConstruct::Deactivate(); pViewShell->SetActivePointer( aOldPointer ); } // #98185# Create default drawing objects via keyboard SdrObject* FuConstPolygon::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle) { // case SID_DRAW_POLYGON: // case SID_DRAW_POLYGON_NOFILL: // case SID_DRAW_BEZIER_NOFILL: // case SID_DRAW_FREELINE_NOFILL: SdrObject* pObj = SdrObjFactory::MakeNewObject( pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(), 0L, pDrDoc); if(pObj) { if(pObj->ISA(SdrPathObj)) { basegfx::B2DPolyPolygon aPoly; switch(nID) { case SID_DRAW_BEZIER_NOFILL: { basegfx::B2DPolygon aInnerPoly; aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left(), rRectangle.Bottom())); const basegfx::B2DPoint aCenterBottom(rRectangle.Center().X(), rRectangle.Bottom()); aInnerPoly.appendBezierSegment( aCenterBottom, aCenterBottom, basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Center().Y())); const basegfx::B2DPoint aCenterTop(rRectangle.Center().X(), rRectangle.Top()); aInnerPoly.appendBezierSegment( aCenterTop, aCenterTop, basegfx::B2DPoint(rRectangle.Right(), rRectangle.Top())); aPoly.append(aInnerPoly); break; } case SID_DRAW_FREELINE_NOFILL: { basegfx::B2DPolygon aInnerPoly; aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left(), rRectangle.Bottom())); aInnerPoly.appendBezierSegment( basegfx::B2DPoint(rRectangle.Left(), rRectangle.Top()), basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Top()), basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Center().Y())); aInnerPoly.appendBezierSegment( basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Bottom()), basegfx::B2DPoint(rRectangle.Right(), rRectangle.Bottom()), basegfx::B2DPoint(rRectangle.Right(), rRectangle.Top())); aPoly.append(aInnerPoly); break; } case SID_DRAW_POLYGON: case SID_DRAW_POLYGON_NOFILL: { basegfx::B2DPolygon aInnerPoly; const sal_Int32 nWdt(rRectangle.GetWidth()); const sal_Int32 nHgt(rRectangle.GetHeight()); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left(), rRectangle.Bottom())); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + (nWdt * 30) / 100, rRectangle.Top() + (nHgt * 70) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left(), rRectangle.Top() + (nHgt * 15) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + (nWdt * 65) / 100, rRectangle.Top())); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + nWdt, rRectangle.Top() + (nHgt * 30) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + (nWdt * 80) / 100, rRectangle.Top() + (nHgt * 50) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + (nWdt * 80) / 100, rRectangle.Top() + (nHgt * 75) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Bottom(), rRectangle.Right())); if(SID_DRAW_POLYGON_NOFILL == nID) { aInnerPoly.append(basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Bottom())); } else { aInnerPoly.setClosed(true); } aPoly.append(aInnerPoly); break; } } ((SdrPathObj*)pObj)->SetPathPoly(aPoly); } else { DBG_ERROR("Object is NO path object"); } pObj->SetLogicRect(rRectangle); } return pObj; } // eof <commit_msg>INTEGRATION: CWS changefileheader (1.8.240); FILE MERGED 2008/04/01 15:30:45 thb 1.8.240.2: #i85898# Stripping all external header guards 2008/03/31 17:15:31 rt 1.8.240.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuconpol.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" //------------------------------------------------------------------------ // TOOLS #define _BIGINT_HXX #define _SFXMULTISEL_HXX #define _STACK_HXX #define _QUEUE_HXX #define _DYNARR_HXX #define _TREELIST_HXX #define _CACHESTR_HXX #define _NEW_HXX //#define _SHL_HXX //#define _LINK_HXX //#define _ERRCODE_HXX //#define _GEN_HXX //#define _FRACT_HXX //#define _STRING_HXX //#define _MTF_HXX //#define _CONTNR_HXX //#define _LIST_HXX //#define _TABLE_HXX #define _DYNARY_HXX //#define _UNQIDX_HXX #define _SVMEMPOOL_HXX //#define _UNQID_HXX //#define _DEBUG_HXX //#define _DATE_HXX //#define _TIME_HXX //#define _DATETIME_HXX //#define _INTN_HXX //#define _WLDCRD_HXX //#define _FSYS_HXX //#define _STREAM_HXX #define _CACHESTR_HXX #define _SV_MULTISEL_HXX //SV //#define _CLIP_HXX *** #define _CONFIG_HXX #define _CURSOR_HXX #define _FONTDLG_HXX #define _PRVWIN_HXX //#define _COLOR_HXX //#define _PAL_HXX //#define _BITMAP_HXX //#define _GDIOBJ_HXX //#define _POINTR_HXX //#define _ICON_HXX //#define _IMAGE_HXX //#define _KEYCOD_HXX //#define _EVENT_HXX #define _HELP_HXX //#define _APP_HXX //#define _MDIAPP_HXX //#define _TIMER_HXX //#define _METRIC_HXX //#define _REGION_HXX //#define _OUTDEV_HXX //#define _SYSTEM_HXX //#define _VIRDEV_HXX //#define _JOBSET_HXX //#define _PRINT_HXX //#define _WINDOW_HXX //#define _SYSWIN_HXX //#define _WRKWIN_HXX #define _MDIWIN_HXX //#define _FLOATWIN_HXX //#define _DOCKWIN_HXX //#define _CTRL_HXX //#define _SCRBAR_HXX //#define _BUTTON_HXX //#define _IMAGEBTN_HXX //#define _FIXED_HXX //#define _GROUP_HXX //#define _EDIT_HXX //#define _COMBOBOX_HXX //#define _LSTBOX_HXX //#define _SELENG_HXX *** //#define _SPLIT_HXX #define _SPIN_HXX //#define _FIELD_HXX //#define _MOREBTN_HXX *** //#define _TOOLBOX_HXX //#define _STATUS_HXX *** //#define _DIALOG_HXX //#define _MSGBOX_HXX //#define _SYSDLG_HXX //#define _FILDLG_HXX //#define _PRNDLG_HXX #define _COLDLG_HXX //#define _TABDLG_HXX //#define _MENU_HXX //#define _GDIMTF_HXX //#define _POLY_HXX //#define _ACCEL_HXX //#define _GRAPH_HXX #define _SOUND_HXX //------------------------------------------------------------------------ #include <svx/svdview.hxx> #include <svx/svdobj.hxx> #include "fuconpol.hxx" #include "tabvwsh.hxx" #include "sc.hrc" // #98185# Create default drawing objects via keyboard #include <svx/svdopath.hxx> #include <basegfx/polygon/b2dpolygon.hxx> #include <basegfx/point/b2dpoint.hxx> // Pixelabstand zum Schliessen von Freihand-Zeichnungen #ifndef CLOSE_PIXDIST #define CLOSE_PIXDIST 5 #endif //------------------------------------------------------------------------ /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuConstPolygon::FuConstPolygon(ScTabViewShell* pViewSh, Window* pWin, SdrView* pViewP, SdrModel* pDoc, SfxRequest& rReq) : FuConstruct(pViewSh, pWin, pViewP, pDoc, rReq) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuConstPolygon::~FuConstPolygon() { } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL __EXPORT FuConstPolygon::MouseButtonDown(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FuConstruct::MouseButtonDown(rMEvt); SdrViewEvent aVEvt; (void)pView->PickAnything(rMEvt, SDRMOUSEBUTTONDOWN, aVEvt); if (aVEvt.eEvent == SDREVENT_BEGTEXTEDIT) { // Texteingabe hier nicht zulassen aVEvt.eEvent = SDREVENT_BEGDRAGOBJ; pView->EnableExtendedMouseEventDispatcher(FALSE); } else { pView->EnableExtendedMouseEventDispatcher(TRUE); } if ( pView->MouseButtonDown(rMEvt, pWindow) ) bReturn = TRUE; return bReturn; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL __EXPORT FuConstPolygon::MouseMove(const MouseEvent& rMEvt) { pView->MouseMove(rMEvt, pWindow); BOOL bReturn = FuConstruct::MouseMove(rMEvt); return bReturn; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL __EXPORT FuConstPolygon::MouseButtonUp(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FALSE; BOOL bSimple = FALSE; SdrViewEvent aVEvt; (void)pView->PickAnything(rMEvt, SDRMOUSEBUTTONUP, aVEvt); pView->MouseButtonUp(rMEvt, pWindow); if (aVEvt.eEvent == SDREVENT_ENDCREATE) { bReturn = TRUE; bSimple = TRUE; // Doppelklick nicht weiterreichen } BOOL bParent; if (bSimple) bParent = FuConstruct::SimpleMouseButtonUp(rMEvt); else bParent = FuConstruct::MouseButtonUp(rMEvt); return (bParent || bReturn); } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL __EXPORT FuConstPolygon::KeyInput(const KeyEvent& rKEvt) { BOOL bReturn = FuConstruct::KeyInput(rKEvt); return(bReturn); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuConstPolygon::Activate() { pView->EnableExtendedMouseEventDispatcher(TRUE); SdrObjKind eKind; switch (GetSlotID()) { case SID_DRAW_POLYGON_NOFILL: case SID_DRAW_XPOLYGON_NOFILL: { eKind = OBJ_PLIN; } break; case SID_DRAW_POLYGON: case SID_DRAW_XPOLYGON: { eKind = OBJ_POLY; } break; case SID_DRAW_BEZIER_NOFILL: { eKind = OBJ_PATHLINE; } break; case SID_DRAW_BEZIER_FILL: { eKind = OBJ_PATHFILL; } break; case SID_DRAW_FREELINE_NOFILL: { eKind = OBJ_FREELINE; } break; case SID_DRAW_FREELINE: { eKind = OBJ_FREEFILL; } break; default: { eKind = OBJ_PATHLINE; } break; } pView->SetCurrentObj(sal::static_int_cast<UINT16>(eKind)); pView->SetEditMode(SDREDITMODE_CREATE); FuConstruct::Activate(); aNewPointer = Pointer( POINTER_DRAW_POLYGON ); aOldPointer = pWindow->GetPointer(); pViewShell->SetActivePointer( aNewPointer ); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuConstPolygon::Deactivate() { pView->SetEditMode(SDREDITMODE_EDIT); pView->EnableExtendedMouseEventDispatcher(FALSE); FuConstruct::Deactivate(); pViewShell->SetActivePointer( aOldPointer ); } // #98185# Create default drawing objects via keyboard SdrObject* FuConstPolygon::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle) { // case SID_DRAW_POLYGON: // case SID_DRAW_POLYGON_NOFILL: // case SID_DRAW_BEZIER_NOFILL: // case SID_DRAW_FREELINE_NOFILL: SdrObject* pObj = SdrObjFactory::MakeNewObject( pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(), 0L, pDrDoc); if(pObj) { if(pObj->ISA(SdrPathObj)) { basegfx::B2DPolyPolygon aPoly; switch(nID) { case SID_DRAW_BEZIER_NOFILL: { basegfx::B2DPolygon aInnerPoly; aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left(), rRectangle.Bottom())); const basegfx::B2DPoint aCenterBottom(rRectangle.Center().X(), rRectangle.Bottom()); aInnerPoly.appendBezierSegment( aCenterBottom, aCenterBottom, basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Center().Y())); const basegfx::B2DPoint aCenterTop(rRectangle.Center().X(), rRectangle.Top()); aInnerPoly.appendBezierSegment( aCenterTop, aCenterTop, basegfx::B2DPoint(rRectangle.Right(), rRectangle.Top())); aPoly.append(aInnerPoly); break; } case SID_DRAW_FREELINE_NOFILL: { basegfx::B2DPolygon aInnerPoly; aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left(), rRectangle.Bottom())); aInnerPoly.appendBezierSegment( basegfx::B2DPoint(rRectangle.Left(), rRectangle.Top()), basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Top()), basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Center().Y())); aInnerPoly.appendBezierSegment( basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Bottom()), basegfx::B2DPoint(rRectangle.Right(), rRectangle.Bottom()), basegfx::B2DPoint(rRectangle.Right(), rRectangle.Top())); aPoly.append(aInnerPoly); break; } case SID_DRAW_POLYGON: case SID_DRAW_POLYGON_NOFILL: { basegfx::B2DPolygon aInnerPoly; const sal_Int32 nWdt(rRectangle.GetWidth()); const sal_Int32 nHgt(rRectangle.GetHeight()); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left(), rRectangle.Bottom())); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + (nWdt * 30) / 100, rRectangle.Top() + (nHgt * 70) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left(), rRectangle.Top() + (nHgt * 15) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + (nWdt * 65) / 100, rRectangle.Top())); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + nWdt, rRectangle.Top() + (nHgt * 30) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + (nWdt * 80) / 100, rRectangle.Top() + (nHgt * 50) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Left() + (nWdt * 80) / 100, rRectangle.Top() + (nHgt * 75) / 100)); aInnerPoly.append(basegfx::B2DPoint(rRectangle.Bottom(), rRectangle.Right())); if(SID_DRAW_POLYGON_NOFILL == nID) { aInnerPoly.append(basegfx::B2DPoint(rRectangle.Center().X(), rRectangle.Bottom())); } else { aInnerPoly.setClosed(true); } aPoly.append(aInnerPoly); break; } } ((SdrPathObj*)pObj)->SetPathPoly(aPoly); } else { DBG_ERROR("Object is NO path object"); } pObj->SetLogicRect(rRectangle); } return pObj; } // eof <|endoftext|>
<commit_before>#include "EventBrowser.h" #include <QTimer> #include "Code/Core.h" #include "ui_EventBrowser.h" enum { COL_NAME = 0, COL_EID = 1, COL_DURATION = 2, COL_CURRENT, COL_FIND, COL_BOOKMARK, }; EventBrowser::EventBrowser(Core *core, QWidget *parent) : QFrame(parent), ui(new Ui::EventBrowser), m_Core(core) { ui->setupUi(this); m_Core->AddLogViewer(this); ui->events->header()->resizeSection(COL_EID, 45); ui->events->header()->setSectionResizeMode(COL_NAME, QHeaderView::Stretch); ui->events->header()->setSectionResizeMode(COL_EID, QHeaderView::Interactive); ui->events->header()->setSectionResizeMode(COL_DURATION, QHeaderView::Interactive); // we set up the name column first, EID second, so that the name column gets the // expand/collapse widgets. Then we need to put them back in order ui->events->header()->moveSection(COL_NAME, COL_EID); // Qt doesn't allow moving the column with the expand/collapse widgets, so this // becomes quickly infuriating to rearrange, just disable until that can be fixed. ui->events->header()->setSectionsMovable(false); m_SizeDelegate = new SizeDelegate(QSize(0, 16)); ui->events->setItemDelegate(m_SizeDelegate); m_FindHighlight = new QTimer(this); m_FindHighlight->setInterval(400); m_FindHighlight->setSingleShot(true); connect(m_FindHighlight, SIGNAL(timeout()), this, SLOT(on_findHighlight_timeout())); QObject::connect(ui->closeFind, &QToolButton::clicked, this, &EventBrowser::on_HideFindJump); QObject::connect(ui->closeJump, &QToolButton::clicked, this, &EventBrowser::on_HideFindJump); QObject::connect(ui->jumpToEID, &LineEditFocusWidget::leave, this, &EventBrowser::on_HideFindJump); QObject::connect(ui->findEvent, &LineEditFocusWidget::leave, this, &EventBrowser::on_HideFindJump); ui->jumpStrip->hide(); ui->findStrip->hide(); ui->bookmarkStrip->hide(); m_CurrentIcon.addFile(QStringLiteral(":/Resources/flag_green.png"), QSize(), QIcon::Normal, QIcon::Off); m_FindIcon.addFile(QStringLiteral(":/Resources/find.png"), QSize(), QIcon::Normal, QIcon::Off); m_BookmarkIcon.addFile(QStringLiteral(":/Resources/asterisk_orange.png"), QSize(), QIcon::Normal, QIcon::Off); } EventBrowser::~EventBrowser() { m_Core->RemoveLogViewer(this); delete ui; delete m_SizeDelegate; } void EventBrowser::OnLogfileLoaded() { QTreeWidgetItem *frame = new QTreeWidgetItem( (QTreeWidget *)NULL, QStringList{QString("Frame #%1").arg(m_Core->FrameInfo().frameNumber), "", ""}); QTreeWidgetItem *framestart = new QTreeWidgetItem(frame, QStringList{"Frame Start", "0", ""}); framestart->setData(COL_EID, Qt::UserRole, QVariant(0)); framestart->setData(COL_CURRENT, Qt::UserRole, QVariant(false)); framestart->setData(COL_FIND, Qt::UserRole, QVariant(false)); framestart->setData(COL_BOOKMARK, Qt::UserRole, QVariant(false)); uint lastEID = AddDrawcalls(frame, m_Core->CurDrawcalls()); frame->setData(COL_EID, Qt::UserRole, QVariant(lastEID)); ui->events->insertTopLevelItem(0, frame); ui->events->expandItem(frame); m_Core->SetEventID(this, lastEID); } void EventBrowser::OnLogfileClosed() { ui->events->clear(); } void EventBrowser::OnEventSelected(uint32_t eventID) { SelectEvent(eventID); } uint EventBrowser::AddDrawcalls(QTreeWidgetItem *parent, const rdctype::array<FetchDrawcall> &draws) { uint lastEID = 0; for(int32_t i = 0; i < draws.count; i++) { QTreeWidgetItem *child = new QTreeWidgetItem( parent, QStringList{QString(draws[i].name.elems), QString("%1").arg(draws[i].eventID), "0.0"}); lastEID = AddDrawcalls(child, draws[i].children); if(lastEID == 0) lastEID = draws[i].eventID; child->setData(COL_EID, Qt::UserRole, QVariant(lastEID)); child->setData(COL_CURRENT, Qt::UserRole, QVariant(false)); child->setData(COL_FIND, Qt::UserRole, QVariant(false)); child->setData(COL_BOOKMARK, Qt::UserRole, QVariant(false)); } return lastEID; } void EventBrowser::SetDrawcallTimes(QTreeWidgetItem *node, const rdctype::array<CounterResult> &results) { if(node == NULL) return; // parent nodes take the value of the sum of their children double duration = 0.0; // look up leaf nodes in the dictionary if(node->childCount() == 0) { uint eid = node->data(COL_EID, Qt::UserRole).toUInt(); duration = -1.0; for(int32_t i = 0; i < results.count; i++) { if(results[i].eventID == eid) duration = results[i].value.d; } node->setText(COL_DURATION, duration < 0.0f ? "" : QString::number(duration * 1000000.0)); node->setData(COL_DURATION, Qt::UserRole, QVariant(duration)); return; } for(int i = 0; i < node->childCount(); i++) { SetDrawcallTimes(node->child(i), results); double nd = node->child(i)->data(COL_DURATION, Qt::UserRole).toDouble(); if(nd > 0.0) duration += nd; } node->setText(COL_DURATION, duration < 0.0f ? "" : QString::number(duration * 1000000.0)); node->setData(COL_DURATION, Qt::UserRole, QVariant(duration)); } void EventBrowser::on_find_clicked() { ui->jumpStrip->hide(); ui->findStrip->show(); ui->bookmarkStrip->hide(); ui->findEvent->setFocus(); } void EventBrowser::on_gotoEID_clicked() { ui->jumpStrip->show(); ui->findStrip->hide(); ui->bookmarkStrip->hide(); ui->jumpToEID->setFocus(); } void EventBrowser::on_toolButton_clicked() { ui->jumpStrip->hide(); ui->findStrip->hide(); ui->bookmarkStrip->show(); } void EventBrowser::on_timeDraws_clicked() { m_Core->Renderer()->AsyncInvoke([this](IReplayRenderer *r) { uint32_t counters[] = {eCounter_EventGPUDuration}; rdctype::array<CounterResult> results; r->FetchCounters(counters, 1, &results); GUIInvoke::blockcall( [this, results]() { SetDrawcallTimes(ui->events->topLevelItem(0), results); }); }); } void EventBrowser::on_events_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) { if(previous) { previous->setData(COL_CURRENT, Qt::UserRole, QVariant(false)); RefreshIcon(previous); } if(!current) return; current->setData(COL_CURRENT, Qt::UserRole, QVariant(true)); RefreshIcon(current); uint EID = current->data(COL_EID, Qt::UserRole).toUInt(); m_Core->SetEventID(this, EID); } void EventBrowser::on_HideFindJump() { ui->jumpStrip->hide(); ui->findStrip->hide(); ui->jumpToEID->setText(""); ClearFindIcons(); ui->findEvent->setText(""); ui->findEvent->setStyleSheet(""); } void EventBrowser::on_jumpToEID_returnPressed() { bool ok = false; uint eid = ui->jumpToEID->text().toUInt(&ok); if(ok) { SelectEvent(eid); } } void EventBrowser::on_findHighlight_timeout() { ClearFindIcons(); int results = SetFindIcons(ui->findEvent->text()); if(results > 0) ui->findEvent->setStyleSheet(""); else ui->findEvent->setStyleSheet("QLineEdit{background-color:#ff0000;}"); } void EventBrowser::on_findEvent_textEdited(const QString &arg1) { if(arg1.isEmpty()) { m_FindHighlight->stop(); ui->findEvent->setStyleSheet(""); ClearFindIcons(); } else { m_FindHighlight->start(); // restart } } void EventBrowser::on_findEvent_returnPressed() { if(m_FindHighlight->isActive()) { // manually fire it instantly m_FindHighlight->stop(); on_findHighlight_timeout(); } if(!ui->findEvent->text().isEmpty()) { Find(true); } } void EventBrowser::on_findNext_clicked() { Find(true); } void EventBrowser::on_findPrev_clicked() { Find(false); } void EventBrowser::RefreshIcon(QTreeWidgetItem *item) { if(item->data(COL_CURRENT, Qt::UserRole).toBool()) item->setIcon(COL_NAME, m_CurrentIcon); else if(item->data(COL_FIND, Qt::UserRole).toBool()) item->setIcon(COL_NAME, m_FindIcon); else if(item->data(COL_BOOKMARK, Qt::UserRole).toBool()) item->setIcon(COL_NAME, m_BookmarkIcon); else item->setIcon(COL_NAME, QIcon()); } bool EventBrowser::FindEventNode(QTreeWidgetItem *&found, QTreeWidgetItem *parent, uint32_t eventID) { for(int i = 0; i < parent->childCount(); i++) { QTreeWidgetItem *n = parent->child(i); uint nEID = n->data(COL_EID, Qt::UserRole).toUInt(); uint fEID = found ? found->data(COL_EID, Qt::UserRole).toUInt() : 0; if(nEID >= eventID && (found == NULL || nEID <= fEID)) found = n; if(nEID == eventID && n->childCount() == 0) return true; if(n->childCount() > 0) { bool exact = FindEventNode(found, n, eventID); if(exact) return true; } } return false; } void EventBrowser::ExpandNode(QTreeWidgetItem *node) { QTreeWidgetItem *n = node; while(node != NULL) { node->setExpanded(true); node = node->parent(); } if(n) ui->events->scrollToItem(n); } bool EventBrowser::SelectEvent(uint32_t eventID) { if(!m_Core->LogLoaded()) return false; QTreeWidgetItem *found = NULL; FindEventNode(found, ui->events->topLevelItem(0), eventID); if(found != NULL) { ui->events->clearSelection(); ui->events->setItemSelected(found, true); ui->events->setCurrentItem(found); ExpandNode(found); return true; } return false; } void EventBrowser::ClearFindIcons(QTreeWidgetItem *parent) { for(int i = 0; i < parent->childCount(); i++) { QTreeWidgetItem *n = parent->child(i); n->setData(COL_FIND, Qt::UserRole, QVariant(false)); RefreshIcon(n); if(n->childCount() > 0) ClearFindIcons(n); } } void EventBrowser::ClearFindIcons() { if(m_Core->LogLoaded()) ClearFindIcons(ui->events->topLevelItem(0)); } int EventBrowser::SetFindIcons(QTreeWidgetItem *parent, QString filter) { int results = 0; for(int i = 0; i < parent->childCount(); i++) { QTreeWidgetItem *n = parent->child(i); if(n->text(COL_NAME).contains(filter, Qt::CaseInsensitive)) { n->setData(COL_FIND, Qt::UserRole, QVariant(true)); RefreshIcon(n); results++; } if(n->childCount() > 0) { results += SetFindIcons(n, filter); } } return results; } int EventBrowser::SetFindIcons(QString filter) { if(filter.isEmpty()) return 0; return SetFindIcons(ui->events->topLevelItem(0), filter); } QTreeWidgetItem *EventBrowser::FindNode(QTreeWidgetItem *parent, QString filter, uint32_t after) { for(int i = 0; i < parent->childCount(); i++) { QTreeWidgetItem *n = parent->child(i); uint eid = n->data(COL_EID, Qt::UserRole).toUInt(); if(eid > after && n->text(COL_NAME).contains(filter, Qt::CaseInsensitive)) return n; if(n->childCount() > 0) { QTreeWidgetItem *found = FindNode(n, filter, after); if(found != NULL) return found; } } return NULL; } int EventBrowser::FindEvent(QTreeWidgetItem *parent, QString filter, uint32_t after, bool forward) { if(parent == NULL) return -1; for(int i = forward ? 0 : parent->childCount() - 1; i >= 0 && i < parent->childCount(); i += forward ? 1 : -1) { auto n = parent->child(i); uint eid = n->data(COL_EID, Qt::UserRole).toUInt(); bool matchesAfter = (forward && eid > after) || (!forward && eid < after); if(matchesAfter) { QString name = n->text(COL_NAME); if(name.contains(filter, Qt::CaseInsensitive)) return (int)eid; } if(n->childCount() > 0) { int found = FindEvent(n, filter, after, forward); if(found > 0) return found; } } return -1; } int EventBrowser::FindEvent(QString filter, uint32_t after, bool forward) { if(!m_Core->LogLoaded()) return 0; return FindEvent(ui->events->topLevelItem(0), filter, after, forward); } void EventBrowser::Find(bool forward) { if(ui->findEvent->text().isEmpty()) return; uint32_t curEID = m_Core->CurEvent(); if(!ui->events->selectedItems().isEmpty()) curEID = ui->events->selectedItems()[0]->data(COL_EID, Qt::UserRole).toUInt(); int eid = FindEvent(ui->findEvent->text(), curEID, forward); if(eid >= 0) { SelectEvent((uint32_t)eid); ui->findEvent->setStyleSheet(""); } else // if(WrapSearch) { eid = FindEvent(ui->findEvent->text(), forward ? 0 : ~0U, forward); if(eid >= 0) { SelectEvent((uint32_t)eid); ui->findEvent->setStyleSheet(""); } else { ui->findEvent->setStyleSheet("QLineEdit{background-color:#ff0000;}"); } } } <commit_msg>When selecting a marker, select the next 'real' draw instead<commit_after>#include "EventBrowser.h" #include <QTimer> #include "Code/Core.h" #include "ui_EventBrowser.h" enum { COL_NAME = 0, COL_EID = 1, COL_DURATION = 2, COL_CURRENT, COL_FIND, COL_BOOKMARK, COL_SELECT_EID, }; EventBrowser::EventBrowser(Core *core, QWidget *parent) : QFrame(parent), ui(new Ui::EventBrowser), m_Core(core) { ui->setupUi(this); m_Core->AddLogViewer(this); ui->events->header()->resizeSection(COL_EID, 45); ui->events->header()->setSectionResizeMode(COL_NAME, QHeaderView::Stretch); ui->events->header()->setSectionResizeMode(COL_EID, QHeaderView::Interactive); ui->events->header()->setSectionResizeMode(COL_DURATION, QHeaderView::Interactive); // we set up the name column first, EID second, so that the name column gets the // expand/collapse widgets. Then we need to put them back in order ui->events->header()->moveSection(COL_NAME, COL_EID); // Qt doesn't allow moving the column with the expand/collapse widgets, so this // becomes quickly infuriating to rearrange, just disable until that can be fixed. ui->events->header()->setSectionsMovable(false); m_SizeDelegate = new SizeDelegate(QSize(0, 16)); ui->events->setItemDelegate(m_SizeDelegate); m_FindHighlight = new QTimer(this); m_FindHighlight->setInterval(400); m_FindHighlight->setSingleShot(true); connect(m_FindHighlight, SIGNAL(timeout()), this, SLOT(on_findHighlight_timeout())); QObject::connect(ui->closeFind, &QToolButton::clicked, this, &EventBrowser::on_HideFindJump); QObject::connect(ui->closeJump, &QToolButton::clicked, this, &EventBrowser::on_HideFindJump); QObject::connect(ui->jumpToEID, &LineEditFocusWidget::leave, this, &EventBrowser::on_HideFindJump); QObject::connect(ui->findEvent, &LineEditFocusWidget::leave, this, &EventBrowser::on_HideFindJump); ui->jumpStrip->hide(); ui->findStrip->hide(); ui->bookmarkStrip->hide(); m_CurrentIcon.addFile(QStringLiteral(":/Resources/flag_green.png"), QSize(), QIcon::Normal, QIcon::Off); m_FindIcon.addFile(QStringLiteral(":/Resources/find.png"), QSize(), QIcon::Normal, QIcon::Off); m_BookmarkIcon.addFile(QStringLiteral(":/Resources/asterisk_orange.png"), QSize(), QIcon::Normal, QIcon::Off); } EventBrowser::~EventBrowser() { m_Core->RemoveLogViewer(this); delete ui; delete m_SizeDelegate; } void EventBrowser::OnLogfileLoaded() { QTreeWidgetItem *frame = new QTreeWidgetItem( (QTreeWidget *)NULL, QStringList{QString("Frame #%1").arg(m_Core->FrameInfo().frameNumber), "", ""}); QTreeWidgetItem *framestart = new QTreeWidgetItem(frame, QStringList{"Frame Start", "0", ""}); framestart->setData(COL_EID, Qt::UserRole, QVariant(0)); framestart->setData(COL_CURRENT, Qt::UserRole, QVariant(false)); framestart->setData(COL_FIND, Qt::UserRole, QVariant(false)); framestart->setData(COL_BOOKMARK, Qt::UserRole, QVariant(false)); framestart->setData(COL_SELECT_EID, Qt::UserRole, QVariant(0)); uint lastEID = AddDrawcalls(frame, m_Core->CurDrawcalls()); frame->setData(COL_EID, Qt::UserRole, QVariant(lastEID)); frame->setData(COL_SELECT_EID, Qt::UserRole, QVariant(lastEID)); ui->events->insertTopLevelItem(0, frame); ui->events->expandItem(frame); m_Core->SetEventID(this, lastEID); } void EventBrowser::OnLogfileClosed() { ui->events->clear(); } void EventBrowser::OnEventSelected(uint32_t eventID) { SelectEvent(eventID); } uint EventBrowser::AddDrawcalls(QTreeWidgetItem *parent, const rdctype::array<FetchDrawcall> &draws) { uint lastEID = 0; for(int32_t i = 0; i < draws.count; i++) { QTreeWidgetItem *child = new QTreeWidgetItem( parent, QStringList{QString(draws[i].name.elems), QString("%1").arg(draws[i].eventID), "0.0"}); lastEID = AddDrawcalls(child, draws[i].children); if(lastEID == 0) { lastEID = draws[i].eventID; if((draws[i].flags & eDraw_SetMarker) && i + 1 < draws.count) lastEID = draws[i + 1].eventID; } child->setData(COL_EID, Qt::UserRole, QVariant(lastEID)); child->setData(COL_CURRENT, Qt::UserRole, QVariant(false)); child->setData(COL_FIND, Qt::UserRole, QVariant(false)); child->setData(COL_BOOKMARK, Qt::UserRole, QVariant(false)); child->setData(COL_SELECT_EID, Qt::UserRole, QVariant(lastEID)); } return lastEID; } void EventBrowser::SetDrawcallTimes(QTreeWidgetItem *node, const rdctype::array<CounterResult> &results) { if(node == NULL) return; // parent nodes take the value of the sum of their children double duration = 0.0; // look up leaf nodes in the dictionary if(node->childCount() == 0) { uint eid = node->data(COL_SELECT_EID, Qt::UserRole).toUInt(); duration = -1.0; for(int32_t i = 0; i < results.count; i++) { if(results[i].eventID == eid) duration = results[i].value.d; } node->setText(COL_DURATION, duration < 0.0f ? "" : QString::number(duration * 1000000.0)); node->setData(COL_DURATION, Qt::UserRole, QVariant(duration)); return; } for(int i = 0; i < node->childCount(); i++) { SetDrawcallTimes(node->child(i), results); double nd = node->child(i)->data(COL_DURATION, Qt::UserRole).toDouble(); if(nd > 0.0) duration += nd; } node->setText(COL_DURATION, duration < 0.0f ? "" : QString::number(duration * 1000000.0)); node->setData(COL_DURATION, Qt::UserRole, QVariant(duration)); } void EventBrowser::on_find_clicked() { ui->jumpStrip->hide(); ui->findStrip->show(); ui->bookmarkStrip->hide(); ui->findEvent->setFocus(); } void EventBrowser::on_gotoEID_clicked() { ui->jumpStrip->show(); ui->findStrip->hide(); ui->bookmarkStrip->hide(); ui->jumpToEID->setFocus(); } void EventBrowser::on_toolButton_clicked() { ui->jumpStrip->hide(); ui->findStrip->hide(); ui->bookmarkStrip->show(); } void EventBrowser::on_timeDraws_clicked() { m_Core->Renderer()->AsyncInvoke([this](IReplayRenderer *r) { uint32_t counters[] = {eCounter_EventGPUDuration}; rdctype::array<CounterResult> results; r->FetchCounters(counters, 1, &results); GUIInvoke::blockcall( [this, results]() { SetDrawcallTimes(ui->events->topLevelItem(0), results); }); }); } void EventBrowser::on_events_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) { if(previous) { previous->setData(COL_CURRENT, Qt::UserRole, QVariant(false)); RefreshIcon(previous); } if(!current) return; current->setData(COL_CURRENT, Qt::UserRole, QVariant(true)); RefreshIcon(current); uint EID = current->data(COL_SELECT_EID, Qt::UserRole).toUInt(); m_Core->SetEventID(this, EID); } void EventBrowser::on_HideFindJump() { ui->jumpStrip->hide(); ui->findStrip->hide(); ui->jumpToEID->setText(""); ClearFindIcons(); ui->findEvent->setText(""); ui->findEvent->setStyleSheet(""); } void EventBrowser::on_jumpToEID_returnPressed() { bool ok = false; uint eid = ui->jumpToEID->text().toUInt(&ok); if(ok) { SelectEvent(eid); } } void EventBrowser::on_findHighlight_timeout() { ClearFindIcons(); int results = SetFindIcons(ui->findEvent->text()); if(results > 0) ui->findEvent->setStyleSheet(""); else ui->findEvent->setStyleSheet("QLineEdit{background-color:#ff0000;}"); } void EventBrowser::on_findEvent_textEdited(const QString &arg1) { if(arg1.isEmpty()) { m_FindHighlight->stop(); ui->findEvent->setStyleSheet(""); ClearFindIcons(); } else { m_FindHighlight->start(); // restart } } void EventBrowser::on_findEvent_returnPressed() { if(m_FindHighlight->isActive()) { // manually fire it instantly m_FindHighlight->stop(); on_findHighlight_timeout(); } if(!ui->findEvent->text().isEmpty()) { Find(true); } } void EventBrowser::on_findNext_clicked() { Find(true); } void EventBrowser::on_findPrev_clicked() { Find(false); } void EventBrowser::RefreshIcon(QTreeWidgetItem *item) { if(item->data(COL_CURRENT, Qt::UserRole).toBool()) item->setIcon(COL_NAME, m_CurrentIcon); else if(item->data(COL_FIND, Qt::UserRole).toBool()) item->setIcon(COL_NAME, m_FindIcon); else if(item->data(COL_BOOKMARK, Qt::UserRole).toBool()) item->setIcon(COL_NAME, m_BookmarkIcon); else item->setIcon(COL_NAME, QIcon()); } bool EventBrowser::FindEventNode(QTreeWidgetItem *&found, QTreeWidgetItem *parent, uint32_t eventID) { for(int i = 0; i < parent->childCount(); i++) { QTreeWidgetItem *n = parent->child(i); uint nEID = n->data(COL_SELECT_EID, Qt::UserRole).toUInt(); uint fEID = found ? found->data(COL_SELECT_EID, Qt::UserRole).toUInt() : 0; if(nEID >= eventID && (found == NULL || nEID <= fEID)) found = n; if(nEID == eventID && n->childCount() == 0) return true; if(n->childCount() > 0) { bool exact = FindEventNode(found, n, eventID); if(exact) return true; } } return false; } void EventBrowser::ExpandNode(QTreeWidgetItem *node) { QTreeWidgetItem *n = node; while(node != NULL) { node->setExpanded(true); node = node->parent(); } if(n) ui->events->scrollToItem(n); } bool EventBrowser::SelectEvent(uint32_t eventID) { if(!m_Core->LogLoaded()) return false; QTreeWidgetItem *found = NULL; FindEventNode(found, ui->events->topLevelItem(0), eventID); if(found != NULL) { ui->events->clearSelection(); ui->events->setItemSelected(found, true); ui->events->setCurrentItem(found); ExpandNode(found); return true; } return false; } void EventBrowser::ClearFindIcons(QTreeWidgetItem *parent) { for(int i = 0; i < parent->childCount(); i++) { QTreeWidgetItem *n = parent->child(i); n->setData(COL_FIND, Qt::UserRole, QVariant(false)); RefreshIcon(n); if(n->childCount() > 0) ClearFindIcons(n); } } void EventBrowser::ClearFindIcons() { if(m_Core->LogLoaded()) ClearFindIcons(ui->events->topLevelItem(0)); } int EventBrowser::SetFindIcons(QTreeWidgetItem *parent, QString filter) { int results = 0; for(int i = 0; i < parent->childCount(); i++) { QTreeWidgetItem *n = parent->child(i); if(n->text(COL_NAME).contains(filter, Qt::CaseInsensitive)) { n->setData(COL_FIND, Qt::UserRole, QVariant(true)); RefreshIcon(n); results++; } if(n->childCount() > 0) { results += SetFindIcons(n, filter); } } return results; } int EventBrowser::SetFindIcons(QString filter) { if(filter.isEmpty()) return 0; return SetFindIcons(ui->events->topLevelItem(0), filter); } QTreeWidgetItem *EventBrowser::FindNode(QTreeWidgetItem *parent, QString filter, uint32_t after) { for(int i = 0; i < parent->childCount(); i++) { QTreeWidgetItem *n = parent->child(i); uint eid = n->data(COL_SELECT_EID, Qt::UserRole).toUInt(); if(eid > after && n->text(COL_NAME).contains(filter, Qt::CaseInsensitive)) return n; if(n->childCount() > 0) { QTreeWidgetItem *found = FindNode(n, filter, after); if(found != NULL) return found; } } return NULL; } int EventBrowser::FindEvent(QTreeWidgetItem *parent, QString filter, uint32_t after, bool forward) { if(parent == NULL) return -1; for(int i = forward ? 0 : parent->childCount() - 1; i >= 0 && i < parent->childCount(); i += forward ? 1 : -1) { auto n = parent->child(i); uint eid = n->data(COL_SELECT_EID, Qt::UserRole).toUInt(); bool matchesAfter = (forward && eid > after) || (!forward && eid < after); if(matchesAfter) { QString name = n->text(COL_NAME); if(name.contains(filter, Qt::CaseInsensitive)) return (int)eid; } if(n->childCount() > 0) { int found = FindEvent(n, filter, after, forward); if(found > 0) return found; } } return -1; } int EventBrowser::FindEvent(QString filter, uint32_t after, bool forward) { if(!m_Core->LogLoaded()) return 0; return FindEvent(ui->events->topLevelItem(0), filter, after, forward); } void EventBrowser::Find(bool forward) { if(ui->findEvent->text().isEmpty()) return; uint32_t curEID = m_Core->CurEvent(); if(!ui->events->selectedItems().isEmpty()) curEID = ui->events->selectedItems()[0]->data(COL_SELECT_EID, Qt::UserRole).toUInt(); int eid = FindEvent(ui->findEvent->text(), curEID, forward); if(eid >= 0) { SelectEvent((uint32_t)eid); ui->findEvent->setStyleSheet(""); } else // if(WrapSearch) { eid = FindEvent(ui->findEvent->text(), forward ? 0 : ~0U, forward); if(eid >= 0) { SelectEvent((uint32_t)eid); ui->findEvent->setStyleSheet(""); } else { ui->findEvent->setStyleSheet("QLineEdit{background-color:#ff0000;}"); } } } <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file Dispatcher.hxx * * Class for dispatching incoming messages to handlers. * * @author Balazs Racz * @date 2 Dec 2013 */ #ifndef _executor_Dispatcher_hxx_ #define _executor_Dispatcher_hxx_ #include <vector> #include "executor/notifiable.hxx" #include "executor/allocator.hxx" #include "executor/control_flow.hxx" #include "nmranet/NMRAnetIf.hxx" #include "nmranet/NMRAnetNode.hxx" /** Abstract class for handling an incoming message of a specifc MTI in NMRAnet. Handle calls are always made on the IF's read executor. There are two allocation mechanism available: . in one case the handler is directly able to process messages and performs the allocation itself. This is helpful for synchronous handlers, or when actual objects (instead of factories) are performing the handling of messages, such as when waiting for responses to outbound messages. . or the handler call actually returns an Allocator, which the caller has to acquire a handler from and re-post the same call to that handler. */ class HandlerBase : public QueueMember { public: /** Retrieves the allocator needed for a handler. The caller must retrieve * an instance from the allocator, or if the returned allocator is NULL, * then the caller may invoke this->handle_message immediately. * * @returns an allocator of type HandlerBase; or NULL. */ virtual AllocatorBase* get_allocator() { return NULL; } }; template <class Param> class ParamHandler : public HandlerBase { public: /** * Initiates handling of an incoming message. * * @param message is the incoming message. Does not take ownership. * @param done notifiable, will be notified when the message handling is * completed and message can be deallocated. Required. */ virtual void handle_message(Param* message, Notifiable* done) = 0; }; /** This class takes registered handlers for incoming messages. When a message shows up, all the handlers that match that message will be invoked. When all the handlers return, the message will be marked as completed, and the current flow will be released for further message calls. Handlers are called in no particular order. Allocation semantics: This flow is attached to a TypedAllocator owned by the If. The flow will return itself to the allocator automatically. */ template <typename ID> class DispatchFlow : public ControlFlow { public: DispatchFlow(Executor* executor); virtual ~DispatchFlow(); /** Handles an incoming message. Prior to this call the parameters needed for the call should be injected into the flow using an implementation-specific method. @param id is the identifier of the incoming message. The flow *this will release itself to the allocator when the message handling is done. */ void IncomingMessage(ID id); TypedAllocator<DispatchFlow<ID>>* allocator() { return &allocator_; } size_t handler_count() { return handlers_.size(); } protected: /** Adds a new handler to this dispatcher. A handler will be called if incoming_mti & mask == mti & mask. @param mti is the identifier of the message to listen to. @param mask is the mask of the mti matcher. @param handler is the MTI handler. It must stay alive so long as this If is alive. */ void RegisterHandler(ID id, ID mask, HandlerBase* handler); //! Removes a specific instance of a handler from this IF. void UnregisterHandler(ID id, ID mask, HandlerBase* handler); /** Makes an implementation-specific call to the actual handler. Implementations will need to take certain handler arguments from member variables. The 'done' notifiable must be called in all cases. */ virtual void CallCurrentHandler(HandlerBase* handler, Notifiable* done) = 0; /** This function will be called when the flow and all children are done. Useful for implementations to release memory and buffers associated with the current parameters. @returns true if the flow instance should be returned to the allocator. If returns false, must take care of changing the flow to a different state. */ virtual bool OnFlowFinished() { return true; }; private: // State handler. Calls the current handler. ControlFlowAction HandleCall(); // State handler. If calling the handler didn't work, this state will be // called after the allocation. ControlFlowAction HandleAllocateResult(); // State handler. Waits for the children to finish. ControlFlowAction HandleWaitForChildren(); struct HandlerInfo { HandlerInfo() : handler(nullptr) { } ID id; ID mask; // NULL if the handler has been removed. HandlerBase* handler; bool Equals(ID id, ID mask, HandlerBase* handler) { return (this->id == id && this->mask == mask && this->handler == handler); } }; vector<HandlerInfo> handlers_; // Index of the current iteration. size_t current_index_; // Points to a deleted entry in the vector, or -1. int pending_delete_index_; // These fields contain the message currently in progress. ID id_; // This notifiable tracks all the pending handlers. BarrierNotifiable children_; OSMutex lock_; TypedAllocator<DispatchFlow<ID>> allocator_; }; template <typename ID, class Params> class TypedDispatchFlow : public DispatchFlow<ID> { public: typedef ParamHandler<Params> Handler; TypedDispatchFlow(Executor* e) : DispatchFlow<ID>(e) { } TypedAllocator<TypedDispatchFlow<ID, Params>>* allocator() { return reinterpret_cast<TypedAllocator<TypedDispatchFlow<ID, Params>>*>( DispatchFlow<ID>::allocator()); } /** Adds a new handler to this dispatcher. A handler will be called if incoming_id & mask == id & mask. @param id is the identifier of the message to listen to. @param mask is the mask of the ID matcher. @param handler is the handler. It must stay alive so long as this Dispatcher is alive. */ void RegisterHandler(ID id, ID mask, Handler* handler) { DispatchFlow<ID>::RegisterHandler(id, mask, handler); } //! Removes a specific instance of a handler. void UnregisterHandler(ID id, ID mask, Handler* handler) { DispatchFlow<ID>::UnregisterHandler(id, mask, handler); } /** @returns the parameters structure to fill in before calling IncomingMessage. The caller must be in ownership of *this from an allocator before using this pointer. */ Params* mutable_params() { return &params_; } protected: virtual void CallCurrentHandler(HandlerBase* b_handler, Notifiable* done) { Handler* handler = static_cast<Handler*>(b_handler); handler->handle_message(&params_, done); } Params params_; }; // ================== IMPLEMENTATION ================== template <typename ID> DispatchFlow<ID>::DispatchFlow(Executor* executor) : ControlFlow(executor, nullptr), pending_delete_index_(-1) { allocator_.Release(this); } template <typename ID> DispatchFlow<ID>::~DispatchFlow() { HASSERT(IsNotStarted()); } template <typename ID> void DispatchFlow<ID>::RegisterHandler(ID id, ID mask, HandlerBase* handler) { OSMutexLock h(&lock_); size_t idx = pending_delete_index_; while (idx < handlers_.size() && handlers_[idx].handler) { ++idx; } if (idx >= handlers_.size()) { idx = handlers_.size(); handlers_.resize(handlers_.size() + 1); } handlers_[idx].handler = handler; handlers_[idx].id = id; handlers_[idx].mask = mask; } template <typename ID> void DispatchFlow<ID>::UnregisterHandler(ID id, ID mask, HandlerBase* handler) { OSMutexLock h(&lock_); // First we try the current index - 1. size_t idx = current_index_; if (idx > 0) idx--; if (idx >= handlers_.size() || !handlers_[idx].Equals(id, mask, handler)) { // We try all others too. idx = 0; while (idx < handlers_.size() && !handlers_[idx].Equals(id, mask, handler)) ++idx; } // Checks that we found the thing to unregister. HASSERT(idx < handlers_.size()); handlers_[idx].handler = nullptr; if (pending_delete_index_ < 0 || idx < (size_t)pending_delete_index_) { pending_delete_index_ = idx; } } template <typename ID> void DispatchFlow<ID>::IncomingMessage(ID id) { HASSERT(IsNotStarted()); HASSERT(children_.IsDone()); current_index_ = 0; id_ = id; children_.Reset(this); StartFlowAt(ST(HandleCall)); } template <typename ID> ControlFlow::ControlFlowAction DispatchFlow<ID>::HandleCall() { HandlerBase* handler; { OSMutexLock l(&lock_); while (true) { if (current_index_ >= handlers_.size()) { children_.MaybeDone(); return WaitAndCall(ST(HandleWaitForChildren)); } auto& h = handlers_[current_index_]; ++current_index_; if (!h.handler) { continue; } if ((id_ & h.mask) != (h.id & h.mask)) { continue; } handler = h.handler; break; } } AllocatorBase* a = handler->get_allocator(); if (a) { return Allocate(a, ST(HandleAllocateResult)); } else { CallCurrentHandler(handler, children_.NewChild()); // Call went OK, proceed to the next handler to call. return RetryCurrentState(); } } template <typename ID> ControlFlow::ControlFlowAction DispatchFlow<ID>::HandleAllocateResult() { HandlerBase* h; GetAllocationResult(&h); CallCurrentHandler(h, children_.NewChild()); return CallImmediately(ST(HandleCall)); } template <typename ID> ControlFlow::ControlFlowAction DispatchFlow<ID>::HandleWaitForChildren() { if (children_.IsDone()) { if (OnFlowFinished()) { // terminate flow. return ReleaseAndExit(&allocator_, this); } else { // The termination was taken care of by OnFlowFinished. return WaitForNotification(); } } else { return WaitForNotification(); } } #endif // _executor_Dispatcher_hxx_ <commit_msg>clang-formats dispatcher.<commit_after>/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file Dispatcher.hxx * * Class for dispatching incoming messages to handlers. * * @author Balazs Racz * @date 2 Dec 2013 */ #ifndef _executor_Dispatcher_hxx_ #define _executor_Dispatcher_hxx_ #include <vector> #include "executor/notifiable.hxx" #include "executor/allocator.hxx" #include "executor/control_flow.hxx" #include "nmranet/NMRAnetIf.hxx" #include "nmranet/NMRAnetNode.hxx" /** Abstract class for handling an incoming message of a specifc MTI in NMRAnet. Handle calls are always made on the IF's read executor. There are two allocation mechanism available: . in one case the handler is directly able to process messages and performs the allocation itself. This is helpful for synchronous handlers, or when actual objects (instead of factories) are performing the handling of messages, such as when waiting for responses to outbound messages. . or the handler call actually returns an Allocator, which the caller has to acquire a handler from and re-post the same call to that handler. */ class HandlerBase : public QueueMember { public: /** Retrieves the allocator needed for a handler. The caller must retrieve * an instance from the allocator, or if the returned allocator is NULL, * then the caller may invoke this->handle_message immediately. * * @returns an allocator of type HandlerBase; or NULL. */ virtual AllocatorBase* get_allocator() { return NULL; } }; template <class Param> class ParamHandler : public HandlerBase { public: /** * Initiates handling of an incoming message. * * @param message is the incoming message. Does not take ownership. * @param done notifiable, will be notified when the message handling is * completed and message can be deallocated. Required. */ virtual void handle_message(Param* message, Notifiable* done) = 0; }; /** This class takes registered handlers for incoming messages. When a message shows up, all the handlers that match that message will be invoked. When all the handlers return, the message will be marked as completed, and the current flow will be released for further message calls. Handlers are called in no particular order. Allocation semantics: This flow is attached to a TypedAllocator owned by the If. The flow will return itself to the allocator automatically. */ template <typename ID> class DispatchFlow : public ControlFlow { public: DispatchFlow(Executor* executor); virtual ~DispatchFlow(); /** Handles an incoming message. Prior to this call the parameters needed for the call should be injected into the flow using an implementation-specific method. @param id is the identifier of the incoming message. The flow *this will release itself to the allocator when the message handling is done. */ void IncomingMessage(ID id); TypedAllocator<DispatchFlow<ID>>* allocator() { return &allocator_; } size_t handler_count() { return handlers_.size(); } protected: /** Adds a new handler to this dispatcher. A handler will be called if incoming_mti & mask == mti & mask. @param mti is the identifier of the message to listen to. @param mask is the mask of the mti matcher. @param handler is the MTI handler. It must stay alive so long as this If is alive. */ void RegisterHandler(ID id, ID mask, HandlerBase* handler); //! Removes a specific instance of a handler from this IF. void UnregisterHandler(ID id, ID mask, HandlerBase* handler); /** Makes an implementation-specific call to the actual handler. Implementations will need to take certain handler arguments from member variables. The 'done' notifiable must be called in all cases. */ virtual void CallCurrentHandler(HandlerBase* handler, Notifiable* done) = 0; /** This function will be called when the flow and all children are done. Useful for implementations to release memory and buffers associated with the current parameters. @returns true if the flow instance should be returned to the allocator. If returns false, must take care of changing the flow to a different state. */ virtual bool OnFlowFinished() { return true; }; private: // State handler. Calls the current handler. ControlFlowAction HandleCall(); // State handler. If calling the handler didn't work, this state will be // called after the allocation. ControlFlowAction HandleAllocateResult(); // State handler. Waits for the children to finish. ControlFlowAction HandleWaitForChildren(); struct HandlerInfo { HandlerInfo() : handler(nullptr) { } ID id; ID mask; // NULL if the handler has been removed. HandlerBase* handler; bool Equals(ID id, ID mask, HandlerBase* handler) { return (this->id == id && this->mask == mask && this->handler == handler); } }; vector<HandlerInfo> handlers_; // Index of the current iteration. size_t current_index_; // Points to a deleted entry in the vector, or -1. int pending_delete_index_; // These fields contain the message currently in progress. ID id_; // This notifiable tracks all the pending handlers. BarrierNotifiable children_; OSMutex lock_; TypedAllocator<DispatchFlow<ID>> allocator_; }; template <typename ID, class Params> class TypedDispatchFlow : public DispatchFlow<ID> { public: typedef ParamHandler<Params> Handler; TypedDispatchFlow(Executor* e) : DispatchFlow<ID>(e) { } TypedAllocator<TypedDispatchFlow<ID, Params>>* allocator() { return reinterpret_cast<TypedAllocator<TypedDispatchFlow<ID, Params>>*>( DispatchFlow<ID>::allocator()); } /** Adds a new handler to this dispatcher. A handler will be called if incoming_id & mask == id & mask. @param id is the identifier of the message to listen to. @param mask is the mask of the ID matcher. @param handler is the handler. It must stay alive so long as this Dispatcher is alive. */ void RegisterHandler(ID id, ID mask, Handler* handler) { DispatchFlow<ID>::RegisterHandler(id, mask, handler); } //! Removes a specific instance of a handler. void UnregisterHandler(ID id, ID mask, Handler* handler) { DispatchFlow<ID>::UnregisterHandler(id, mask, handler); } /** @returns the parameters structure to fill in before calling IncomingMessage. The caller must be in ownership of *this from an allocator before using this pointer. */ Params* mutable_params() { return &params_; } protected: virtual void CallCurrentHandler(HandlerBase* b_handler, Notifiable* done) { Handler* handler = static_cast<Handler*>(b_handler); handler->handle_message(&params_, done); } Params params_; }; // ================== IMPLEMENTATION ================== template <typename ID> DispatchFlow<ID>::DispatchFlow(Executor* executor) : ControlFlow(executor, nullptr), pending_delete_index_(-1) { allocator_.Release(this); } template <typename ID> DispatchFlow<ID>::~DispatchFlow() { HASSERT(IsNotStarted()); } template <typename ID> void DispatchFlow<ID>::RegisterHandler(ID id, ID mask, HandlerBase* handler) { OSMutexLock h(&lock_); size_t idx = pending_delete_index_; while (idx < handlers_.size() && handlers_[idx].handler) { ++idx; } if (idx >= handlers_.size()) { idx = handlers_.size(); handlers_.resize(handlers_.size() + 1); } handlers_[idx].handler = handler; handlers_[idx].id = id; handlers_[idx].mask = mask; } template <typename ID> void DispatchFlow<ID>::UnregisterHandler(ID id, ID mask, HandlerBase* handler) { OSMutexLock h(&lock_); // First we try the current index - 1. size_t idx = current_index_; if (idx > 0) idx--; if (idx >= handlers_.size() || !handlers_[idx].Equals(id, mask, handler)) { // We try all others too. idx = 0; while (idx < handlers_.size() && !handlers_[idx].Equals(id, mask, handler)) ++idx; } // Checks that we found the thing to unregister. HASSERT(idx < handlers_.size()); handlers_[idx].handler = nullptr; if (pending_delete_index_ < 0 || idx < (size_t)pending_delete_index_) { pending_delete_index_ = idx; } } template <typename ID> void DispatchFlow<ID>::IncomingMessage(ID id) { HASSERT(IsNotStarted()); HASSERT(children_.IsDone()); current_index_ = 0; id_ = id; children_.Reset(this); StartFlowAt(ST(HandleCall)); } template <typename ID> ControlFlow::ControlFlowAction DispatchFlow<ID>::HandleCall() { HandlerBase* handler; { OSMutexLock l(&lock_); while (true) { if (current_index_ >= handlers_.size()) { children_.MaybeDone(); return WaitAndCall(ST(HandleWaitForChildren)); } auto& h = handlers_[current_index_]; ++current_index_; if (!h.handler) { continue; } if ((id_ & h.mask) != (h.id & h.mask)) { continue; } handler = h.handler; break; } } AllocatorBase* a = handler->get_allocator(); if (a) { return Allocate(a, ST(HandleAllocateResult)); } else { CallCurrentHandler(handler, children_.NewChild()); // Call went OK, proceed to the next handler to call. return RetryCurrentState(); } } template <typename ID> ControlFlow::ControlFlowAction DispatchFlow<ID>::HandleAllocateResult() { HandlerBase* h; GetAllocationResult(&h); CallCurrentHandler(h, children_.NewChild()); return CallImmediately(ST(HandleCall)); } template <typename ID> ControlFlow::ControlFlowAction DispatchFlow<ID>::HandleWaitForChildren() { if (children_.IsDone()) { if (OnFlowFinished()) { // terminate flow. return ReleaseAndExit(&allocator_, this); } else { // The termination was taken care of by OnFlowFinished. return WaitForNotification(); } } else { return WaitForNotification(); } } #endif // _executor_Dispatcher_hxx_ <|endoftext|>
<commit_before>// Copyright (c) 2018 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. // A test of roundtrips through the encoder and decoder. #include <stddef.h> #include "absl/strings/string_view.h" #include "http2/decoder/decode_buffer.h" #include "http2/decoder/decode_status.h" #include "http2/hpack/huffman/hpack_huffman_decoder.h" #include "http2/hpack/huffman/hpack_huffman_encoder.h" #include "http2/tools/random_decoder_test.h" #include "common/platform/api/quiche_test.h" #include "common/quiche_text_utils.h" using ::testing::AssertionResult; using ::testing::AssertionSuccess; using ::testing::tuple; namespace http2 { namespace test { namespace { std::string GenAsciiNonControlSet() { std::string s; const char space = ' '; // First character after the control characters: 0x20 const char del = 127; // First character after the non-control characters. for (char c = space; c < del; ++c) { s.push_back(c); } return s; } class HpackHuffmanTranscoderTest : public RandomDecoderTest { protected: HpackHuffmanTranscoderTest() : ascii_non_control_set_(GenAsciiNonControlSet()) { // The decoder may return true, and its accumulator may be empty, at // many boundaries while decoding, and yet the whole string hasn't // been decoded. stop_decode_on_done_ = false; } DecodeStatus StartDecoding(DecodeBuffer* b) override { input_bytes_seen_ = 0; output_buffer_.clear(); decoder_.Reset(); return ResumeDecoding(b); } DecodeStatus ResumeDecoding(DecodeBuffer* b) override { input_bytes_seen_ += b->Remaining(); absl::string_view sp(b->cursor(), b->Remaining()); if (decoder_.Decode(sp, &output_buffer_)) { b->AdvanceCursor(b->Remaining()); // Successfully decoded (or buffered) the bytes in absl::string_view. EXPECT_LE(input_bytes_seen_, input_bytes_expected_); // Have we reached the end of the encoded string? if (input_bytes_expected_ == input_bytes_seen_) { if (decoder_.InputProperlyTerminated()) { return DecodeStatus::kDecodeDone; } else { return DecodeStatus::kDecodeError; } } return DecodeStatus::kDecodeInProgress; } return DecodeStatus::kDecodeError; } AssertionResult TranscodeAndValidateSeveralWays( absl::string_view plain, absl::string_view expected_huffman) { size_t encoded_size = HuffmanSize(plain); std::string encoded; HuffmanEncode(plain, encoded_size, &encoded); VERIFY_EQ(encoded_size, encoded.size()); if (expected_huffman.size() > 0 || plain.empty()) { VERIFY_EQ(encoded, expected_huffman); } input_bytes_expected_ = encoded.size(); auto validator = [plain, this]() -> AssertionResult { VERIFY_EQ(output_buffer_.size(), plain.size()); VERIFY_EQ(output_buffer_, plain); return AssertionSuccess(); }; DecodeBuffer db(encoded); bool return_non_zero_on_first = false; return DecodeAndValidateSeveralWays(&db, return_non_zero_on_first, ValidateDoneAndEmpty(validator)); } AssertionResult TranscodeAndValidateSeveralWays(absl::string_view plain) { return TranscodeAndValidateSeveralWays(plain, ""); } std::string RandomAsciiNonControlString(int length) { return Random().RandStringWithAlphabet(length, ascii_non_control_set_); } std::string RandomBytes(int length) { return Random().RandString(length); } const std::string ascii_non_control_set_; HpackHuffmanDecoder decoder_; std::string output_buffer_; size_t input_bytes_seen_; size_t input_bytes_expected_; }; TEST_F(HpackHuffmanTranscoderTest, RoundTripRandomAsciiNonControlString) { for (size_t length = 0; length != 20; length++) { const std::string s = RandomAsciiNonControlString(length); ASSERT_TRUE(TranscodeAndValidateSeveralWays(s)) << "Unable to decode:\n\n" << quiche::QuicheTextUtils::HexDump(s) << "\n\noutput_buffer_:\n" << quiche::QuicheTextUtils::HexDump(output_buffer_); } } TEST_F(HpackHuffmanTranscoderTest, RoundTripRandomBytes) { for (size_t length = 0; length != 20; length++) { const std::string s = RandomBytes(length); ASSERT_TRUE(TranscodeAndValidateSeveralWays(s)) << "Unable to decode:\n\n" << quiche::QuicheTextUtils::HexDump(s) << "\n\noutput_buffer_:\n" << quiche::QuicheTextUtils::HexDump(output_buffer_); } } // Two parameters: decoder choice, and the character to round-trip. class HpackHuffmanTranscoderAdjacentCharTest : public HpackHuffmanTranscoderTest, public ::testing::WithParamInterface<int> { protected: HpackHuffmanTranscoderAdjacentCharTest() : c_(static_cast<char>(GetParam())) {} const char c_; }; INSTANTIATE_TEST_SUITE_P(HpackHuffmanTranscoderAdjacentCharTest, HpackHuffmanTranscoderAdjacentCharTest, ::testing::Range(0, 256)); // Test c_ adjacent to every other character, both before and after. TEST_P(HpackHuffmanTranscoderAdjacentCharTest, RoundTripAdjacentChar) { std::string s; for (int a = 0; a < 256; ++a) { s.push_back(static_cast<char>(a)); s.push_back(c_); s.push_back(static_cast<char>(a)); } ASSERT_TRUE(TranscodeAndValidateSeveralWays(s)); } // Two parameters: character to repeat, number of repeats. class HpackHuffmanTranscoderRepeatedCharTest : public HpackHuffmanTranscoderTest, public ::testing::WithParamInterface<tuple<int, int>> { protected: HpackHuffmanTranscoderRepeatedCharTest() : c_(static_cast<char>(::testing::get<0>(GetParam()))), length_(::testing::get<1>(GetParam())) {} std::string MakeString() { return std::string(length_, c_); } private: const char c_; const size_t length_; }; INSTANTIATE_TEST_SUITE_P(HpackHuffmanTranscoderRepeatedCharTest, HpackHuffmanTranscoderRepeatedCharTest, ::testing::Combine(::testing::Range(0, 256), ::testing::Values(1, 2, 3, 4, 8, 16, 32))); TEST_P(HpackHuffmanTranscoderRepeatedCharTest, RoundTripRepeatedChar) { ASSERT_TRUE(TranscodeAndValidateSeveralWays(MakeString())); } } // namespace } // namespace test } // namespace http2 <commit_msg>'empty' method should be used to check for emptiness instead of 'size'<commit_after>// Copyright (c) 2018 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. // A test of roundtrips through the encoder and decoder. #include <stddef.h> #include "absl/strings/string_view.h" #include "http2/decoder/decode_buffer.h" #include "http2/decoder/decode_status.h" #include "http2/hpack/huffman/hpack_huffman_decoder.h" #include "http2/hpack/huffman/hpack_huffman_encoder.h" #include "http2/tools/random_decoder_test.h" #include "common/platform/api/quiche_test.h" #include "common/quiche_text_utils.h" using ::testing::AssertionResult; using ::testing::AssertionSuccess; using ::testing::Combine; using ::testing::Range; using ::testing::Values; namespace http2 { namespace test { namespace { std::string GenAsciiNonControlSet() { std::string s; const char space = ' '; // First character after the control characters: 0x20 const char del = 127; // First character after the non-control characters. for (char c = space; c < del; ++c) { s.push_back(c); } return s; } class HpackHuffmanTranscoderTest : public RandomDecoderTest { protected: HpackHuffmanTranscoderTest() : ascii_non_control_set_(GenAsciiNonControlSet()) { // The decoder may return true, and its accumulator may be empty, at // many boundaries while decoding, and yet the whole string hasn't // been decoded. stop_decode_on_done_ = false; } DecodeStatus StartDecoding(DecodeBuffer* b) override { input_bytes_seen_ = 0; output_buffer_.clear(); decoder_.Reset(); return ResumeDecoding(b); } DecodeStatus ResumeDecoding(DecodeBuffer* b) override { input_bytes_seen_ += b->Remaining(); absl::string_view sp(b->cursor(), b->Remaining()); if (decoder_.Decode(sp, &output_buffer_)) { b->AdvanceCursor(b->Remaining()); // Successfully decoded (or buffered) the bytes in absl::string_view. EXPECT_LE(input_bytes_seen_, input_bytes_expected_); // Have we reached the end of the encoded string? if (input_bytes_expected_ == input_bytes_seen_) { if (decoder_.InputProperlyTerminated()) { return DecodeStatus::kDecodeDone; } else { return DecodeStatus::kDecodeError; } } return DecodeStatus::kDecodeInProgress; } return DecodeStatus::kDecodeError; } AssertionResult TranscodeAndValidateSeveralWays( absl::string_view plain, absl::string_view expected_huffman) { size_t encoded_size = HuffmanSize(plain); std::string encoded; HuffmanEncode(plain, encoded_size, &encoded); VERIFY_EQ(encoded_size, encoded.size()); if (!expected_huffman.empty() || plain.empty()) { VERIFY_EQ(encoded, expected_huffman); } input_bytes_expected_ = encoded.size(); auto validator = [plain, this]() -> AssertionResult { VERIFY_EQ(output_buffer_.size(), plain.size()); VERIFY_EQ(output_buffer_, plain); return AssertionSuccess(); }; DecodeBuffer db(encoded); bool return_non_zero_on_first = false; return DecodeAndValidateSeveralWays(&db, return_non_zero_on_first, ValidateDoneAndEmpty(validator)); } AssertionResult TranscodeAndValidateSeveralWays(absl::string_view plain) { return TranscodeAndValidateSeveralWays(plain, ""); } std::string RandomAsciiNonControlString(int length) { return Random().RandStringWithAlphabet(length, ascii_non_control_set_); } std::string RandomBytes(int length) { return Random().RandString(length); } const std::string ascii_non_control_set_; HpackHuffmanDecoder decoder_; std::string output_buffer_; size_t input_bytes_seen_; size_t input_bytes_expected_; }; TEST_F(HpackHuffmanTranscoderTest, RoundTripRandomAsciiNonControlString) { for (size_t length = 0; length != 20; length++) { const std::string s = RandomAsciiNonControlString(length); ASSERT_TRUE(TranscodeAndValidateSeveralWays(s)) << "Unable to decode:\n\n" << quiche::QuicheTextUtils::HexDump(s) << "\n\noutput_buffer_:\n" << quiche::QuicheTextUtils::HexDump(output_buffer_); } } TEST_F(HpackHuffmanTranscoderTest, RoundTripRandomBytes) { for (size_t length = 0; length != 20; length++) { const std::string s = RandomBytes(length); ASSERT_TRUE(TranscodeAndValidateSeveralWays(s)) << "Unable to decode:\n\n" << quiche::QuicheTextUtils::HexDump(s) << "\n\noutput_buffer_:\n" << quiche::QuicheTextUtils::HexDump(output_buffer_); } } // Two parameters: decoder choice, and the character to round-trip. class HpackHuffmanTranscoderAdjacentCharTest : public HpackHuffmanTranscoderTest, public testing::WithParamInterface<int> { protected: HpackHuffmanTranscoderAdjacentCharTest() : c_(static_cast<char>(GetParam())) {} const char c_; }; INSTANTIATE_TEST_SUITE_P(HpackHuffmanTranscoderAdjacentCharTest, HpackHuffmanTranscoderAdjacentCharTest, Range(0, 256)); // Test c_ adjacent to every other character, both before and after. TEST_P(HpackHuffmanTranscoderAdjacentCharTest, RoundTripAdjacentChar) { std::string s; for (int a = 0; a < 256; ++a) { s.push_back(static_cast<char>(a)); s.push_back(c_); s.push_back(static_cast<char>(a)); } ASSERT_TRUE(TranscodeAndValidateSeveralWays(s)); } // Two parameters: character to repeat, number of repeats. class HpackHuffmanTranscoderRepeatedCharTest : public HpackHuffmanTranscoderTest, public testing::WithParamInterface<std::tuple<int, int>> { protected: HpackHuffmanTranscoderRepeatedCharTest() : c_(static_cast<char>(std::get<0>(GetParam()))), length_(std::get<1>(GetParam())) {} std::string MakeString() { return std::string(length_, c_); } private: const char c_; const size_t length_; }; INSTANTIATE_TEST_SUITE_P(HpackHuffmanTranscoderRepeatedCharTest, HpackHuffmanTranscoderRepeatedCharTest, Combine(Range(0, 256), Values(1, 2, 3, 4, 8, 16, 32))); TEST_P(HpackHuffmanTranscoderRepeatedCharTest, RoundTripRepeatedChar) { ASSERT_TRUE(TranscodeAndValidateSeveralWays(MakeString())); } } // namespace } // namespace test } // namespace http2 <|endoftext|>
<commit_before>// Copyright (c) 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/core/quic_stream_id_manager.h" #include <cstdint> #include <string> #include "net/third_party/quiche/src/quic/core/quic_connection.h" #include "net/third_party/quiche/src/quic/core/quic_constants.h" #include "net/third_party/quiche/src/quic/core/quic_session.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h" namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? " Server: " : " Client: ") QuicStreamIdManager::QuicStreamIdManager( DelegateInterface* delegate, bool unidirectional, Perspective perspective, QuicTransportVersion transport_version, QuicStreamCount max_allowed_outgoing_streams, QuicStreamCount max_allowed_incoming_streams) : delegate_(delegate), unidirectional_(unidirectional), perspective_(perspective), transport_version_(transport_version), outgoing_max_streams_(max_allowed_outgoing_streams), next_outgoing_stream_id_(GetFirstOutgoingStreamId()), outgoing_stream_count_(0), incoming_actual_max_streams_(max_allowed_incoming_streams), // Advertised max starts at actual because it's communicated in the // handshake. incoming_advertised_max_streams_(max_allowed_incoming_streams), incoming_initial_max_open_streams_(max_allowed_incoming_streams), incoming_stream_count_(0), largest_peer_created_stream_id_( QuicUtils::GetInvalidStreamId(transport_version)), max_streams_window_(0) { CalculateIncomingMaxStreamsWindow(); } QuicStreamIdManager::~QuicStreamIdManager() {} // The peer sends a streams blocked frame when it can not open any more // streams because it has runs into the limit. bool QuicStreamIdManager::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& frame, std::string* error_details) { // Ensure that the frame has the correct directionality. DCHECK_EQ(frame.unidirectional, unidirectional_); if (frame.stream_count > incoming_advertised_max_streams_) { // Peer thinks it can send more streams that we've told it. // This is a protocol error. *error_details = quiche::QuicheStrCat( "StreamsBlockedFrame's stream count ", frame.stream_count, " exceeds incoming max stream ", incoming_advertised_max_streams_); return false; } if (frame.stream_count < incoming_actual_max_streams_) { // Peer thinks it's blocked on a stream count that is less than our current // max. Inform the peer of the correct stream count. Sending a MAX_STREAMS // frame in this case is not controlled by the window. SendMaxStreamsFrame(); } return true; } bool QuicStreamIdManager::MaybeAllowNewOutgoingStreams( QuicStreamCount max_open_streams) { if (max_open_streams <= outgoing_max_streams_) { // Only update the stream count if it would increase the limit. return false; } // This implementation only supports 32 bit Stream IDs, so limit max streams // if it would exceed the max 32 bits can express. outgoing_max_streams_ = std::min(max_open_streams, QuicUtils::GetMaxStreamCount()); return true; } void QuicStreamIdManager::SetMaxOpenIncomingStreams( QuicStreamCount max_open_streams) { QUIC_BUG_IF(incoming_stream_count_ > 0) << "non-zero stream count when setting max incoming stream."; QUIC_LOG_IF(WARNING, incoming_initial_max_open_streams_ != max_open_streams) << quiche::QuicheStrCat( unidirectional_ ? "unidirectional " : "bidirectional: ", "incoming stream limit changed from ", incoming_initial_max_open_streams_, " to ", max_open_streams); incoming_actual_max_streams_ = max_open_streams; incoming_advertised_max_streams_ = max_open_streams; incoming_initial_max_open_streams_ = max_open_streams; CalculateIncomingMaxStreamsWindow(); } void QuicStreamIdManager::MaybeSendMaxStreamsFrame() { if ((incoming_advertised_max_streams_ - incoming_stream_count_) > max_streams_window_) { // window too large, no advertisement return; } SendMaxStreamsFrame(); } void QuicStreamIdManager::SendMaxStreamsFrame() { incoming_advertised_max_streams_ = incoming_actual_max_streams_; delegate_->SendMaxStreams(incoming_advertised_max_streams_, unidirectional_); } void QuicStreamIdManager::OnStreamClosed(QuicStreamId stream_id) { DCHECK_NE(QuicUtils::IsBidirectionalStreamId(stream_id), unidirectional_); if (!IsIncomingStream(stream_id)) { // Nothing to do for outgoing streams. return; } // If the stream is inbound, we can increase the actual stream limit and maybe // advertise the new limit to the peer. Have to check to make sure that we do // not exceed the maximum. if (incoming_actual_max_streams_ == QuicUtils::GetMaxStreamCount()) { // Reached the maximum stream id value that the implementation // supports. Nothing can be done here. return; } // One stream closed ... another can be opened. incoming_actual_max_streams_++; MaybeSendMaxStreamsFrame(); } QuicStreamId QuicStreamIdManager::GetNextOutgoingStreamId() { // Applications should always consult CanOpenNextOutgoingStream() first. // If they ask for stream ids that violate the limit, it's an implementation // bug. QUIC_BUG_IF(outgoing_stream_count_ >= outgoing_max_streams_) << "Attempt to allocate a new outgoing stream that would exceed the " "limit (" << outgoing_max_streams_ << ")"; QuicStreamId id = next_outgoing_stream_id_; next_outgoing_stream_id_ += QuicUtils::StreamIdDelta(transport_version_); outgoing_stream_count_++; return id; } bool QuicStreamIdManager::CanOpenNextOutgoingStream() const { DCHECK(VersionHasIetfQuicFrames(transport_version_)); return outgoing_stream_count_ < outgoing_max_streams_; } bool QuicStreamIdManager::MaybeIncreaseLargestPeerStreamId( const QuicStreamId stream_id, std::string* error_details) { // |stream_id| must be an incoming stream of the right directionality. DCHECK_NE(QuicUtils::IsBidirectionalStreamId(stream_id), unidirectional_); DCHECK_NE(QuicUtils::IsServerInitiatedStreamId(transport_version_, stream_id), perspective() == Perspective::IS_SERVER); if (available_streams_.erase(stream_id) == 1) { // stream_id is available. return true; } if (largest_peer_created_stream_id_ != QuicUtils::GetInvalidStreamId(transport_version_)) { DCHECK_GT(stream_id, largest_peer_created_stream_id_); } // Calculate increment of incoming_stream_count_ by creating stream_id. const QuicStreamCount delta = QuicUtils::StreamIdDelta(transport_version_); const QuicStreamId least_new_stream_id = largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_) ? GetFirstIncomingStreamId() : largest_peer_created_stream_id_ + delta; const QuicStreamCount stream_count_increment = (stream_id - least_new_stream_id) / delta + 1; if (incoming_stream_count_ + stream_count_increment > incoming_advertised_max_streams_) { QUIC_DLOG(INFO) << ENDPOINT << "Failed to create a new incoming stream with id:" << stream_id << ", reaching MAX_STREAMS limit: " << incoming_advertised_max_streams_ << "."; *error_details = quiche::QuicheStrCat("Stream id ", stream_id, " would exceed stream count limit ", incoming_advertised_max_streams_); return false; } for (QuicStreamId id = least_new_stream_id; id < stream_id; id += delta) { available_streams_.insert(id); } incoming_stream_count_ += stream_count_increment; largest_peer_created_stream_id_ = stream_id; return true; } bool QuicStreamIdManager::IsAvailableStream(QuicStreamId id) const { DCHECK_NE(QuicUtils::IsBidirectionalStreamId(id), unidirectional_); if (!IsIncomingStream(id)) { // Stream IDs under next_ougoing_stream_id_ are either open or previously // open but now closed. return id >= next_outgoing_stream_id_; } // For peer created streams, we also need to consider available streams. return largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_) || id > largest_peer_created_stream_id_ || QuicContainsKey(available_streams_, id); } bool QuicStreamIdManager::IsIncomingStream(QuicStreamId id) const { DCHECK_NE(QuicUtils::IsBidirectionalStreamId(id), unidirectional_); // The 0x1 bit in the stream id indicates whether the stream id is // server- or client- initiated. Next_OUTGOING_stream_id_ has that bit // set based on whether this node is a server or client. Thus, if the stream // id in question has the 0x1 bit set opposite of next_OUTGOING_stream_id_, // then that stream id is incoming -- it is for streams initiated by the peer. return (id & 0x1) != (next_outgoing_stream_id_ & 0x1); } QuicStreamId QuicStreamIdManager::GetFirstOutgoingStreamId() const { return (unidirectional_) ? QuicUtils::GetFirstUnidirectionalStreamId( transport_version_, perspective()) : QuicUtils::GetFirstBidirectionalStreamId( transport_version_, perspective()); } QuicStreamId QuicStreamIdManager::GetFirstIncomingStreamId() const { return (unidirectional_) ? QuicUtils::GetFirstUnidirectionalStreamId( transport_version_, peer_perspective()) : QuicUtils::GetFirstBidirectionalStreamId( transport_version_, peer_perspective()); } Perspective QuicStreamIdManager::perspective() const { return perspective_; } Perspective QuicStreamIdManager::peer_perspective() const { return QuicUtils::InvertPerspective(perspective()); } QuicStreamCount QuicStreamIdManager::available_incoming_streams() { return incoming_advertised_max_streams_ - incoming_stream_count_; } void QuicStreamIdManager::CalculateIncomingMaxStreamsWindow() { max_streams_window_ = incoming_actual_max_streams_ / kMaxStreamsWindowDivisor; if (max_streams_window_ == 0) { max_streams_window_ = 1; } } } // namespace quic <commit_msg>Parameterize QuicJetstreamSessionTest by QUIC version<commit_after>// Copyright (c) 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/core/quic_stream_id_manager.h" #include <cstdint> #include <string> #include "net/third_party/quiche/src/quic/core/quic_connection.h" #include "net/third_party/quiche/src/quic/core/quic_constants.h" #include "net/third_party/quiche/src/quic/core/quic_session.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h" namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? " Server: " : " Client: ") QuicStreamIdManager::QuicStreamIdManager( DelegateInterface* delegate, bool unidirectional, Perspective perspective, QuicTransportVersion transport_version, QuicStreamCount max_allowed_outgoing_streams, QuicStreamCount max_allowed_incoming_streams) : delegate_(delegate), unidirectional_(unidirectional), perspective_(perspective), transport_version_(transport_version), outgoing_max_streams_(max_allowed_outgoing_streams), next_outgoing_stream_id_(GetFirstOutgoingStreamId()), outgoing_stream_count_(0), incoming_actual_max_streams_(max_allowed_incoming_streams), // Advertised max starts at actual because it's communicated in the // handshake. incoming_advertised_max_streams_(max_allowed_incoming_streams), incoming_initial_max_open_streams_(max_allowed_incoming_streams), incoming_stream_count_(0), largest_peer_created_stream_id_( QuicUtils::GetInvalidStreamId(transport_version)), max_streams_window_(0) { CalculateIncomingMaxStreamsWindow(); } QuicStreamIdManager::~QuicStreamIdManager() {} // The peer sends a streams blocked frame when it can not open any more // streams because it has runs into the limit. bool QuicStreamIdManager::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& frame, std::string* error_details) { // Ensure that the frame has the correct directionality. DCHECK_EQ(frame.unidirectional, unidirectional_); if (frame.stream_count > incoming_advertised_max_streams_) { // Peer thinks it can send more streams that we've told it. // This is a protocol error. *error_details = quiche::QuicheStrCat( "StreamsBlockedFrame's stream count ", frame.stream_count, " exceeds incoming max stream ", incoming_advertised_max_streams_); return false; } if (frame.stream_count < incoming_actual_max_streams_) { // Peer thinks it's blocked on a stream count that is less than our current // max. Inform the peer of the correct stream count. Sending a MAX_STREAMS // frame in this case is not controlled by the window. SendMaxStreamsFrame(); } return true; } bool QuicStreamIdManager::MaybeAllowNewOutgoingStreams( QuicStreamCount max_open_streams) { if (max_open_streams <= outgoing_max_streams_) { // Only update the stream count if it would increase the limit. return false; } // This implementation only supports 32 bit Stream IDs, so limit max streams // if it would exceed the max 32 bits can express. outgoing_max_streams_ = std::min(max_open_streams, QuicUtils::GetMaxStreamCount()); return true; } void QuicStreamIdManager::SetMaxOpenIncomingStreams( QuicStreamCount max_open_streams) { QUIC_BUG_IF(incoming_stream_count_ > 0) << "non-zero incoming stream count " << incoming_stream_count_ << " when setting max incoming stream to " << max_open_streams; QUIC_LOG_IF(WARNING, incoming_initial_max_open_streams_ != max_open_streams) << quiche::QuicheStrCat( unidirectional_ ? "unidirectional " : "bidirectional: ", "incoming stream limit changed from ", incoming_initial_max_open_streams_, " to ", max_open_streams); incoming_actual_max_streams_ = max_open_streams; incoming_advertised_max_streams_ = max_open_streams; incoming_initial_max_open_streams_ = max_open_streams; CalculateIncomingMaxStreamsWindow(); } void QuicStreamIdManager::MaybeSendMaxStreamsFrame() { if ((incoming_advertised_max_streams_ - incoming_stream_count_) > max_streams_window_) { // window too large, no advertisement return; } SendMaxStreamsFrame(); } void QuicStreamIdManager::SendMaxStreamsFrame() { incoming_advertised_max_streams_ = incoming_actual_max_streams_; delegate_->SendMaxStreams(incoming_advertised_max_streams_, unidirectional_); } void QuicStreamIdManager::OnStreamClosed(QuicStreamId stream_id) { DCHECK_NE(QuicUtils::IsBidirectionalStreamId(stream_id), unidirectional_); if (!IsIncomingStream(stream_id)) { // Nothing to do for outgoing streams. return; } // If the stream is inbound, we can increase the actual stream limit and maybe // advertise the new limit to the peer. Have to check to make sure that we do // not exceed the maximum. if (incoming_actual_max_streams_ == QuicUtils::GetMaxStreamCount()) { // Reached the maximum stream id value that the implementation // supports. Nothing can be done here. return; } // One stream closed ... another can be opened. incoming_actual_max_streams_++; MaybeSendMaxStreamsFrame(); } QuicStreamId QuicStreamIdManager::GetNextOutgoingStreamId() { // Applications should always consult CanOpenNextOutgoingStream() first. // If they ask for stream ids that violate the limit, it's an implementation // bug. QUIC_BUG_IF(outgoing_stream_count_ >= outgoing_max_streams_) << "Attempt to allocate a new outgoing stream that would exceed the " "limit (" << outgoing_max_streams_ << ")"; QuicStreamId id = next_outgoing_stream_id_; next_outgoing_stream_id_ += QuicUtils::StreamIdDelta(transport_version_); outgoing_stream_count_++; return id; } bool QuicStreamIdManager::CanOpenNextOutgoingStream() const { DCHECK(VersionHasIetfQuicFrames(transport_version_)); return outgoing_stream_count_ < outgoing_max_streams_; } bool QuicStreamIdManager::MaybeIncreaseLargestPeerStreamId( const QuicStreamId stream_id, std::string* error_details) { // |stream_id| must be an incoming stream of the right directionality. DCHECK_NE(QuicUtils::IsBidirectionalStreamId(stream_id), unidirectional_); DCHECK_NE(QuicUtils::IsServerInitiatedStreamId(transport_version_, stream_id), perspective() == Perspective::IS_SERVER); if (available_streams_.erase(stream_id) == 1) { // stream_id is available. return true; } if (largest_peer_created_stream_id_ != QuicUtils::GetInvalidStreamId(transport_version_)) { DCHECK_GT(stream_id, largest_peer_created_stream_id_); } // Calculate increment of incoming_stream_count_ by creating stream_id. const QuicStreamCount delta = QuicUtils::StreamIdDelta(transport_version_); const QuicStreamId least_new_stream_id = largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_) ? GetFirstIncomingStreamId() : largest_peer_created_stream_id_ + delta; const QuicStreamCount stream_count_increment = (stream_id - least_new_stream_id) / delta + 1; if (incoming_stream_count_ + stream_count_increment > incoming_advertised_max_streams_) { QUIC_DLOG(INFO) << ENDPOINT << "Failed to create a new incoming stream with id:" << stream_id << ", reaching MAX_STREAMS limit: " << incoming_advertised_max_streams_ << "."; *error_details = quiche::QuicheStrCat("Stream id ", stream_id, " would exceed stream count limit ", incoming_advertised_max_streams_); return false; } for (QuicStreamId id = least_new_stream_id; id < stream_id; id += delta) { available_streams_.insert(id); } incoming_stream_count_ += stream_count_increment; largest_peer_created_stream_id_ = stream_id; return true; } bool QuicStreamIdManager::IsAvailableStream(QuicStreamId id) const { DCHECK_NE(QuicUtils::IsBidirectionalStreamId(id), unidirectional_); if (!IsIncomingStream(id)) { // Stream IDs under next_ougoing_stream_id_ are either open or previously // open but now closed. return id >= next_outgoing_stream_id_; } // For peer created streams, we also need to consider available streams. return largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_) || id > largest_peer_created_stream_id_ || QuicContainsKey(available_streams_, id); } bool QuicStreamIdManager::IsIncomingStream(QuicStreamId id) const { DCHECK_NE(QuicUtils::IsBidirectionalStreamId(id), unidirectional_); // The 0x1 bit in the stream id indicates whether the stream id is // server- or client- initiated. Next_OUTGOING_stream_id_ has that bit // set based on whether this node is a server or client. Thus, if the stream // id in question has the 0x1 bit set opposite of next_OUTGOING_stream_id_, // then that stream id is incoming -- it is for streams initiated by the peer. return (id & 0x1) != (next_outgoing_stream_id_ & 0x1); } QuicStreamId QuicStreamIdManager::GetFirstOutgoingStreamId() const { return (unidirectional_) ? QuicUtils::GetFirstUnidirectionalStreamId( transport_version_, perspective()) : QuicUtils::GetFirstBidirectionalStreamId( transport_version_, perspective()); } QuicStreamId QuicStreamIdManager::GetFirstIncomingStreamId() const { return (unidirectional_) ? QuicUtils::GetFirstUnidirectionalStreamId( transport_version_, peer_perspective()) : QuicUtils::GetFirstBidirectionalStreamId( transport_version_, peer_perspective()); } Perspective QuicStreamIdManager::perspective() const { return perspective_; } Perspective QuicStreamIdManager::peer_perspective() const { return QuicUtils::InvertPerspective(perspective()); } QuicStreamCount QuicStreamIdManager::available_incoming_streams() { return incoming_advertised_max_streams_ - incoming_stream_count_; } void QuicStreamIdManager::CalculateIncomingMaxStreamsWindow() { max_streams_window_ = incoming_actual_max_streams_ / kMaxStreamsWindowDivisor; if (max_streams_window_ == 0) { max_streams_window_ = 1; } } } // namespace quic <|endoftext|>
<commit_before>#ifndef SKSAT_WINDOW_HPP #define SKSAT_WINDOW_HPP #include <sksat/common.hpp> #include <sksat/platform.hpp> namespace sksat { class window_base { public: window_base() : opend(false), xsize(default_xsize), ysize(default_ysize), xpos(default_xpos), ypos(default_ypos) {} window_base(size_t x, size_t y) : opend(false), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} window_base(sksat::string &t, size_t x, size_t y) : opend(false), title(t), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} void open(){ opend = api_open(); } void open(size_t x, size_t y){ open(); set_size(x,y); } void open(sksat::string &t){ set_title(t); open(); } void open(sksat::string &t, size_t x, size_t y){ set_title(t); open(x,y); } void close(){ if(opend) api_close(); opend=false; } void show(){ if(opend) api_show(); } void set_title(sksat::string &t){ title = t; set_title(t.c_str()); } void set_title(const char *t){ title = t; api_set_title(t); } sksat::string get_title() const { return title; } virtual void set_size(size_t x, size_t y){ xsize=x; ysize=y; if(opend) api_set_size(x,y); } void set_xsize(size_t x){ set_size(x, ysize); } void set_ysize(size_t y){ set_size(xsize, y); } size_t get_xsize() const { return xsize; } size_t get_ysize() const { return ysize; } void move(size_t x, size_t y){ xpos=x; ypos=y; api_move(x,y); } void set_pos(size_t x, size_t y){ move(x,y); } void set_xpos(size_t x){ move(x,ypos); } void set_ypos(size_t y){ move(xpos,y); } operator bool () const { return opend; } // 描画関数 /* void draw_point(sksat::color &col, size_t x, size_t y); void draw_line(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1); void draw_rect(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1, bool fill); // set_color()でセットした色 void draw_point(size_t x, size_t y); void draw_line(size_t x0, size_t y0, size_t x1, size_t y1); void draw_rect(size_t x0, size_t y0, size_t x1, size_t y1, bool fill); void fill_rect(size_t x0, size_t y0, size_t x1, size_t y1){ draw_rect(x0,y0,x1,y1,true); } */ inline void flush(){ if(opend) api_flush(); } inline bool step_loop(){ if(opend) return api_step_loop(); } inline void loop(){ while(api_step_loop()); } protected: // 環境依存部(純粋仮想関数) virtual bool api_open() = 0; virtual void api_close() = 0; virtual void api_show() = 0; virtual void api_set_title(const char *t) = 0; virtual void api_set_size(size_t x, size_t y) = 0; virtual void api_flush() = 0; virtual void api_move() = 0; virtual bool api_step_loop() = 0; public: static size_t default_xsize, default_ysize; static size_t default_xpos, default_ypos; protected: bool opend; size_t xsize, ysize; size_t xpos, ypos; sksat::string title; }; size_t window_base::default_xsize = 100; size_t window_base::default_ysize = 100; size_t window_base::default_xpos = 0; size_t window_base::default_ypos = 0; } #if defined(OS_WIN32) #include <sksat/win32/window.hpp> namespace sksat{ using sksat::win32::window; } #elif defined(OS_LINUX) #include <sksat/linux/window.hpp> namespace sksat{ using sksat::linux::window; } #else #error not implemented. #endif #endif <commit_msg>[FIX] func arg<commit_after>#ifndef SKSAT_WINDOW_HPP #define SKSAT_WINDOW_HPP #include <sksat/common.hpp> #include <sksat/platform.hpp> namespace sksat { class window_base { public: window_base() : opend(false), xsize(default_xsize), ysize(default_ysize), xpos(default_xpos), ypos(default_ypos) {} window_base(size_t x, size_t y) : opend(false), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} window_base(sksat::string &t, size_t x, size_t y) : opend(false), title(t), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} void open(){ opend = api_open(); } void open(size_t x, size_t y){ open(); set_size(x,y); } void open(sksat::string &t){ set_title(t); open(); } void open(sksat::string &t, size_t x, size_t y){ set_title(t); open(x,y); } void close(){ if(opend) api_close(); opend=false; } void show(){ if(opend) api_show(); } void set_title(sksat::string &t){ title = t; set_title(t.c_str()); } void set_title(const char *t){ title = t; api_set_title(t); } sksat::string get_title() const { return title; } virtual void set_size(size_t x, size_t y){ xsize=x; ysize=y; if(opend) api_set_size(x,y); } void set_xsize(size_t x){ set_size(x, ysize); } void set_ysize(size_t y){ set_size(xsize, y); } size_t get_xsize() const { return xsize; } size_t get_ysize() const { return ysize; } void move(size_t x, size_t y){ xpos=x; ypos=y; api_move(x,y); } void set_pos(size_t x, size_t y){ move(x,y); } void set_xpos(size_t x){ move(x,ypos); } void set_ypos(size_t y){ move(xpos,y); } operator bool () const { return opend; } // 描画関数 /* void draw_point(sksat::color &col, size_t x, size_t y); void draw_line(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1); void draw_rect(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1, bool fill); // set_color()でセットした色 void draw_point(size_t x, size_t y); void draw_line(size_t x0, size_t y0, size_t x1, size_t y1); void draw_rect(size_t x0, size_t y0, size_t x1, size_t y1, bool fill); void fill_rect(size_t x0, size_t y0, size_t x1, size_t y1){ draw_rect(x0,y0,x1,y1,true); } */ inline void flush(){ if(opend) api_flush(); } inline bool step_loop(){ if(opend) return api_step_loop(); } inline void loop(){ while(api_step_loop()); } protected: // 環境依存部(純粋仮想関数) virtual bool api_open() = 0; virtual void api_close() = 0; virtual void api_show() = 0; virtual void api_set_title(const char *t) = 0; virtual void api_set_size(size_t x, size_t y) = 0; virtual void api_flush() = 0; virtual void api_move(size_t x, size_t y) = 0; virtual bool api_step_loop() = 0; public: static size_t default_xsize, default_ysize; static size_t default_xpos, default_ypos; protected: bool opend; size_t xsize, ysize; size_t xpos, ypos; sksat::string title; }; size_t window_base::default_xsize = 100; size_t window_base::default_ysize = 100; size_t window_base::default_xpos = 0; size_t window_base::default_ypos = 0; } #if defined(OS_WIN32) #include <sksat/win32/window.hpp> namespace sksat{ using sksat::win32::window; } #elif defined(OS_LINUX) #include <sksat/linux/window.hpp> namespace sksat{ using sksat::linux::window; } #else #error not implemented. #endif #endif <|endoftext|>
<commit_before>// Copyright Benoit Blanchon 2014 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson #include <gtest/gtest.h> #include <ArduinoJson/Internals/QuotedString.hpp> #include <ArduinoJson/Internals/StringBuilder.hpp> using namespace ArduinoJson::Internals; class QuotedString_PrintTo_Tests : public testing::Test { protected: void whenInputIs(const char *input) { StringBuilder sb(buffer, sizeof(buffer)); returnValue = QuotedString::printTo(input, &sb); } void outputMustBe(const char *expected) { EXPECT_STREQ(expected, buffer); EXPECT_EQ(strlen(expected), returnValue); } private: char buffer[1024]; size_t returnValue; }; TEST_F(QuotedString_PrintTo_Tests, Null) { whenInputIs(0); outputMustBe("null"); } TEST_F(QuotedString_PrintTo_Tests, EmptyString) { whenInputIs(""); outputMustBe("\"\""); } TEST_F(QuotedString_PrintTo_Tests, QuotationMark) { whenInputIs("\""); outputMustBe("\"\\\"\""); } TEST_F(QuotedString_PrintTo_Tests, ReverseSolidus) { whenInputIs("\\"); outputMustBe("\"\\\\\""); } TEST_F(QuotedString_PrintTo_Tests, Solidus) { whenInputIs("/"); outputMustBe("\"/\""); // but the JSON format allows \/ } TEST_F(QuotedString_PrintTo_Tests, Backspace) { whenInputIs("\b"); outputMustBe("\"\\b\""); } TEST_F(QuotedString_PrintTo_Tests, Formfeed) { whenInputIs("\f"); outputMustBe("\"\\f\""); } TEST_F(QuotedString_PrintTo_Tests, Newline) { whenInputIs("\n"); outputMustBe("\"\\n\""); } TEST_F(QuotedString_PrintTo_Tests, CarriageReturn) { whenInputIs("\r"); outputMustBe("\"\\r\""); } TEST_F(QuotedString_PrintTo_Tests, HorizontalTab) { whenInputIs("\t"); outputMustBe("\"\\t\""); } <commit_msg>Fixed compilartion error<commit_after>// Copyright Benoit Blanchon 2014 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson #include <gtest/gtest.h> #include <ArduinoJson/Internals/QuotedString.hpp> #include <ArduinoJson/Internals/StringBuilder.hpp> using namespace ArduinoJson::Internals; class QuotedString_PrintTo_Tests : public testing::Test { protected: void whenInputIs(const char *input) { StringBuilder sb(buffer, sizeof(buffer)); returnValue = QuotedString::printTo(input, sb); } void outputMustBe(const char *expected) { EXPECT_STREQ(expected, buffer); EXPECT_EQ(strlen(expected), returnValue); } private: char buffer[1024]; size_t returnValue; }; TEST_F(QuotedString_PrintTo_Tests, Null) { whenInputIs(0); outputMustBe("null"); } TEST_F(QuotedString_PrintTo_Tests, EmptyString) { whenInputIs(""); outputMustBe("\"\""); } TEST_F(QuotedString_PrintTo_Tests, QuotationMark) { whenInputIs("\""); outputMustBe("\"\\\"\""); } TEST_F(QuotedString_PrintTo_Tests, ReverseSolidus) { whenInputIs("\\"); outputMustBe("\"\\\\\""); } TEST_F(QuotedString_PrintTo_Tests, Solidus) { whenInputIs("/"); outputMustBe("\"/\""); // but the JSON format allows \/ } TEST_F(QuotedString_PrintTo_Tests, Backspace) { whenInputIs("\b"); outputMustBe("\"\\b\""); } TEST_F(QuotedString_PrintTo_Tests, Formfeed) { whenInputIs("\f"); outputMustBe("\"\\f\""); } TEST_F(QuotedString_PrintTo_Tests, Newline) { whenInputIs("\n"); outputMustBe("\"\\n\""); } TEST_F(QuotedString_PrintTo_Tests, CarriageReturn) { whenInputIs("\r"); outputMustBe("\"\\r\""); } TEST_F(QuotedString_PrintTo_Tests, HorizontalTab) { whenInputIs("\t"); outputMustBe("\"\\t\""); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkRenderWindowInteractor.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkRenderWindowInteractor.hh" #include "vtkActor.hh" #include "vtkCellPicker.hh" // Description: // Construct object so that light follows camera motion. vtkRenderWindowInteractor::vtkRenderWindowInteractor() { this->RenderWindow = NULL; this->CurrentCamera = NULL; this->CurrentLight = NULL; this->CurrentRenderer = NULL; this->LightFollowCamera = 1; this->Initialized = 0; this->SelfCreatedPicker = 0; this->Picker = this->CreateDefaultPicker(); this->OutlineActor = NULL; this->OutlineMapper.SetInput(this->Outline); this->PickedRenderer = NULL; this->CurrentActor = NULL; this->StartPickMethod = NULL; this->StartPickMethodArgDelete = NULL; this->StartPickMethodArg = NULL; this->EndPickMethod = NULL; this->EndPickMethodArgDelete = NULL; this->EndPickMethodArg = NULL; this->UserMethod = NULL; this->UserMethodArgDelete = NULL; this->UserMethodArg = NULL; } vtkRenderWindowInteractor::~vtkRenderWindowInteractor() { if ( this->OutlineActor ) this->OutlineActor->Delete(); if ( this->SelfCreatedPicker && this->Picker) this->Picker->Delete(); } void vtkRenderWindowInteractor::FindPokedRenderer(int x,int y) { vtkRendererCollection *rc; vtkRenderer *aren; this->CurrentRenderer = NULL; rc = this->RenderWindow->GetRenderers(); for (rc->InitTraversal(); ((aren = rc->GetNextItem())&&(!this->CurrentRenderer));) { if (aren->IsInViewport(x,y)) { this->CurrentRenderer = aren; } } // we must have a value if (this->CurrentRenderer == NULL) { rc->InitTraversal(); aren = rc->GetNextItem(); this->CurrentRenderer = aren; } } void vtkRenderWindowInteractor::FindPokedCamera(int x,int y) { float *vp; vtkLightCollection *lc; this->FindPokedRenderer(x,y); vp = this->CurrentRenderer->GetViewport(); this->CurrentCamera = this->CurrentRenderer->GetActiveCamera(); memcpy(this->Center,this->CurrentRenderer->GetCenter(),sizeof(int)*2); this->DeltaElevation = 20.0/((vp[3] - vp[1])*this->Size[1]); this->DeltaAzimuth = 20.0/((vp[2] - vp[0])*this->Size[0]); // as a side effect also set the light // in case they are using light follow camera lc = this->CurrentRenderer->GetLights(); lc->InitTraversal(); this->CurrentLight = lc->GetNextItem(); } // Description: // When pick action successfully selects actor, this method highlights the // actor appropriately. void vtkRenderWindowInteractor::HighlightActor(vtkActor *actor) { if ( ! this->OutlineActor ) { // have to defer creation to get right type this->OutlineActor = new vtkActor; this->OutlineActor->PickableOff(); this->OutlineActor->DragableOff(); this->OutlineActor->SetMapper(this->OutlineMapper); this->OutlineActor->GetProperty()->SetColor(1.0,1.0,1.0); this->OutlineActor->GetProperty()->SetAmbient(1.0); this->OutlineActor->GetProperty()->SetDiffuse(0.0); } if ( this->PickedRenderer ) this->PickedRenderer->RemoveActors(OutlineActor); if ( ! actor ) { this->PickedRenderer = NULL; } else { this->PickedRenderer = this->CurrentRenderer; this->CurrentRenderer->AddActors(OutlineActor); this->Outline.SetBounds(actor->GetBounds()); this->CurrentActor = actor; } this->RenderWindow->Render(); } // Description: // Specify a method to be executed prior to the pick operation. void vtkRenderWindowInteractor::SetStartPickMethod(void (*f)(void *), void *arg) { if ( f != this->StartPickMethod || arg != this->StartPickMethodArg ) { this->StartPickMethod = f; this->StartPickMethodArg = arg; this->Modified(); } } // Description: // Specify a method to be executed after the pick operation. void vtkRenderWindowInteractor::SetEndPickMethod(void (*f)(void *), void *arg) { if ( f != this->EndPickMethod || arg != this->EndPickMethodArg ) { this->EndPickMethod = f; this->EndPickMethodArg = arg; this->Modified(); } } // Description: // Set the object used to perform pick operations. You can use this to // control what type of data is picked. void vtkRenderWindowInteractor::SetPicker(vtkPicker *picker) { if ( this->Picker != picker ) { if ( this->SelfCreatedPicker ) this->Picker->Delete(); this->SelfCreatedPicker = 0; this->Picker = picker; this->Modified(); } } vtkPicker *vtkRenderWindowInteractor::CreateDefaultPicker() { if ( this->SelfCreatedPicker ) this->Picker->Delete(); this->SelfCreatedPicker = 1; return new vtkCellPicker; } // Description: // Set the user method. This method is invokedon a ctrl-u. void vtkRenderWindowInteractor::SetUserMethod(void (*f)(void *), void *arg) { if ( f != this->UserMethod || arg != this->UserMethodArg ) { // delete the current arg if there is one and a delete meth if ((this->UserMethodArg)&&(this->UserMethodArgDelete)) { (*this->UserMethodArgDelete)(this->UserMethodArg); } this->UserMethod = f; this->UserMethodArg = arg; this->Modified(); } } // Description: // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetUserMethodArgDelete(void (*f)(void *)) { if ( f != this->UserMethodArgDelete) { this->UserMethodArgDelete = f; this->Modified(); } } // Description: // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetStartPickMethodArgDelete(void (*f)(void *)) { if ( f != this->StartPickMethodArgDelete) { this->StartPickMethodArgDelete = f; this->Modified(); } } // Description: // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetEndPickMethodArgDelete(void (*f)(void *)) { if ( f != this->EndPickMethodArgDelete) { this->EndPickMethodArgDelete = f; this->Modified(); } } void vtkRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent) { vtkObject::PrintSelf(os,indent); os << indent << "RenderWindow: " << this->RenderWindow << "\n"; os << indent << "CurrentCamera: " << this->CurrentCamera << "\n"; os << indent << "CurrentLight: " << this->CurrentLight << "\n"; os << indent << "CurrentRenderer: " << this->CurrentRenderer << "\n"; os << indent << "LightFollowCamera: " << (this->LightFollowCamera ? "On\n" : "Off\n"); } <commit_msg>added LOD support<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkRenderWindowInteractor.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkRenderWindowInteractor.hh" #include "vtkActor.hh" #include "vtkCellPicker.hh" // Description: // Construct object so that light follows camera motion. vtkRenderWindowInteractor::vtkRenderWindowInteractor() { this->RenderWindow = NULL; this->CurrentCamera = NULL; this->CurrentLight = NULL; this->CurrentRenderer = NULL; this->LightFollowCamera = 1; this->Initialized = 0; this->DesiredUpdateRate = 15; this->StillUpdateRate = 0; this->SelfCreatedPicker = 0; this->Picker = this->CreateDefaultPicker(); this->OutlineActor = NULL; this->OutlineMapper.SetInput(this->Outline); this->PickedRenderer = NULL; this->CurrentActor = NULL; this->StartPickMethod = NULL; this->StartPickMethodArgDelete = NULL; this->StartPickMethodArg = NULL; this->EndPickMethod = NULL; this->EndPickMethodArgDelete = NULL; this->EndPickMethodArg = NULL; this->UserMethod = NULL; this->UserMethodArgDelete = NULL; this->UserMethodArg = NULL; } vtkRenderWindowInteractor::~vtkRenderWindowInteractor() { if ( this->OutlineActor ) this->OutlineActor->Delete(); if ( this->SelfCreatedPicker && this->Picker) this->Picker->Delete(); } void vtkRenderWindowInteractor::FindPokedRenderer(int x,int y) { vtkRendererCollection *rc; vtkRenderer *aren; this->CurrentRenderer = NULL; rc = this->RenderWindow->GetRenderers(); for (rc->InitTraversal(); ((aren = rc->GetNextItem())&&(!this->CurrentRenderer));) { if (aren->IsInViewport(x,y)) { this->CurrentRenderer = aren; } } // we must have a value if (this->CurrentRenderer == NULL) { rc->InitTraversal(); aren = rc->GetNextItem(); this->CurrentRenderer = aren; } } void vtkRenderWindowInteractor::FindPokedCamera(int x,int y) { float *vp; vtkLightCollection *lc; this->FindPokedRenderer(x,y); vp = this->CurrentRenderer->GetViewport(); this->CurrentCamera = this->CurrentRenderer->GetActiveCamera(); memcpy(this->Center,this->CurrentRenderer->GetCenter(),sizeof(int)*2); this->DeltaElevation = 20.0/((vp[3] - vp[1])*this->Size[1]); this->DeltaAzimuth = 20.0/((vp[2] - vp[0])*this->Size[0]); // as a side effect also set the light // in case they are using light follow camera lc = this->CurrentRenderer->GetLights(); lc->InitTraversal(); this->CurrentLight = lc->GetNextItem(); } // Description: // When pick action successfully selects actor, this method highlights the // actor appropriately. void vtkRenderWindowInteractor::HighlightActor(vtkActor *actor) { if ( ! this->OutlineActor ) { // have to defer creation to get right type this->OutlineActor = new vtkActor; this->OutlineActor->PickableOff(); this->OutlineActor->DragableOff(); this->OutlineActor->SetMapper(this->OutlineMapper); this->OutlineActor->GetProperty()->SetColor(1.0,1.0,1.0); this->OutlineActor->GetProperty()->SetAmbient(1.0); this->OutlineActor->GetProperty()->SetDiffuse(0.0); } if ( this->PickedRenderer ) this->PickedRenderer->RemoveActors(OutlineActor); if ( ! actor ) { this->PickedRenderer = NULL; } else { this->PickedRenderer = this->CurrentRenderer; this->CurrentRenderer->AddActors(OutlineActor); this->Outline.SetBounds(actor->GetBounds()); this->CurrentActor = actor; } this->RenderWindow->Render(); } // Description: // Specify a method to be executed prior to the pick operation. void vtkRenderWindowInteractor::SetStartPickMethod(void (*f)(void *), void *arg) { if ( f != this->StartPickMethod || arg != this->StartPickMethodArg ) { this->StartPickMethod = f; this->StartPickMethodArg = arg; this->Modified(); } } // Description: // Specify a method to be executed after the pick operation. void vtkRenderWindowInteractor::SetEndPickMethod(void (*f)(void *), void *arg) { if ( f != this->EndPickMethod || arg != this->EndPickMethodArg ) { this->EndPickMethod = f; this->EndPickMethodArg = arg; this->Modified(); } } // Description: // Set the object used to perform pick operations. You can use this to // control what type of data is picked. void vtkRenderWindowInteractor::SetPicker(vtkPicker *picker) { if ( this->Picker != picker ) { if ( this->SelfCreatedPicker ) this->Picker->Delete(); this->SelfCreatedPicker = 0; this->Picker = picker; this->Modified(); } } vtkPicker *vtkRenderWindowInteractor::CreateDefaultPicker() { if ( this->SelfCreatedPicker ) this->Picker->Delete(); this->SelfCreatedPicker = 1; return new vtkCellPicker; } // Description: // Set the user method. This method is invokedon a ctrl-u. void vtkRenderWindowInteractor::SetUserMethod(void (*f)(void *), void *arg) { if ( f != this->UserMethod || arg != this->UserMethodArg ) { // delete the current arg if there is one and a delete meth if ((this->UserMethodArg)&&(this->UserMethodArgDelete)) { (*this->UserMethodArgDelete)(this->UserMethodArg); } this->UserMethod = f; this->UserMethodArg = arg; this->Modified(); } } // Description: // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetUserMethodArgDelete(void (*f)(void *)) { if ( f != this->UserMethodArgDelete) { this->UserMethodArgDelete = f; this->Modified(); } } // Description: // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetStartPickMethodArgDelete(void (*f)(void *)) { if ( f != this->StartPickMethodArgDelete) { this->StartPickMethodArgDelete = f; this->Modified(); } } // Description: // Called when a void* argument is being discarded. Lets the user free it. void vtkRenderWindowInteractor::SetEndPickMethodArgDelete(void (*f)(void *)) { if ( f != this->EndPickMethodArgDelete) { this->EndPickMethodArgDelete = f; this->Modified(); } } void vtkRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent) { vtkObject::PrintSelf(os,indent); os << indent << "RenderWindow: " << this->RenderWindow << "\n"; os << indent << "CurrentCamera: " << this->CurrentCamera << "\n"; os << indent << "CurrentLight: " << this->CurrentLight << "\n"; os << indent << "CurrentRenderer: " << this->CurrentRenderer << "\n"; os << indent << "LightFollowCamera: " << (this->LightFollowCamera ? "On\n" : "Off\n"); os << indent << "DesiredUpdateRate: " << this->DesiredUpdateRate << "\n"; os << indent << "StillUpdateRate: " << this->StillUpdateRate << "\n"; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include "Identity.h" #include "Base.h" int main (int argc, char * argv[]) { if (argc < 2) { std::cout << "Usage: regaddr filename address" << std::endl; return -1; } i2p::crypto::InitCrypto (false); i2p::data::PrivateKeys keys; std::ifstream s(argv[1], std::ifstream::binary); if (s.is_open ()) { s.seekg (0, std::ios::end); size_t len = s.tellg(); s.seekg (0, std::ios::beg); uint8_t * buf = new uint8_t[len]; s.read ((char *)buf, len); if(keys.FromBuffer (buf, len)) { auto signatureLen = keys.GetPublic ()->GetSignatureLen (); uint8_t * signature = new uint8_t[signatureLen]; char * sig = new char[signatureLen*2]; std::stringstream out; out << argv[2] << "="; // address out << keys.GetPublic ()->ToBase64 (); keys.Sign ((uint8_t *)out.str ().c_str (), out.str ().length (), signature); auto len = i2p::data::ByteStreamToBase64 (signature, signatureLen, sig, signatureLen*2); sig[len] = 0; out << "#!sig=" << sig; delete[] signature; delete[] sig; std::cout << out.str () << std::endl; } else std::cout << "Failed to load keyfile " << argv[1] << std::endl; delete[] buf; } i2p::crypto::TerminateCrypto (); return 0; } <commit_msg>support GOST R 34.10<commit_after>#include <iostream> #include <fstream> #include <sstream> #include "Identity.h" #include "Base.h" int main (int argc, char * argv[]) { if (argc < 2) { std::cout << "Usage: regaddr filename address" << std::endl; return -1; } i2p::crypto::InitCrypto (false); i2p::crypto::InitGost (); i2p::data::PrivateKeys keys; std::ifstream s(argv[1], std::ifstream::binary); if (s.is_open ()) { s.seekg (0, std::ios::end); size_t len = s.tellg(); s.seekg (0, std::ios::beg); uint8_t * buf = new uint8_t[len]; s.read ((char *)buf, len); if(keys.FromBuffer (buf, len)) { auto signatureLen = keys.GetPublic ()->GetSignatureLen (); uint8_t * signature = new uint8_t[signatureLen]; char * sig = new char[signatureLen*2]; std::stringstream out; out << argv[2] << "="; // address out << keys.GetPublic ()->ToBase64 (); keys.Sign ((uint8_t *)out.str ().c_str (), out.str ().length (), signature); auto len = i2p::data::ByteStreamToBase64 (signature, signatureLen, sig, signatureLen*2); sig[len] = 0; out << "#!sig=" << sig; delete[] signature; delete[] sig; std::cout << out.str () << std::endl; } else std::cout << "Failed to load keyfile " << argv[1] << std::endl; delete[] buf; } i2p::crypto::TerminateGost (); i2p::crypto::TerminateCrypto (); return 0; } <|endoftext|>
<commit_before>#include <cassert> #include <iostream> #include <fstream> #include <map> #include <unordered_map> #include <unordered_set> #include <tuple> #include <stack> #include <vector> #include <string> #include <algorithm> #include <functional> // uncomment to enable debugging: //#define CDEBUG 1 // util for debug #ifdef CDEBUG #define LOGnl(m,x,y,z,a) log_message(m,x,y,z,a,"\n") #define LOG(m,x,y,z,a) log_message(m,x,y,z,a,"") #else #define LOGnl(m,x,y,z,a) #define LOG(m,x,y,z,a) #endif inline void log_message(std::string m, double x, double y, double z, double a, std::string e) { std::cerr << m << "," << x << "," << y << "," << z << "," << a << e; } typedef std::tuple<uint64_t,uint64_t,bool,double,size_t> traceEntry; //id, size, hasNext, pvalue, nextSeen (index of next request) int main(int argc, char* argv[]) { // parameters std::string path(argv[1]); uint64_t cacheSize(atoll(argv[2])); // each interval is represented by the index of the trace, where it started // store trace here std::vector<traceEntry> trace; // store lastSeen entries here std::map<std::pair<uint64_t, uint64_t>, size_t> lastSeen; // intervals that intersect at a time, point to request index std::vector<std::map< std::pair<uint64_t, uint64_t>, size_t > > sameTime; // store which intervals are in the schedule std::unordered_set< size_t > inSchedule; // open trace file std::ifstream traceFile(path); uint64_t time, id, size, reqc=0, uniqc=0; // scan trace and initialize data structures while(traceFile >> time >> id >> size) { // only consider objects that are requested at least once (ignore last request, because doesn't make sense to cache that one) if(lastSeen.count(std::make_pair(id,size))>0) { // see object second time: add to schedule and initialize datastructures // find trace index where this interval started const size_t indexLastSeen = lastSeen[std::make_pair(id,size)]; // add to schedule the start index of this interval inSchedule.insert(indexLastSeen); // update trace so that we know this interval has finite length std::get<2>(trace[indexLastSeen]) = true; // update trace so that we know the end time of this interval std::get<4>(trace[indexLastSeen]) = reqc; // intersection set of this interval: // store indexLastSeen for every discrete time step this request has spanned for(uint64_t i=indexLastSeen; i<reqc; i++) { (sameTime[i])[std::make_pair(id,size)] = indexLastSeen; } } else { // see for first time, so count unique objects uniqc++; } // store: id, size, bool seen before, pvalue, start of this interval (if started) trace.emplace_back(id,size,false,1,0); sameTime.push_back( std::map< std::pair<uint64_t, uint64_t>, size_t >() ); lastSeen[std::make_pair(id,size)]=reqc++; } std::cerr << "parsed trace\n"; // DEBUG print trace reqc = 0; LOGnl("TRACE",0,0,0,0); for(traceEntry & thisTrEntry: trace) { const uint64_t id = std::get<0>(thisTrEntry); const uint64_t size = std::get<1>(thisTrEntry); double & pval = std::get<3>(thisTrEntry); const size_t firstSeen = reqc++; const size_t nextSeen = std::get<4>(thisTrEntry); LOGnl(" ",id,size,firstSeen,nextSeen); } // END DEBUG // initialize time width (total sum of object sizes that span a discrete time step) std::multimap<int64_t, uint64_t > widthToTime; std::unordered_map<uint64_t, std::multimap<int64_t, uint64_t >::iterator > timeToWidthIterator; // reverse mapping uint64_t currentWidth; reqc = 0; for(auto & it: sameTime) { currentWidth = 0; for(auto & vit: it) { const traceEntry & thisTrEntry = trace[vit.second]; const uint64_t id = std::get<0>(thisTrEntry); const uint64_t size = std::get<1>(thisTrEntry); LOG("|",id,size,0,0); currentWidth+=size; } const int64_t currentDelta = currentWidth-cacheSize; auto tWIt = widthToTime.emplace(currentDelta, reqc); timeToWidthIterator[reqc] = tWIt; LOGnl("| TW ",currentDelta,reqc,0,0); reqc++; } // create feasible schedule by excluding worst feasibility violations // i.e., select largest delta in every iteration // store excluded intervals in a stack for later std::stack<size_t> excluded; // find largest delta auto widthIt = --widthToTime.end(); int64_t deltaStar = widthIt->first; // iterate while (deltaStar > 0) { const uint64_t timeStar = widthIt->second; LOGnl("\nd*,t* ",deltaStar,timeStar,0,0); // find smallest rho so that p2 reaches zero double rho = 1; for(auto & it : sameTime[timeStar]) { const traceEntry & thisTrEntry = trace[it.second]; const uint64_t id = std::get<0>(thisTrEntry); const double size = std::get<1>(thisTrEntry); const double pval = std::get<3>(thisTrEntry); const double thisRho = pval/size; rho = thisRho <= rho ? thisRho : rho; } assert(rho < 1); LOGnl("min rho ",rho,0,0,0); // update p2, exclude p2=0 intervals from schedule for(auto it=sameTime[timeStar].begin(); it!=sameTime[timeStar].end(); ) { // define constants with this object's properties traceEntry & thisTrEntry = trace[it->second]; const uint64_t id = std::get<0>(thisTrEntry); const uint64_t size = std::get<1>(thisTrEntry); double & pval = std::get<3>(thisTrEntry); const size_t firstSeen = it->second; const size_t nextSeen = std::get<4>(thisTrEntry); // p2==0 if(pval <= rho * size ) { LOGnl("exclude (t,id,size,p2)",it->second,id,size,pval - rho*size); // exclude from schedule and update width of all times between firstSeen and nextSeen for(size_t i=firstSeen; i<nextSeen; i++) { // find iterator to widthToTime map and assert it exists auto wTITold = timeToWidthIterator.find(i); assert(wTITold != timeToWidthIterator.end()); auto tWItold = timeToWidthIterator[i]; // iterator to this widthToTime field assert(i==tWItold->second); // calculate new delta const int64_t oldDelta = tWItold->first; const int64_t newDelta = oldDelta-size; // delete from widthToTime map widthToTime.erase(tWItold); // create new entry in widthToTime with new delta value auto tWItnew = widthToTime.emplace(newDelta, i); timeToWidthIterator[i] = tWItnew; // skip current it iterator if(i!=timeStar) { (sameTime[i]).erase(std::make_pair(id,size)); } // added to queue of excluded intervals } // set p2 to 0 by definition pval = 0; // add current interval to excluded ones excluded.push(it->second); // delete from current schedule inSchedule.erase(it->second); // delete current entry from current sameTime map it = sameTime[timeStar].erase(it); } else { // p2 >= 0 pval -= size <= deltaStar ? rho * size : rho * deltaStar; // pval = pval - p1 it++; // continue iterator } } // find time step with max delta assert(widthToTime.size()>0); //debug reqc = 0; for(auto & it: sameTime) { for(auto & vit: it) { const traceEntry & thisTrEntry = trace[vit.second]; const uint64_t id = std::get<0>(thisTrEntry); const uint64_t size = std::get<1>(thisTrEntry); LOG("|",id,size,0,0); } LOGnl("| TW ",timeToWidthIterator[reqc]->first,reqc,0,0); reqc++; } // end of debug widthIt = --widthToTime.end(); deltaStar = widthIt->first; } std::cerr << "found feasible schedule\n"; // we now have a feasible schedule, which might not be maximal while (!excluded.empty()) { traceEntry & thisTrEntry = trace[excluded.top()]; const uint64_t id = std::get<0>(thisTrEntry); const uint64_t size = std::get<1>(thisTrEntry); const size_t firstSeen = excluded.top(); const size_t nextSeen = std::get<4>(thisTrEntry); bool feasibleToAdd = true; // check consistency (shouldn't be necessary) assert(inSchedule.find(firstSeen)==inSchedule.end()); // check feasibility for all time steps for(size_t i=firstSeen; i<nextSeen; i++) { // find iterator to widthToTime map and assert it exists auto wTITold = timeToWidthIterator.find(i); assert(wTITold != timeToWidthIterator.end()); auto tWItold = timeToWidthIterator[i]; // iterator to this widthToTime field assert(i==tWItold->second); // calculate new delta const int64_t oldDelta = tWItold->first; const int64_t newDelta = oldDelta+size; if(newDelta > 0) { feasibleToAdd = false; break; } } // actually add this one if(feasibleToAdd) { LOGnl("adding to schedule",firstSeen,0,0,0); // add to feasible schedule inSchedule.insert(firstSeen); // update intersecting time steps for(size_t i=firstSeen; i<nextSeen; i++) { // find iterator to widthToTime map and assert it exists auto wTITold = timeToWidthIterator.find(i); assert(wTITold != timeToWidthIterator.end()); auto tWItold = timeToWidthIterator[i]; // iterator to this widthToTime field assert(i==tWItold->second); // calculate new delta const int64_t oldDelta = tWItold->first; const int64_t newDelta = oldDelta+size; // delete from widthToTime map widthToTime.erase(tWItold); // create new entry in widthToTime with new delta value auto tWItnew = widthToTime.emplace(newDelta, i); timeToWidthIterator[i] = tWItnew; } } excluded.pop(); } std::cerr << "found maximal schedule\n"; std::cout << "hitc " << inSchedule.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(inSchedule.size())/trace.size() << "\n"; return 0; } <commit_msg>complete rewrite of localratio using more straightforward n^3 algorithm<commit_after>#include <cassert> #include <iostream> #include <fstream> #include <map> #include <unordered_map> #include <unordered_set> #include <tuple> #include <stack> #include <vector> #include <string> #include <algorithm> #include <functional> // uncomment to enable debugging: //#define CDEBUG 1 // util for debug #ifdef CDEBUG #define LOGnl(m,x,y,z,a) log_message(m,x,y,z,a,"\n") #define LOG(m,x,y,z,a) log_message(m,x,y,z,a,"") #else #define LOGnl(m,x,y,z,a) #define LOG(m,x,y,z,a) #endif inline void log_message(std::string m, double x, double y, double z, double a, std::string e) { std::cerr << m << "," << x << "," << y << "," << z << "," << a << e; } struct trEntry { const uint64_t id; const uint64_t size; double pval; size_t nextSeen; bool inSchedule; bool hasNext; trEntry(uint64_t nid, uint64_t nsize) : id(nid), size(nsize) { pval = 1; nextSeen = 0; inSchedule = false; hasNext = false; }; }; int main(int argc, char* argv[]) { // parameters std::string path(argv[1]); uint64_t cacheSize(atoll(argv[2])); // each interval is represented by the index of the trace, where it started // store trace here std::vector<trEntry> trace; // store lastSeen entries here std::map<std::pair<uint64_t, uint64_t>, size_t> lastSeen; // store which intervals are in the schedule std::unordered_set< size_t > scheduleSet; // open trace file std::ifstream traceFile(path); uint64_t time, id, size, reqc=0; // scan trace and initialize data structures while(traceFile >> time >> id >> size) { // only consider objects that are requested at least once (ignore last request, because doesn't make sense to cache that one) if(lastSeen.count(std::make_pair(id,size))>0) { // see object second time: add to schedule and initialize datastructures // find trace index where this interval started const size_t indexLastSeen = lastSeen[std::make_pair(id,size)]; // add to schedule the start index of this interval // TODO MIGHT NOT NEED THIS scheduleSet.insert(indexLastSeen); trEntry & lastSeenEntry = trace[indexLastSeen]; // update trace so that we know this interval has finite length lastSeenEntry.hasNext = true; // update trace so that we know the end time of this interval lastSeenEntry.nextSeen = reqc; // update trace: this interval is in schedule lastSeenEntry.inSchedule = true; } // store: id, size, bool seen before, pvalue, start of this interval (if started) trace.emplace_back(id,size); lastSeen[std::make_pair(id,size)]=reqc++; } // free memory lastSeen.clear(); std::cerr << "parsed trace\n"; // DEBUG print trace #ifdef CDEBUG reqc = 0; LOGnl("TRACE",0,0,0,0); for(auto & curEntry : trace) { LOGnl(" ",curEntry.id,curEntry.size,0,curEntry.nextSeen); } #endif // END DEBUG // create feasible schedule by excluding worst feasibility violations // i.e., select largest delta in every iteration // store excluded intervals in a stack for later std::stack<size_t> excluded; // delta data structures int64_t curDelta; int64_t deltaStar; size_t timeStar; // map: intersecting interval set std::map<std::pair<uint64_t, uint64_t>, size_t> curI; //intersecting intervals at current time std::map<std::pair<uint64_t, uint64_t>, size_t> maxI; // intersectin intervals at timeStar // iterate (every iteration removes one interval, so max iteration count = trace size) for(size_t i=0; i<trace.size(); i++) { // find highest delta reqc = 0; // iterate over all time instances (we can skip the last one) maxI.clear(); curDelta = -cacheSize; deltaStar = -cacheSize; timeStar = 0; for(size_t j=0; j<trace.size(); j++) { trEntry & curEntry = trace[j]; // if no next request and in intersecting intervals -> remove if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) { curI.erase(std::make_pair(curEntry.id,curEntry.size)); curDelta -= curEntry.size; assert(!curEntry.inSchedule); } // if in schedule -> update curI if(curEntry.inSchedule) { // if not already in current intersecting set if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) { curDelta += curEntry.size; } // else: don't need update the size/width // add to current intersecting set curI[std::make_pair(curEntry.id,curEntry.size)] = j; // check if we need to update deltaStar if(curDelta > deltaStar) { deltaStar = curDelta; timeStar = j; // copy intersecting set maxI = curI; } } #ifdef CDEBUG for(auto it: curI) { trEntry & curEntry = trace[it.second]; LOG("|",curEntry.id,curEntry.size,0,0); } LOGnl("| TW ",curDelta,j,deltaStar,timeStar); #endif } // check if we found a feasible solution if(deltaStar <= 0) break; curI.clear(); assert(maxI.size()>0); assert(deltaStar > 0); assert(timeStar > 0); // first time interval can't be the unstable one LOGnl("\nd*,t*",deltaStar,timeStar,0,0); std::cout << "d*" << deltaStar << " t* " << timeStar; // find smallest rho so that p2 reaches zero double rho = 1; for(auto & vit : maxI) { trEntry & curEntry = trace[vit.second]; const double thisRho = curEntry.pval/curEntry.size; rho = thisRho <= rho ? thisRho : rho; } assert(rho < 1); LOGnl("min rho ",rho,0,0,0); std::cout << " mrho " << rho << "\n"; // update p2, exclude intervals with p2=0 from schedule for(auto & vit : maxI) { trEntry & curEntry = trace[vit.second]; // p2==0 if(curEntry.pval <= rho * curEntry.size ) { LOGnl("exclude (t,id,size,p2)",vit.second,id,curEntry.size,curEntry.pval - rho*curEntry.size); curEntry.pval = 0; curEntry.inSchedule = false; // add current interval to excluded ones excluded.push(vit.second); // delete from current schedule scheduleSet.erase(vit.second); } else { // p2 >= 0 curEntry.pval -= curEntry.size <= deltaStar ? rho * curEntry.size : rho * deltaStar; // pval = pval - p1 } } } maxI.clear(); std::cerr << "found feasible schedule\n"; std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n"; // we now have a feasible schedule, which might not be maximal while (!excluded.empty()) { const size_t firstSeen = excluded.top(); trEntry & newEntry = trace[excluded.top()]; curI.clear(); curDelta = -cacheSize; deltaStar = -cacheSize; for(size_t j=0; j<trace.size(); j++) { trEntry & curEntry = trace[j]; // if no next request and in intersecting intervals -> remove if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) { curI.erase(std::make_pair(curEntry.id,curEntry.size)); curDelta -= curEntry.size; assert(!curEntry.inSchedule); } // if in schedule -> update curI if(j==excluded.top() || curEntry.inSchedule) { // if not already in current intersecting set if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) { curDelta += curEntry.size; } // else: don't need update the size/width // add to current intersecting set curI[std::make_pair(curEntry.id,curEntry.size)] = j; // check if we need to update deltaStar if(curDelta > deltaStar) { deltaStar = curDelta; } } } // if still feasible add excluded.top() to schedule if(deltaStar <=0) { newEntry.inSchedule = true; scheduleSet.insert(excluded.top()); } // pop stack excluded.pop(); } std::cerr << "found maximal schedule\n"; std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n"; return 0; } <|endoftext|>
<commit_before> #include "../Flare.h" #include "../Game/FlareWorld.h" #include "../Game/FlareGame.h" #include "../Game/FlareSimulatedSector.h" #include "../Spacecrafts/FlareSimulatedSpacecraft.h" #include "FlareScenarioTools.h" #define LOCTEXT_NAMESPACE "FlareScenarioToolsInfo" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareScenarioTools::UFlareScenarioTools(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } /*---------------------------------------------------- Public methods ----------------------------------------------------*/ void UFlareScenarioTools::Init(UFlareCompany* Company, FFlarePlayerSave* Player) { Game = Cast<AFlareGame>(GetOuter()); World = Game->GetGameWorld(); PlayerCompany = Company; PlayerData = Player; } void UFlareScenarioTools::GenerateEmptyScenario() { } void UFlareScenarioTools::GenerateFighterScenario() { SetupWorld(); // Create player ship FLOG("UFlareScenarioTools::GenerateFighterScenario create initial ship"); UFlareSimulatedSpacecraft* InitialShip = World->FindSector("first-light")->CreateShip("ship-ghoul", PlayerCompany, FVector::ZeroVector); PlayerData->LastFlownShipIdentifier = InitialShip->GetImmatriculation(); PlayerData->SelectedFleetIdentifier = InitialShip->GetCurrentFleet()->GetIdentifier(); // Initial setup : outpost UFlareSimulatedSector* Outpost = World->FindSector("outpost"); Outpost->CreateShip("ship-dragon", PlayerCompany, FVector::ZeroVector); Outpost->CreateStation("station-hub", PlayerCompany, FVector::ZeroVector); Outpost->CreateStation("station-tokamak", PlayerCompany, FVector::ZeroVector); Outpost->CreateStation("station-solar-plant", PlayerCompany, FVector::ZeroVector); Outpost->CreateStation("station-solar-plant", World->FindCompanyByShortName("HFR"), FVector::ZeroVector); Outpost->CreateStation("station-solar-plant", World->FindCompanyByShortName("HFR"), FVector::ZeroVector); Outpost->CreateStation("station-tokamak", World->FindCompanyByShortName("SUN"), FVector::ZeroVector); Outpost->CreateStation("station-hub", World->FindCompanyByShortName("GWS"), FVector::ZeroVector); } void UFlareScenarioTools::GenerateDebugScenario() { SetupWorld(); UFlareSimulatedSector* Outpost = World->FindSector("outpost"); FFlareResourceDescription* Water = Game->GetResourceCatalog()->Get("h2o"); FFlareResourceDescription* Food = Game->GetResourceCatalog()->Get("food"); FFlareResourceDescription* Fuel = Game->GetResourceCatalog()->Get("fuel"); FFlareResourceDescription* Plastics = Game->GetResourceCatalog()->Get("plastics"); FFlareResourceDescription* Hydrogen = Game->GetResourceCatalog()->Get("h2"); FFlareResourceDescription* Helium = Game->GetResourceCatalog()->Get("he3"); // Create player ship FLOG("UFlareScenarioTools::GenerateDebugScenario create initial ship"); UFlareSimulatedSpacecraft* InitialShip = Outpost->CreateShip("ship-solen", PlayerCompany, FVector::ZeroVector); PlayerData->LastFlownShipIdentifier = InitialShip->GetImmatriculation(); PlayerData->SelectedFleetIdentifier = InitialShip->GetCurrentFleet()->GetIdentifier(); // Initial setup : "Outpost" for(int Index = 0; Index < 5; Index ++) { Outpost->CreateShip("ship-omen", PlayerCompany, FVector::ZeroVector)->AssignToSector(true); } for(int Index = 0; Index < 3; Index ++) { Outpost->CreateStation("station-solar-plant", PlayerCompany, FVector::ZeroVector)->GiveResources(Water, 100); } Outpost->CreateStation("station-habitation", PlayerCompany, FVector::ZeroVector)->GiveResources(Food, 30); Outpost->CreateStation("station-farm", PlayerCompany, FVector::ZeroVector); UFlareSimulatedSpacecraft* Refinery = Outpost->CreateStation("station-refinery", PlayerCompany, FVector::ZeroVector); Refinery->GetFactories()[0]->SetOutputLimit(Plastics, 1); Refinery->GetFactories()[0]->SetOutputLimit(Hydrogen, 1); Refinery->GiveResources(Fuel, 50); UFlareSimulatedSpacecraft* PompingStation = Outpost->CreateStation("station-pomping", PlayerCompany, FVector::ZeroVector); PompingStation->GetFactories()[0]->SetOutputLimit(Hydrogen, 1); PompingStation->GetFactories()[0]->SetOutputLimit(Helium, 1); PompingStation->GiveResources(Fuel, 50); Outpost->GetPeople()->GiveBirth(1000); Outpost->GetPeople()->SetHappiness(1); World->FindSector("frozen-realm")->CreateShip("ship-omen", PlayerCompany, FVector::ZeroVector); // Discover known sectors if (!PlayerData->QuestData.PlayTutorial) { for (int SectorIndex = 0; SectorIndex < World->GetSectors().Num(); SectorIndex++) { PlayerCompany->DiscoverSector(World->GetSectors()[SectorIndex]); } } } /*---------------------------------------------------- Helpers ----------------------------------------------------*/ void UFlareScenarioTools::SetupWorld() { // Create asteroids at "Outpost" for (int32 Index = 0; Index < 20; Index++) { FString AsteroidName = FString("asteroid") + FString::FromInt(Index); World->FindSector("outpost")->CreateAsteroid(FMath::RandRange(0, 5), FName(*AsteroidName) , 200000 * FMath::VRand()); } // Create asteroids at "Frozen Realm" for (int32 Index = 0; Index < 50; Index++) { FString AsteroidName = FString("asteroid") + FString::FromInt(Index); World->FindSector("frozen-realm")->CreateAsteroid(FMath::RandRange(0, 5), FName(*AsteroidName), 200000 * FMath::VRand()); } } #undef LOCTEXT_NAMESPACE <commit_msg>Improve debug scenario and add a lot of balance<commit_after> #include "../Flare.h" #include "../Game/FlareWorld.h" #include "../Game/FlareGame.h" #include "../Game/FlareSimulatedSector.h" #include "../Spacecrafts/FlareSimulatedSpacecraft.h" #include "FlareScenarioTools.h" #define LOCTEXT_NAMESPACE "FlareScenarioToolsInfo" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareScenarioTools::UFlareScenarioTools(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } /*---------------------------------------------------- Public methods ----------------------------------------------------*/ void UFlareScenarioTools::Init(UFlareCompany* Company, FFlarePlayerSave* Player) { Game = Cast<AFlareGame>(GetOuter()); World = Game->GetGameWorld(); PlayerCompany = Company; PlayerData = Player; } void UFlareScenarioTools::GenerateEmptyScenario() { } void UFlareScenarioTools::GenerateFighterScenario() { SetupWorld(); // Create player ship FLOG("UFlareScenarioTools::GenerateFighterScenario create initial ship"); UFlareSimulatedSpacecraft* InitialShip = World->FindSector("first-light")->CreateShip("ship-ghoul", PlayerCompany, FVector::ZeroVector); PlayerData->LastFlownShipIdentifier = InitialShip->GetImmatriculation(); PlayerData->SelectedFleetIdentifier = InitialShip->GetCurrentFleet()->GetIdentifier(); // Initial setup : outpost UFlareSimulatedSector* Outpost = World->FindSector("outpost"); Outpost->CreateShip("ship-dragon", PlayerCompany, FVector::ZeroVector); Outpost->CreateStation("station-hub", PlayerCompany, FVector::ZeroVector); Outpost->CreateStation("station-tokamak", PlayerCompany, FVector::ZeroVector); Outpost->CreateStation("station-solar-plant", PlayerCompany, FVector::ZeroVector); Outpost->CreateStation("station-solar-plant", World->FindCompanyByShortName("HFR"), FVector::ZeroVector); Outpost->CreateStation("station-solar-plant", World->FindCompanyByShortName("HFR"), FVector::ZeroVector); Outpost->CreateStation("station-tokamak", World->FindCompanyByShortName("SUN"), FVector::ZeroVector); Outpost->CreateStation("station-hub", World->FindCompanyByShortName("GWS"), FVector::ZeroVector); } void UFlareScenarioTools::GenerateDebugScenario() { SetupWorld(); UFlareSimulatedSector* Outpost = World->FindSector("outpost"); UFlareSimulatedSector* MinerHome = World->FindSector("miners-home"); FFlareResourceDescription* Water = Game->GetResourceCatalog()->Get("h2o"); FFlareResourceDescription* Food = Game->GetResourceCatalog()->Get("food"); FFlareResourceDescription* Fuel = Game->GetResourceCatalog()->Get("fuel"); FFlareResourceDescription* Plastics = Game->GetResourceCatalog()->Get("plastics"); FFlareResourceDescription* Hydrogen = Game->GetResourceCatalog()->Get("h2"); FFlareResourceDescription* Helium = Game->GetResourceCatalog()->Get("he3"); // Create player ship FLOG("UFlareScenarioTools::GenerateDebugScenario create initial ship"); UFlareSimulatedSpacecraft* InitialShip = Outpost->CreateShip("ship-solen", PlayerCompany, FVector::ZeroVector); PlayerData->LastFlownShipIdentifier = InitialShip->GetImmatriculation(); PlayerData->SelectedFleetIdentifier = InitialShip->GetCurrentFleet()->GetIdentifier(); // Initial setup : "Outpost" for(int Index = 0; Index < 5; Index ++) { Outpost->CreateShip("ship-omen", PlayerCompany, FVector::ZeroVector)->AssignToSector(true); } for(int Index = 0; Index < 3; Index ++) { Outpost->CreateStation("station-solar-plant", PlayerCompany, FVector::ZeroVector)->GiveResources(Water, 100); } Outpost->CreateStation("station-habitation", PlayerCompany, FVector::ZeroVector)->GiveResources(Food, 30); Outpost->CreateStation("station-farm", PlayerCompany, FVector::ZeroVector); UFlareSimulatedSpacecraft* Refinery = Outpost->CreateStation("station-refinery", PlayerCompany, FVector::ZeroVector); Refinery->GetFactories()[0]->SetOutputLimit(Plastics, 1); Refinery->GetFactories()[0]->SetOutputLimit(Hydrogen, 1); Refinery->GiveResources(Fuel, 50); UFlareSimulatedSpacecraft* PompingStation = Outpost->CreateStation("station-pomping", PlayerCompany, FVector::ZeroVector); PompingStation->GetFactories()[0]->SetOutputLimit(Hydrogen, 1); PompingStation->GetFactories()[0]->SetOutputLimit(Helium, 1); PompingStation->GiveResources(Fuel, 50); Outpost->GetPeople()->GiveBirth(1000); Outpost->GetPeople()->SetHappiness(1); // Initial setup : "Miner's home" for(int Index = 0; Index < 5; Index ++) { MinerHome->CreateShip("ship-omen", PlayerCompany, FVector::ZeroVector)->AssignToSector(true); } UFlareSimulatedSpacecraft* Tokamak = MinerHome->CreateStation("station-tokamak", PlayerCompany, FVector::ZeroVector); Tokamak->GiveResources(Water, 200); UFlareSimulatedSpacecraft* Steelworks = MinerHome->CreateStation("station-steelworks", PlayerCompany, FVector::ZeroVector); UFlareSimulatedSpacecraft* Manufacture = MinerHome->CreateStation("station-manufacture", PlayerCompany, FVector::ZeroVector); UFlareSimulatedSpacecraft* Mine = MinerHome->CreateStation("station-mine", PlayerCompany, FVector::ZeroVector, FRotator::ZeroRotator, MinerHome->Save()->AsteroidData[0].Identifier); UFlareTradeRoute* OutpostToMinerHome = PlayerCompany->CreateTradeRoute(FText::FromString(TEXT("Trade route 1"))); OutpostToMinerHome->AddSector(Outpost); OutpostToMinerHome->AddSector(MinerHome); OutpostToMinerHome->SetSectorLoadOrder(0, Helium, 0); OutpostToMinerHome->SetSectorLoadOrder(0, Hydrogen, 0); OutpostToMinerHome->SetSectorLoadOrder(0, Plastics, 0); OutpostToMinerHome->SetSectorUnloadOrder(0, Water, 0); OutpostToMinerHome->SetSectorLoadOrder(1, Water, 200); OutpostToMinerHome->SetSectorUnloadOrder(1, Helium, 0); OutpostToMinerHome->SetSectorUnloadOrder(1, Hydrogen, 0); OutpostToMinerHome->SetSectorUnloadOrder(1, Plastics, 0); UFlareFleet* TradeFleet1 = PlayerCompany->CreateFleet(FText::FromString(TEXT("Trade fleet 1")), MinerHome); TradeFleet1->AddShip(MinerHome->CreateShip("ship-omen", PlayerCompany, FVector::ZeroVector)); TradeFleet1->AddShip(MinerHome->CreateShip("ship-omen", PlayerCompany, FVector::ZeroVector)); TradeFleet1->AddShip(MinerHome->CreateShip("ship-omen", PlayerCompany, FVector::ZeroVector)); TradeFleet1->AddShip(MinerHome->CreateShip("ship-omen", PlayerCompany, FVector::ZeroVector)); OutpostToMinerHome->AddFleet(TradeFleet1); World->FindSector("frozen-realm")->CreateShip("ship-omen", PlayerCompany, FVector::ZeroVector); // Discover known sectors if (!PlayerData->QuestData.PlayTutorial) { for (int SectorIndex = 0; SectorIndex < World->GetSectors().Num(); SectorIndex++) { PlayerCompany->DiscoverSector(World->GetSectors()[SectorIndex]); } } } /*---------------------------------------------------- Helpers ----------------------------------------------------*/ void UFlareScenarioTools::SetupWorld() { // Create asteroids at "Outpost" for (int32 Index = 0; Index < 20; Index++) { FString AsteroidName = FString("asteroid") + FString::FromInt(Index); World->FindSector("outpost")->CreateAsteroid(FMath::RandRange(0, 5), FName(*AsteroidName) , 200000 * FMath::VRand()); } // Create asteroids at "Miner's home" for (int32 Index = 0; Index < 40; Index++) { FString AsteroidName = FString("asteroid") + FString::FromInt(Index); World->FindSector("miners-home")->CreateAsteroid(FMath::RandRange(0, 5), FName(*AsteroidName) , 200000 * FMath::VRand()); } // Create asteroids at "Frozen Realm" for (int32 Index = 0; Index < 50; Index++) { FString AsteroidName = FString("asteroid") + FString::FromInt(Index); World->FindSector("frozen-realm")->CreateAsteroid(FMath::RandRange(0, 5), FName(*AsteroidName), 200000 * FMath::VRand()); } } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/kernel/object_table.h" #include <algorithm> #include "xenia/kernel/xobject.h" #include "xenia/kernel/objects/xthread.h" namespace xe { namespace kernel { ObjectTable::ObjectTable() : table_capacity_(0), table_(nullptr), last_free_entry_(0) {} ObjectTable::~ObjectTable() { std::lock_guard<std::mutex> lock(table_mutex_); // Release all objects. for (uint32_t n = 0; n < table_capacity_; n++) { ObjectTableEntry& entry = table_[n]; if (entry.object) { entry.object->ReleaseHandle(); entry.object->Release(); } } table_capacity_ = 0; last_free_entry_ = 0; free(table_); table_ = NULL; } X_STATUS ObjectTable::FindFreeSlot(uint32_t* out_slot) { // Find a free slot. uint32_t slot = last_free_entry_; uint32_t scan_count = 0; while (scan_count < table_capacity_) { ObjectTableEntry& entry = table_[slot]; if (!entry.object) { *out_slot = slot; return X_STATUS_SUCCESS; } scan_count++; slot = (slot + 1) % table_capacity_; if (slot == 0) { // Never allow 0 handles. scan_count++; slot++; } } // Table out of slots, expand. uint32_t new_table_capacity = std::max(16 * 1024u, table_capacity_ * 2); size_t new_table_size = new_table_capacity * sizeof(ObjectTableEntry); size_t old_table_size = table_capacity_ * sizeof(ObjectTableEntry); ObjectTableEntry* new_table = (ObjectTableEntry*)realloc(table_, new_table_size); if (!new_table) { return X_STATUS_NO_MEMORY; } // Zero out new memory. if (new_table_size > old_table_size) { memset(reinterpret_cast<uint8_t*>(new_table) + old_table_size, 0, new_table_size - old_table_size); } last_free_entry_ = table_capacity_; table_capacity_ = new_table_capacity; table_ = new_table; // Never allow 0 handles. slot = ++last_free_entry_; *out_slot = slot; return X_STATUS_SUCCESS; } X_STATUS ObjectTable::AddHandle(XObject* object, X_HANDLE* out_handle, bool removable) { assert_not_null(out_handle); X_STATUS result = X_STATUS_SUCCESS; uint32_t slot = 0; { std::lock_guard<std::mutex> lock(table_mutex_); // Find a free slot. result = FindFreeSlot(&slot); // Stash. if (XSUCCEEDED(result)) { ObjectTableEntry& entry = table_[slot]; entry.object = object; entry.removable = removable; // Retain so long as the object is in the table. object->RetainHandle(); object->Retain(); } } if (XSUCCEEDED(result)) { *out_handle = slot << 2; } return result; } X_STATUS ObjectTable::RemoveHandle(X_HANDLE handle, bool force) { X_STATUS result = X_STATUS_SUCCESS; handle = TranslateHandle(handle); if (!handle) { return X_STATUS_INVALID_HANDLE; } XObject* object = NULL; { std::lock_guard<std::mutex> lock(table_mutex_); // Lower 2 bits are ignored. uint32_t slot = handle >> 2; // Verify slot. if (slot > table_capacity_) { result = X_STATUS_INVALID_HANDLE; } else { ObjectTableEntry& entry = table_[slot]; if (entry.object) { // Check to see if user code can remove this handle. if (entry.removable || force) { // Release after we lose the lock. object = entry.object; } else { result = X_STATUS_UNSUCCESSFUL; } } else { result = X_STATUS_INVALID_HANDLE; } entry.object = nullptr; } } if (object) { // Release the object handle now that it is out of the table. object->ReleaseHandle(); object->Release(); } return result; } X_STATUS ObjectTable::GetObject(X_HANDLE handle, XObject** out_object, bool already_locked) { assert_not_null(out_object); X_STATUS result = X_STATUS_SUCCESS; handle = TranslateHandle(handle); if (!handle) { return X_STATUS_INVALID_HANDLE; } XObject* object = NULL; if (!already_locked) { table_mutex_.lock(); } // Lower 2 bits are ignored. uint32_t slot = handle >> 2; // Verify slot. if (slot > table_capacity_) { result = X_STATUS_INVALID_HANDLE; } else { ObjectTableEntry& entry = table_[slot]; if (entry.object) { object = entry.object; } else { result = X_STATUS_INVALID_HANDLE; } } // Retain the object pointer. if (object) { object->Retain(); } if (!already_locked) { table_mutex_.unlock(); } *out_object = object; return result; } X_HANDLE ObjectTable::TranslateHandle(X_HANDLE handle) { if (handle == 0xFFFFFFFF) { // CurrentProcess // assert_always(); return 0; } else if (handle == 0xFFFFFFFE) { // CurrentThread return XThread::GetCurrentThreadHandle(); } else { return handle; } } X_STATUS ObjectTable::AddNameMapping(const std::string& name, X_HANDLE handle) { std::lock_guard<std::mutex> lock(table_mutex_); if (name_table_.count(name)) { return X_STATUS_OBJECT_NAME_COLLISION; } name_table_.insert({name, handle}); return X_STATUS_SUCCESS; } void ObjectTable::RemoveNameMapping(const std::string& name) { std::lock_guard<std::mutex> lock(table_mutex_); auto it = name_table_.find(name); if (it != name_table_.end()) { name_table_.erase(it); } } X_STATUS ObjectTable::GetObjectByName(const std::string& name, X_HANDLE* out_handle) { std::lock_guard<std::mutex> lock(table_mutex_); auto it = name_table_.find(name); if (it == name_table_.end()) { *out_handle = X_INVALID_HANDLE_VALUE; return X_STATUS_OBJECT_NAME_NOT_FOUND; } *out_handle = it->second; // We need to ref the handle. I think. XObject* obj = nullptr; if (XSUCCEEDED(GetObject(it->second, &obj, true))) { obj->RetainHandle(); obj->Release(); } return X_STATUS_SUCCESS; } } // namespace kernel } // namespace xe <commit_msg>Release the object in the proper spot<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/kernel/object_table.h" #include <algorithm> #include "xenia/kernel/xobject.h" #include "xenia/kernel/objects/xthread.h" namespace xe { namespace kernel { ObjectTable::ObjectTable() : table_capacity_(0), table_(nullptr), last_free_entry_(0) {} ObjectTable::~ObjectTable() { std::lock_guard<std::mutex> lock(table_mutex_); // Release all objects. for (uint32_t n = 0; n < table_capacity_; n++) { ObjectTableEntry& entry = table_[n]; if (entry.object) { entry.object->ReleaseHandle(); entry.object->Release(); } } table_capacity_ = 0; last_free_entry_ = 0; free(table_); table_ = NULL; } X_STATUS ObjectTable::FindFreeSlot(uint32_t* out_slot) { // Find a free slot. uint32_t slot = last_free_entry_; uint32_t scan_count = 0; while (scan_count < table_capacity_) { ObjectTableEntry& entry = table_[slot]; if (!entry.object) { *out_slot = slot; return X_STATUS_SUCCESS; } scan_count++; slot = (slot + 1) % table_capacity_; if (slot == 0) { // Never allow 0 handles. scan_count++; slot++; } } // Table out of slots, expand. uint32_t new_table_capacity = std::max(16 * 1024u, table_capacity_ * 2); size_t new_table_size = new_table_capacity * sizeof(ObjectTableEntry); size_t old_table_size = table_capacity_ * sizeof(ObjectTableEntry); ObjectTableEntry* new_table = (ObjectTableEntry*)realloc(table_, new_table_size); if (!new_table) { return X_STATUS_NO_MEMORY; } // Zero out new memory. if (new_table_size > old_table_size) { memset(reinterpret_cast<uint8_t*>(new_table) + old_table_size, 0, new_table_size - old_table_size); } last_free_entry_ = table_capacity_; table_capacity_ = new_table_capacity; table_ = new_table; // Never allow 0 handles. slot = ++last_free_entry_; *out_slot = slot; return X_STATUS_SUCCESS; } X_STATUS ObjectTable::AddHandle(XObject* object, X_HANDLE* out_handle, bool removable) { assert_not_null(out_handle); X_STATUS result = X_STATUS_SUCCESS; uint32_t slot = 0; { std::lock_guard<std::mutex> lock(table_mutex_); // Find a free slot. result = FindFreeSlot(&slot); // Stash. if (XSUCCEEDED(result)) { ObjectTableEntry& entry = table_[slot]; entry.object = object; entry.removable = removable; // Retain so long as the object is in the table. object->RetainHandle(); object->Retain(); } } if (XSUCCEEDED(result)) { *out_handle = slot << 2; } return result; } X_STATUS ObjectTable::RemoveHandle(X_HANDLE handle, bool force) { X_STATUS result = X_STATUS_SUCCESS; handle = TranslateHandle(handle); if (!handle) { return X_STATUS_INVALID_HANDLE; } XObject* object = NULL; { std::lock_guard<std::mutex> lock(table_mutex_); // Lower 2 bits are ignored. uint32_t slot = handle >> 2; // Verify slot. if (slot > table_capacity_) { result = X_STATUS_INVALID_HANDLE; } else { ObjectTableEntry& entry = table_[slot]; if (entry.object) { // Check to see if user code can remove this handle. if (entry.removable || force) { // Release after we lose the lock. object = entry.object; entry.object = nullptr; } else { result = X_STATUS_UNSUCCESSFUL; } } else { result = X_STATUS_INVALID_HANDLE; } } } if (object) { // Release the object handle now that it is out of the table. object->ReleaseHandle(); object->Release(); } return result; } X_STATUS ObjectTable::GetObject(X_HANDLE handle, XObject** out_object, bool already_locked) { assert_not_null(out_object); X_STATUS result = X_STATUS_SUCCESS; handle = TranslateHandle(handle); if (!handle) { return X_STATUS_INVALID_HANDLE; } XObject* object = NULL; if (!already_locked) { table_mutex_.lock(); } // Lower 2 bits are ignored. uint32_t slot = handle >> 2; // Verify slot. if (slot > table_capacity_) { result = X_STATUS_INVALID_HANDLE; } else { ObjectTableEntry& entry = table_[slot]; if (entry.object) { object = entry.object; } else { result = X_STATUS_INVALID_HANDLE; } } // Retain the object pointer. if (object) { object->Retain(); } if (!already_locked) { table_mutex_.unlock(); } *out_object = object; return result; } X_HANDLE ObjectTable::TranslateHandle(X_HANDLE handle) { if (handle == 0xFFFFFFFF) { // CurrentProcess // assert_always(); return 0; } else if (handle == 0xFFFFFFFE) { // CurrentThread return XThread::GetCurrentThreadHandle(); } else { return handle; } } X_STATUS ObjectTable::AddNameMapping(const std::string& name, X_HANDLE handle) { std::lock_guard<std::mutex> lock(table_mutex_); if (name_table_.count(name)) { return X_STATUS_OBJECT_NAME_COLLISION; } name_table_.insert({name, handle}); return X_STATUS_SUCCESS; } void ObjectTable::RemoveNameMapping(const std::string& name) { std::lock_guard<std::mutex> lock(table_mutex_); auto it = name_table_.find(name); if (it != name_table_.end()) { name_table_.erase(it); } } X_STATUS ObjectTable::GetObjectByName(const std::string& name, X_HANDLE* out_handle) { std::lock_guard<std::mutex> lock(table_mutex_); auto it = name_table_.find(name); if (it == name_table_.end()) { *out_handle = X_INVALID_HANDLE_VALUE; return X_STATUS_OBJECT_NAME_NOT_FOUND; } *out_handle = it->second; // We need to ref the handle. I think. XObject* obj = nullptr; if (XSUCCEEDED(GetObject(it->second, &obj, true))) { obj->RetainHandle(); obj->Release(); } return X_STATUS_SUCCESS; } } // namespace kernel } // namespace xe <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <spdlog/spdlog.h> #include "file_util.hpp" #include "singleton.hpp" namespace czrpc { namespace base { static const std::string logger_name = "czrpc"; static const std::size_t max_file_size = 3 * 1024 * 1024; static const std::size_t max_files = 30; class logger_impl { DEFINE_SINGLETON(logger_impl); public: logger_impl() { init(); } std::shared_ptr<spdlog::logger> get_console_logger() { return _console_logger; } std::shared_ptr<spdlog::logger> get_file_logger() { return _file_logger; } private: bool init() { std::string file_name = create_log_file(); if (file_name.empty()) { return false; } return init_log_core(file_name); } std::string create_log_file() { std::string exe_path = file_util::current_exe_path(); if (exe_path.empty()) { return ""; } std::string log_path; if (exe_path[exe_path.size() - 1] == '/' || exe_path[exe_path.size() - 1] == '\\') { log_path = exe_path + "logs"; } else { log_path = exe_path + "/logs"; } if (!file_util::mkdir(log_path)) { return ""; } std::string exe_name = file_util::current_exe_name(); if (exe_name.empty()) { return ""; } return log_path + "/" + exe_name + "_" + logger_name; } bool init_log_core(const std::string& file_name) { try { _console_logger = spdlog::stdout_logger_mt("console"); _file_logger = spdlog::rotating_logger_mt("file", file_name, max_file_size, max_files); _file_logger->flush_on(spdlog::level::level_enum::debug); _console_logger->set_level(spdlog::level::debug); _file_logger->set_level(spdlog::level::debug); } catch (std::exception&) { return false; } return true; } private: std::shared_ptr<spdlog::logger> _console_logger; std::shared_ptr<spdlog::logger> _file_logger; }; class logger { public: logger() = default; logger(const logger&) = delete; logger& operator=(const logger&) = delete; logger(const char* file_path, const char* func_name, unsigned long line, spdlog::level::level_enum level) : file_path_(file_path), file_name_(func_name), line_(line), level_(level) {} template<typename... Args> void log(const std::string& fmt, Args&&... args) { log(fmt.c_str(), std::forward<Args>(args)...); } template<typename... Args> void log(const char* fmt, Args&&... args) { const std::string& content = make_content(fmt); logger_impl::singleton::get()->get_console_logger()->log(level_, content.c_str(), std::forward<Args>(args)...); logger_impl::singleton::get()->get_file_logger()->log(level_, content.c_str(), std::forward<Args>(args)...); } private: std::string make_content(const std::string& fmt) { #ifdef _WIN32 int pos = file_path_.find_last_of("\\"); #else int pos = file_path_.find_last_of("/"); #endif std::string content = file_path_.substr(pos + 1) + " " + file_name_ + "(" + std::to_string(line_) + ") " + fmt; return content; } private: std::string file_path_; std::string file_name_; unsigned long line_; spdlog::level::level_enum level_; }; #define LOCATION __FILE__, __FUNCTION__, __LINE__ #define log_trace logger(LOCATION, spdlog::level::level_enum::trace).log #define log_debug logger(LOCATION, spdlog::level::level_enum::debug).log #define log_info logger(LOCATION, spdlog::level::level_enum::info).log #define log_warn logger(LOCATION, spdlog::level::level_enum::warn).log #define log_error logger(LOCATION, spdlog::level::level_enum::err).log #define log_critical logger(LOCATION, spdlog::level::level_enum::critical).log } } <commit_msg>update logger<commit_after>#pragma once #include <iostream> #include <spdlog/spdlog.h> #include "file_util.hpp" #include "singleton.hpp" namespace czrpc { namespace base { static const std::string logger_name = "czrpc"; static const std::size_t max_file_size = 3 * 1024 * 1024; static const std::size_t max_files = 30; class logger_impl { DEFINE_SINGLETON(logger_impl); public: logger_impl() { init(); } std::shared_ptr<spdlog::logger> get_console_logger() { return console_logger_; } std::shared_ptr<spdlog::logger> get_file_logger() { return file_logger_; } private: bool init() { std::string file_name = create_log_file(); if (file_name.empty()) { return false; } return init_log_core(file_name); } std::string create_log_file() { std::string exe_path = file_util::current_exe_path(); if (exe_path.empty()) { return ""; } std::string log_path; if (exe_path[exe_path.size() - 1] == '/' || exe_path[exe_path.size() - 1] == '\\') { log_path = exe_path + "logs"; } else { log_path = exe_path + "/logs"; } if (!file_util::mkdir(log_path)) { return ""; } std::string exe_name = file_util::current_exe_name(); if (exe_name.empty()) { return ""; } return log_path + "/" + exe_name + "_" + logger_name; } bool init_log_core(const std::string& file_name) { try { console_logger_ = spdlog::stdout_logger_mt("console"); file_logger_ = spdlog::rotating_logger_mt("file", file_name, max_file_size, max_files); file_logger_->flush_on(spdlog::level::level_enum::debug); console_logger_->set_level(spdlog::level::debug); file_logger_->set_level(spdlog::level::debug); } catch (std::exception&) { return false; } return true; } private: std::shared_ptr<spdlog::logger> console_logger_; std::shared_ptr<spdlog::logger> file_logger_; }; class logger { public: logger() = default; logger(const logger&) = delete; logger& operator=(const logger&) = delete; logger(const char* file_path, const char* func_name, unsigned long line, spdlog::level::level_enum level) : file_path_(file_path), file_name_(func_name), line_(line), level_(level) {} template<typename... Args> void log(const std::string& fmt, Args&&... args) { log(fmt.c_str(), std::forward<Args>(args)...); } template<typename... Args> void log(const char* fmt, Args&&... args) { std::string content = make_content(fmt); logger_impl::singleton::get()->get_console_logger()->log(level_, content.c_str(), std::forward<Args>(args)...); logger_impl::singleton::get()->get_file_logger()->log(level_, content.c_str(), std::forward<Args>(args)...); } private: std::string make_content(const std::string& fmt) { #ifdef _WIN32 int pos = file_path_.find_last_of("\\"); #else int pos = file_path_.find_last_of("/"); #endif std::string content = file_path_.substr(pos + 1) + " " + file_name_ + "(" + std::to_string(line_) + ") " + fmt; return std::move(content); } private: std::string file_path_; std::string file_name_; unsigned long line_; spdlog::level::level_enum level_; }; #define LOCATION __FILE__, __FUNCTION__, __LINE__ #define log_trace logger(LOCATION, spdlog::level::level_enum::trace).log #define log_debug logger(LOCATION, spdlog::level::level_enum::debug).log #define log_info logger(LOCATION, spdlog::level::level_enum::info).log #define log_warn logger(LOCATION, spdlog::level::level_enum::warn).log #define log_error logger(LOCATION, spdlog::level::level_enum::err).log #define log_critical logger(LOCATION, spdlog::level::level_enum::critical).log } } <|endoftext|>
<commit_before>// This file is part of the "libxzero" project // (c) 2009-2015 Christian Parpart <https://github.com/christianparpart> // (c) 2014-2015 Paul Asmuth <https://github.com/paulasmuth> // // libxzero is free software: you can redistribute it and/or modify it under // the terms of the GNU Affero General Public License v3.0. // 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 <xzero/io/FileOutputStream.h> #include <xzero/RuntimeError.h> #include <xzero/Buffer.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> namespace xzero { FileOutputStream::FileOutputStream(const std::string& path) : handle_(::open(path.c_str(), O_WRONLY | O_CREAT)), closeOnDestroy_(true) { if (handle_ < 0) { RAISE_ERRNO(errno); } } FileOutputStream::~FileOutputStream() { if (closeOnDestroy_) { ::close(handle_); } } int FileOutputStream::write(const char* buf, size_t size) { ssize_t n = ::write(handle_, buf, size); if (n < 0) { RAISE_ERRNO(errno); } return n; } } // namespace xzero <commit_msg>FileOutputStream: pass reasonable mode mask to open()<commit_after>// This file is part of the "libxzero" project // (c) 2009-2015 Christian Parpart <https://github.com/christianparpart> // (c) 2014-2015 Paul Asmuth <https://github.com/paulasmuth> // // libxzero is free software: you can redistribute it and/or modify it under // the terms of the GNU Affero General Public License v3.0. // 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 <xzero/io/FileOutputStream.h> #include <xzero/RuntimeError.h> #include <xzero/Buffer.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> namespace xzero { FileOutputStream::FileOutputStream(const std::string& path) : handle_(::open(path.c_str(), O_WRONLY | O_CREAT, 0666)), closeOnDestroy_(true) { if (handle_ < 0) { RAISE_ERRNO(errno); } } FileOutputStream::~FileOutputStream() { if (closeOnDestroy_) { ::close(handle_); } } int FileOutputStream::write(const char* buf, size_t size) { ssize_t n = ::write(handle_, buf, size); if (n < 0) { RAISE_ERRNO(errno); } return n; } } // namespace xzero <|endoftext|>
<commit_before>#include <xzero/testing.h> #include <xzero/BufferUtil.h> #include <xzero/raft/Generator.h> using namespace xzero; using namespace xzero::raft; TEST(raft_Generator, VoteRequest) { Buffer out; raft::Generator g(BufferUtil::writer(&out)); g.generateVoteRequest(VoteRequest{ .term = 0x11, .candidateId = 0x22, .lastLogIndex = 0x33, .lastLogTerm = 0x44 }); //logf("VoteRequest: $0", BufferUtil::hexPrint(&out)); EXPECT_EQ("\x01\x11\x22\x33\x44", out); } TEST(raft_Generator, VoteResponse) { Buffer out; raft::Generator g(BufferUtil::writer(&out)); g.generateVoteResponse(VoteResponse{ .term = 0x11, .voteGranted = true }); //logf("VoteResponse: $0", BufferUtil::hexPrint(&out)); EXPECT_EQ("\x02\x11\x01", out); } TEST(raft_Generator, AppendEntriesRequest) { Buffer out; raft::Generator g(BufferUtil::writer(&out)); g.generateAppendEntriesRequest(AppendEntriesRequest{ .term = 0x11, .leaderId = 0x12, .prevLogIndex = 0x13, .prevLogTerm = 0x14, .leaderCommit = 0x15, .entries = { LogEntry{0x11, Command{1, 2, 3, 4}}, LogEntry{0x11, Command{5, 6, 7, 8}} }}); logf("AppendEntriesRequest: <$0>", BufferUtil::hexPrint(&out)); //EXPECT_EQ("\x02\x11\x01", out); } TEST(raft_Generator, AppendEntriesResponse) { } TEST(raft_Generator, InstallSnapshotRequest) { } TEST(raft_Generator, InstallSnapshotResponse) { } <commit_msg>[xzero] raft: finishes unit tests for Generator impl<commit_after>#include <xzero/testing.h> #include <xzero/BufferUtil.h> #include <xzero/raft/Generator.h> using namespace xzero; using namespace xzero::raft; TEST(raft_Generator, VoteRequest) { Buffer out; raft::Generator g(BufferUtil::writer(&out)); g.generateVoteRequest(VoteRequest{ .term = 0x11, .candidateId = 0x22, .lastLogIndex = 0x33, .lastLogTerm = 0x44 }); EXPECT_EQ("\x01\x11\x22\x33\x44", out); } TEST(raft_Generator, VoteResponse) { Buffer out; raft::Generator g(BufferUtil::writer(&out)); g.generateVoteResponse(VoteResponse{ .term = 0x11, .voteGranted = true }); EXPECT_EQ("\x02\x11\x01", out); } TEST(raft_Generator, AppendEntriesRequest) { Buffer out; raft::Generator g(BufferUtil::writer(&out)); g.generateAppendEntriesRequest(AppendEntriesRequest{ .term = 0x11, .leaderId = 0x12, .prevLogIndex = 0x13, .prevLogTerm = 0x14, .leaderCommit = 0x15, .entries = { LogEntry{0x11, Command{1, 2, 3, 4}}, LogEntry{0x11, Command{5, 6, 7, 8}} }}); EXPECT_EQ("\x03\x11\x12\x13\x14\x15\x02\x11\x01\x04\x01\x02\x03\x04\x11\x01\x04\x05\x06\x07\x08", out); } TEST(raft_Generator, AppendEntriesResponse) { Buffer out; raft::Generator g(BufferUtil::writer(&out)); g.generateAppendEntriesResponse(AppendEntriesResponse{ .term = 2, .success = true }); EXPECT_EQ("\x04\x02\x01", out); } TEST(raft_Generator, InstallSnapshotRequest) { Buffer out; raft::Generator g(BufferUtil::writer(&out)); g.generateInstallSnapshotRequest(InstallSnapshotRequest{ .term = 1, .leaderId = 2, .lastIncludedIndex = 3, .lastIncludedTerm = 4, .offset = 0, .data = {0x42, 0x13, 0x37}, .done = true }); EXPECT_EQ("\x05\x01\x02\x03\x04\x00\x03\x42\x13\x37\x01", out); } TEST(raft_Generator, InstallSnapshotResponse) { Buffer out; raft::Generator g(BufferUtil::writer(&out)); g.generateInstallSnapshotResponse(InstallSnapshotResponse{ .term = 1 }); EXPECT_EQ("\x06\x01", out); } <|endoftext|>
<commit_before>// Regression test for // http://code.google.com/p/address-sanitizer/issues/detail?id=19 // Bug description: // 1. application dlopens foo.so // 2. asan registers all globals from foo.so // 3. application dlcloses foo.so // 4. application mmaps some memory to the location where foo.so was before // 5. application starts using this mmaped memory, but asan still thinks there // are globals. // 6. BOOM // This sublte test assumes that after a foo.so is dlclose-d // we can mmap the region of memory that has been occupied by the library. // It works on i368/x86_64 Linux, but not necessary anywhere else. // REQUIRES: x86_64-supported-target,i386-supported-target // RUN: %clangxx_asan -O0 -DSHARED_LIB %s -fPIC -shared -o %t-so.so // RUN: %clangxx_asan -O0 %s %libdl -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O1 -DSHARED_LIB %s -fPIC -shared -o %t-so.so // RUN: %clangxx_asan -O1 %s %libdl -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O2 -DSHARED_LIB %s -fPIC -shared -o %t-so.so // RUN: %clangxx_asan -O2 %s %libdl -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O3 -DSHARED_LIB %s -fPIC -shared -o %t-so.so // RUN: %clangxx_asan -O3 %s %libdl -o %t && %run %t 2>&1 | FileCheck %s #if !defined(SHARED_LIB) #include <assert.h> #include <dlfcn.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <unistd.h> #include <string> using std::string; typedef int *(fun_t)(); int main(int argc, char *argv[]) { string path = string(argv[0]) + "-so.so"; size_t PageSize = sysconf(_SC_PAGESIZE); printf("opening %s ... \n", path.c_str()); void *lib = dlopen(path.c_str(), RTLD_NOW); if (!lib) { printf("error in dlopen(): %s\n", dlerror()); return 1; } fun_t *get = (fun_t*)dlsym(lib, "get_address_of_static_var"); if (!get) { printf("failed dlsym\n"); return 1; } int *addr = get(); assert(((size_t)addr % 32) == 0); // should be 32-byte aligned. printf("addr: %p\n", addr); addr[0] = 1; // make sure we can write there. // Now dlclose the shared library. printf("attempting to dlclose\n"); if (dlclose(lib)) { printf("failed to dlclose\n"); return 1; } // Now, the page where 'addr' is unmapped. Map it. size_t page_beg = ((size_t)addr) & ~(PageSize - 1); void *res = mmap((void*)(page_beg), PageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE, -1, 0); if (res == (char*)-1L) { printf("failed to mmap\n"); return 1; } addr[1] = 2; // BOOM (if the bug is not fixed). printf("PASS\n"); // CHECK: PASS return 0; } #else // SHARED_LIB #include <stdio.h> static int pad1; static int static_var; static int pad2; extern "C" int *get_address_of_static_var() { return &static_var; } __attribute__((constructor)) void at_dlopen() { printf("%s: I am being dlopened\n", __FILE__); } __attribute__((destructor)) void at_dlclose() { printf("%s: I am being dlclosed\n", __FILE__); } #endif // SHARED_LIB <commit_msg>[Asan] Fix the dlclose-test.cc unit test to build on FreeBSD 11 Differential Revision: http://reviews.llvm.org/D7586<commit_after>// Regression test for // http://code.google.com/p/address-sanitizer/issues/detail?id=19 // Bug description: // 1. application dlopens foo.so // 2. asan registers all globals from foo.so // 3. application dlcloses foo.so // 4. application mmaps some memory to the location where foo.so was before // 5. application starts using this mmaped memory, but asan still thinks there // are globals. // 6. BOOM // This sublte test assumes that after a foo.so is dlclose-d // we can mmap the region of memory that has been occupied by the library. // It works on i368/x86_64 Linux, but not necessary anywhere else. // REQUIRES: x86_64-supported-target,i386-supported-target // RUN: %clangxx_asan -O0 -DSHARED_LIB %s -fPIC -shared -o %t-so.so // RUN: %clangxx_asan -O0 %s %libdl -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O1 -DSHARED_LIB %s -fPIC -shared -o %t-so.so // RUN: %clangxx_asan -O1 %s %libdl -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O2 -DSHARED_LIB %s -fPIC -shared -o %t-so.so // RUN: %clangxx_asan -O2 %s %libdl -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O3 -DSHARED_LIB %s -fPIC -shared -o %t-so.so // RUN: %clangxx_asan -O3 %s %libdl -o %t && %run %t 2>&1 | FileCheck %s #if !defined(SHARED_LIB) #include <assert.h> #include <dlfcn.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <unistd.h> #include <string> #if defined(__FreeBSD__) // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before // that, it was never implemented. So just define it to zero. #undef MAP_NORESERVE #define MAP_NORESERVE 0 #endif using std::string; typedef int *(fun_t)(); int main(int argc, char *argv[]) { string path = string(argv[0]) + "-so.so"; size_t PageSize = sysconf(_SC_PAGESIZE); printf("opening %s ... \n", path.c_str()); void *lib = dlopen(path.c_str(), RTLD_NOW); if (!lib) { printf("error in dlopen(): %s\n", dlerror()); return 1; } fun_t *get = (fun_t*)dlsym(lib, "get_address_of_static_var"); if (!get) { printf("failed dlsym\n"); return 1; } int *addr = get(); assert(((size_t)addr % 32) == 0); // should be 32-byte aligned. printf("addr: %p\n", addr); addr[0] = 1; // make sure we can write there. // Now dlclose the shared library. printf("attempting to dlclose\n"); if (dlclose(lib)) { printf("failed to dlclose\n"); return 1; } // Now, the page where 'addr' is unmapped. Map it. size_t page_beg = ((size_t)addr) & ~(PageSize - 1); void *res = mmap((void*)(page_beg), PageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE, -1, 0); if (res == (char*)-1L) { printf("failed to mmap\n"); return 1; } addr[1] = 2; // BOOM (if the bug is not fixed). printf("PASS\n"); // CHECK: PASS return 0; } #else // SHARED_LIB #include <stdio.h> static int pad1; static int static_var; static int pad2; extern "C" int *get_address_of_static_var() { return &static_var; } __attribute__((constructor)) void at_dlopen() { printf("%s: I am being dlopened\n", __FILE__); } __attribute__((destructor)) void at_dlclose() { printf("%s: I am being dlclosed\n", __FILE__); } #endif // SHARED_LIB <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/inspector/PromiseTracker.h" #include "bindings/core/v8/ScopedPersistent.h" #include "bindings/core/v8/ScriptCallStackFactory.h" #include "bindings/core/v8/ScriptState.h" #include "wtf/PassOwnPtr.h" #include "wtf/WeakPtr.h" using blink::TypeBuilder::Array; using blink::TypeBuilder::Console::CallFrame; using blink::TypeBuilder::Debugger::PromiseDetails; namespace blink { class PromiseTracker::PromiseData FINAL : public RefCountedWillBeGarbageCollectedFinalized<PromiseData> { public: static PassRefPtrWillBeRawPtr<PromiseData> create(v8::Isolate* isolate, int promiseHash, int promiseId, v8::Handle<v8::Object> promise) { return adoptRefWillBeNoop(new PromiseData(isolate, promiseHash, promiseId, promise)); } int promiseHash() const { return m_promiseHash; } ScopedPersistent<v8::Object>& promise() { return m_promise; } #if !ENABLE(OILPAN) WeakPtr<PromiseData> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(); } #endif void trace(Visitor* visitor) { visitor->trace(m_callStack); } private: friend class PromiseTracker; PromiseData(v8::Isolate* isolate, int promiseHash, int promiseId, v8::Handle<v8::Object> promise) : m_promiseHash(promiseHash) , m_promiseId(promiseId) , m_promise(isolate, promise) , m_parentPromiseId(0) , m_status(0) #if !ENABLE(OILPAN) , m_weakPtrFactory(this) #endif { } int m_promiseHash; int m_promiseId; ScopedPersistent<v8::Object> m_promise; int m_parentPromiseId; int m_status; RefPtrWillBeMember<ScriptCallStack> m_callStack; ScopedPersistent<v8::Object> m_parentPromise; #if !ENABLE(OILPAN) WeakPtrFactory<PromiseData> m_weakPtrFactory; #endif }; static int indexOf(PromiseTracker::PromiseDataVector* vector, const ScopedPersistent<v8::Object>& promise) { for (size_t index = 0; index < vector->size(); ++index) { if (vector->at(index)->promise() == promise) return index; } return -1; } namespace { class PromiseDataWrapper FINAL : public NoBaseWillBeGarbageCollected<PromiseDataWrapper> { public: static PassOwnPtrWillBeRawPtr<PromiseDataWrapper> create(PromiseTracker::PromiseData* data, PromiseTracker* tracker) { #if ENABLE(OILPAN) return new PromiseDataWrapper(data, tracker); #else return adoptPtr(new PromiseDataWrapper(data->createWeakPtr(), tracker)); #endif } #if ENABLE(OILPAN) static void didRemovePromise(const v8::WeakCallbackData<v8::Object, Persistent<PromiseDataWrapper> >& data) #else static void didRemovePromise(const v8::WeakCallbackData<v8::Object, PromiseDataWrapper>& data) #endif { #if ENABLE(OILPAN) OwnPtr<Persistent<PromiseDataWrapper> > persistentWrapper = adoptPtr(data.GetParameter()); RawPtr<PromiseDataWrapper> wrapper = *persistentWrapper; #else OwnPtr<PromiseDataWrapper> wrapper = adoptPtr(data.GetParameter()); #endif WeakPtrWillBeRawPtr<PromiseTracker::PromiseData> promiseData = wrapper->m_data; if (!promiseData || !wrapper->m_tracker) return; PromiseTracker::PromiseDataMap& map = wrapper->m_tracker->promiseDataMap(); int promiseHash = promiseData->promiseHash(); PromiseTracker::PromiseDataVector* vector = &map.find(promiseHash)->value; int index = indexOf(vector, promiseData->promise()); ASSERT(index >= 0); vector->remove(index); if (vector->isEmpty()) map.remove(promiseHash); } void trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_data); visitor->trace(m_tracker); #endif } private: PromiseDataWrapper(WeakPtrWillBeRawPtr<PromiseTracker::PromiseData> data, PromiseTracker* tracker) : m_data(data) , m_tracker(tracker) { } WeakPtrWillBeWeakMember<PromiseTracker::PromiseData> m_data; RawPtrWillBeWeakMember<PromiseTracker> m_tracker; }; } PromiseTracker::PromiseTracker() : m_circularSequentialId(0) , m_isEnabled(false) { } DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(PromiseTracker); void PromiseTracker::trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_promiseDataMap); #endif } void PromiseTracker::setEnabled(bool enabled) { m_isEnabled = enabled; if (!enabled) clear(); } void PromiseTracker::clear() { m_promiseDataMap.clear(); } int PromiseTracker::circularSequentialId() { ++m_circularSequentialId; if (m_circularSequentialId <= 0) m_circularSequentialId = 1; return m_circularSequentialId; } PassRefPtrWillBeRawPtr<PromiseTracker::PromiseData> PromiseTracker::createPromiseDataIfNeeded(v8::Isolate* isolate, v8::Handle<v8::Object> promise) { int promiseHash = promise->GetIdentityHash(); RawPtr<PromiseDataVector> vector = nullptr; PromiseDataMap::iterator it = m_promiseDataMap.find(promiseHash); if (it != m_promiseDataMap.end()) vector = &it->value; else vector = &m_promiseDataMap.add(promiseHash, PromiseDataVector()).storedValue->value; int index = indexOf(vector, ScopedPersistent<v8::Object>(isolate, promise)); if (index != -1) return vector->at(index); // FIXME: Consider using the ScriptState's DOMWrapperWorld instead // to handle the lifetime of PromiseDataWrapper, avoiding all this // manual labor to achieve the same, with and without Oilpan. RefPtrWillBeRawPtr<PromiseData> data = PromiseData::create(isolate, promiseHash, circularSequentialId(), promise); OwnPtrWillBeRawPtr<PromiseDataWrapper> dataWrapper = PromiseDataWrapper::create(data.get(), this); #if ENABLE(OILPAN) OwnPtr<Persistent<PromiseDataWrapper> > wrapper = adoptPtr(new Persistent<PromiseDataWrapper>(dataWrapper)); #else OwnPtr<PromiseDataWrapper> wrapper = dataWrapper.release(); #endif data->m_promise.setWeak(wrapper.leakPtr(), &PromiseDataWrapper::didRemovePromise); vector->append(data); return data.release(); } void PromiseTracker::didReceiveV8PromiseEvent(ScriptState* scriptState, v8::Handle<v8::Object> promise, v8::Handle<v8::Value> parentPromise, int status) { ASSERT(isEnabled()); v8::Isolate* isolate = scriptState->isolate(); RefPtrWillBeRawPtr<PromiseData> data = createPromiseDataIfNeeded(isolate, promise); if (!parentPromise.IsEmpty() && parentPromise->IsObject()) { v8::Handle<v8::Object> handle = parentPromise->ToObject(); RefPtrWillBeRawPtr<PromiseData> parentData = createPromiseDataIfNeeded(isolate, handle); data->m_parentPromiseId = parentData->m_promiseId; data->m_parentPromise.set(isolate, handle); } else { data->m_status = status; if (!status && !data->m_callStack) { v8::Handle<v8::StackTrace> stackTrace(v8::StackTrace::CurrentStackTrace(isolate, 1)); RefPtrWillBeRawPtr<ScriptCallStack> stack = createScriptCallStack(stackTrace, 1, isolate); if (stack->size()) data->m_callStack = stack; } } } PassRefPtr<Array<PromiseDetails> > PromiseTracker::promises() { ASSERT(isEnabled()); RefPtr<Array<PromiseDetails> > result = Array<PromiseDetails>::create(); for (PromiseDataMap::iterator it = m_promiseDataMap.begin(); it != m_promiseDataMap.end(); ++it) { PromiseDataVector* vector = &it->value; for (size_t index = 0; index < vector->size(); ++index) { RefPtrWillBeRawPtr<PromiseData> data = vector->at(index); PromiseDetails::Status::Enum status; if (!data->m_status) status = PromiseDetails::Status::Pending; else if (data->m_status == 1) status = PromiseDetails::Status::Resolved; else status = PromiseDetails::Status::Rejected; RefPtr<PromiseDetails> promiseDetails = PromiseDetails::create() .setId(data->m_promiseId) .setStatus(status); if (data->m_parentPromiseId) promiseDetails->setParentId(data->m_parentPromiseId); if (data->m_callStack) promiseDetails->setCallFrame(data->m_callStack->at(0).buildInspectorObject()); result->addItem(promiseDetails); } } return result.release(); } } // namespace blink <commit_msg>Oilpan: handle delayed removal of PromiseTracker promises.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/inspector/PromiseTracker.h" #include "bindings/core/v8/ScopedPersistent.h" #include "bindings/core/v8/ScriptCallStackFactory.h" #include "bindings/core/v8/ScriptState.h" #include "wtf/PassOwnPtr.h" #include "wtf/WeakPtr.h" using blink::TypeBuilder::Array; using blink::TypeBuilder::Console::CallFrame; using blink::TypeBuilder::Debugger::PromiseDetails; namespace blink { class PromiseTracker::PromiseData FINAL : public RefCountedWillBeGarbageCollectedFinalized<PromiseData> { public: static PassRefPtrWillBeRawPtr<PromiseData> create(v8::Isolate* isolate, int promiseHash, int promiseId, v8::Handle<v8::Object> promise) { return adoptRefWillBeNoop(new PromiseData(isolate, promiseHash, promiseId, promise)); } int promiseHash() const { return m_promiseHash; } ScopedPersistent<v8::Object>& promise() { return m_promise; } #if ENABLE(OILPAN) void dispose() { m_promise.clear(); m_parentPromise.clear(); } #else WeakPtr<PromiseData> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(); } #endif void trace(Visitor* visitor) { visitor->trace(m_callStack); } private: friend class PromiseTracker; PromiseData(v8::Isolate* isolate, int promiseHash, int promiseId, v8::Handle<v8::Object> promise) : m_promiseHash(promiseHash) , m_promiseId(promiseId) , m_promise(isolate, promise) , m_parentPromiseId(0) , m_status(0) #if !ENABLE(OILPAN) , m_weakPtrFactory(this) #endif { } int m_promiseHash; int m_promiseId; ScopedPersistent<v8::Object> m_promise; int m_parentPromiseId; int m_status; RefPtrWillBeMember<ScriptCallStack> m_callStack; ScopedPersistent<v8::Object> m_parentPromise; #if !ENABLE(OILPAN) WeakPtrFactory<PromiseData> m_weakPtrFactory; #endif }; static int indexOf(PromiseTracker::PromiseDataVector* vector, const ScopedPersistent<v8::Object>& promise) { for (size_t index = 0; index < vector->size(); ++index) { if (vector->at(index)->promise() == promise) return index; } return -1; } namespace { class PromiseDataWrapper FINAL : public NoBaseWillBeGarbageCollected<PromiseDataWrapper> { public: static PassOwnPtrWillBeRawPtr<PromiseDataWrapper> create(PromiseTracker::PromiseData* data, PromiseTracker* tracker) { #if ENABLE(OILPAN) return new PromiseDataWrapper(data, tracker); #else return adoptPtr(new PromiseDataWrapper(data->createWeakPtr(), tracker)); #endif } #if ENABLE(OILPAN) static void didRemovePromise(const v8::WeakCallbackData<v8::Object, Persistent<PromiseDataWrapper> >& data) #else static void didRemovePromise(const v8::WeakCallbackData<v8::Object, PromiseDataWrapper>& data) #endif { #if ENABLE(OILPAN) OwnPtr<Persistent<PromiseDataWrapper> > persistentWrapper = adoptPtr(data.GetParameter()); RawPtr<PromiseDataWrapper> wrapper = *persistentWrapper; #else OwnPtr<PromiseDataWrapper> wrapper = adoptPtr(data.GetParameter()); #endif WeakPtrWillBeRawPtr<PromiseTracker::PromiseData> promiseData = wrapper->m_data; if (!promiseData || !wrapper->m_tracker) return; #if ENABLE(OILPAN) // Oilpan: let go of ScopedPersistent<>s right here (and not wait until the // PromiseDataWrapper is GCed later.) The v8 weak callback handling expects // to see the callback data upon return. promiseData->dispose(); #endif PromiseTracker::PromiseDataMap& map = wrapper->m_tracker->promiseDataMap(); int promiseHash = promiseData->promiseHash(); PromiseTracker::PromiseDataMap::iterator it = map.find(promiseHash); // The PromiseTracker may have been disabled (and, possibly, re-enabled later), // leaving the promiseHash as unmapped. if (it == map.end()) return; PromiseTracker::PromiseDataVector* vector = &it->value; int index = indexOf(vector, promiseData->promise()); ASSERT(index >= 0); vector->remove(index); if (vector->isEmpty()) map.remove(promiseHash); } void trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_data); visitor->trace(m_tracker); #endif } private: PromiseDataWrapper(WeakPtrWillBeRawPtr<PromiseTracker::PromiseData> data, PromiseTracker* tracker) : m_data(data) , m_tracker(tracker) { } WeakPtrWillBeWeakMember<PromiseTracker::PromiseData> m_data; RawPtrWillBeWeakMember<PromiseTracker> m_tracker; }; } PromiseTracker::PromiseTracker() : m_circularSequentialId(0) , m_isEnabled(false) { } DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(PromiseTracker); void PromiseTracker::trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_promiseDataMap); #endif } void PromiseTracker::setEnabled(bool enabled) { m_isEnabled = enabled; if (!enabled) clear(); } void PromiseTracker::clear() { m_promiseDataMap.clear(); } int PromiseTracker::circularSequentialId() { ++m_circularSequentialId; if (m_circularSequentialId <= 0) m_circularSequentialId = 1; return m_circularSequentialId; } PassRefPtrWillBeRawPtr<PromiseTracker::PromiseData> PromiseTracker::createPromiseDataIfNeeded(v8::Isolate* isolate, v8::Handle<v8::Object> promise) { int promiseHash = promise->GetIdentityHash(); RawPtr<PromiseDataVector> vector = nullptr; PromiseDataMap::iterator it = m_promiseDataMap.find(promiseHash); if (it != m_promiseDataMap.end()) vector = &it->value; else vector = &m_promiseDataMap.add(promiseHash, PromiseDataVector()).storedValue->value; int index = indexOf(vector, ScopedPersistent<v8::Object>(isolate, promise)); if (index != -1) return vector->at(index); // FIXME: Consider using the ScriptState's DOMWrapperWorld instead // to handle the lifetime of PromiseDataWrapper, avoiding all this // manual labor to achieve the same, with and without Oilpan. RefPtrWillBeRawPtr<PromiseData> data = PromiseData::create(isolate, promiseHash, circularSequentialId(), promise); OwnPtrWillBeRawPtr<PromiseDataWrapper> dataWrapper = PromiseDataWrapper::create(data.get(), this); #if ENABLE(OILPAN) OwnPtr<Persistent<PromiseDataWrapper> > wrapper = adoptPtr(new Persistent<PromiseDataWrapper>(dataWrapper)); #else OwnPtr<PromiseDataWrapper> wrapper = dataWrapper.release(); #endif data->m_promise.setWeak(wrapper.leakPtr(), &PromiseDataWrapper::didRemovePromise); vector->append(data); return data.release(); } void PromiseTracker::didReceiveV8PromiseEvent(ScriptState* scriptState, v8::Handle<v8::Object> promise, v8::Handle<v8::Value> parentPromise, int status) { ASSERT(isEnabled()); v8::Isolate* isolate = scriptState->isolate(); RefPtrWillBeRawPtr<PromiseData> data = createPromiseDataIfNeeded(isolate, promise); if (!parentPromise.IsEmpty() && parentPromise->IsObject()) { v8::Handle<v8::Object> handle = parentPromise->ToObject(); RefPtrWillBeRawPtr<PromiseData> parentData = createPromiseDataIfNeeded(isolate, handle); data->m_parentPromiseId = parentData->m_promiseId; data->m_parentPromise.set(isolate, handle); } else { data->m_status = status; if (!status && !data->m_callStack) { v8::Handle<v8::StackTrace> stackTrace(v8::StackTrace::CurrentStackTrace(isolate, 1)); RefPtrWillBeRawPtr<ScriptCallStack> stack = createScriptCallStack(stackTrace, 1, isolate); if (stack->size()) data->m_callStack = stack; } } } PassRefPtr<Array<PromiseDetails> > PromiseTracker::promises() { ASSERT(isEnabled()); RefPtr<Array<PromiseDetails> > result = Array<PromiseDetails>::create(); for (PromiseDataMap::iterator it = m_promiseDataMap.begin(); it != m_promiseDataMap.end(); ++it) { PromiseDataVector* vector = &it->value; for (size_t index = 0; index < vector->size(); ++index) { RefPtrWillBeRawPtr<PromiseData> data = vector->at(index); PromiseDetails::Status::Enum status; if (!data->m_status) status = PromiseDetails::Status::Pending; else if (data->m_status == 1) status = PromiseDetails::Status::Resolved; else status = PromiseDetails::Status::Rejected; RefPtr<PromiseDetails> promiseDetails = PromiseDetails::create() .setId(data->m_promiseId) .setStatus(status); if (data->m_parentPromiseId) promiseDetails->setParentId(data->m_parentPromiseId); if (data->m_callStack) promiseDetails->setCallFrame(data->m_callStack->at(0).buildInspectorObject()); result->addItem(promiseDetails); } } return result.release(); } } // namespace blink <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkExtractImageTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include "itkImage.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "itkExtractImageFilter.h" #include "itkFileOutputWindow.h" #include "itkStreamingImageFilter.h" int itkExtractImageTest(int, char* [] ) { itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); fow->SetInstance(fow); int nextVal; // typedefs to simplify the syntax typedef itk::Image<short, 2> SimpleImage; SimpleImage::Pointer simpleImage = SimpleImage::New(); std::cout << "Simple image spacing: " << simpleImage->GetSpacing()[0] << ", " << simpleImage->GetSpacing()[1] << std::endl; // typedefs to simplify the syntax typedef itk::Image<short, 2> ShortImage; typedef itk::Image<short, 1> LineImage; // Test the creation of an image with native type ShortImage::Pointer if2 = ShortImage::New(); // fill in an image ShortImage::IndexType index = {{0, 0}}; ShortImage::SizeType size = {{8, 12}}; ShortImage::RegionType region; int row, column; region.SetSize( size ); region.SetIndex( index ); if2->SetLargestPossibleRegion( region ); if2->SetBufferedRegion( region ); if2->Allocate(); DirectionType directions; directions.SetIdentity(); directions[0][0] = 0.0; directions[1][0] = 1.0; directions[2][0] = 0.0; directions[0][1] = 1.0; directions[1][1] = 0.0; directions[2][1] = 0.0; if2->SetDirection (directions); itk::ImageRegionIterator<ShortImage> iterator(if2, region); short i=0; for (; !iterator.IsAtEnd(); ++iterator, ++i) { iterator.Set( i ); } std::cout << "Input Image: " << if2 << std::endl; // Create a filter itk::ExtractImageFilter< ShortImage, ShortImage >::Pointer extract; extract = itk::ExtractImageFilter< ShortImage, ShortImage >::New(); extract->SetInput( if2 ); // fill in an image ShortImage::IndexType extractIndex = {{0, 0}}; ShortImage::SizeType extractSize = {{8, 12}}; ShortImage::RegionType extractRegion; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); extract->UpdateLargestPossibleRegion(); std::cout << extract << std::endl; std::cout << "Input spacing: " << if2->GetSpacing()[0] << ", " << if2->GetSpacing()[1] << std::endl; std::cout << "Output spacing: " << extract->GetOutput()->GetSpacing()[0] << ", " << extract->GetOutput()->GetSpacing()[1] << std::endl; ShortImage::RegionType requestedRegion; bool passed; // CASE 1 extractIndex[0] = 1; extractIndex[1] = 2; extractSize[0] = 5; extractSize[1] = 6; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); extract->UpdateLargestPossibleRegion(); requestedRegion = extract->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn1(extract->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { for (; !iteratorIn1.IsAtEnd(); ++iteratorIn1) { row = iteratorIn1.GetIndex()[0]; column = iteratorIn1.GetIndex()[1]; if ((row < 0) || (row>7) || (column < 0) || (column > 11)) { if ( iteratorIn1.Get() != 13 ) { passed = false; } } else { nextVal = 8*column+row; if (iteratorIn1.Get() != nextVal) { std::cout << "Error: (" << row << ", " << column << "), expected " << nextVal << " got " << iteratorIn1.Get() << std::endl; passed = false; } } } } if (passed) { std::cout << "ExtractImageFilter case 1 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 1 failed." << std::endl; return EXIT_FAILURE; } extract->GetOutput()->Print(std::cout); // CASE 2 extractIndex[0] = 1; extractIndex[1] = 1; extractSize[0] = 7; extractSize[1] = 11; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); // Create a stream itk::StreamingImageFilter< ShortImage, ShortImage >::Pointer stream; stream = itk::StreamingImageFilter< ShortImage, ShortImage >::New(); stream->SetInput( extract->GetOutput() ); stream->SetNumberOfStreamDivisions(2); ShortImage::RegionType setRegion = extract->GetExtractionRegion(); size = setRegion.GetSize(); index = setRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { stream->UpdateLargestPossibleRegion(); requestedRegion = stream->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn2(stream->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { for (; !iteratorIn2.IsAtEnd(); ++iteratorIn2) { row = iteratorIn2.GetIndex()[0]; column = iteratorIn2.GetIndex()[1]; if ((row < 0) || (row>7) || (column < 0) || (column > 11)) { if ( iteratorIn2.Get() != 13 ) { passed = false; } } else { nextVal = 8*column+row; if (iteratorIn2.Get() != nextVal) { std::cout << "Error: (" << row << ", " << column << "), expected " << nextVal << " got " << iteratorIn2.Get() << std::endl; passed = false; } } } } } // need to put in code to check whether the proper region was extracted. // if (passed) { std::cout << "ExtractImageFilter case 2 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 2 failed." << std::endl; return EXIT_FAILURE; } //Case 3: Try extracting a single row itk::ExtractImageFilter<ShortImage, LineImage>::Pointer lineExtract; lineExtract = itk::ExtractImageFilter<ShortImage, LineImage>::New(); lineExtract->SetInput( if2 ); extractIndex[0] = 2; extractIndex[1] = 0; extractSize[0] = 0; extractSize[1] = 3; extractRegion.SetIndex( extractIndex ); extractRegion.SetSize( extractSize ); lineExtract->SetExtractionRegion( extractRegion ); lineExtract->UpdateLargestPossibleRegion(); lineExtract->GetOutput()->Print(std::cout); std::cout << "After 1D extraction. " << std::endl; //test the dimension collapse LineImage::RegionType requestedLineRegion; requestedLineRegion = lineExtract->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<LineImage> iteratorLineIn(lineExtract->GetOutput(), requestedLineRegion); ShortImage::IndexType testIndex; for (; !iteratorLineIn.IsAtEnd(); ++iteratorLineIn) { LineImage::PixelType linePixelValue = iteratorLineIn.Get(); testIndex[0] = extractIndex[0]; testIndex[1] = iteratorLineIn.GetIndex()[0]; if (linePixelValue != if2->GetPixel(testIndex)) { passed = false; } } if (passed) { std::cout << "ExtractImageFilter case 3 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 3 failed." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>COMP: DirectionType is a trait from the ImageType. It was wrongly being used in isolation.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkExtractImageTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include "itkImage.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "itkExtractImageFilter.h" #include "itkFileOutputWindow.h" #include "itkStreamingImageFilter.h" int itkExtractImageTest(int, char* [] ) { itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); fow->SetInstance(fow); int nextVal; // typedefs to simplify the syntax typedef itk::Image<short, 2> SimpleImage; SimpleImage::Pointer simpleImage = SimpleImage::New(); std::cout << "Simple image spacing: " << simpleImage->GetSpacing()[0] << ", " << simpleImage->GetSpacing()[1] << std::endl; // typedefs to simplify the syntax typedef itk::Image<short, 2> ShortImage; typedef itk::Image<short, 1> LineImage; // Test the creation of an image with native type ShortImage::Pointer if2 = ShortImage::New(); // fill in an image ShortImage::IndexType index = {{0, 0}}; ShortImage::SizeType size = {{8, 12}}; ShortImage::RegionType region; int row, column; region.SetSize( size ); region.SetIndex( index ); if2->SetLargestPossibleRegion( region ); if2->SetBufferedRegion( region ); if2->Allocate(); ShortImage::DirectionType directions; directions.SetIdentity(); directions[0][0] = 0.0; directions[1][0] = 1.0; directions[2][0] = 0.0; directions[0][1] = 1.0; directions[1][1] = 0.0; directions[2][1] = 0.0; if2->SetDirection (directions); itk::ImageRegionIterator<ShortImage> iterator(if2, region); short i=0; for (; !iterator.IsAtEnd(); ++iterator, ++i) { iterator.Set( i ); } std::cout << "Input Image: " << if2 << std::endl; // Create a filter itk::ExtractImageFilter< ShortImage, ShortImage >::Pointer extract; extract = itk::ExtractImageFilter< ShortImage, ShortImage >::New(); extract->SetInput( if2 ); // fill in an image ShortImage::IndexType extractIndex = {{0, 0}}; ShortImage::SizeType extractSize = {{8, 12}}; ShortImage::RegionType extractRegion; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); extract->UpdateLargestPossibleRegion(); std::cout << extract << std::endl; std::cout << "Input spacing: " << if2->GetSpacing()[0] << ", " << if2->GetSpacing()[1] << std::endl; std::cout << "Output spacing: " << extract->GetOutput()->GetSpacing()[0] << ", " << extract->GetOutput()->GetSpacing()[1] << std::endl; ShortImage::RegionType requestedRegion; bool passed; // CASE 1 extractIndex[0] = 1; extractIndex[1] = 2; extractSize[0] = 5; extractSize[1] = 6; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); extract->UpdateLargestPossibleRegion(); requestedRegion = extract->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn1(extract->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { for (; !iteratorIn1.IsAtEnd(); ++iteratorIn1) { row = iteratorIn1.GetIndex()[0]; column = iteratorIn1.GetIndex()[1]; if ((row < 0) || (row>7) || (column < 0) || (column > 11)) { if ( iteratorIn1.Get() != 13 ) { passed = false; } } else { nextVal = 8*column+row; if (iteratorIn1.Get() != nextVal) { std::cout << "Error: (" << row << ", " << column << "), expected " << nextVal << " got " << iteratorIn1.Get() << std::endl; passed = false; } } } } if (passed) { std::cout << "ExtractImageFilter case 1 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 1 failed." << std::endl; return EXIT_FAILURE; } extract->GetOutput()->Print(std::cout); // CASE 2 extractIndex[0] = 1; extractIndex[1] = 1; extractSize[0] = 7; extractSize[1] = 11; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); // Create a stream itk::StreamingImageFilter< ShortImage, ShortImage >::Pointer stream; stream = itk::StreamingImageFilter< ShortImage, ShortImage >::New(); stream->SetInput( extract->GetOutput() ); stream->SetNumberOfStreamDivisions(2); ShortImage::RegionType setRegion = extract->GetExtractionRegion(); size = setRegion.GetSize(); index = setRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { stream->UpdateLargestPossibleRegion(); requestedRegion = stream->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn2(stream->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { for (; !iteratorIn2.IsAtEnd(); ++iteratorIn2) { row = iteratorIn2.GetIndex()[0]; column = iteratorIn2.GetIndex()[1]; if ((row < 0) || (row>7) || (column < 0) || (column > 11)) { if ( iteratorIn2.Get() != 13 ) { passed = false; } } else { nextVal = 8*column+row; if (iteratorIn2.Get() != nextVal) { std::cout << "Error: (" << row << ", " << column << "), expected " << nextVal << " got " << iteratorIn2.Get() << std::endl; passed = false; } } } } } // need to put in code to check whether the proper region was extracted. // if (passed) { std::cout << "ExtractImageFilter case 2 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 2 failed." << std::endl; return EXIT_FAILURE; } //Case 3: Try extracting a single row itk::ExtractImageFilter<ShortImage, LineImage>::Pointer lineExtract; lineExtract = itk::ExtractImageFilter<ShortImage, LineImage>::New(); lineExtract->SetInput( if2 ); extractIndex[0] = 2; extractIndex[1] = 0; extractSize[0] = 0; extractSize[1] = 3; extractRegion.SetIndex( extractIndex ); extractRegion.SetSize( extractSize ); lineExtract->SetExtractionRegion( extractRegion ); lineExtract->UpdateLargestPossibleRegion(); lineExtract->GetOutput()->Print(std::cout); std::cout << "After 1D extraction. " << std::endl; //test the dimension collapse LineImage::RegionType requestedLineRegion; requestedLineRegion = lineExtract->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<LineImage> iteratorLineIn(lineExtract->GetOutput(), requestedLineRegion); ShortImage::IndexType testIndex; for (; !iteratorLineIn.IsAtEnd(); ++iteratorLineIn) { LineImage::PixelType linePixelValue = iteratorLineIn.Get(); testIndex[0] = extractIndex[0]; testIndex[1] = iteratorLineIn.GetIndex()[0]; if (linePixelValue != if2->GetPixel(testIndex)) { passed = false; } } if (passed) { std::cout << "ExtractImageFilter case 3 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 3 failed." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* $Id$ */ # ifndef CPPAD_EXP_EPS_INCLUDED # define CPPAD_EXP_EPS_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-07 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin exp_eps$$ $spell cppad-%yyyymmdd% hpp Apx cpp const exp_eps bool $$ $section An Epsilon Accurate Exponential Approximation$$ $index exp_eps$$ $index example, algorithm$$ $index algorithm, example$$ $index exp, example$$ $head Syntax$$ $codei%# include "exp_eps.hpp"%$$ $pre $$ $icode%y% = exp_eps(%x%, %epsilon%)%$$ $head Purpose$$ This is a an example algorithm that is used to demonstrate how Algorithmic Differentiation works with loops and boolean decision variables (see $cref/exp_2/$$ for a simpler example). $head Mathematical Function$$ The exponential function can be defined by $latex \[ \exp (x) = 1 + x^1 / 1 ! + x^2 / 2 ! + \cdots \] $$ We define $latex k ( x, \varepsilon ) $$ as the smallest non-negative integer such that $latex \varepsilon \geq x^k / k !$$; i.e., $latex \[ k( x, \varepsilon ) = \min \{ k \in {\rm Z}_+ \; | \; \varepsilon \geq x^k / k ! \} \] $$ The mathematical form for our approximation of the exponential function is $latex \[ \begin{array}{rcl} {\rm exp\_eps} (x , \varepsilon ) & = & \left\{ \begin{array}{ll} \frac{1}{ {\rm exp\_eps} (-x , \varepsilon ) } & {\rm if} \; x < 0 \\ 1 + x^1 / 1 ! + \cdots + x^{k( x, \varepsilon)} / k( x, \varepsilon ) ! & {\rm otherwise} \end{array} \right. \end{array} \] $$ $head include$$ The include command in the syntax is relative to $codei% cppad-%yyyymmdd%/introduction/exp_apx %$$ where $codei%cppad-%yyyymmdd%$$ is the distribution directory created during the beginning steps of the $cref%installation%Install%$$ of CppAD. $head x$$ The argument $icode x$$ has prototype $codei% const %Type% &%x% %$$ (see $icode Type$$ below). It specifies the point at which to evaluate the approximation for the exponential function. $head epsilon$$ The argument $icode epsilon$$ has prototype $codei% const %Type% &%epsilon% %$$ It specifies the accuracy with which to approximate the exponential function value; i.e., it is the value of $latex \varepsilon$$ in the exponential function approximation defined above. $head y$$ The result $icode y$$ has prototype $codei% %Type% %y% %$$ It is the value of the exponential function approximation defined above. $head Type$$ If $icode u$$ and $italic v$$ are $italic Type$$ objects and $italic i$$ is an $code int$$: $table $bold Operation$$ $cnext $bold Result Type$$ $cnext $bold Description$$ $rnext $icode%Type%(%i%)%$$ $cnext $icode Type$$ $cnext object with value equal to $icode i$$ $rnext $icode%u% > %v%$$ $cnext $code bool$$ $cnext true, if $icode u$$ greater than $italic v$$, an false otherwise $rnext $icode%u% = %v%$$ $cnext $icode Type$$ $cnext new $icode u$$ (and result) is value of $italic v$$ $rnext $icode%u% * %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u * v$$ $rnext $icode%u% / %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u / v$$ $rnext $icode%u% + %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u + v$$ $rnext $codei%-%u%$$ $cnext $icode Type$$ $cnext result is value of $latex - u$$ $tend $children% introduction/exp_apx/exp_eps.omh% introduction/exp_apx/exp_eps_cppad.cpp %$$ $head Implementation$$ The file $cref/exp_eps.hpp/$$ contains a C++ implementation of this function. $head Test$$ The file $cref/exp_eps.cpp/$$ contains a test of this implementation. It returns true for success and false for failure. $head Exercises$$ $list number$$ Using the definition of $latex k( x, \varepsilon )$$ above, what is the value of $latex k(.5, 1)$$, $latex k(.5, .1)$$, and $latex k(.5, .01)$$ ? $lnext Suppose that we make the following call to $code exp_eps$$: $codep double x = 1.; double epsilon = .01; double y = exp_eps(x, epsilon); $$ What is the value assigned to $code k$$, $code temp$$, $code term$$, and $code sum$$ the first time through the $code while$$ loop in $cref/exp_eps.hpp/$$ ? $lnext Continuing the previous exercise, what is the value assigned to $code k$$, $code temp$$, $code term$$, and $code sum$$ the second time through the $code while$$ loop in $cref/exp_eps.hpp/$$ ? $lend $end ----------------------------------------------------------------------------- */ // BEGIN PROGRAM template <class Type> Type exp_eps(const Type &x, const Type &epsilon) { // abs_x = |x| Type abs_x = x; if( Type(0) > x ) abs_x = - x; // initialize int k = 0; // initial order Type term = 1.; // term = |x|^k / k ! Type sum = term; // initial sum while(term > epsilon) { k = k + 1; // order for next term Type temp = term * abs_x; // term = |x|^k / (k-1)! term = temp / Type(k); // term = |x|^k / k ! sum = sum + term; // sum = 1 + ... + |x|^k / k ! } // In the case where x is negative, use exp(x) = 1 / exp(-|x|) if( Type(0) > x ) sum = Type(1) / sum; return sum; } // END PROGRAM # endif <commit_msg>add missing requirement on template Type<commit_after>/* $Id$ */ # ifndef CPPAD_EXP_EPS_INCLUDED # define CPPAD_EXP_EPS_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-07 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin exp_eps$$ $spell cppad-%yyyymmdd% hpp Apx cpp const exp_eps bool $$ $section An Epsilon Accurate Exponential Approximation$$ $index exp_eps$$ $index example, algorithm$$ $index algorithm, example$$ $index exp, example$$ $head Syntax$$ $codei%# include "exp_eps.hpp"%$$ $pre $$ $icode%y% = exp_eps(%x%, %epsilon%)%$$ $head Purpose$$ This is a an example algorithm that is used to demonstrate how Algorithmic Differentiation works with loops and boolean decision variables (see $cref/exp_2/$$ for a simpler example). $head Mathematical Function$$ The exponential function can be defined by $latex \[ \exp (x) = 1 + x^1 / 1 ! + x^2 / 2 ! + \cdots \] $$ We define $latex k ( x, \varepsilon ) $$ as the smallest non-negative integer such that $latex \varepsilon \geq x^k / k !$$; i.e., $latex \[ k( x, \varepsilon ) = \min \{ k \in {\rm Z}_+ \; | \; \varepsilon \geq x^k / k ! \} \] $$ The mathematical form for our approximation of the exponential function is $latex \[ \begin{array}{rcl} {\rm exp\_eps} (x , \varepsilon ) & = & \left\{ \begin{array}{ll} \frac{1}{ {\rm exp\_eps} (-x , \varepsilon ) } & {\rm if} \; x < 0 \\ 1 + x^1 / 1 ! + \cdots + x^{k( x, \varepsilon)} / k( x, \varepsilon ) ! & {\rm otherwise} \end{array} \right. \end{array} \] $$ $head include$$ The include command in the syntax is relative to $codei% cppad-%yyyymmdd%/introduction/exp_apx %$$ where $codei%cppad-%yyyymmdd%$$ is the distribution directory created during the beginning steps of the $cref%installation%Install%$$ of CppAD. $head x$$ The argument $icode x$$ has prototype $codei% const %Type% &%x% %$$ (see $icode Type$$ below). It specifies the point at which to evaluate the approximation for the exponential function. $head epsilon$$ The argument $icode epsilon$$ has prototype $codei% const %Type% &%epsilon% %$$ It specifies the accuracy with which to approximate the exponential function value; i.e., it is the value of $latex \varepsilon$$ in the exponential function approximation defined above. $head y$$ The result $icode y$$ has prototype $codei% %Type% %y% %$$ It is the value of the exponential function approximation defined above. $head Type$$ If $icode u$$ and $italic v$$ are $italic Type$$ objects and $italic i$$ is an $code int$$: $table $bold Operation$$ $cnext $bold Result Type$$ $cnext $bold Description$$ $rnext $icode%Type%(%i%)%$$ $cnext $icode Type$$ $cnext object with value equal to $icode i$$ $rnext $icode%Type u %=% v%$$ $cnext $icode Type$$ $cnext construct $icode u$$ with value equal to $icode v$$ $rnext $icode%u% > %v%$$ $cnext $code bool$$ $cnext true, if $icode u$$ greater than $italic v$$, an false otherwise $rnext $icode%u% = %v%$$ $cnext $icode Type$$ $cnext new $icode u$$ (and result) is value of $italic v$$ $rnext $icode%u% * %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u * v$$ $rnext $icode%u% / %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u / v$$ $rnext $icode%u% + %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u + v$$ $rnext $codei%-%u%$$ $cnext $icode Type$$ $cnext result is value of $latex - u$$ $tend $children% introduction/exp_apx/exp_eps.omh% introduction/exp_apx/exp_eps_cppad.cpp %$$ $head Implementation$$ The file $cref/exp_eps.hpp/$$ contains a C++ implementation of this function. $head Test$$ The file $cref/exp_eps.cpp/$$ contains a test of this implementation. It returns true for success and false for failure. $head Exercises$$ $list number$$ Using the definition of $latex k( x, \varepsilon )$$ above, what is the value of $latex k(.5, 1)$$, $latex k(.5, .1)$$, and $latex k(.5, .01)$$ ? $lnext Suppose that we make the following call to $code exp_eps$$: $codep double x = 1.; double epsilon = .01; double y = exp_eps(x, epsilon); $$ What is the value assigned to $code k$$, $code temp$$, $code term$$, and $code sum$$ the first time through the $code while$$ loop in $cref/exp_eps.hpp/$$ ? $lnext Continuing the previous exercise, what is the value assigned to $code k$$, $code temp$$, $code term$$, and $code sum$$ the second time through the $code while$$ loop in $cref/exp_eps.hpp/$$ ? $lend $end ----------------------------------------------------------------------------- */ // BEGIN PROGRAM template <class Type> Type exp_eps(const Type &x, const Type &epsilon) { // abs_x = |x| Type abs_x = x; if( Type(0) > x ) abs_x = - x; // initialize int k = 0; // initial order Type term = 1.; // term = |x|^k / k ! Type sum = term; // initial sum while(term > epsilon) { k = k + 1; // order for next term Type temp = term * abs_x; // term = |x|^k / (k-1)! term = temp / Type(k); // term = |x|^k / k ! sum = sum + term; // sum = 1 + ... + |x|^k / k ! } // In the case where x is negative, use exp(x) = 1 / exp(-|x|) if( Type(0) > x ) sum = Type(1) / sum; return sum; } // END PROGRAM # endif <|endoftext|>
<commit_before> #include "CPipelineState.h" #include <ionWindow.h> #include <glad/glad.h> namespace ion { namespace Graphics { namespace GL { CPipelineState::CPipelineState(CWindow * Window) { this->Window = Window; this->PrimitiveType = GL_TRIANGLES; } CPipelineState::~CPipelineState() { } void CPipelineState::SetProgram(SharedPointer<IShaderProgram> inShaderProgram) { if (inShaderProgram) { ShaderProgram = std::dynamic_pointer_cast<CShaderProgram>(inShaderProgram); if (! ShaderProgram->Linked) { ShaderProgram->Link(); if (! ShaderProgram->Linked) { Log::Error("Failed to link shader prograg in PipelineState creation, unsetting shader."); ShaderProgram = nullptr; return; } } UnboundUniforms = KeySet(ShaderProgram->Uniforms); UnboundAttributes = KeySet(ShaderProgram->Attributes); UnboundAttributes.erase("gl_VertexID"); Loaded = false; } } void CPipelineState::SetVertexBuffer(uint const Index, SharedPointer<IVertexBuffer> inVertexBuffer) { if (Index >= VertexBuffers.size()) { VertexBuffers.resize(Index + 1); } VertexBuffers[Index] = std::dynamic_pointer_cast<CVertexBuffer>(inVertexBuffer); // Bound VBOs are not part of VAO state Loaded = false; } void CPipelineState::SetIndexBuffer(SharedPointer<IIndexBuffer> inIndexBuffer) { IndexBuffer = std::dynamic_pointer_cast<CIndexBuffer>(inIndexBuffer); Window->MakeContextCurrent(); SafeGLCall(glBindVertexArray, (VertexArrayHandle)); SafeGLCall(glBindBuffer, (GL_ELEMENT_ARRAY_BUFFER, IndexBuffer->Handle)); SafeGLCall(glBindVertexArray, (0)); } void CPipelineState::SetUniform(string const & Name, SharedPointer<IUniform> Uniform) { if (! ShaderProgram) { Log::Error("Cannot set uniforms or textures on a PipelineState with no specified shader program."); return; } if (Uniform) { if (UnboundUniforms.count(Name) == 1) { Uniforms[Name] = Uniform; UnboundUniforms.erase(Name); } else { Log::Warn("Attempting to set uniform or texture '%s' that is not required by shader, ignoring.", Name); } } else { if (Uniforms.erase(Name) == 1) { UnboundUniforms.insert(Name); } else { Log::Error("Attempting to remove uniform or texture '%s' that was never specified, ignoring.", Name); } } } void CPipelineState::SetTexture(string const & Name, SharedPointer<ITexture> Texture) { if (! ShaderProgram) { Log::Error("Cannot set uniforms or textures on a PipelineState with no specified shader program."); return; } if (Texture) { if (UnboundUniforms.count(Name) == 1) { Textures[Name] = Texture; UnboundUniforms.erase(Name); } else if (Textures.find(Name) != Textures.end()) { Textures[Name] = Texture; } else { Log::Warn("Attempting to set uniform or texture '%s' that is not required by shader, ignoring.", Name); } } else { if (Textures.erase(Name) == 1) { UnboundUniforms.insert(Name); } else { Log::Error("Attempting to remove uniform or texture '%s' that was never specified, ignoring.", Name); } } } void CPipelineState::SetPrimitiveType(EPrimitiveType const PrimitiveType) { switch (PrimitiveType) { default: case EPrimitiveType::Triangle: this->PrimitiveType = GL_TRIANGLES; break; case EPrimitiveType::Point: this->PrimitiveType = GL_POINTS; break; case EPrimitiveType::Line: this->PrimitiveType = GL_LINES; break; case EPrimitiveType::LineStrip: this->PrimitiveType = GL_LINE_STRIP; break; } } void CPipelineState::SetFeatureEnabled(EDrawFeature const Feature, bool const Enabled) { switch (Feature) { case EDrawFeature::Wireframe: DrawWireframe = Enabled; break; case EDrawFeature::CullFront: CullFront = Enabled; break; case EDrawFeature::CullBack: CullBack = Enabled; break; case EDrawFeature::DisableDepthTest: DisableDepthTest = Enabled; break; case EDrawFeature::DisableDepthWrite: DisableDepthWrite = Enabled; break; case EDrawFeature::PolygonOffset: PolygonOffset = Enabled; break; } } void CPipelineState::SetPolygonOffsetAmount(float const Amount) { PolygonOffsetAmount = Amount; } void CPipelineState::SetBlendMode(EBlendMode const BlendMode) { this->BlendMode = BlendMode; } void CPipelineState::OfferUniform(string const & Name, SharedPointer<IUniform> Uniform) { if (! ShaderProgram) { Log::Error("Cannot set uniforms or textures on a PipelineState with no specified shader program."); return; } if (! Uniform) { Log::Error("Invalid paramter to CPipelineState::OfferUniform: expected non-null Uniform"); return; } if (UnboundUniforms.count(Name) == 1) { Uniforms[Name] = Uniform; UnboundUniforms.erase(Name); } } void CPipelineState::OfferTexture(string const & Name, SharedPointer<ITexture> Texture) { if (! ShaderProgram) { Log::Error("Cannot set uniforms or textures on a PipelineState with no specified shader program."); return; } if (! Texture) { Log::Error("Invalid paramter to CPipelineState::OfferTexture: expected non-null Texture"); return; } if (UnboundUniforms.count(Name) == 1) { Textures[Name] = Texture; UnboundUniforms.erase(Name); } } void CPipelineState::IgnoreUniform(string const & Name) { UnboundUniforms.erase(Name); } set<string> CPipelineState::GetUnboundUniforms() const { return UnboundUniforms; } void CPipelineState::Load() { if (! ShaderProgram || VertexBuffers.empty() || ! IndexBuffer) { Log::Error("Attempting to load an invalid PipelineState"); return; } Window->MakeContextCurrent(); CheckedGLCall(glUseProgram(ShaderProgram->Handle)); CheckedGLCall(glBindVertexArray(VertexArrayHandle)); for (auto & VertexBuffer : VertexBuffers) { CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer->Handle)); ////////////////////////////// // Set up VBOs (attributes) // ////////////////////////////// // Calculate stride of VBO data size_t TotalStride = 0; for (auto & InputLayoutElement : VertexBuffer->InputLayout) { TotalStride += GetAttributeTypeSize(InputLayoutElement.Type) * InputLayoutElement.Components; } size_t CurrentOffset = 0; for (auto & InputLayoutElement : VertexBuffer->InputLayout) { pair<uint, uint> AttributeInfo; if (TryMapAccess(ShaderProgram->Attributes, InputLayoutElement.Name, AttributeInfo)) { uint const AttributeLocation = AttributeInfo.first; uint const AttributeType = AttributeInfo.second; // Validate Attribute Type (does the VBO layout match what the shader wants?) { bool IsAttributeTypeCorrect = false; string ShaderAttributeTypeString = "Unknown"; switch (AttributeType) { default: Log::Error("Unexpected type for attribute %s: %u", InputLayoutElement.Name, AttributeType); break; case GL_FLOAT: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Float && InputLayoutElement.Components == 1); ShaderAttributeTypeString = "GL_FLOAT"; break; case GL_FLOAT_VEC2: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Float && InputLayoutElement.Components == 2); ShaderAttributeTypeString = "GL_FLOAT_VEC2"; break; case GL_FLOAT_VEC3: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Float && InputLayoutElement.Components == 3); ShaderAttributeTypeString = "GL_FLOAT_VEC3"; break; case GL_FLOAT_VEC4: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Float && InputLayoutElement.Components == 4); ShaderAttributeTypeString = "GL_FLOAT_VEC4"; break; case GL_INT: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Int && InputLayoutElement.Components == 1); ShaderAttributeTypeString = "GL_INT"; break; case GL_INT_VEC2: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Int && InputLayoutElement.Components == 2); ShaderAttributeTypeString = "GL_INT_VEC2"; break; case GL_INT_VEC3: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Int && InputLayoutElement.Components == 3); ShaderAttributeTypeString = "GL_INT_VEC3"; break; case GL_INT_VEC4: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Int && InputLayoutElement.Components == 4); ShaderAttributeTypeString = "GL_INT_VEC4"; break; } if (! IsAttributeTypeCorrect) { Log::Error("Mistmatch for attribute type '%s': VBO supplied %d components of type %s but shader expected '%s'", InputLayoutElement.Name, InputLayoutElement.Components, GetAttributeTypeString(InputLayoutElement.Type), ShaderAttributeTypeString); } } CheckedGLCall(glEnableVertexAttribArray(AttributeLocation)); switch (AttributeType) { case GL_FLOAT: case GL_FLOAT_VEC2: case GL_FLOAT_VEC3: case GL_FLOAT_VEC4: CheckedGLCall(glVertexAttribPointer( AttributeLocation, InputLayoutElement.Components, GetAttributeTypeOpenGLEnum(InputLayoutElement.Type), GL_FALSE, (int) TotalStride, (void *) CurrentOffset)); break; case GL_INT: case GL_INT_VEC2: case GL_INT_VEC3: case GL_INT_VEC4: CheckedGLCall(glVertexAttribIPointer( AttributeLocation, InputLayoutElement.Components, GetAttributeTypeOpenGLEnum(InputLayoutElement.Type), (int) TotalStride, (void *) CurrentOffset)); break; } if (VertexBuffer->Instancing) { CheckedGLCall(glVertexAttribDivisor(AttributeLocation, 1)); } UnboundAttributes.erase(InputLayoutElement.Name); } CurrentOffset += GetAttributeTypeSize(InputLayoutElement.Type) * InputLayoutElement.Components; } CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, 0)); // Remember, VBOs are not part of VAO state (that's why we never leave them set in the VAO) } std::for_each(UnboundAttributes.begin(), UnboundAttributes.end(), [](string const & Attribuite) { Log::Error("Attribute expected by shader but not provided by VBO: %s", Attribuite); }); CheckedGLCall(glBindVertexArray(0)); CheckedGLCall(glUseProgram(0)); ///////////////////// // Set up Uniforms // ///////////////////// BoundUniforms.clear(); for (auto const & it : Uniforms) { uint Handle = 0; if (TryMapAccess(ShaderProgram->Uniforms, it.first, Handle)) { BoundUniforms[Handle] = it.second; } } for (auto const & it : Textures) { uint Handle = 0; if (TryMapAccess(ShaderProgram->Uniforms, it.first, Handle)) { BoundTextures[Handle] = it.second; } } std::for_each(UnboundUniforms.begin(), UnboundUniforms.end(), [](string const & Uniform) { Log::Error("Uniform expected by shader but not provided by PSO: %s", Uniform); }); Loaded = true; } } } } <commit_msg>[ionGraphicsGL] Fix some issues when changing the program of a pipelinestate after initial load<commit_after> #include "CPipelineState.h" #include <ionWindow.h> #include <glad/glad.h> namespace ion { namespace Graphics { namespace GL { CPipelineState::CPipelineState(CWindow * Window) { this->Window = Window; this->PrimitiveType = GL_TRIANGLES; } CPipelineState::~CPipelineState() { } void CPipelineState::SetProgram(SharedPointer<IShaderProgram> inShaderProgram) { if (inShaderProgram) { ShaderProgram = std::dynamic_pointer_cast<CShaderProgram>(inShaderProgram); if (! ShaderProgram->Linked) { ShaderProgram->Link(); if (! ShaderProgram->Linked) { Log::Error("Failed to link shader prograg in PipelineState creation, unsetting shader."); ShaderProgram = nullptr; return; } } Textures.clear(); Uniforms.clear(); UnboundUniforms = KeySet(ShaderProgram->Uniforms); UnboundAttributes = KeySet(ShaderProgram->Attributes); UnboundAttributes.erase("gl_VertexID"); Loaded = false; } } void CPipelineState::SetVertexBuffer(uint const Index, SharedPointer<IVertexBuffer> inVertexBuffer) { if (Index >= VertexBuffers.size()) { VertexBuffers.resize(Index + 1); } VertexBuffers[Index] = std::dynamic_pointer_cast<CVertexBuffer>(inVertexBuffer); // Bound VBOs are not part of VAO state Loaded = false; } void CPipelineState::SetIndexBuffer(SharedPointer<IIndexBuffer> inIndexBuffer) { IndexBuffer = std::dynamic_pointer_cast<CIndexBuffer>(inIndexBuffer); Window->MakeContextCurrent(); SafeGLCall(glBindVertexArray, (VertexArrayHandle)); SafeGLCall(glBindBuffer, (GL_ELEMENT_ARRAY_BUFFER, IndexBuffer->Handle)); SafeGLCall(glBindVertexArray, (0)); } void CPipelineState::SetUniform(string const & Name, SharedPointer<IUniform> Uniform) { if (! ShaderProgram) { Log::Error("Cannot set uniforms or textures on a PipelineState with no specified shader program."); return; } if (Uniform) { if (UnboundUniforms.count(Name) == 1) { Uniforms[Name] = Uniform; UnboundUniforms.erase(Name); } else { Log::Warn("Attempting to set uniform or texture '%s' that is not required by shader, ignoring.", Name); } } else { if (Uniforms.erase(Name) == 1) { UnboundUniforms.insert(Name); } else { Log::Error("Attempting to remove uniform or texture '%s' that was never specified, ignoring.", Name); } } } void CPipelineState::SetTexture(string const & Name, SharedPointer<ITexture> Texture) { if (! ShaderProgram) { Log::Error("Cannot set uniforms or textures on a PipelineState with no specified shader program."); return; } if (Texture) { if (UnboundUniforms.count(Name) == 1) { Textures[Name] = Texture; UnboundUniforms.erase(Name); } else if (Textures.find(Name) != Textures.end()) { Textures[Name] = Texture; } else { Log::Warn("Attempting to set uniform or texture '%s' that is not required by shader, ignoring.", Name); } } else { if (Textures.erase(Name) == 1) { UnboundUniforms.insert(Name); } else { Log::Error("Attempting to remove uniform or texture '%s' that was never specified, ignoring.", Name); } } } void CPipelineState::SetPrimitiveType(EPrimitiveType const PrimitiveType) { switch (PrimitiveType) { default: case EPrimitiveType::Triangle: this->PrimitiveType = GL_TRIANGLES; break; case EPrimitiveType::Point: this->PrimitiveType = GL_POINTS; break; case EPrimitiveType::Line: this->PrimitiveType = GL_LINES; break; case EPrimitiveType::LineStrip: this->PrimitiveType = GL_LINE_STRIP; break; } } void CPipelineState::SetFeatureEnabled(EDrawFeature const Feature, bool const Enabled) { switch (Feature) { case EDrawFeature::Wireframe: DrawWireframe = Enabled; break; case EDrawFeature::CullFront: CullFront = Enabled; break; case EDrawFeature::CullBack: CullBack = Enabled; break; case EDrawFeature::DisableDepthTest: DisableDepthTest = Enabled; break; case EDrawFeature::DisableDepthWrite: DisableDepthWrite = Enabled; break; case EDrawFeature::PolygonOffset: PolygonOffset = Enabled; break; } } void CPipelineState::SetPolygonOffsetAmount(float const Amount) { PolygonOffsetAmount = Amount; } void CPipelineState::SetBlendMode(EBlendMode const BlendMode) { this->BlendMode = BlendMode; } void CPipelineState::OfferUniform(string const & Name, SharedPointer<IUniform> Uniform) { if (! ShaderProgram) { Log::Error("Cannot set uniforms or textures on a PipelineState with no specified shader program."); return; } if (! Uniform) { Log::Error("Invalid paramter to CPipelineState::OfferUniform: expected non-null Uniform"); return; } if (UnboundUniforms.count(Name) == 1) { Uniforms[Name] = Uniform; UnboundUniforms.erase(Name); } } void CPipelineState::OfferTexture(string const & Name, SharedPointer<ITexture> Texture) { if (! ShaderProgram) { Log::Error("Cannot set uniforms or textures on a PipelineState with no specified shader program."); return; } if (! Texture) { Log::Error("Invalid paramter to CPipelineState::OfferTexture: expected non-null Texture"); return; } if (UnboundUniforms.count(Name) == 1) { Textures[Name] = Texture; UnboundUniforms.erase(Name); } } void CPipelineState::IgnoreUniform(string const & Name) { UnboundUniforms.erase(Name); } set<string> CPipelineState::GetUnboundUniforms() const { return UnboundUniforms; } void CPipelineState::Load() { if (! ShaderProgram || VertexBuffers.empty() || ! IndexBuffer) { Log::Error("Attempting to load an invalid PipelineState"); return; } Window->MakeContextCurrent(); CheckedGLCall(glUseProgram(ShaderProgram->Handle)); CheckedGLCall(glBindVertexArray(VertexArrayHandle)); for (auto & VertexBuffer : VertexBuffers) { CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer->Handle)); ////////////////////////////// // Set up VBOs (attributes) // ////////////////////////////// // Calculate stride of VBO data size_t TotalStride = 0; for (auto & InputLayoutElement : VertexBuffer->InputLayout) { TotalStride += GetAttributeTypeSize(InputLayoutElement.Type) * InputLayoutElement.Components; } size_t CurrentOffset = 0; for (auto & InputLayoutElement : VertexBuffer->InputLayout) { pair<uint, uint> AttributeInfo; if (TryMapAccess(ShaderProgram->Attributes, InputLayoutElement.Name, AttributeInfo)) { uint const AttributeLocation = AttributeInfo.first; uint const AttributeType = AttributeInfo.second; // Validate Attribute Type (does the VBO layout match what the shader wants?) { bool IsAttributeTypeCorrect = false; string ShaderAttributeTypeString = "Unknown"; switch (AttributeType) { default: Log::Error("Unexpected type for attribute %s: %u", InputLayoutElement.Name, AttributeType); break; case GL_FLOAT: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Float && InputLayoutElement.Components == 1); ShaderAttributeTypeString = "GL_FLOAT"; break; case GL_FLOAT_VEC2: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Float && InputLayoutElement.Components == 2); ShaderAttributeTypeString = "GL_FLOAT_VEC2"; break; case GL_FLOAT_VEC3: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Float && InputLayoutElement.Components == 3); ShaderAttributeTypeString = "GL_FLOAT_VEC3"; break; case GL_FLOAT_VEC4: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Float && InputLayoutElement.Components == 4); ShaderAttributeTypeString = "GL_FLOAT_VEC4"; break; case GL_INT: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Int && InputLayoutElement.Components == 1); ShaderAttributeTypeString = "GL_INT"; break; case GL_INT_VEC2: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Int && InputLayoutElement.Components == 2); ShaderAttributeTypeString = "GL_INT_VEC2"; break; case GL_INT_VEC3: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Int && InputLayoutElement.Components == 3); ShaderAttributeTypeString = "GL_INT_VEC3"; break; case GL_INT_VEC4: IsAttributeTypeCorrect = (InputLayoutElement.Type == EAttributeType::Int && InputLayoutElement.Components == 4); ShaderAttributeTypeString = "GL_INT_VEC4"; break; } if (! IsAttributeTypeCorrect) { Log::Error("Mistmatch for attribute type '%s': VBO supplied %d components of type %s but shader expected '%s'", InputLayoutElement.Name, InputLayoutElement.Components, GetAttributeTypeString(InputLayoutElement.Type), ShaderAttributeTypeString); } } CheckedGLCall(glEnableVertexAttribArray(AttributeLocation)); switch (AttributeType) { case GL_FLOAT: case GL_FLOAT_VEC2: case GL_FLOAT_VEC3: case GL_FLOAT_VEC4: CheckedGLCall(glVertexAttribPointer( AttributeLocation, InputLayoutElement.Components, GetAttributeTypeOpenGLEnum(InputLayoutElement.Type), GL_FALSE, (int) TotalStride, (void *) CurrentOffset)); break; case GL_INT: case GL_INT_VEC2: case GL_INT_VEC3: case GL_INT_VEC4: CheckedGLCall(glVertexAttribIPointer( AttributeLocation, InputLayoutElement.Components, GetAttributeTypeOpenGLEnum(InputLayoutElement.Type), (int) TotalStride, (void *) CurrentOffset)); break; } if (VertexBuffer->Instancing) { CheckedGLCall(glVertexAttribDivisor(AttributeLocation, 1)); } UnboundAttributes.erase(InputLayoutElement.Name); } CurrentOffset += GetAttributeTypeSize(InputLayoutElement.Type) * InputLayoutElement.Components; } CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, 0)); // Remember, VBOs are not part of VAO state (that's why we never leave them set in the VAO) } std::for_each(UnboundAttributes.begin(), UnboundAttributes.end(), [](string const & Attribuite) { Log::Error("Attribute expected by shader but not provided by VBO: %s", Attribuite); }); CheckedGLCall(glBindVertexArray(0)); CheckedGLCall(glUseProgram(0)); ///////////////////// // Set up Uniforms // ///////////////////// BoundUniforms.clear(); for (auto const & it : Uniforms) { uint Handle = 0; if (TryMapAccess(ShaderProgram->Uniforms, it.first, Handle)) { BoundUniforms[Handle] = it.second; } } BoundTextures.clear(); for (auto const & it : Textures) { uint Handle = 0; if (TryMapAccess(ShaderProgram->Uniforms, it.first, Handle)) { BoundTextures[Handle] = it.second; } } std::for_each(UnboundUniforms.begin(), UnboundUniforms.end(), [](string const & Uniform) { Log::Error("Uniform expected by shader but not provided by PSO: %s", Uniform); }); Loaded = true; } } } } <|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. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, 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 the copyright holders 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*/ #ifndef OPENCV_BACKGROUND_SEGM_HPP #define OPENCV_BACKGROUND_SEGM_HPP #include "opencv2/core.hpp" namespace cv { //! @addtogroup video_motion //! @{ /** @brief Base class for background/foreground segmentation. : The class is only used to define the common interface for the whole family of background/foreground segmentation algorithms. */ class CV_EXPORTS_W BackgroundSubtractor : public Algorithm { public: /** @brief Computes a foreground mask. @param image Next video frame. @param fgmask The output foreground mask as an 8-bit binary image. @param learningRate The value between 0 and 1 that indicates how fast the background model is learnt. Negative parameter value makes the algorithm to use some automatically chosen learning rate. 0 means that the background model is not updated at all, 1 means that the background model is completely reinitialized from the last frame. */ CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) = 0; /** @brief Computes a background image. @param backgroundImage The output background image. @note Sometimes the background image can be very blurry, as it contain the average background statistics. */ CV_WRAP virtual void getBackgroundImage(OutputArray backgroundImage) const = 0; }; /** @brief Gaussian Mixture-based Background/Foreground Segmentation Algorithm. The class implements the Gaussian mixture model background subtraction described in @cite Zivkovic2004 and @cite Zivkovic2006 . */ class CV_EXPORTS_W BackgroundSubtractorMOG2 : public BackgroundSubtractor { public: /** @brief Returns the number of last frames that affect the background model */ CV_WRAP virtual int getHistory() const = 0; /** @brief Sets the number of last frames that affect the background model */ CV_WRAP virtual void setHistory(int history) = 0; /** @brief Returns the number of gaussian components in the background model */ CV_WRAP virtual int getNMixtures() const = 0; /** @brief Sets the number of gaussian components in the background model. The model needs to be reinitalized to reserve memory. */ CV_WRAP virtual void setNMixtures(int nmixtures) = 0;//needs reinitialization! /** @brief Returns the "background ratio" parameter of the algorithm If a foreground pixel keeps semi-constant value for about backgroundRatio\*history frames, it's considered background and added to the model as a center of a new component. It corresponds to TB parameter in the paper. */ CV_WRAP virtual double getBackgroundRatio() const = 0; /** @brief Sets the "background ratio" parameter of the algorithm */ CV_WRAP virtual void setBackgroundRatio(double ratio) = 0; /** @brief Returns the variance threshold for the pixel-model match The main threshold on the squared Mahalanobis distance to decide if the sample is well described by the background model or not. Related to Cthr from the paper. */ CV_WRAP virtual double getVarThreshold() const = 0; /** @brief Sets the variance threshold for the pixel-model match */ CV_WRAP virtual void setVarThreshold(double varThreshold) = 0; /** @brief Returns the variance threshold for the pixel-model match used for new mixture component generation Threshold for the squared Mahalanobis distance that helps decide when a sample is close to the existing components (corresponds to Tg in the paper). If a pixel is not close to any component, it is considered foreground or added as a new component. 3 sigma =\> Tg=3\*3=9 is default. A smaller Tg value generates more components. A higher Tg value may result in a small number of components but they can grow too large. */ CV_WRAP virtual double getVarThresholdGen() const = 0; /** @brief Sets the variance threshold for the pixel-model match used for new mixture component generation */ CV_WRAP virtual void setVarThresholdGen(double varThresholdGen) = 0; /** @brief Returns the initial variance of each gaussian component */ CV_WRAP virtual double getVarInit() const = 0; /** @brief Sets the initial variance of each gaussian component */ CV_WRAP virtual void setVarInit(double varInit) = 0; CV_WRAP virtual double getVarMin() const = 0; CV_WRAP virtual void setVarMin(double varMin) = 0; CV_WRAP virtual double getVarMax() const = 0; CV_WRAP virtual void setVarMax(double varMax) = 0; /** @brief Returns the complexity reduction threshold This parameter defines the number of samples needed to accept to prove the component exists. CT=0.05 is a default value for all the samples. By setting CT=0 you get an algorithm very similar to the standard Stauffer&Grimson algorithm. */ CV_WRAP virtual double getComplexityReductionThreshold() const = 0; /** @brief Sets the complexity reduction threshold */ CV_WRAP virtual void setComplexityReductionThreshold(double ct) = 0; /** @brief Returns the shadow detection flag If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorMOG2 for details. */ CV_WRAP virtual bool getDetectShadows() const = 0; /** @brief Enables or disables shadow detection */ CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; /** @brief Returns the shadow value Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 in the mask always means background, 255 means foreground. */ CV_WRAP virtual int getShadowValue() const = 0; /** @brief Sets the shadow value */ CV_WRAP virtual void setShadowValue(int value) = 0; /** @brief Returns the shadow threshold A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiarra, *Detecting Moving Shadows...*, IEEE PAMI,2003. */ CV_WRAP virtual double getShadowThreshold() const = 0; /** @brief Sets the shadow threshold */ CV_WRAP virtual void setShadowThreshold(double threshold) = 0; }; /** @brief Creates MOG2 Background Subtractor @param history Length of the history. @param varThreshold Threshold on the squared Mahalanobis distance between the pixel and the model to decide whether a pixel is well described by the background model. This parameter does not affect the background update. @param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the speed a bit, so if you do not need this feature, set the parameter to false. */ CV_EXPORTS_W Ptr<BackgroundSubtractorMOG2> createBackgroundSubtractorMOG2(int history=500, double varThreshold=16, bool detectShadows=true); /** @brief K-nearest neigbours - based Background/Foreground Segmentation Algorithm. The class implements the K-nearest neigbours background subtraction described in @cite Zivkovic2006 . Very efficient if number of foreground pixels is low. */ class CV_EXPORTS_W BackgroundSubtractorKNN : public BackgroundSubtractor { public: /** @brief Returns the number of last frames that affect the background model */ CV_WRAP virtual int getHistory() const = 0; /** @brief Sets the number of last frames that affect the background model */ CV_WRAP virtual void setHistory(int history) = 0; /** @brief Returns the number of data samples in the background model */ CV_WRAP virtual int getNSamples() const = 0; /** @brief Sets the number of data samples in the background model. The model needs to be reinitalized to reserve memory. */ CV_WRAP virtual void setNSamples(int _nN) = 0;//needs reinitialization! /** @brief Returns the threshold on the squared distance between the pixel and the sample The threshold on the squared distance between the pixel and the sample to decide whether a pixel is close to a data sample. */ CV_WRAP virtual double getDist2Threshold() const = 0; /** @brief Sets the threshold on the squared distance */ CV_WRAP virtual void setDist2Threshold(double _dist2Threshold) = 0; /** @brief Returns the number of neighbours, the k in the kNN. K is the number of samples that need to be within dist2Threshold in order to decide that that pixel is matching the kNN background model. */ CV_WRAP virtual int getkNNSamples() const = 0; /** @brief Sets the k in the kNN. How many nearest neigbours need to match. */ CV_WRAP virtual void setkNNSamples(int _nkNN) = 0; /** @brief Returns the shadow detection flag If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorKNN for details. */ CV_WRAP virtual bool getDetectShadows() const = 0; /** @brief Enables or disables shadow detection */ CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; /** @brief Returns the shadow value Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 in the mask always means background, 255 means foreground. */ CV_WRAP virtual int getShadowValue() const = 0; /** @brief Sets the shadow value */ CV_WRAP virtual void setShadowValue(int value) = 0; /** @brief Returns the shadow threshold A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiarra, *Detecting Moving Shadows...*, IEEE PAMI,2003. */ CV_WRAP virtual double getShadowThreshold() const = 0; /** @brief Sets the shadow threshold */ CV_WRAP virtual void setShadowThreshold(double threshold) = 0; }; /** @brief Creates KNN Background Subtractor @param history Length of the history. @param dist2Threshold Threshold on the squared distance between the pixel and the sample to decide whether a pixel is close to that sample. This parameter does not affect the background update. @param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the speed a bit, so if you do not need this feature, set the parameter to false. */ CV_EXPORTS_W Ptr<BackgroundSubtractorKNN> createBackgroundSubtractorKNN(int history=500, double dist2Threshold=400.0, bool detectShadows=true); //! @} video_motion } // cv #endif <commit_msg>Clarify docs for MOG2::apply<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. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, 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 the copyright holders 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*/ #ifndef OPENCV_BACKGROUND_SEGM_HPP #define OPENCV_BACKGROUND_SEGM_HPP #include "opencv2/core.hpp" namespace cv { //! @addtogroup video_motion //! @{ /** @brief Base class for background/foreground segmentation. : The class is only used to define the common interface for the whole family of background/foreground segmentation algorithms. */ class CV_EXPORTS_W BackgroundSubtractor : public Algorithm { public: /** @brief Computes a foreground mask. @param image Next video frame. @param fgmask The output foreground mask as an 8-bit binary image. @param learningRate The value between 0 and 1 that indicates how fast the background model is learnt. Negative parameter value makes the algorithm to use some automatically chosen learning rate. 0 means that the background model is not updated at all, 1 means that the background model is completely reinitialized from the last frame. */ CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) = 0; /** @brief Computes a background image. @param backgroundImage The output background image. @note Sometimes the background image can be very blurry, as it contain the average background statistics. */ CV_WRAP virtual void getBackgroundImage(OutputArray backgroundImage) const = 0; }; /** @brief Gaussian Mixture-based Background/Foreground Segmentation Algorithm. The class implements the Gaussian mixture model background subtraction described in @cite Zivkovic2004 and @cite Zivkovic2006 . */ class CV_EXPORTS_W BackgroundSubtractorMOG2 : public BackgroundSubtractor { public: /** @brief Returns the number of last frames that affect the background model */ CV_WRAP virtual int getHistory() const = 0; /** @brief Sets the number of last frames that affect the background model */ CV_WRAP virtual void setHistory(int history) = 0; /** @brief Returns the number of gaussian components in the background model */ CV_WRAP virtual int getNMixtures() const = 0; /** @brief Sets the number of gaussian components in the background model. The model needs to be reinitalized to reserve memory. */ CV_WRAP virtual void setNMixtures(int nmixtures) = 0;//needs reinitialization! /** @brief Returns the "background ratio" parameter of the algorithm If a foreground pixel keeps semi-constant value for about backgroundRatio\*history frames, it's considered background and added to the model as a center of a new component. It corresponds to TB parameter in the paper. */ CV_WRAP virtual double getBackgroundRatio() const = 0; /** @brief Sets the "background ratio" parameter of the algorithm */ CV_WRAP virtual void setBackgroundRatio(double ratio) = 0; /** @brief Returns the variance threshold for the pixel-model match The main threshold on the squared Mahalanobis distance to decide if the sample is well described by the background model or not. Related to Cthr from the paper. */ CV_WRAP virtual double getVarThreshold() const = 0; /** @brief Sets the variance threshold for the pixel-model match */ CV_WRAP virtual void setVarThreshold(double varThreshold) = 0; /** @brief Returns the variance threshold for the pixel-model match used for new mixture component generation Threshold for the squared Mahalanobis distance that helps decide when a sample is close to the existing components (corresponds to Tg in the paper). If a pixel is not close to any component, it is considered foreground or added as a new component. 3 sigma =\> Tg=3\*3=9 is default. A smaller Tg value generates more components. A higher Tg value may result in a small number of components but they can grow too large. */ CV_WRAP virtual double getVarThresholdGen() const = 0; /** @brief Sets the variance threshold for the pixel-model match used for new mixture component generation */ CV_WRAP virtual void setVarThresholdGen(double varThresholdGen) = 0; /** @brief Returns the initial variance of each gaussian component */ CV_WRAP virtual double getVarInit() const = 0; /** @brief Sets the initial variance of each gaussian component */ CV_WRAP virtual void setVarInit(double varInit) = 0; CV_WRAP virtual double getVarMin() const = 0; CV_WRAP virtual void setVarMin(double varMin) = 0; CV_WRAP virtual double getVarMax() const = 0; CV_WRAP virtual void setVarMax(double varMax) = 0; /** @brief Returns the complexity reduction threshold This parameter defines the number of samples needed to accept to prove the component exists. CT=0.05 is a default value for all the samples. By setting CT=0 you get an algorithm very similar to the standard Stauffer&Grimson algorithm. */ CV_WRAP virtual double getComplexityReductionThreshold() const = 0; /** @brief Sets the complexity reduction threshold */ CV_WRAP virtual void setComplexityReductionThreshold(double ct) = 0; /** @brief Returns the shadow detection flag If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorMOG2 for details. */ CV_WRAP virtual bool getDetectShadows() const = 0; /** @brief Enables or disables shadow detection */ CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; /** @brief Returns the shadow value Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 in the mask always means background, 255 means foreground. */ CV_WRAP virtual int getShadowValue() const = 0; /** @brief Sets the shadow value */ CV_WRAP virtual void setShadowValue(int value) = 0; /** @brief Returns the shadow threshold A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiarra, *Detecting Moving Shadows...*, IEEE PAMI,2003. */ CV_WRAP virtual double getShadowThreshold() const = 0; /** @brief Sets the shadow threshold */ CV_WRAP virtual void setShadowThreshold(double threshold) = 0; /** @brief Computes a foreground mask. @param image Next video frame. Floating point frame will be used without scaling and should be in range \f$[0,255]\f$. @param fgmask The output foreground mask as an 8-bit binary image. @param learningRate The value between 0 and 1 that indicates how fast the background model is learnt. Negative parameter value makes the algorithm to use some automatically chosen learning rate. 0 means that the background model is not updated at all, 1 means that the background model is completely reinitialized from the last frame. */ CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) = 0; }; /** @brief Creates MOG2 Background Subtractor @param history Length of the history. @param varThreshold Threshold on the squared Mahalanobis distance between the pixel and the model to decide whether a pixel is well described by the background model. This parameter does not affect the background update. @param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the speed a bit, so if you do not need this feature, set the parameter to false. */ CV_EXPORTS_W Ptr<BackgroundSubtractorMOG2> createBackgroundSubtractorMOG2(int history=500, double varThreshold=16, bool detectShadows=true); /** @brief K-nearest neigbours - based Background/Foreground Segmentation Algorithm. The class implements the K-nearest neigbours background subtraction described in @cite Zivkovic2006 . Very efficient if number of foreground pixels is low. */ class CV_EXPORTS_W BackgroundSubtractorKNN : public BackgroundSubtractor { public: /** @brief Returns the number of last frames that affect the background model */ CV_WRAP virtual int getHistory() const = 0; /** @brief Sets the number of last frames that affect the background model */ CV_WRAP virtual void setHistory(int history) = 0; /** @brief Returns the number of data samples in the background model */ CV_WRAP virtual int getNSamples() const = 0; /** @brief Sets the number of data samples in the background model. The model needs to be reinitalized to reserve memory. */ CV_WRAP virtual void setNSamples(int _nN) = 0;//needs reinitialization! /** @brief Returns the threshold on the squared distance between the pixel and the sample The threshold on the squared distance between the pixel and the sample to decide whether a pixel is close to a data sample. */ CV_WRAP virtual double getDist2Threshold() const = 0; /** @brief Sets the threshold on the squared distance */ CV_WRAP virtual void setDist2Threshold(double _dist2Threshold) = 0; /** @brief Returns the number of neighbours, the k in the kNN. K is the number of samples that need to be within dist2Threshold in order to decide that that pixel is matching the kNN background model. */ CV_WRAP virtual int getkNNSamples() const = 0; /** @brief Sets the k in the kNN. How many nearest neigbours need to match. */ CV_WRAP virtual void setkNNSamples(int _nkNN) = 0; /** @brief Returns the shadow detection flag If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorKNN for details. */ CV_WRAP virtual bool getDetectShadows() const = 0; /** @brief Enables or disables shadow detection */ CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; /** @brief Returns the shadow value Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 in the mask always means background, 255 means foreground. */ CV_WRAP virtual int getShadowValue() const = 0; /** @brief Sets the shadow value */ CV_WRAP virtual void setShadowValue(int value) = 0; /** @brief Returns the shadow threshold A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiarra, *Detecting Moving Shadows...*, IEEE PAMI,2003. */ CV_WRAP virtual double getShadowThreshold() const = 0; /** @brief Sets the shadow threshold */ CV_WRAP virtual void setShadowThreshold(double threshold) = 0; }; /** @brief Creates KNN Background Subtractor @param history Length of the history. @param dist2Threshold Threshold on the squared distance between the pixel and the sample to decide whether a pixel is close to that sample. This parameter does not affect the background update. @param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the speed a bit, so if you do not need this feature, set the parameter to false. */ CV_EXPORTS_W Ptr<BackgroundSubtractorKNN> createBackgroundSubtractorKNN(int history=500, double dist2Threshold=400.0, bool detectShadows=true); //! @} video_motion } // cv #endif <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2018 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "critical_section_test.h" #include "hal/critical_section_api.h" #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "mbed.h" #include "cmsis.h" #ifdef TARGET_NRF5 // for all NRF5x targets #include "nrf_nvic.h" // for __NRF_NVIC_APP_IRQS_0 / __NRF_NVIC_APP_IRQS_1 #endif using utest::v1::Case; bool test_are_interrupts_enabled(void) { // NRF5x targets don't disable interrupts when in critical section, instead they mask application interrupts this is due to BLE stack // (BLE to be operational requires some interrupts to be always enabled) #ifdef TARGET_NRF52_DK // check if APP interrupts are masked for NRF52_DK board return (((NVIC->ISER[0] & __NRF_NVIC_APP_IRQS_0) != 0) || ((NVIC->ISER[1] & __NRF_NVIC_APP_IRQS_1) != 0)); #elif TARGET_NRF5 // check if APP interrupts are masked for other NRF5 boards return ((NVIC->ISER[0] & __NRF_NVIC_APP_IRQS_0) != 0); #else #if defined(__CORTEX_A9) return ((__get_CPSR() & 0x80) == 0); #else return ((__get_PRIMASK() & 0x1) == 0); #endif #endif } template<int N> void test_critical_section() { TEST_ASSERT_FALSE(hal_in_critical_section()); TEST_ASSERT_TRUE(test_are_interrupts_enabled()); for (int i = 0; i < N; i++) { hal_critical_section_enter(); TEST_ASSERT_TRUE(hal_in_critical_section()); TEST_ASSERT_FALSE(test_are_interrupts_enabled()); } // assumed to be called once (according API) hal_critical_section_exit(); TEST_ASSERT_FALSE(hal_in_critical_section()); TEST_ASSERT_TRUE(test_are_interrupts_enabled()); } Case cases[] = { Case("Test critical section single lock", test_critical_section<1>), Case("Test critical section nested lock", test_critical_section<10>) }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(10, "timing_drift_auto"); return utest::v1::greentea_test_setup_handler(number_of_cases); } utest::v1::Specification specification(greentea_test_setup, cases); int main() { return !utest::v1::Harness::run(specification); } <commit_msg>Renamed NRF52 targets for HAL critical section test<commit_after>/* mbed Microcontroller Library * Copyright (c) 2018 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "critical_section_test.h" #include "hal/critical_section_api.h" #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "mbed.h" #include "cmsis.h" #if defined(TARGET_NRF5) || defined(TARGET_NRF5x) // for all NRF5x targets #include "nrf_nvic.h" // for __NRF_NVIC_APP_IRQS_0 / __NRF_NVIC_APP_IRQS_1 #endif using utest::v1::Case; bool test_are_interrupts_enabled(void) { // NRF5x targets don't disable interrupts when in critical section, instead they mask application interrupts this is due to BLE stack // (BLE to be operational requires some interrupts to be always enabled) #ifdef TARGET_NRF52 // check if APP interrupts are masked for NRF52_DK board return (((NVIC->ISER[0] & __NRF_NVIC_APP_IRQS_0) != 0) || ((NVIC->ISER[1] & __NRF_NVIC_APP_IRQS_1) != 0)); #elif TARGET_NRF5 // check if APP interrupts are masked for other NRF5 boards return ((NVIC->ISER[0] & __NRF_NVIC_APP_IRQS_0) != 0); #else #if defined(__CORTEX_A9) return ((__get_CPSR() & 0x80) == 0); #else return ((__get_PRIMASK() & 0x1) == 0); #endif #endif } template<int N> void test_critical_section() { TEST_ASSERT_FALSE(hal_in_critical_section()); TEST_ASSERT_TRUE(test_are_interrupts_enabled()); for (int i = 0; i < N; i++) { hal_critical_section_enter(); TEST_ASSERT_TRUE(hal_in_critical_section()); TEST_ASSERT_FALSE(test_are_interrupts_enabled()); } // assumed to be called once (according API) hal_critical_section_exit(); TEST_ASSERT_FALSE(hal_in_critical_section()); TEST_ASSERT_TRUE(test_are_interrupts_enabled()); } Case cases[] = { Case("Test critical section single lock", test_critical_section<1>), Case("Test critical section nested lock", test_critical_section<10>) }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(10, "timing_drift_auto"); return utest::v1::greentea_test_setup_handler(number_of_cases); } utest::v1::Specification specification(greentea_test_setup, cases); int main() { return !utest::v1::Harness::run(specification); } <|endoftext|>
<commit_before>#include <algorithm> #include <cassert> #include <cerrno> #include <condition_variable> #include <csignal> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <limits> #include <map> #include <mutex> #include <pthread.h> #include <sstream> #include <string> #include <sys/ptrace.h> #include <sys/time.h> #include <sys/user.h> #include <sys/wait.h> #include <thread> #include <unistd.h> #include <utility> #include <vector> #include "papi.h" #ifdef DEBUG #define print(...) printf(__VA_ARGS__) #else #define print(...) #endif using namespace std; namespace{ const unsigned kSleepSecs = 1; const unsigned kSleepUsecs = 0; const double kNanoToBase = 1e-9; const long long kBaseToNano = 1000000000; const long long kMicroToNano = 1000; const long long kCounterMax = numeric_limits<unsigned int>::max(); const char* kOutFileName = "eaudit.tsv"; const char* kCounterNames[] = { //(char*) "rapl:::PACKAGE_ENERGY:PACKAGE0", //(char*) "rapl:::PP0_ENERGY:PACKAGE0", (char*) "PAPI_TOT_INS", (char*) "PAPI_TOT_CYC", }; constexpr int kNumCounters = sizeof(kCounterNames) / sizeof(kCounterNames[0]); } volatile bool is_timer_done = false; volatile bool is_done = false; volatile bool should_profile = false; mutex profile_mutex; condition_variable profile_cv; struct stats_t { long long time; long long counters[kNumCounters]; stats_t& operator+=(const stats_t &rhs){ time += rhs.time; for(int i = 0; i < kNumCounters; ++i){ counters[i] += rhs.counters[i]; } return *this; } }; inline stats_t operator+(stats_t lhs, const stats_t& rhs) { return lhs += rhs; } struct event_info_t{ int component; int set; vector<int> codes; vector<string> names; }; void overflow(int signum, siginfo_t* info, void* context){ (void)info; (void)context; if(signum == SIGALRM){ is_timer_done = true; } } stats_t read_rapl(const vector<event_info_t>& eventsets){ stats_t res; int cntr_offset = 0; for(const auto& eventset : eventsets){ int retval=PAPI_stop(eventset.set, res.counters + cntr_offset); if(retval != PAPI_OK){ PAPI_perror(NULL); exit(-1); } retval = PAPI_start(eventset.set); if(retval != PAPI_OK){ PAPI_perror(NULL); exit(-1); } cntr_offset += eventset.codes.size(); } res.time = kSleepSecs * kBaseToNano + kSleepUsecs * kMicroToNano; return res; } vector<event_info_t> init_papi_counters() { vector<event_info_t> eventsets; int retval; for (auto& event_name : kCounterNames) { int event_code; retval = PAPI_event_name_to_code((char*)event_name, &event_code); if (retval != PAPI_OK) { PAPI_perror(NULL); exit(-1); } int component = PAPI_get_event_component(event_code); auto elem = find_if( begin(eventsets), end(eventsets), [&](const event_info_t& c) { return c.component == component; }); if (elem == end(eventsets)) { event_info_t new_info; new_info.component = component; new_info.codes.push_back(event_code); new_info.names.emplace_back(event_name); eventsets.push_back(new_info); } else { elem->codes.push_back(event_code); elem->names.emplace_back(event_name); } } for (auto& event : eventsets) { int eventset = PAPI_NULL; PAPI_create_eventset(&eventset); if (retval != PAPI_OK) { PAPI_perror(NULL); exit(-1); } PAPI_add_events(eventset, &event.codes[0], event.codes.size()); if (retval != PAPI_OK) { PAPI_perror(NULL); exit(-1); } event.set = eventset; retval = PAPI_start(eventset); if (retval != PAPI_OK) { PAPI_perror(NULL); exit(-1); } } return eventsets; } void profile_core(int id) { /* Set affinity */ cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(id, &cpuset); pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset); /* Initialize PAPI counters for this core */ auto counters = init_papi_counters(); while(!is_done){ // wait on condition variable unique_lock<mutex> locker(profile_mutex); cout << "TID " << id << " waiting\n"; profile_cv.wait(locker, []{ return should_profile; }); // do profiling cout << "TID " << id << " profiling\n"; // update output (global) data // go back to sleep //should_profile = false; //WHELKHKLJDHFLKSDHFLSKD //TODO //where to set should_profile back to false??? } cout << "TID " << id << " DONE\n"; } void do_profiling(int profilee_pid, char* profilee_name) { /* * Structures holding profiling data */ vector<int> children_pids; map<void*, stats_t> stat_map; vector<thread> threads; threads.reserve(thread::hardware_concurrency()); /* * Initialize PAPI */ print("Init PAPI\n"); int retval; if ((retval = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) { cerr << "Unable to init PAPI library: "; switch (retval) { case PAPI_EINVAL: cerr << "einval\n"; break; case PAPI_ENOMEM: cerr << "enomem\n"; break; case PAPI_ESBSTR: cerr << "esbstr\n"; break; case PAPI_ESYS: cerr << "esys\n"; break; default: cerr << "\n"; } exit(-1); } /* * Initialize PAPI measurement threads */ if(PAPI_thread_init(pthread_self) != PAPI_OK){ cerr << "Unable to init PAPI threads\n"; exit(-1); } for(unsigned int i = 0; i < thread::hardware_concurrency(); ++i){ cout << "eaudit Starting thread " << i << "\n"; threads.emplace_back(profile_core, i); } /* * Setup tracing of all profilee threads */ children_pids.push_back(profilee_pid); ptrace(PTRACE_SETOPTIONS, profilee_pid, nullptr, PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXIT); /* * Set up timer */ struct sigaction sa; sa.sa_sigaction = overflow; sa.sa_flags = SA_SIGINFO; if (sigaction(SIGALRM, &sa, nullptr) != 0) { cerr << "Unable to set up signal handler\n"; exit(-1); } struct itimerval work_time; work_time.it_value.tv_sec = kSleepSecs; work_time.it_value.tv_usec = kSleepUsecs; work_time.it_interval.tv_sec = kSleepSecs; work_time.it_interval.tv_usec = kSleepUsecs; setitimer(ITIMER_REAL, &work_time, nullptr); /* * Let the profilee run, periodically interrupting to collect profile data. */ print("Start profiling.\n"); ptrace(PTRACE_CONT, profilee_pid, nullptr, nullptr); struct user_regs_struct regs; for (;;) { int status; //auto wait_res = wait(&status); auto wait_res = waitpid(-1, &status, __WALL); if(wait_res == -1){ // bad wait! if(errno == EINTR && is_timer_done){ // timer expired, do profiling // halt timer work_time.it_value.tv_sec = 0; work_time.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &work_time, nullptr); // kill all the children for(const auto& child : children_pids){ kill(child, SIGSTOP); } // TODO // find last executing core ID for each child // send signal requesting updates from each profiling thread associated with a child core id { unique_lock<mutex> locker(profile_mutex); should_profile = true; cout << "EAUDIT notifying\n"; profile_cv.notify_all(); } // wait on output from profiling threads and accumulate /* // read all the children registers for(const auto& child : children_pids){ ptrace(PTRACE_GETREGS, child, nullptr, &regs); void* rip = (void*)regs.rip; auto rapl = read_rapl(eventsets); stat_map[rip] += rapl; } */ // resume all children for(const auto& child : children_pids){ ptrace(PTRACE_CONT, child, nullptr, nullptr); } is_timer_done = false; // resume timer work_time.it_value.tv_sec = kSleepSecs; work_time.it_value.tv_usec = kSleepUsecs; setitimer(ITIMER_REAL, &work_time, nullptr); continue; // this isn't really necessary } else { cerr << "Error: unexpected return from wait.\n"; exit(-1); } } else { // good wait, add new thread if(status>>8 == (SIGTRAP | (PTRACE_EVENT_CLONE<<8))) { // new thread created print("New thread created.\n"); unsigned long new_pid; ptrace(PTRACE_GETEVENTMSG, wait_res, nullptr, &new_pid); auto pid_iter = find(begin(children_pids), end(children_pids), new_pid); if(pid_iter != end(children_pids)) { cerr << "Already have this newly cloned pid: " << new_pid << ".\n"; exit(-1); } print("Thread ID %lu created from thread ID %d\n", new_pid, wait_res); children_pids.push_back(new_pid); ptrace(PTRACE_SETOPTIONS, new_pid, nullptr, PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXIT); ptrace(PTRACE_CONT, wait_res, nullptr, nullptr); } else { if(status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))){ print("Deleting child %d\n", wait_res); auto pid_iter = find(begin(children_pids), end(children_pids), wait_res); if(pid_iter == end(children_pids)){ cerr << "Error: Saw exit from pid " << wait_res << ". We haven't seen before!\n"; exit(-1); } children_pids.erase(pid_iter); if(children_pids.size() == 0){ // All done, not tracking any more threads is_done = true; { unique_lock<mutex> locker(profile_mutex); should_profile = true; profile_cv.notify_all(); } for(auto& thread : threads){ thread.join(); } break; } print("%lu children left\n", children_pids.size()); } // always let the stopped tracee continue ptrace(PTRACE_CONT, wait_res, nullptr, nullptr); } } } /* * Done profiling. Convert data to output file. */ print("Finalize profile.\n"); vector<pair<string, stats_t> > stats; // Convert stack IDs into function names. for (auto& func : stat_map) { stringstream cmd; cmd << "addr2line -f -s -C -e " << profilee_name << " " << func.first; auto pipe = popen(cmd.str().c_str(), "r"); // call command and read output if (!pipe) { cerr << "Unable to open pipe to call addr2line.\n"; return; } char buffer[128]; string result = ""; while (!feof(pipe)) { if (fgets(buffer, 128, pipe) != nullptr) { result += buffer; } } pclose(pipe); stringstream resultstream{result}; string line; getline(resultstream, line); print("Reporting function %s\n", line.c_str()); auto stat = find_if( begin(stats), end(stats), [&](const pair<string, stats_t>& obj) { return obj.first == line; }); if (stat == end(stats)) { stats.emplace_back(line, func.second); } else { stat->second += func.second; } } stable_sort(stats.begin(), stats.end(), [](const pair<string, stats_t>& a, const pair<string, stats_t>& b) { return a.second.time > b.second.time; }); /* * Write profile to file */ /* ofstream myfile; myfile.open(kOutFileName); myfile << "Func Name" << "\t" << "Time(s)"; for(const auto& eventset : eventsets){ for(const auto& name : eventset.names){ myfile << "\t" << name; } } myfile << endl; for (auto& func : stats) { myfile << func.first << "\t" << func.second.time* kNanoToBase; for (int i = 0; i < kNumCounters; ++i) { myfile << "\t" << func.second.counters[i]; } myfile << endl; } myfile.close(); */ } int main(int argc, char* argv[]) { (void)argc; /* * Fork a process to run the profiled application */ auto profilee = fork(); if(profilee > 0){ /* parent */ // Let's do this. int status; wait(&status); if(WIFEXITED(status)){ cerr << "Child exited too fast.\n"; return 0; } do_profiling(profilee, argv[1]); } else if(profilee == 0){ /* profilee */ // prepare for tracing ptrace(PTRACE_TRACEME, 0, nullptr, nullptr); // start up client program execve(argv[1], &argv[1], nullptr); cerr << "Error: profilee couldn't start its program!\n"; exit(-1); } else { /* error */ cerr << "Error: couldn't fork audited program.\n"; return -1; } } <commit_msg>Profiler wakes up one thread per core to do counter readings<commit_after>#include <algorithm> #include <cassert> #include <cerrno> #include <condition_variable> #include <csignal> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <limits> #include <map> #include <mutex> #include <pthread.h> #include <sstream> #include <string> #include <sys/ptrace.h> #include <sys/time.h> #include <sys/user.h> #include <sys/wait.h> #include <thread> #include <unistd.h> #include <utility> #include <vector> #include "papi.h" #ifdef DEBUG #define print(...) printf(__VA_ARGS__) #else #define print(...) #endif using namespace std; namespace{ const unsigned kSleepSecs = 1; const unsigned kSleepUsecs = 0; const double kNanoToBase = 1e-9; const long long kBaseToNano = 1000000000; const long long kMicroToNano = 1000; const long long kCounterMax = numeric_limits<unsigned int>::max(); const char* kOutFileName = "eaudit.tsv"; const char* kCounterNames[] = { //(char*) "rapl:::PACKAGE_ENERGY:PACKAGE0", //(char*) "rapl:::PP0_ENERGY:PACKAGE0", (char*) "PAPI_TOT_INS", (char*) "PAPI_TOT_CYC", }; constexpr int kNumCounters = sizeof(kCounterNames) / sizeof(kCounterNames[0]); } volatile bool is_timer_done = false; volatile bool is_done = false; mutex profile_mutex; condition_variable profile_cv; vector<bool> should_profile; struct stats_t { long long time; long long counters[kNumCounters]; stats_t& operator+=(const stats_t &rhs){ time += rhs.time; for(int i = 0; i < kNumCounters; ++i){ counters[i] += rhs.counters[i]; } return *this; } }; inline stats_t operator+(stats_t lhs, const stats_t& rhs) { return lhs += rhs; } struct event_info_t{ int component; int set; vector<int> codes; vector<string> names; }; void overflow(int signum, siginfo_t* info, void* context){ (void)info; (void)context; if(signum == SIGALRM){ is_timer_done = true; } } stats_t read_rapl(const vector<event_info_t>& eventsets){ stats_t res; int cntr_offset = 0; for(const auto& eventset : eventsets){ int retval=PAPI_stop(eventset.set, res.counters + cntr_offset); if(retval != PAPI_OK){ PAPI_perror(NULL); exit(-1); } retval = PAPI_start(eventset.set); if(retval != PAPI_OK){ PAPI_perror(NULL); exit(-1); } cntr_offset += eventset.codes.size(); } res.time = kSleepSecs * kBaseToNano + kSleepUsecs * kMicroToNano; return res; } vector<event_info_t> init_papi_counters() { vector<event_info_t> eventsets; int retval; for (auto& event_name : kCounterNames) { int event_code; retval = PAPI_event_name_to_code((char*)event_name, &event_code); if (retval != PAPI_OK) { PAPI_perror(NULL); exit(-1); } int component = PAPI_get_event_component(event_code); auto elem = find_if( begin(eventsets), end(eventsets), [&](const event_info_t& c) { return c.component == component; }); if (elem == end(eventsets)) { event_info_t new_info; new_info.component = component; new_info.codes.push_back(event_code); new_info.names.emplace_back(event_name); eventsets.push_back(new_info); } else { elem->codes.push_back(event_code); elem->names.emplace_back(event_name); } } for (auto& event : eventsets) { int eventset = PAPI_NULL; PAPI_create_eventset(&eventset); if (retval != PAPI_OK) { PAPI_perror(NULL); exit(-1); } PAPI_add_events(eventset, &event.codes[0], event.codes.size()); if (retval != PAPI_OK) { PAPI_perror(NULL); exit(-1); } event.set = eventset; retval = PAPI_start(eventset); if (retval != PAPI_OK) { PAPI_perror(NULL); exit(-1); } } return eventsets; } void profile_core(int id) { /* Set affinity */ cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(id, &cpuset); pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset); /* Initialize PAPI counters for this core */ auto counters = init_papi_counters(); while(!is_done){ // wait on condition variable { unique_lock<mutex> locker(profile_mutex); print("TID %d waiting\n", id); profile_cv.wait(locker, [&]{ return should_profile[id]; }); } // do profiling print("TID %d profiling\n", id); // update output (global) data // go back to sleep { lock_guard<mutex> lock(profile_mutex); should_profile[id] = false; } } print("TID %d DONE\n", id); } void do_profiling(int profilee_pid, char* profilee_name) { /* * Structures holding profiling data */ vector<int> children_pids; map<void*, stats_t> stat_map; vector<thread> threads; auto nthreads = thread::hardware_concurrency(); threads.reserve(nthreads); { lock_guard<mutex> lock(profile_mutex); should_profile.resize(nthreads, false); } /* * Initialize PAPI */ print("Init PAPI\n"); int retval; if ((retval = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) { cerr << "Unable to init PAPI library: "; switch (retval) { case PAPI_EINVAL: cerr << "einval\n"; break; case PAPI_ENOMEM: cerr << "enomem\n"; break; case PAPI_ESBSTR: cerr << "esbstr\n"; break; case PAPI_ESYS: cerr << "esys\n"; break; default: cerr << "\n"; } exit(-1); } /* * Initialize PAPI measurement threads */ if(PAPI_thread_init(pthread_self) != PAPI_OK){ cerr << "Unable to init PAPI threads\n"; exit(-1); } for(unsigned int i = 0; i < nthreads; ++i){ print("eaudit Starting thread %d\n", i); threads.emplace_back(profile_core, i); } /* * Setup tracing of all profilee threads */ children_pids.push_back(profilee_pid); ptrace(PTRACE_SETOPTIONS, profilee_pid, nullptr, PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXIT); /* * Set up timer */ struct sigaction sa; sa.sa_sigaction = overflow; sa.sa_flags = SA_SIGINFO; if (sigaction(SIGALRM, &sa, nullptr) != 0) { cerr << "Unable to set up signal handler\n"; exit(-1); } struct itimerval work_time; work_time.it_value.tv_sec = kSleepSecs; work_time.it_value.tv_usec = kSleepUsecs; work_time.it_interval.tv_sec = kSleepSecs; work_time.it_interval.tv_usec = kSleepUsecs; setitimer(ITIMER_REAL, &work_time, nullptr); /* * Let the profilee run, periodically interrupting to collect profile data. */ print("Start profiling.\n"); ptrace(PTRACE_CONT, profilee_pid, nullptr, nullptr); struct user_regs_struct regs; for (;;) { int status; //auto wait_res = wait(&status); auto wait_res = waitpid(-1, &status, __WALL); if(wait_res == -1){ // bad wait! if(errno == EINTR && is_timer_done){ // timer expired, do profiling // halt timer work_time.it_value.tv_sec = 0; work_time.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &work_time, nullptr); // kill all the children for(const auto& child : children_pids){ kill(child, SIGSTOP); } // TODO // find last executing core ID for each child // send signal requesting updates from each profiling thread associated with a child core id { lock_guard<mutex> lock(profile_mutex); for(unsigned int i = 0; i < nthreads; ++i){ should_profile[i] = true; } } { unique_lock<mutex> locker(profile_mutex); print("EAUDIT notifying\n"); profile_cv.notify_all(); } // wait on output from profiling threads and accumulate /* // read all the children registers for(const auto& child : children_pids){ ptrace(PTRACE_GETREGS, child, nullptr, &regs); void* rip = (void*)regs.rip; auto rapl = read_rapl(eventsets); stat_map[rip] += rapl; } */ // resume all children for(const auto& child : children_pids){ ptrace(PTRACE_CONT, child, nullptr, nullptr); } is_timer_done = false; // resume timer work_time.it_value.tv_sec = kSleepSecs; work_time.it_value.tv_usec = kSleepUsecs; setitimer(ITIMER_REAL, &work_time, nullptr); continue; // this isn't really necessary } else { cerr << "Error: unexpected return from wait.\n"; exit(-1); } } else { // good wait, add new thread if(status>>8 == (SIGTRAP | (PTRACE_EVENT_CLONE<<8))) { // new thread created print("New thread created.\n"); unsigned long new_pid; ptrace(PTRACE_GETEVENTMSG, wait_res, nullptr, &new_pid); auto pid_iter = find(begin(children_pids), end(children_pids), new_pid); if(pid_iter != end(children_pids)) { cerr << "Already have this newly cloned pid: " << new_pid << ".\n"; exit(-1); } print("Thread ID %lu created from thread ID %d\n", new_pid, wait_res); children_pids.push_back(new_pid); ptrace(PTRACE_SETOPTIONS, new_pid, nullptr, PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXIT); ptrace(PTRACE_CONT, wait_res, nullptr, nullptr); } else { if(status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))){ print("Deleting child %d\n", wait_res); auto pid_iter = find(begin(children_pids), end(children_pids), wait_res); if(pid_iter == end(children_pids)){ cerr << "Error: Saw exit from pid " << wait_res << ". We haven't seen before!\n"; exit(-1); } children_pids.erase(pid_iter); if(children_pids.size() == 0){ // All done, not tracking any more threads is_done = true; { lock_guard<mutex> lock(profile_mutex); for(unsigned int i = 0; i < nthreads; ++i){ should_profile[i] = true; } } { unique_lock<mutex> locker(profile_mutex); profile_cv.notify_all(); } for(auto& thread : threads){ thread.join(); } break; } print("%lu children left\n", children_pids.size()); } // always let the stopped tracee continue ptrace(PTRACE_CONT, wait_res, nullptr, nullptr); } } } /* * Done profiling. Convert data to output file. */ print("Finalize profile.\n"); vector<pair<string, stats_t> > stats; // Convert stack IDs into function names. for (auto& func : stat_map) { stringstream cmd; cmd << "addr2line -f -s -C -e " << profilee_name << " " << func.first; auto pipe = popen(cmd.str().c_str(), "r"); // call command and read output if (!pipe) { cerr << "Unable to open pipe to call addr2line.\n"; return; } char buffer[128]; string result = ""; while (!feof(pipe)) { if (fgets(buffer, 128, pipe) != nullptr) { result += buffer; } } pclose(pipe); stringstream resultstream{result}; string line; getline(resultstream, line); print("Reporting function %s\n", line.c_str()); auto stat = find_if( begin(stats), end(stats), [&](const pair<string, stats_t>& obj) { return obj.first == line; }); if (stat == end(stats)) { stats.emplace_back(line, func.second); } else { stat->second += func.second; } } stable_sort(stats.begin(), stats.end(), [](const pair<string, stats_t>& a, const pair<string, stats_t>& b) { return a.second.time > b.second.time; }); /* * Write profile to file */ /* ofstream myfile; myfile.open(kOutFileName); myfile << "Func Name" << "\t" << "Time(s)"; for(const auto& eventset : eventsets){ for(const auto& name : eventset.names){ myfile << "\t" << name; } } myfile << endl; for (auto& func : stats) { myfile << func.first << "\t" << func.second.time* kNanoToBase; for (int i = 0; i < kNumCounters; ++i) { myfile << "\t" << func.second.counters[i]; } myfile << endl; } myfile.close(); */ } int main(int argc, char* argv[]) { (void)argc; /* * Fork a process to run the profiled application */ auto profilee = fork(); if(profilee > 0){ /* parent */ // Let's do this. int status; wait(&status); if(WIFEXITED(status)){ cerr << "Child exited too fast.\n"; return 0; } do_profiling(profilee, argv[1]); } else if(profilee == 0){ /* profilee */ // prepare for tracing ptrace(PTRACE_TRACEME, 0, nullptr, nullptr); // start up client program execve(argv[1], &argv[1], nullptr); cerr << "Error: profilee couldn't start its program!\n"; exit(-1); } else { /* error */ cerr << "Error: couldn't fork audited program.\n"; return -1; } } <|endoftext|>