hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
693651132ff94d0597023f3ade82c653348b193b | 864 | hpp | C++ | Source/Colyseus/Compare.hpp | endel/colyseus-cocos2d-x | 96a12a15d1f70f061365769e6cc84ba9bde49c72 | [
"MIT"
] | 15 | 2019-01-24T22:05:12.000Z | 2022-01-19T08:40:42.000Z | Source/Colyseus/Compare.hpp | endel/colyseus-cocos2d-x | 96a12a15d1f70f061365769e6cc84ba9bde49c72 | [
"MIT"
] | 3 | 2019-02-09T14:19:21.000Z | 2021-05-08T01:41:38.000Z | Source/Colyseus/Compare.hpp | endel/colyseus-cocos2d-x | 96a12a15d1f70f061365769e6cc84ba9bde49c72 | [
"MIT"
] | 2 | 2019-02-05T04:52:12.000Z | 2020-03-17T17:21:16.000Z | #ifndef Compare_h
#define Compare_h
#include <sstream>
#include <iostream>
#include <stdio.h>
#include "msgpack.hpp"
class PatchObject
{
public:
PatchObject(std::vector<std::string> path, std::string op, msgpack::object value);
std::vector<std::string> path;
std::string op; // "add" | "remove" | "replace"
msgpack::object value;
msgpack::object previousValue;
};
class Compare
{
public:
static msgpack::object_handle *emptyState;
static bool containsKey(msgpack::object_map map, msgpack::object_kv key);
static std::vector<PatchObject> getPatchList(const msgpack::object tree1, const msgpack::object tree2);
static void generate(
const msgpack::object mirrorPacked,
const msgpack::object objPacked, std::vector<PatchObject> *patches,
std::vector<std::string> path
);
};
#endif /* Compare_h */
| 24.685714 | 107 | 0.696759 | [
"object",
"vector"
] |
693a263cb32e0adc16b6725e42304e0f8fade0e7 | 2,375 | cpp | C++ | codeforces/3/3C_TicTacToe.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | codeforces/3/3C_TicTacToe.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | codeforces/3/3C_TicTacToe.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <cassert>
#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <cstring>
using namespace std;
inline int illegal() {
cout << "illegal\n";
return 0;
}
inline int first() {
cout << "first\n";
return 0;
}
inline int second() {
cout << "second\n";
return 0;
}
inline int draw() {
cout << "draw\n";
return 0;
}
inline int fwin() {
cout << "the first player won\n";
return 0;
}
inline int swin() {
cout << "the second player won\n";
return 0;
}
string A[3];
bool is_win(char c) {
for (int i=0; i<3; ++i) {
bool ok = true;
for (int j=0; j<3; ++j) {
if (A[i][j] != c) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
for (int j=0; j<3; ++j) {
bool ok = true;
for (int i=0; i<3; ++i) {
if (A[i][j] != c) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
int i = 0;
int j = 0;
int di = 1;
int dj = 1;
int k = 0;
bool ok = true;
while (k < 3) {
if (A[i][j] != c) {
ok = false;
break;
}
i += di;
j += dj;
++k;
}
if (ok) {
return true;
}
dj = -1;
i = 0;
j = 2;
k = 0;
ok = true;
while (k < 3) {
if (A[i][j] != c) {
ok = false;
break;
}
i += di;
j += dj;
++k;
}
return ok;
}
int main() {
for (int i=0; i<3; ++i) {
cin >> A[i];
}
int x = 0, o = 0;
for (int i=0; i<3; ++i) {
for (int j=0; j<3; ++j) {
if (A[i][j] == 'X') {
++x;
} else if (A[i][j] == '0') {
++o;
}
}
}
if (!(x==o || x==o+1)) {
return illegal();
}
bool xwin = x>=3 && is_win('X');
bool owin = o>=3 && is_win('0');
if (xwin && x==o || owin && x==o+1 || xwin && owin) {
return illegal();
}
if (xwin) {
return fwin();
}
if (owin) {
return swin();
}
if (x+o == 9) {
return draw();
}
return x==o ? first() : second();
}
| 17.723881 | 57 | 0.365895 | [
"vector"
] |
6941ccf4952ac92b4d73786c1e4a5b2b89c76929 | 27,054 | cc | C++ | mysql-server/storage/ndb/plugin/ha_ndbinfo.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/plugin/ha_ndbinfo.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/plugin/ha_ndbinfo.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /*
Copyright (c) 2009, 2020, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "storage/ndb/plugin/ha_ndbinfo.h"
#include <mysql/plugin.h>
#include "my_compiler.h"
#include "my_dbug.h"
#include "sql/current_thd.h"
#include "sql/derror.h" // ER_THD
#include "sql/field.h"
#include "sql/sql_class.h"
#include "sql/sql_table.h" // build_table_filename
#include "sql/table.h"
#include "storage/ndb/include/ndbapi/ndb_cluster_connection.hpp"
#include "storage/ndb/plugin/ndb_dummy_ts.h"
#include "storage/ndb/plugin/ndb_log.h"
#include "storage/ndb/plugin/ndb_tdc.h"
#include "storage/ndb/src/ndbapi/NdbInfo.hpp"
static MYSQL_THDVAR_UINT(
max_rows, /* name */
PLUGIN_VAR_RQCMDARG,
"Specify max number of rows to fetch per roundtrip to cluster",
NULL, /* check func. */
NULL, /* update func. */
10, /* default */
1, /* min */
256, /* max */
0 /* block */
);
static MYSQL_THDVAR_UINT(
max_bytes, /* name */
PLUGIN_VAR_RQCMDARG,
"Specify approx. max number of bytes to fetch per roundtrip to cluster",
NULL, /* check func. */
NULL, /* update func. */
0, /* default */
0, /* min */
65535, /* max */
0 /* block */
);
static MYSQL_THDVAR_BOOL(show_hidden, /* name */
PLUGIN_VAR_RQCMDARG,
"Control if tables should be visible or not",
NULL, /* check func. */
NULL, /* update func. */
false /* default */
);
static char *opt_ndbinfo_dbname = const_cast<char *>("ndbinfo");
static MYSQL_SYSVAR_STR(database, /* name */
opt_ndbinfo_dbname, /* var */
PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
"Name of the database used by ndbinfo",
NULL, /* check func. */
NULL, /* update func. */
NULL /* default */
);
static char *opt_ndbinfo_table_prefix = const_cast<char *>("ndb$");
static MYSQL_SYSVAR_STR(table_prefix, /* name */
opt_ndbinfo_table_prefix, /* var */
PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
"Prefix to use for all virtual tables loaded from NDB",
NULL, /* check func. */
NULL, /* update func. */
NULL /* default */
);
static Uint32 opt_ndbinfo_version = NDB_VERSION_D;
static MYSQL_SYSVAR_UINT(version, /* name */
opt_ndbinfo_version, /* var */
PLUGIN_VAR_NOCMDOPT | PLUGIN_VAR_READONLY |
PLUGIN_VAR_NOPERSIST,
"Compile version for ndbinfo", NULL, /* check func. */
NULL, /* update func. */
0, /* default */
0, /* min */
0, /* max */
0 /* block */
);
static bool opt_ndbinfo_offline;
static void offline_update(THD *, SYS_VAR *, void *, const void *save) {
DBUG_TRACE;
const bool new_offline = (*(static_cast<const bool *>(save)) != 0);
if (new_offline == opt_ndbinfo_offline) {
// No change
return;
}
// Set offline mode, any tables opened from here on will
// be opened in the new mode
opt_ndbinfo_offline = new_offline;
// Close any open tables which may be in the old mode
(void)ndb_tdc_close_cached_tables();
}
static MYSQL_SYSVAR_BOOL(offline, /* name */
opt_ndbinfo_offline, /* var */
PLUGIN_VAR_NOCMDOPT,
"Set ndbinfo in offline mode, tables and views can "
"be opened even if they don't exist or have different "
"definition in NDB. No rows will be returned.",
NULL, /* check func. */
offline_update, /* update func. */
0 /* default */
);
static NdbInfo *g_ndbinfo;
extern Ndb_cluster_connection *g_ndb_cluster_connection;
static bool ndbcluster_is_disabled(void) {
/*
ndbinfo uses the same connection as ndbcluster
to avoid using up another nodeid, this also means that
if ndbcluster is not enabled, ndbinfo won't start
*/
if (g_ndb_cluster_connection) return false;
assert(g_ndbinfo == NULL);
return true;
}
static handler *create_handler(handlerton *hton, TABLE_SHARE *table, bool,
MEM_ROOT *mem_root) {
return new (mem_root) ha_ndbinfo(hton, table);
}
struct ha_ndbinfo_impl {
const NdbInfo::Table *m_table;
NdbInfoScanOperation *m_scan_op;
Vector<const NdbInfoRecAttr *> m_columns;
bool m_first_use;
enum struct Table_Status {
CLOSED,
OFFLINE_NDBINFO_OFFLINE, // Table offline as ndbinfo is offline
OFFLINE_DISCONNECTED, // Table offline as cluster is disconnected
OFFLINE_UPGRADING, // Table offline due to an ongoing upgrade
OPEN // Table is online and accessible
} m_status;
ha_ndbinfo_impl()
: m_table(nullptr),
m_scan_op(nullptr),
m_first_use(true),
m_status(Table_Status::CLOSED) {}
};
ha_ndbinfo::ha_ndbinfo(handlerton *hton, TABLE_SHARE *table_arg)
: handler(hton, table_arg), m_impl(*new ha_ndbinfo_impl) {}
ha_ndbinfo::~ha_ndbinfo() { delete &m_impl; }
enum ndbinfo_error_codes { ERR_INCOMPAT_TABLE_DEF = 40001 };
static struct error_message {
int error;
const char *message;
} error_messages[] = {
{ERR_INCOMPAT_TABLE_DEF, "Incompatible table definitions"},
{HA_ERR_NO_CONNECTION, "Connection to NDB failed"},
{0, 0}};
static const char *find_error_message(int error) {
struct error_message *err = error_messages;
while (err->error && err->message) {
if (err->error == error) {
assert(err->message);
return err->message;
}
err++;
}
return NULL;
}
static int err2mysql(int error) {
DBUG_TRACE;
DBUG_PRINT("enter", ("error: %d", error));
assert(error != 0);
switch (error) {
case NdbInfo::ERR_ClusterFailure:
return HA_ERR_NO_CONNECTION;
break;
case NdbInfo::ERR_OutOfMemory:
return HA_ERR_OUT_OF_MEM;
break;
default:
break;
}
{
char errbuf[MYSQL_ERRMSG_SIZE];
push_warning_printf(current_thd, Sql_condition::SL_WARNING, ER_GET_ERRNO,
ER_THD(current_thd, ER_GET_ERRNO), error,
my_strerror(errbuf, MYSQL_ERRMSG_SIZE, error));
}
return HA_ERR_INTERNAL_ERROR;
}
bool ha_ndbinfo::get_error_message(int error, String *buf) {
DBUG_TRACE;
DBUG_PRINT("enter", ("error: %d", error));
const char *message = find_error_message(error);
if (!message) return false;
buf->set(message, (uint32)strlen(message), &my_charset_bin);
DBUG_PRINT("exit", ("message: %s", buf->ptr()));
return false;
}
static void generate_sql(const NdbInfo::Table *ndb_tab, BaseString &sql) {
sql.appfmt("'CREATE TABLE `%s`.`%s%s` (", opt_ndbinfo_dbname,
opt_ndbinfo_table_prefix, ndb_tab->getName());
const char *separator = "";
for (unsigned i = 0; i < ndb_tab->columns(); i++) {
const NdbInfo::Column *col = ndb_tab->getColumn(i);
sql.appfmt("%s", separator);
separator = ", ";
sql.appfmt("`%s` ", col->m_name.c_str());
switch (col->m_type) {
case NdbInfo::Column::Number:
sql.appfmt("INT UNSIGNED");
break;
case NdbInfo::Column::Number64:
sql.appfmt("BIGINT UNSIGNED");
break;
case NdbInfo::Column::String:
sql.appfmt("VARCHAR(512)");
break;
default:
sql.appfmt("UNKNOWN");
assert(false);
break;
}
}
sql.appfmt(") ENGINE=NDBINFO'");
}
/*
Push a warning with explanation of the problem as well as the
proper SQL so the user can regenerate the table definition
*/
static void warn_incompatible(const NdbInfo::Table *ndb_tab, bool fatal,
const char *format, ...)
MY_ATTRIBUTE((format(printf, 3, 4)));
static void warn_incompatible(const NdbInfo::Table *ndb_tab, bool fatal,
const char *format, ...) {
BaseString msg;
DBUG_TRACE;
DBUG_PRINT("enter", ("table_name: %s, fatal: %d", ndb_tab->getName(), fatal));
DBUG_ASSERT(format != NULL);
va_list args;
char explanation[128];
va_start(args, format);
vsnprintf(explanation, sizeof(explanation), format, args);
va_end(args);
msg.assfmt(
"Table '%s%s' is defined differently in NDB, %s. The "
"SQL to regenerate is: ",
opt_ndbinfo_table_prefix, ndb_tab->getName(), explanation);
generate_sql(ndb_tab, msg);
const Sql_condition::enum_severity_level level =
(fatal ? Sql_condition::SL_WARNING : Sql_condition::SL_NOTE);
push_warning(current_thd, level, ERR_INCOMPAT_TABLE_DEF, msg.c_str());
}
int ha_ndbinfo::create(const char *, TABLE *, HA_CREATE_INFO *, dd::Table *) {
DBUG_TRACE;
return 0;
}
bool ha_ndbinfo::is_open() const {
return m_impl.m_status == ha_ndbinfo_impl::Table_Status::OPEN;
}
bool ha_ndbinfo::is_closed() const {
return m_impl.m_status == ha_ndbinfo_impl::Table_Status::CLOSED;
}
bool ha_ndbinfo::is_offline() const {
return m_impl.m_status ==
ha_ndbinfo_impl::Table_Status::OFFLINE_NDBINFO_OFFLINE ||
m_impl.m_status ==
ha_ndbinfo_impl::Table_Status::OFFLINE_DISCONNECTED ||
m_impl.m_status == ha_ndbinfo_impl::Table_Status::OFFLINE_UPGRADING;
}
int ha_ndbinfo::open(const char *name, int mode, uint, const dd::Table *) {
DBUG_TRACE;
DBUG_PRINT("enter", ("name: %s, mode: %d", name, mode));
assert(is_closed());
if (mode == O_RDWR) {
if (table->db_stat & HA_TRY_READ_ONLY) {
DBUG_PRINT("info", ("Telling server to use readonly mode"));
return EROFS; // Read only fs
}
// Find any commands that does not allow open readonly
DBUG_ASSERT(false);
}
if (opt_ndbinfo_offline || ndbcluster_is_disabled()) {
// Mark table as being offline and allow it to be opened
m_impl.m_status = ha_ndbinfo_impl::Table_Status::OFFLINE_NDBINFO_OFFLINE;
return 0;
}
int err = g_ndbinfo->openTable(name, &m_impl.m_table);
if (err) {
assert(m_impl.m_table == 0);
if (err == NdbInfo::ERR_NoSuchTable) {
if (g_ndb_cluster_connection->get_min_db_version() < NDB_VERSION_D) {
// The table does not exist but there is a data node from a lower
// version connected to this Server. This is in the middle of an upgrade
// and the possibility is that the data node does not have this ndbinfo
// table definition yet. So we open this table in an offline mode so as
// to allow the upgrade to continue further. The table will be reopened
// properly after the upgrade completes.
m_impl.m_status = ha_ndbinfo_impl::Table_Status::OFFLINE_UPGRADING;
return 0;
}
return HA_ERR_NO_SUCH_TABLE;
}
if (err == NdbInfo::ERR_ClusterFailure) {
/* Not currently connected to cluster, but open in offline mode */
m_impl.m_status = ha_ndbinfo_impl::Table_Status::OFFLINE_DISCONNECTED;
return 0;
}
return err2mysql(err);
}
/*
Check table def. to detect incompatible differences which should
return an error. Differences which only generate a warning
is checked on first use
*/
DBUG_PRINT("info", ("Comparing MySQL's table def against NDB"));
const NdbInfo::Table *ndb_tab = m_impl.m_table;
for (uint i = 0; i < table->s->fields; i++) {
const Field *field = table->field[i];
// Check if field is NULLable
if (const_cast<Field *>(field)->is_nullable() == false) {
// Only NULLable fields supported
warn_incompatible(ndb_tab, true, "column '%s' is NOT NULL",
field->field_name);
delete m_impl.m_table;
m_impl.m_table = 0;
return ERR_INCOMPAT_TABLE_DEF;
}
// Check if column exist in NDB
const NdbInfo::Column *col = ndb_tab->getColumn(field->field_name);
if (!col) {
// The column didn't exist
continue;
}
// Check compatible field and column type
bool compatible = false;
switch (col->m_type) {
case NdbInfo::Column::Number:
if (field->type() == MYSQL_TYPE_LONG) compatible = true;
break;
case NdbInfo::Column::Number64:
if (field->type() == MYSQL_TYPE_LONGLONG) compatible = true;
break;
case NdbInfo::Column::String:
if (field->type() == MYSQL_TYPE_VARCHAR) compatible = true;
break;
default:
assert(false);
break;
}
if (!compatible) {
// The column type is not compatible
warn_incompatible(ndb_tab, true, "column '%s' is not compatible",
field->field_name);
delete m_impl.m_table;
m_impl.m_table = 0;
return ERR_INCOMPAT_TABLE_DEF;
}
}
/* Increase "ref_length" to allow a whole row to be stored in "ref" */
ref_length = 0;
for (uint i = 0; i < table->s->fields; i++)
ref_length += table->field[i]->pack_length();
DBUG_PRINT("info", ("ref_length: %u", ref_length));
// Mark table as opened
m_impl.m_status = ha_ndbinfo_impl::Table_Status::OPEN;
return 0;
}
int ha_ndbinfo::close(void) {
DBUG_TRACE;
if (is_offline()) return 0;
assert(is_open());
if (m_impl.m_table) {
g_ndbinfo->closeTable(m_impl.m_table);
m_impl.m_table = NULL;
m_impl.m_status = ha_ndbinfo_impl::Table_Status::CLOSED;
}
return 0;
}
int ha_ndbinfo::rnd_init(bool scan) {
DBUG_TRACE;
DBUG_PRINT("info", ("scan: %d", scan));
if (!is_open()) {
switch (m_impl.m_status) {
case ha_ndbinfo_impl::Table_Status::OFFLINE_NDBINFO_OFFLINE: {
push_warning(current_thd, Sql_condition::SL_NOTE, 1,
"'NDBINFO' has been started in offline mode "
"since the 'NDBCLUSTER' engine is disabled "
"or @@global.ndbinfo_offline is turned on "
"- no rows can be returned");
return 0;
}
case ha_ndbinfo_impl::Table_Status::OFFLINE_DISCONNECTED:
return HA_ERR_NO_CONNECTION;
case ha_ndbinfo_impl::Table_Status::OFFLINE_UPGRADING: {
// Upgrade in progress.
push_warning(current_thd, Sql_condition::SL_NOTE, 1,
"This table is not available as the data nodes are not "
"upgraded yet - no rows can be returned");
// Close the table in MySQL Server's table definition cache to force
// reload it the next time.
const std::string db_name(table_share->db.str, table_share->db.length);
const std::string table_name(table_share->table_name.str,
table_share->table_name.length);
ndb_tdc_close_cached_table(current_thd, db_name.c_str(),
table_name.c_str());
return 0;
}
default:
// Should not happen
DBUG_ASSERT(false);
return 0;
}
}
if (m_impl.m_scan_op) {
/*
It should be impossible to come here with an already open
scan, assumption is that rnd_end() would be called to indicate
that the previous scan should be closed or perhaps like it says
in decsription of rnd_init() that it "may be called two times". Once
to open the cursor and once to position te cursor at first row.
Unfortunately the assumption and description of rnd_init() is not
correct. The rnd_init function is used on an open scan to reposition
it back to first row. For ha_ndbinfo this means closing
the scan and letting it be reopened.
*/
assert(scan); // "only makes sense if scan=1" (from rnd_init() description)
DBUG_PRINT("info", ("Closing scan to position it back to first row"));
// Release the scan operation
g_ndbinfo->releaseScanOperation(m_impl.m_scan_op);
m_impl.m_scan_op = NULL;
// Release pointers to the columns
m_impl.m_columns.clear();
}
assert(m_impl.m_scan_op == NULL); // No scan already ongoing
if (m_impl.m_first_use) {
m_impl.m_first_use = false;
/*
Check table def. and generate warnings for incompatibilites
which is allowed but should generate a warning.
(Done this late due to different code paths in MySQL Server for
prepared statement protocol, where warnings from 'handler::open'
are lost).
*/
uint fields_found_in_ndb = 0;
const NdbInfo::Table *ndb_tab = m_impl.m_table;
for (uint i = 0; i < table->s->fields; i++) {
const Field *field = table->field[i];
const NdbInfo::Column *col = ndb_tab->getColumn(field->field_name);
if (!col) {
// The column didn't exist
warn_incompatible(ndb_tab, true, "column '%s' does not exist",
field->field_name);
continue;
}
fields_found_in_ndb++;
}
if (fields_found_in_ndb < ndb_tab->columns()) {
// There are more columns available in NDB
warn_incompatible(ndb_tab, false, "there are more columns available");
}
}
if (!scan) {
// Just an init to read using 'rnd_pos'
DBUG_PRINT("info", ("not scan"));
return 0;
}
THD *thd = current_thd;
int err;
NdbInfoScanOperation *scan_op = NULL;
if ((err = g_ndbinfo->createScanOperation(m_impl.m_table, &scan_op,
THDVAR(thd, max_rows),
THDVAR(thd, max_bytes))) != 0)
return err2mysql(err);
if ((err = scan_op->readTuples()) != 0) {
// Release the scan operation
g_ndbinfo->releaseScanOperation(scan_op);
return err2mysql(err);
}
/* Read all columns specified in read_set */
for (uint i = 0; i < table->s->fields; i++) {
Field *field = table->field[i];
if (bitmap_is_set(table->read_set, i))
m_impl.m_columns.push_back(scan_op->getValue(field->field_name));
else
m_impl.m_columns.push_back(NULL);
}
if ((err = scan_op->execute()) != 0) {
// Release pointers to the columns
m_impl.m_columns.clear();
// Release the scan operation
g_ndbinfo->releaseScanOperation(scan_op);
return err2mysql(err);
}
m_impl.m_scan_op = scan_op;
return 0;
}
int ha_ndbinfo::rnd_end() {
DBUG_TRACE;
if (is_offline()) return 0;
assert(is_open());
if (m_impl.m_scan_op) {
g_ndbinfo->releaseScanOperation(m_impl.m_scan_op);
m_impl.m_scan_op = NULL;
}
m_impl.m_columns.clear();
return 0;
}
int ha_ndbinfo::rnd_next(uchar *buf) {
int err;
DBUG_TRACE;
if (is_offline()) return HA_ERR_END_OF_FILE;
assert(is_open());
if (!m_impl.m_scan_op) {
/*
It should be impossible to come here without a scan operation.
But apparently it's not safe to assume that rnd_next() isn't
called even though rnd_init() returned an error. Thus double check
that the scan operation exists and bail out in case it doesn't.
*/
return HA_ERR_INTERNAL_ERROR;
}
if ((err = m_impl.m_scan_op->nextResult()) == 0) return HA_ERR_END_OF_FILE;
if (err != 1) return err2mysql(err);
unpack_record(buf);
return 0;
}
int ha_ndbinfo::rnd_pos(uchar *buf, uchar *pos) {
DBUG_TRACE;
assert(is_open());
assert(m_impl.m_scan_op == NULL); // No scan started
/* Copy the saved row into "buf" and set all fields to not null */
memcpy(buf, pos, ref_length);
for (uint i = 0; i < table->s->fields; i++) table->field[i]->set_notnull();
return 0;
}
void ha_ndbinfo::position(const uchar *record) {
DBUG_TRACE;
assert(is_open());
assert(m_impl.m_scan_op);
/* Save away the whole row in "ref" */
memcpy(ref, record, ref_length);
}
int ha_ndbinfo::info(uint) {
DBUG_TRACE;
return 0;
}
void ha_ndbinfo::unpack_record(uchar *dst_row) {
DBUG_TRACE;
ptrdiff_t dst_offset = dst_row - table->record[0];
for (uint i = 0; i < table->s->fields; i++) {
Field *field = table->field[i];
const NdbInfoRecAttr *record = m_impl.m_columns[i];
if (record && !record->isNULL()) {
field->set_notnull();
field->move_field_offset(dst_offset);
switch (field->type()) {
case (MYSQL_TYPE_VARCHAR): {
DBUG_PRINT("info", ("str: %s", record->c_str()));
Field_varstring *vfield = (Field_varstring *)field;
/* Field_bit in DBUG requires the bit set in write_set for store(). */
my_bitmap_map *old_map =
dbug_tmp_use_all_columns(table, table->write_set);
(void)vfield->store(record->c_str(),
MIN(record->length(), field->field_length) - 1,
field->charset());
dbug_tmp_restore_column_map(table->write_set, old_map);
break;
}
case (MYSQL_TYPE_LONG): {
memcpy(field->field_ptr(), record->ptr(), sizeof(Uint32));
break;
}
case (MYSQL_TYPE_LONGLONG): {
memcpy(field->field_ptr(), record->ptr(), sizeof(Uint64));
break;
}
default:
ndb_log_error("Found unexpected field type %u", field->type());
break;
}
field->move_field_offset(-dst_offset);
} else {
field->set_null();
}
}
}
static int ndbinfo_find_files(handlerton *, THD *thd, const char *db,
const char *, const char *, bool dir,
List<LEX_STRING> *files) {
DBUG_TRACE;
DBUG_PRINT("enter", ("db: '%s', dir: %d", db, dir));
const bool show_hidden = THDVAR(thd, show_hidden);
if (show_hidden) return 0; // Don't filter out anything
if (dir) {
if (!ndbcluster_is_disabled()) return 0;
// Hide our database when ndbcluster is disabled
LEX_STRING *dir_name;
List_iterator<LEX_STRING> it(*files);
while ((dir_name = it++)) {
if (strcmp(dir_name->str, opt_ndbinfo_dbname)) continue;
DBUG_PRINT("info", ("Hiding own database '%s'", dir_name->str));
it.remove();
}
return 0;
}
DBUG_ASSERT(db);
if (strcmp(db, opt_ndbinfo_dbname)) return 0; // Only hide files in "our" db
/* Hide all files that start with "our" prefix */
LEX_STRING *file_name;
List_iterator<LEX_STRING> it(*files);
while ((file_name = it++)) {
if (is_prefix(file_name->str, opt_ndbinfo_table_prefix)) {
DBUG_PRINT("info", ("Hiding '%s'", file_name->str));
it.remove();
}
}
return 0;
}
extern bool ndbinfo_define_dd_tables(List<const Plugin_table> *);
static bool ndbinfo_dict_init(dict_init_mode_t, uint,
List<const Plugin_table> *table_list,
List<const Plugin_tablespace> *) {
return ndbinfo_define_dd_tables(table_list);
}
static int ndbinfo_init(void *plugin) {
DBUG_TRACE;
handlerton *hton = (handlerton *)plugin;
hton->create = create_handler;
hton->flags = HTON_TEMPORARY_NOT_SUPPORTED | HTON_ALTER_NOT_SUPPORTED;
hton->find_files = ndbinfo_find_files;
hton->dict_init = ndbinfo_dict_init;
{
// Install dummy callbacks to avoid writing <tablename>_<id>.SDI files
// in the data directory, those are just cumbersome having to delete
// and or rename on the other MySQL servers
hton->sdi_create = ndb_dummy_ts::sdi_create;
hton->sdi_drop = ndb_dummy_ts::sdi_drop;
hton->sdi_get_keys = ndb_dummy_ts::sdi_get_keys;
hton->sdi_get = ndb_dummy_ts::sdi_get;
hton->sdi_set = ndb_dummy_ts::sdi_set;
hton->sdi_delete = ndb_dummy_ts::sdi_delete;
}
if (ndbcluster_is_disabled()) {
// Starting in limited mode since ndbcluster is disabled
return 0;
}
char prefix[FN_REFLEN];
build_table_filename(prefix, sizeof(prefix) - 1, opt_ndbinfo_dbname,
opt_ndbinfo_table_prefix, "", 0);
DBUG_PRINT("info", ("prefix: '%s'", prefix));
assert(g_ndb_cluster_connection);
g_ndbinfo =
new (std::nothrow) NdbInfo(g_ndb_cluster_connection, prefix,
opt_ndbinfo_dbname, opt_ndbinfo_table_prefix);
if (!g_ndbinfo) {
ndb_log_error("Failed to create NdbInfo");
return 1;
}
if (!g_ndbinfo->init()) {
ndb_log_error("Failed to init NdbInfo");
delete g_ndbinfo;
g_ndbinfo = NULL;
return 1;
}
return 0;
}
static int ndbinfo_deinit(void *) {
DBUG_TRACE;
if (g_ndbinfo) {
delete g_ndbinfo;
g_ndbinfo = NULL;
}
return 0;
}
SYS_VAR *ndbinfo_system_variables[] = {MYSQL_SYSVAR(max_rows),
MYSQL_SYSVAR(max_bytes),
MYSQL_SYSVAR(show_hidden),
MYSQL_SYSVAR(database),
MYSQL_SYSVAR(table_prefix),
MYSQL_SYSVAR(version),
MYSQL_SYSVAR(offline),
NULL};
struct st_mysql_storage_engine ndbinfo_storage_engine = {
MYSQL_HANDLERTON_INTERFACE_VERSION};
struct st_mysql_plugin ndbinfo_plugin = {
MYSQL_STORAGE_ENGINE_PLUGIN,
&ndbinfo_storage_engine,
"ndbinfo",
PLUGIN_AUTHOR_ORACLE,
"MySQL Cluster system information storage engine",
PLUGIN_LICENSE_GPL,
ndbinfo_init, /* plugin init */
NULL, /* plugin uninstall check */
ndbinfo_deinit, /* plugin deinit */
0x0001, /* plugin version */
NULL, /* status variables */
ndbinfo_system_variables, /* system variables */
NULL, /* config options */
0};
template class Vector<const NdbInfoRecAttr *>;
| 32.054502 | 80 | 0.618984 | [
"vector"
] |
6943def6537d4e60570dae158468d619dce6fcd3 | 3,361 | cpp | C++ | er_perception/src/er_pointcloud_to_2d_node.cpp | RAS18G3/everything_robot | 7453610dc68babac3a397a1f08754b473ef99c67 | [
"MIT"
] | null | null | null | er_perception/src/er_pointcloud_to_2d_node.cpp | RAS18G3/everything_robot | 7453610dc68babac3a397a1f08754b473ef99c67 | [
"MIT"
] | 4 | 2018-10-07T11:37:26.000Z | 2018-11-29T20:52:19.000Z | er_perception/src/er_pointcloud_to_2d_node.cpp | RAS18G3/everything_robot | 7453610dc68babac3a397a1f08754b473ef99c67 | [
"MIT"
] | null | null | null | #include "er_pointcloud_to_2d_node.h"
PointCloudTo2DNode::PointCloudTo2DNode() : nh_() {
}
PointCloudTo2DNode::~PointCloudTo2DNode() {
}
void PointCloudTo2DNode::pointcloud_cb(const PointCloud::ConstPtr& msg) {
PointCloud transformed_pointcloud;
PointCloud modified_pointcloud;
PointCloud map_pointcloud;
// transform the point cloud such that ground is parallel to the floor
pcl_ros::transformPointCloud("/base_link", pcl_conversions::fromPCL(msg->header.stamp), *msg, "/camera_depth_frame", transformed_pointcloud, tf_listener_);
pcl_ros::transformPointCloud("/map", pcl_conversions::fromPCL(msg->header.stamp), *msg, "/camera_depth_frame", map_pointcloud, tf_listener_);
for(auto it=map_pointcloud.begin(); it != map_pointcloud.end(); ++it) {
if(!std::isnan(it->x)) {
if(it->x >= safearea_xmin_-0.01 && it->x <= safearea_xmax_+0.01 && it->y <= safearea_ymax_+0.01 && it->y >= safearea_ymin_-0.01) {
for(auto it=transformed_pointcloud.begin(); it != transformed_pointcloud.end(); ++it) {
if(!std::isnan(it->x)) {
if(it-> z > min_height_ && it->z < min_height_+range_ && std::sqrt(std::pow(it->x,2)+std::pow(it->y,2)) < 0.6) {
it->z = 0;
modified_pointcloud.push_back(*it);
break;
}
}
}
break;
}
else {
// remove all nan entrise (which correspond to now point), and threshold based on the defined height
for(auto it=transformed_pointcloud.begin(); it != transformed_pointcloud.end(); ++it) {
if(!std::isnan(it->x)) {
if(it-> z > min_height_ && it->z < min_height_+range_ && std::sqrt(std::pow(it->x,2)+std::pow(it->y,2)) < 0.6) {
it->z = 0;
modified_pointcloud.push_back(*it);
}
}
}
break;
}
}
}
// set the reference frame
// this could also be map/odom, but this way no transform is required to get the distance from this points to the robot
modified_pointcloud.header.frame_id = "/base_link";
modified_pointcloud.header.stamp = msg->header.stamp;
pointcloud_publisher_.publish(modified_pointcloud);
}
void PointCloudTo2DNode::init_node() {
std::string camera_pointcloud_topic;
std::string out_pointcloud_topic;
ros::param::param<double>("~min_height", min_height_, 0);
ros::param::param<double>("~range", range_, 0.01);
ros::param::param<double>("/safe_area/x_min", safearea_xmin_, 0.0);
ros::param::param<double>("/safe_area/x_max", safearea_xmax_, 0.5);
ros::param::param<double>("/safe_area/y_min", safearea_ymin_, 0.0);
ros::param::param<double>("/safe_area/y_max", safearea_ymax_, 0.5);
ros::param::param<std::string>("~camera_pointcloud_topic", camera_pointcloud_topic, "/camera/depth/points");
ros::param::param<std::string>("~out_pointcloud_topic", out_pointcloud_topic, "/camera/pointcloud_2d");
pointcloud_subsriber_ = nh_.subscribe<PointCloud>(camera_pointcloud_topic, 1, &PointCloudTo2DNode::pointcloud_cb, this);
pointcloud_publisher_ = nh_.advertise<PointCloud>(out_pointcloud_topic, 1);
}
void PointCloudTo2DNode::run_node() {
init_node();
ros::spin();
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "er_slam_node");
PointCloudTo2DNode pointcloud_to_2d_node;
pointcloud_to_2d_node.run_node();
return 0;
}
| 36.934066 | 157 | 0.670336 | [
"transform"
] |
69514aa98b5f52e1078bf509467c156d4b88779a | 1,570 | cpp | C++ | production_apps/ESPRESO/src/input/openfoam/foam/face.cpp | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 2 | 2020-11-25T13:10:11.000Z | 2021-03-15T20:26:35.000Z | production_apps/ESPRESO/src/input/openfoam/foam/face.cpp | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | null | null | null | production_apps/ESPRESO/src/input/openfoam/foam/face.cpp | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 1 | 2018-09-30T19:04:38.000Z | 2018-09-30T19:04:38.000Z | #include "face.h"
using namespace espreso::input;
Face::Face()
{
numberOfPoints =0;
}
Face::~Face()
{
//dtor
}
ParseError* Face::parse(Tokenizer &ts)
{
PARSE_GUARD(ts.readeslocal(numberOfPoints));
PARSE_GUARD(ts.consumeChar('('));
PARSE_GUARD(ts.readeslocal(p[0]));
PARSE_GUARD(ts.readeslocal(p[1]));
PARSE_GUARD(ts.readeslocal(p[2]));
if (numberOfPoints == 4)
{
PARSE_GUARD(ts.readeslocal(p[3]));
}
else if (numberOfPoints > 4)
{
return new ParseError("Face with more than 4 corners encountered.", "object: Face");
}
PARSE_GUARD(ts.consumeChar(')'));
return NULL;
}
bool Face::containsLine(eslocal x, eslocal y)
{
for(int i=0; i<numberOfPoints; i++)
{
if (p[i]==x)
{
if (p[(i+1)%numberOfPoints]==y) return true;
if (p[(i-1+numberOfPoints)%numberOfPoints]==y) return true;
}
}
return false;
}
ParseError* Face::nextPoint(eslocal x, eslocal y, eslocal &next)
{
for(int i=0; i<numberOfPoints; i++)
{
if (p[i]==x)
{
if (p[(i+1)%numberOfPoints]==y)
{
next = p[(i+2)%numberOfPoints];
return NULL;
}
if (p[(i-1+numberOfPoints)%numberOfPoints]==y)
{
next = p[(i-2+numberOfPoints)%numberOfPoints];
return NULL;
}
}
}
std::stringstream ss;
ss<<"No next point for line ("<<x<<","<<y<<") in Face: "<<this;
return new ParseError(ss.str(), "Faces");
}
| 22.428571 | 92 | 0.536306 | [
"object"
] |
69544214e85dd1cde7a4face967b5bd6e46fe994 | 5,842 | cc | C++ | src/PowerGen.cc | oseikuffuor1/mgmol | 5442962959a54c919a5e18c4e78db6ce41ee8f4e | [
"BSD-3-Clause-LBNL",
"FSFAP"
] | null | null | null | src/PowerGen.cc | oseikuffuor1/mgmol | 5442962959a54c919a5e18c4e78db6ce41ee8f4e | [
"BSD-3-Clause-LBNL",
"FSFAP"
] | null | null | null | src/PowerGen.cc | oseikuffuor1/mgmol | 5442962959a54c919a5e18c4e78db6ce41ee8f4e | [
"BSD-3-Clause-LBNL",
"FSFAP"
] | null | null | null | // Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory.
// LLNL-CODE-743438
// All rights reserved.
// This file is part of MGmol. For details, see https://github.com/llnl/mgmol.
// Please also read this link https://github.com/llnl/mgmol/LICENSE
#include "PowerGen.h"
#include "Control.h"
#include "DistVector.h"
#include "GramMatrix.h"
#include "mputils.h"
#include "random.h"
#include <vector>
Timer PowerGen::compute_tm_("PowerGen::compute");
/* Use the power method to compute the extents of the spectrum of the
* generalized eigenproblem. In order to use a residual-based convergence
* criterion in an efficient way, we delay normalization of the vectors to avoid
* multiple matvecs. NOTE: We are only interested in the eigenvalues, so the
* final eigenvector may not be normalized.
*/
void PowerGen::computeGenEigenInterval(dist_matrix::DistMatrix<double>& mat,
GramMatrix& gm, std::vector<double>& interval, const int maxits,
const double pad)
{
srand(13579);
Control& ct = *(Control::instance());
compute_tm_.start();
interval.clear();
dist_matrix::DistMatrix<double> smat(gm.getMatrix());
// use the power method to get the eigenvalue interval
const int m = mat.m(); // number of global rows
const int mloc = mat.mloc(); // number of local rows
const double one = 1., zero = 0.;
// shift
mat.axpy(shift_, smat);
// initialize solution data
// initial guess
dist_matrix::DistVector<double> sol("sol", m);
sol.assign(vec1_); // initialize local solution data
// new solution
dist_matrix::DistVector<double> new_sol("new_sol", m);
std::vector<double> vec(mloc, 0.);
new_sol.assign(vec);
// get norm of initial sol
double alpha = sol.nrm2();
double gamma = 1. / alpha;
#ifdef DEBUG
if (onpe0)
{
std::cout << "e1:: ITER 0:: alpha = " << alpha << " beta = " << beta
<< " shift = " << shift_ << std::endl;
}
#endif
// residual
dist_matrix::DistVector<double> res(new_sol);
// initial eigenvalue estimate (for shifted system)
double beta = sol.dot(new_sol);
// compute first extent
int iter1 = 0;
// loop
for (int i = 0; i < maxits; i++)
{
iter1++;
// First compute residual for convergence check
res.gemv('N', one, mat, sol, zero);
// store matvec result appropriately scaled for later reuse
new_sol.clear();
new_sol.axpy(gamma, res);
// Compute residual: res = beta*S*x - mat*x
res.gemm('N', 'N', beta, smat, sol, -1.);
// compute residual norm
double resnorm = res.nrm2();
// check for convergence
if (resnorm < 1.0e-2) break;
// apply inverse to new_sol to update solution
// No need to do matvec with scaled copy of sol.
// Reuse previously stored matvec from residual calculation
gm.applyInv(new_sol); // can also do gemv with gm_->getInverse()
// compute 'shifted' eigenvalue
beta = sol.dot(new_sol);
// scale beta by gamma to account for normalizing sol
beta *= gamma;
// update solution data
sol = new_sol;
// compute norm and update gamma
alpha = sol.nrm2();
gamma = 1. / alpha;
}
// compute first extent (eigenvalue)
double e1 = beta - shift_;
sol.copyDataToVector(vec1_);
// shift matrix by beta and compute second extent
// store shift
double shft_e1 = -beta;
mat.axpy(shft_e1, smat);
// reset data and begin loop
sol.assign(vec2_);
new_sol.assign(vec);
alpha = sol.nrm2();
gamma = 1. / alpha;
beta = sol.dot(new_sol);
// loop
#ifdef DEBUG
if (onpe0)
{
std::cout << "e2:: ITER 0:: alpha = " << alpha << " beta = " << beta
<< std::endl;
}
#endif
int iter2 = 0;
for (int i = 0; i < maxits; i++)
{
iter2++;
// First compute residual for convergence check
res.gemv('N', one, mat, sol, zero);
// store matvec result appropriately scaled for later reuse
new_sol.clear();
new_sol.axpy(gamma, res);
// Compute residual: res = beta*S*x - mat*x
res.gemm('N', 'N', beta, smat, sol, -1.);
// compute residual norm
double resnorm = res.nrm2();
// check for convergence
if (resnorm < 1.0e-2) break;
// apply inverse to new_sol to update solution
// No need to do matvec with scaled copy of sol.
// Reuse previously stored matvec from residual calculation
gm.applyInv(new_sol); // can also do gemv with gm_->getInverse()
// compute 'shifted' eigenvalue
beta = sol.dot(new_sol);
// scale beta by gamma to account for not normalizing sol
beta *= gamma;
// update solution data
sol = new_sol;
// compute norm and update gamma
alpha = sol.nrm2();
gamma = 1. / alpha;
}
// compute second extent
double e2 = beta - shft_e1 - shift_;
sol.copyDataToVector(vec2_);
// save results
double tmp = e1;
e1 = std::min(tmp, e2);
e2 = std::max(tmp, e2);
double padding = pad * (e2 - e1);
if (onpe0 && ct.verbose > 1)
{
std::cout << "'Generalized' Power method Eigen "
"intervals******************** = ( "
<< e1 << ", " << e2 << ")\n"
<< "iter1 = " << iter1 << ", iter2 = " << iter2
<< ", padding = " << padding << std::endl;
}
e1 -= padding;
e2 += padding;
interval.push_back(e1);
interval.push_back(e2);
// update shft
shift_ = std::max(fabs(e1), fabs(e2));
compute_tm_.stop();
}
| 30.747368 | 80 | 0.586101 | [
"vector"
] |
695af9473cdb33eab5f942ad920d44866c63d986 | 7,294 | cpp | C++ | demos/FiniteVolume/AMR_Burgers_Hat.cpp | hpc-maths/samurai | 30627951044aa3e31f94445286521c63a0011c4b | [
"BSD-3-Clause"
] | 13 | 2021-01-07T19:23:42.000Z | 2022-01-26T13:07:41.000Z | demos/FiniteVolume/AMR_Burgers_Hat.cpp | gouarin/samurai | 7ae877997e8b9bdb85b84acaabb3c0483ff78689 | [
"BSD-3-Clause"
] | 1 | 2021-07-04T17:30:47.000Z | 2021-07-04T17:30:47.000Z | demos/FiniteVolume/AMR_Burgers_Hat.cpp | gouarin/samurai | 7ae877997e8b9bdb85b84acaabb3c0483ff78689 | [
"BSD-3-Clause"
] | 2 | 2021-01-07T15:54:49.000Z | 2021-02-24T13:11:42.000Z | // Copyright 2021 SAMURAI TEAM. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include <iostream>
#include <fmt/format.h>
#include <samurai/box.hpp>
#include <samurai/field.hpp>
#include <samurai/hdf5.hpp>
#include <samurai/amr/mesh.hpp>
#include <samurai/algorithm/update.hpp>
#include <samurai/algorithm/graduation.hpp>
#include "stencil_field.hpp"
#include "../LBM/boundary_conditions.hpp"
template <class Mesh>
auto init_solution(Mesh & mesh)
{
using mesh_id_t = typename Mesh::mesh_id_t;
auto phi = samurai::make_field<double, 1>("phi", mesh);
phi.fill(0);
samurai::for_each_cell(mesh[mesh_id_t::cells], [&](auto &cell)
{
auto center = cell.center();
double x = center[0];
double u = 0.;
// Initial hat solution
if (x < -1. or x > 1.) {
u = 0.;
}
else
{
u = (x < 0.) ? (1 + x) : (1 - x);
}
// phi[cell] = u;
phi[cell] = std::exp(-20.*x*x);
});
return phi;
}
template<class Field, class Tag>
void AMR_criteria(Field& f, Tag& tag)
{
auto mesh = f.mesh();
using mesh_id_t = typename Field::mesh_t::mesh_id_t;
std::size_t min_level = mesh.min_level();
std::size_t max_level = mesh.max_level();
tag.fill(static_cast<int>(samurai::CellFlag::keep)); // Important
for (std::size_t level = min_level; level <= max_level; ++level) {
double dx = 1./(1 << level);
auto leaves = samurai::intersection(mesh[mesh_id_t::cells][level],
mesh[mesh_id_t::cells][level]);
leaves([&](auto& interval, auto& ) {
auto k = interval;
auto der_approx = xt::eval(xt::abs((f(level, k + 1) - f(level, k - 1)) / (2.*dx)));
auto der_der_approx = xt::eval(xt::abs((f(level, k + 1) - 2.*f(level, k) + f(level, k - 1)) / (dx*dx)));
auto der_plus = xt::eval(xt::abs((f(level, k + 1) - f(level, k)) / (dx)));
auto der_minus = xt::eval(xt::abs((f(level, k) - f(level, k - 1)) / (dx)));
// auto mask = xt::abs(f(level, k)) > 0.001;
auto mask = der_approx > 0.01;
// auto mask = der_der_approx > 0.01;
// auto mask = (xt::abs(der_plus) - xt::abs(der_minus)) > 0.001;
if (level == max_level) {
xt::masked_view(tag(level, k), mask) = static_cast<int>(samurai::CellFlag::keep);
xt::masked_view(tag(level, k), !mask) = static_cast<int>(samurai::CellFlag::coarsen);
}
else
{
if (level == min_level) {
tag(level, k) = static_cast<int>(samurai::CellFlag::keep);
}
else
{
xt::masked_view(tag(level, k), mask) = static_cast<int>(samurai::CellFlag::refine);
xt::masked_view(tag(level, k), !mask) = static_cast<int>(samurai::CellFlag::coarsen);
}
}
});
}
}
template<class Field>
void save_solution(Field &f, std::size_t ite)
{
// using Config = typename Field::Config;
auto mesh = f.mesh();
using mesh_id_t = typename Field::mesh_t::mesh_id_t;
std::size_t min_level = mesh.min_level();
std::size_t max_level = mesh.max_level();
auto level_ = samurai::make_field<double, 1>("level", mesh);
samurai::for_each_cell(mesh[mesh_id_t::cells], [&](auto &cell)
{
level_[cell] = static_cast<double>(cell.level);
});
samurai::save(fmt::format("Burgers_AMR_lmin-{}_lmax-{}_ite-{}", min_level, max_level, ite), mesh, f, level_);
}
template <class Field>
void flux_correction(Field& phi_np1, const Field& phi_n, double dt)
{
using mesh_t = typename Field::mesh_t;
using mesh_id_t = typename mesh_t::mesh_id_t;
using interval_t = typename mesh_t::interval_t;
auto mesh = phi_np1.mesh();
std::size_t min_level = mesh[mesh_id_t::cells].min_level();
std::size_t max_level = mesh[mesh_id_t::cells].max_level();
double dx = 1./(1 << max_level);
for (std::size_t level = min_level; level < max_level; ++level)
{
double dx_loc = 1./(1<<level);
xt::xtensor_fixed<int, xt::xshape<1>> stencil;
stencil = {{-1}};
auto subset_right = samurai::intersection(samurai::translate(mesh[mesh_id_t::cells][level+1], stencil),
mesh[mesh_id_t::cells][level])
.on(level);
subset_right([&](const auto& i, const auto& )
{
phi_np1(level, i) = phi_np1(level, i) + dt/dx_loc * (samurai::upwind_Burgers_op<interval_t>(level, i).right_flux(phi_n, dx/dt)
-samurai::upwind_Burgers_op<interval_t>(level+1, 2*i+1).right_flux(phi_n, dx/dt));
});
stencil = {{1}};
auto subset_left = samurai::intersection(samurai::translate(mesh[mesh_id_t::cells][level+1], stencil),
mesh[mesh_id_t::cells][level])
.on(level);
subset_left([&](const auto& i, const auto& )
{
phi_np1(level, i) = phi_np1(level, i) - dt/dx_loc * (samurai::upwind_Burgers_op<interval_t>(level, i).left_flux(phi_n, dx/dt)
-samurai::upwind_Burgers_op<interval_t>(level+1, 2*i).left_flux(phi_n, dx/dt));
});
}
}
int main(int argc, char *argv[])
{
constexpr std::size_t dim = 1;
std::size_t start_level = 6;
std::size_t min_level = 1;
std::size_t max_level = 6;
samurai::Box<double, dim> box({-3}, {3});
using Config = samurai::amr::Config<dim>;
samurai::amr::Mesh<Config> mesh(box, start_level, min_level, max_level);
using mesh_id_t = typename Config::mesh_id_t;
auto phi = init_solution(mesh);
auto update_bc = [](std::size_t level, auto& field)
{
update_bc_D2Q4_3_Euler_constant_extension(field, level);
};
xt::xtensor_fixed<int, xt::xshape<2, 1>> stencil_grad{{ 1 }, { -1 }};
double Tf = 1.5; // We have blowup at t = 1
double dx = 1./(1 << max_level);
double dt = 0.99 * dx;
double t = 0.;
std::size_t it = 0;
while (t < Tf)
{
std::cout << "Iteration = " << it << " Time = " << t <<std::endl;
std::size_t ite_adapt = 0;
while(1)
{
std::cout << "\tmesh adaptation: " << ite_adapt++ << std::endl;
samurai::update_ghost(update_bc, phi);
auto tag = samurai::make_field<int, 1>("tag", mesh);
AMR_criteria(phi, tag);
samurai::graduation(tag, stencil_grad);
if (samurai::update_field(tag, phi))
{
break;
}
}
// Numerical scheme
samurai::update_ghost(update_bc, phi);
auto phinp1 = samurai::make_field<double, 1>("phi", mesh);
phinp1 = phi - dt * samurai::upwind_Burgers(phi, dx/dt);
flux_correction(phinp1, phi, dt);
std::swap(phi.array(), phinp1.array());
save_solution(phi, it);
t += dt;
it += 1;
}
return 0;
}
| 32.5625 | 146 | 0.548807 | [
"mesh"
] |
696165bbf4c53bacf9b648adeadeecb3f00b2dbc | 7,828 | cpp | C++ | Eunoia-Engine/Src/Eunoia/Core/Engine.cpp | EunoiaGames/Eunoia-Dev | 94edea774d1de05dc6a0c24ffdd3bb91b91a3346 | [
"Apache-2.0"
] | null | null | null | Eunoia-Engine/Src/Eunoia/Core/Engine.cpp | EunoiaGames/Eunoia-Dev | 94edea774d1de05dc6a0c24ffdd3bb91b91a3346 | [
"Apache-2.0"
] | null | null | null | Eunoia-Engine/Src/Eunoia/Core/Engine.cpp | EunoiaGames/Eunoia-Dev | 94edea774d1de05dc6a0c24ffdd3bb91b91a3346 | [
"Apache-2.0"
] | null | null | null | #include "Engine.h"
#include "../Utils/Log.h"
#include "Application.h"
#include "../Rendering/MasterRenderer.h"
#include "../Rendering/Asset/AssetManager.h"
#include "Input.h"
#include "../Metadata/Metadata.h"
#include "../ECS/Systems/TransformHierarchy3DSystem.h"
#include "../ECS/Systems/TransformHierarchy2DSystem.h"
#include "../Rendering/GuiManager.h"
#include "../Physics/PhysicsEngine3D.h"
#define EU_WORLD0 0
#define EU_WORLD1 1
namespace Eunoia {
struct EunoiaWorldData
{
Display* display;
RenderContext* renderContext;
MasterRenderer* renderer;
PhysicsEngine3D* physicsEngine;
b32 created;
b32 active;
};
struct Engine_Data
{
List<Application*> applications;
Application* activeApp;
b32 running;
r32 timeInSeconds;
b32 editorAttached;
EunoiaWorldData activeWorlds[MAX_EUNOIA_WORLDS];
};
static Engine_Data s_Data;
void Engine::Init(Application* app, const String& title, u32 width, u32 height, RenderAPI api, b32 editorAttached)
{
Logger::Init();
Metadata::Init();
ECSLoader::Init();
if (!app->GetECS())
{
app->InitECS();
app->GetECS()->CreateSystem<TransformHierarchy3DSystem>();
app->GetECS()->CreateSystem<TransformHierarchy2DSystem>();
}
s_Data.editorAttached = editorAttached;
s_Data.applications.Push(app);
s_Data.activeApp = app;
for (u32 i = 0; i < MAX_EUNOIA_WORLDS; i++)
{
s_Data.activeWorlds[i].created = false;
s_Data.activeWorlds[i].active = false;
}
DisplayInfo displayInfo;
displayInfo.title = title;
displayInfo.width = width;
displayInfo.height = height;
CreateWorld(displayInfo, api, EUNOIA_WORLD_FLAG_ALL, true, EUNOIA_WORLD_MAIN);
AssetManager::Init();
EUInput::InitInput();
GuiManager::Init();
}
void Engine::Start()
{
s_Data.running = true;
s_Data.activeApp->Init();
r32 dt = 1.0f / 60.0f;
while (s_Data.running)
{
for (u32 i = 0; i < MAX_EUNOIA_WORLDS; i++)
{
EunoiaWorldData* world = &s_Data.activeWorlds[i];
if (!world->active)
continue;
if (world->display->CheckForEvent(DISPLAY_EVENT_CLOSE))
{
if (i == EUNOIA_WORLD_MAIN)
{
Stop();
}
else
{
DestroyWorld((EunoiaWorld)i);
break;
}
}
}
Update(dt);
Render();
s_Data.timeInSeconds += dt;
}
}
void Engine::Stop()
{
s_Data.running = false;
}
EngineApplicationHandle Engine::AddApplication(Application* app, b32 setActive)
{
EngineApplicationHandle handle = s_Data.applications.Size();
s_Data.applications.Push(app);
if (setActive)
s_Data.activeApp = app;
return handle;
}
void Engine::SetActiveApplication(EngineApplicationHandle handle)
{
s_Data.activeApp = s_Data.applications[handle];
}
EunoiaWorld Engine::CreateWorld(const DisplayInfo& displayInfo, RenderAPI renderAPI, EunoiaWorldFlags flags, b32 active, EunoiaWorld setHandle)
{
if (setHandle > EUNOIA_WORLD_INVALID)
{
EU_LOG_WARN("Engine::CreateWorld() Invalid set handle");
return EUNOIA_WORLD_INVALID;
}
EunoiaWorld worldHandle = EUNOIA_WORLD_INVALID;
if (setHandle == EUNOIA_WORLD_INVALID)
{
for (u32 i = 0; i < MAX_EUNOIA_WORLDS; i++)
{
if (!s_Data.activeWorlds[i].created)
{
worldHandle = (EunoiaWorld)i;
break;
}
}
}
else
{
worldHandle = setHandle;
}
if (worldHandle == EUNOIA_WORLD_INVALID)
{
EU_LOG_ERROR("Engine::CreateWorld() Cannot create anymore worlds");
return EUNOIA_WORLD_INVALID;
}
EunoiaWorldData* world = &s_Data.activeWorlds[worldHandle];
if (world->created)
{
DestroyWorld(worldHandle);
}
world->display = Display::CreateDisplay();
world->display->Create(displayInfo.title, displayInfo.width, displayInfo.height);
world->renderContext = RenderContext::CreateRenderContext(renderAPI);
world->renderContext->Init(world->display);
world->renderer = new MasterRenderer(world->renderContext, world->display);
world->renderer->Init();
world->physicsEngine = new PhysicsEngine3D();
world->physicsEngine->Init();
world->created = true;
world->active = active;
return worldHandle;
}
void Engine::DestroyWorld(EunoiaWorld worldID)
{
EunoiaWorldData* world = &s_Data.activeWorlds[worldID];
if (world->created)
{
world->display->Destroy();
world->physicsEngine->Destroy();
delete world->display;
delete world->renderContext;
delete world->renderer;
delete world->physicsEngine;
world->created = false;
world->active = false;
}
}
EunoiaWorld Engine::RecreateWorld(EunoiaWorld world, EunoiaWorldFlags flags, b32 active)
{
DisplayInfo displayInfo;
displayInfo.title = GetDisplay(world)->GetTitle();
displayInfo.width = GetDisplay(world)->GetWidth();
displayInfo.height = GetDisplay(world)->GetHeigth();
RenderAPI renderAPI = GetRenderContext(world)->GetRenderAPI();
DestroyWorld(world);
CreateWorld(displayInfo, renderAPI, flags, active, world);
return world;
}
RenderContext* Engine::GetRenderContext(EunoiaWorld world)
{
return s_Data.activeWorlds[world].renderContext;
}
MasterRenderer* Engine::GetRenderer(EunoiaWorld world)
{
return s_Data.activeWorlds[world].renderer;
}
Display* Engine::GetDisplay(EunoiaWorld world)
{
return s_Data.activeWorlds[world].display;
}
PhysicsEngine3D* Engine::GetPhysicsEngine(EunoiaWorld world)
{
return s_Data.activeWorlds[world].physicsEngine;
}
b32 Engine::IsWorldAvailable(EunoiaWorld world)
{
return s_Data.activeWorlds[world].created;
}
b32 Engine::IsWorldActive(EunoiaWorld world)
{
return s_Data.activeWorlds[world].active;
}
void Engine::SetWorldActive(EunoiaWorld worldID, b32 active)
{
EunoiaWorldData* world = &s_Data.activeWorlds[worldID];
if (!world->created)
{
EU_LOG_WARN("Engine::SetWorldActive() world has not been created yet");
return;
}
world->active = active;
}
void Engine::SetWorldActiveOpposite(EunoiaWorld worldID)
{
EunoiaWorldData* world = &s_Data.activeWorlds[worldID];
if (!world->created)
{
EU_LOG_WARN("Engine::SetWorldActiveOpposite() world has not been created yet");
return;
}
world->active = !world->active;
}
r32 Engine::GetTime()
{
return s_Data.timeInSeconds;
}
b32 Engine::IsEditorAttached()
{
return s_Data.editorAttached;
}
Application* Engine::GetActiveApplication()
{
return s_Data.activeApp;
}
Application* Engine::GetApplication(EngineApplicationHandle handle)
{
return s_Data.applications[handle];
}
void Engine::Update(r32 dt)
{
EUInput::BeginInput();
s_Data.activeApp->BeginECS();
s_Data.activeApp->UpdateECS(dt);
s_Data.activeApp->Update(dt);
for (u32 i = 0; i < s_Data.applications.Size(); i++)
if (s_Data.applications[i] != s_Data.activeApp)
s_Data.applications[i]->GetECS()->OnlyUpdateRequiredSystems(dt);
s_Data.activeApp->GetECS()->PrePhysicsSystems(dt);
s_Data.activeApp->PrePhysicsSimulation(dt);
for (u32 i = 0; i < MAX_EUNOIA_WORLDS; i++)
{
if (!s_Data.activeWorlds[i].active)
continue;
s_Data.activeWorlds[i].physicsEngine->StepSimulation(dt);
}
s_Data.activeApp->GetECS()->PostPhysicsSystems(dt);
s_Data.activeApp->PostPhysicsSimulation(dt);
EUInput::UpdateInput();
}
void Engine::Render()
{
for (u32 i = 0; i < MAX_EUNOIA_WORLDS; i++)
{
EunoiaWorldData* world = &s_Data.activeWorlds[i];
if (!world->active)
continue;
world->renderContext->BeginFrame();
world->renderer->BeginFrame();
}
s_Data.activeApp->RenderECS();
s_Data.activeApp->Render();
for (u32 i = 0; i < MAX_EUNOIA_WORLDS; i++)
{
EunoiaWorldData* world = &s_Data.activeWorlds[i];
if (!world->active)
continue;
world->renderer->EndFrame();
world->renderer->RenderFrame();
s_Data.activeApp->EndFrame();
world->renderContext->Present();
world->display->Update();
}
}
}
| 22.238636 | 144 | 0.702095 | [
"render"
] |
6965837d77b5cca7e494283504f0bb11a9f19736 | 10,845 | cpp | C++ | src/pooling_global_avg.cpp | Pandinosaurus/MinkowskiEngine | a40123a32eb1208f6a11fa32c36ee866ad4d4827 | [
"MIT"
] | 1 | 2021-07-28T18:31:06.000Z | 2021-07-28T18:31:06.000Z | src/pooling_global_avg.cpp | Pandinosaurus/MinkowskiEngine | a40123a32eb1208f6a11fa32c36ee866ad4d4827 | [
"MIT"
] | null | null | null | src/pooling_global_avg.cpp | Pandinosaurus/MinkowskiEngine | a40123a32eb1208f6a11fa32c36ee866ad4d4827 | [
"MIT"
] | null | null | null | /* Copyright (c) Chris Choy (chrischoy@ai.stanford.edu).
*
* 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.
*
* Please cite "4D Spatio-Temporal ConvNets: Minkowski Convolutional Neural
* Networks", CVPR'19 (https://arxiv.org/abs/1904.08755) if you use any part
* of the code.
*/
#include "common.hpp"
#include "pooling_avg.hpp"
#ifndef CPU_ONLY
#include "pooling_avg.cuh"
#endif
#include <pybind11/pybind11.h>
namespace minkowski {
template <typename Dtype>
vector<at::Tensor> GlobalPoolingForwardCPU(at::Tensor in_feat,
py::object py_in_coords_key,
py::object py_out_coords_key,
py::object py_coords_manager,
bool use_avg, int pooling_mode) {
CoordsManager *p_coords_manager = py_coords_manager.cast<CoordsManager *>();
const auto batch_size = p_coords_manager->getBatchSize();
if (batch_size == 1) {
p_coords_manager->setOriginCoordsKey(py_out_coords_key);
auto out_feat = in_feat.sum(0, true);
if (use_avg)
out_feat /= in_feat.size(0);
auto num_nonzero = torch::zeros({batch_size}, in_feat.options());
num_nonzero[0] = in_feat.size(0);
return {out_feat, num_nonzero};
} else {
if (pooling_mode == 0)
pooling_mode = in_feat.size(0) / batch_size > 100 ? 1 : 2;
auto out_feat =
torch::zeros({batch_size, in_feat.size(1)}, in_feat.options());
auto num_nonzero = torch::zeros({batch_size}, in_feat.options());
// If the policy is GlobalPoolingMode.INDEX_SELECT
switch (pooling_mode) {
case 1: {
const auto vec_maps = p_coords_manager->getRowIndicesPerBatch(
py_in_coords_key, py_out_coords_key);
for (int b = 0; b < batch_size; ++b) {
if (use_avg)
out_feat[b] = in_feat.index_select(0, vec_maps[b]).mean(0);
else
out_feat[b] = in_feat.index_select(0, vec_maps[b]).sum(0);
num_nonzero[b] = vec_maps[b].numel();
}
} break;
case 2: {
const auto &in_outs = p_coords_manager->getOriginInOutMaps(
py_in_coords_key, py_out_coords_key);
NonzeroAvgPoolingForwardKernelCPU<Dtype, int>(
in_feat.data<Dtype>(), out_feat.data<Dtype>(),
num_nonzero.data<Dtype>(), in_feat.size(1), in_outs.first,
in_outs.second, batch_size, use_avg);
} break;
default:
ASSERT(false, "Invalid pooling mode", pooling_mode);
}
return {out_feat, num_nonzero};
}
}
template <typename Dtype>
at::Tensor
GlobalPoolingBackwardCPU(at::Tensor in_feat, at::Tensor grad_out_feat,
at::Tensor num_nonzero, py::object py_in_coords_key,
py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg) {
CoordsManager *p_coords_manager = py_coords_manager.cast<CoordsManager *>();
const auto batch_size = p_coords_manager->getBatchSize();
auto grad_in_feat = torch::empty_like(in_feat);
if (batch_size == 1) {
if (use_avg)
grad_in_feat.copy_(grad_out_feat / in_feat.size(0));
else
grad_in_feat.copy_(grad_out_feat);
} else {
const InOutMapKey map_key = p_coords_manager->getOriginMapHashKey(
py_in_coords_key, py_out_coords_key);
ASSERT(
p_coords_manager->existsInOutMapKey(map_key),
"The in-out map doesn't exist for backward. Did you run forward pass?");
grad_in_feat.zero_();
NonzeroAvgPoolingBackwardKernelCPU<Dtype, int>(
grad_in_feat.data<Dtype>(), in_feat.size(0),
grad_out_feat.data<Dtype>(), num_nonzero.data<Dtype>(), in_feat.size(1),
p_coords_manager->in_maps[map_key], p_coords_manager->out_maps[map_key],
use_avg);
}
return grad_in_feat;
}
#ifndef CPU_ONLY
template <typename Dtype>
vector<at::Tensor> GlobalPoolingForwardGPU(at::Tensor in_feat,
py::object py_in_coords_key,
py::object py_out_coords_key,
py::object py_coords_manager,
bool use_avg, int pooling_mode) {
CoordsManager *p_coords_manager = py_coords_manager.cast<CoordsManager *>();
const auto batch_size = p_coords_manager->getBatchSize();
if (batch_size == 1) {
p_coords_manager->setOriginCoordsKey(py_out_coords_key);
auto out_feat = in_feat.sum(0, true);
if (use_avg)
out_feat /= in_feat.size(0);
auto num_nonzero = torch::zeros({batch_size}, in_feat.options());
num_nonzero[0] = in_feat.size(0);
return {out_feat, num_nonzero};
} else {
if (pooling_mode == 0)
pooling_mode = in_feat.size(0) / batch_size > 100 ? 1 : 2;
auto out_feat =
torch::zeros({batch_size, in_feat.size(1)}, in_feat.options());
auto num_nonzero = torch::zeros({batch_size}, in_feat.options());
// If the policy is GlobalPoolingMode.INDEX_SELECT
switch (pooling_mode) {
case 1: {
const auto vec_maps = p_coords_manager->getRowIndicesPerBatch(
py_in_coords_key, py_out_coords_key);
for (int b = 0; b < batch_size; ++b) {
if (use_avg)
out_feat[b] =
in_feat.index_select(0, vec_maps[b].to(in_feat.device())).mean(0);
else
out_feat[b] =
in_feat.index_select(0, vec_maps[b].to(in_feat.device())).sum(0);
num_nonzero[b] = vec_maps[b].numel();
}
} break;
case 2: {
const auto &in_outs = p_coords_manager->getOriginInOutMapsGPU(
py_in_coords_key, py_out_coords_key);
cusparseHandle_t handle = at::cuda::getCurrentCUDASparseHandle();
cusparseSetStream(handle, at::cuda::getCurrentCUDAStream());
NonzeroAvgPoolingForwardKernelGPU<Dtype, int>(
in_feat.data<Dtype>(), in_feat.size(0), out_feat.data<Dtype>(),
batch_size, num_nonzero.data<Dtype>(), in_feat.size(1), in_outs.first,
in_outs.second, use_avg, handle, at::cuda::getCurrentCUDAStream());
} break;
default:
ASSERT(false, "Invalid pooling mode", pooling_mode);
}
return {out_feat, num_nonzero};
}
}
template <typename Dtype>
at::Tensor
GlobalPoolingBackwardGPU(at::Tensor in_feat, at::Tensor grad_out_feat,
at::Tensor num_nonzero, py::object py_in_coords_key,
py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg) {
CoordsManager *p_coords_man = py_coords_manager.cast<CoordsManager *>();
const auto batch_size = p_coords_man->getBatchSize();
auto grad_in_feat = torch::empty_like(in_feat);
if (batch_size == 1) {
if (use_avg)
grad_in_feat.copy_(grad_out_feat / in_feat.size(0));
else
grad_in_feat.copy_(grad_out_feat);
} else {
const InOutMapKey map_key =
p_coords_man->getOriginMapHashKey(py_in_coords_key, py_out_coords_key);
ASSERT(
p_coords_man->existsInOutMapKey(map_key),
"The in-out map doesn't exist for backward. Did you run forward pass?");
p_coords_man->copyInOutMapsToGPU(map_key);
grad_in_feat.zero_();
NonzeroAvgPoolingBackwardKernelGPU<Dtype, int>(
grad_in_feat.data<Dtype>(), in_feat.size(0),
grad_out_feat.data<Dtype>(), grad_out_feat.size(0),
num_nonzero.data<Dtype>(), in_feat.size(1),
p_coords_man->d_in_maps[map_key], p_coords_man->d_out_maps[map_key],
use_avg, at::cuda::getCurrentCUDAStream());
}
return grad_in_feat;
}
#endif // CPU_ONLY
template vector<at::Tensor>
GlobalPoolingForwardCPU<float>(at::Tensor in_feat, py::object py_in_coords_key,
py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg,
int pooling_mode);
template vector<at::Tensor>
GlobalPoolingForwardCPU<double>(at::Tensor in_feat, py::object py_in_coords_key,
py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg,
int pooling_mode);
template at::Tensor GlobalPoolingBackwardCPU<float>(
at::Tensor in_feat, at::Tensor grad_out_feat, at::Tensor num_nonzero,
py::object py_in_coords_key, py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg);
template at::Tensor GlobalPoolingBackwardCPU<double>(
at::Tensor in_feat, at::Tensor grad_out_feat, at::Tensor num_nonzero,
py::object py_in_coords_key, py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg);
#ifndef CPU_ONLY
template vector<at::Tensor>
GlobalPoolingForwardGPU<float>(at::Tensor in_feat, py::object py_in_coords_key,
py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg,
int pooling_mode);
template vector<at::Tensor>
GlobalPoolingForwardGPU<double>(at::Tensor in_feat, py::object py_in_coords_key,
py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg,
int pooling_mode);
template at::Tensor GlobalPoolingBackwardGPU<float>(
at::Tensor in_feat, at::Tensor grad_out_feat, at::Tensor num_nonzero,
py::object py_in_coords_key, py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg);
template at::Tensor GlobalPoolingBackwardGPU<double>(
at::Tensor in_feat, at::Tensor grad_out_feat, at::Tensor num_nonzero,
py::object py_in_coords_key, py::object py_out_coords_key,
py::object py_coords_manager, bool use_avg);
#endif // end CPU_ONLY
} // end namespace minkowski
| 39.010791 | 80 | 0.657077 | [
"object",
"vector"
] |
69787cbd3aab2f2ae771b7c49db7ae8df714463a | 4,151 | cpp | C++ | NAS2D/Renderer/Renderer.cpp | Brett208/nas2d-core | f9506540f32d34f3c60bc83b87b34460d582ae81 | [
"Zlib"
] | null | null | null | NAS2D/Renderer/Renderer.cpp | Brett208/nas2d-core | f9506540f32d34f3c60bc83b87b34460d582ae81 | [
"Zlib"
] | null | null | null | NAS2D/Renderer/Renderer.cpp | Brett208/nas2d-core | f9506540f32d34f3c60bc83b87b34460d582ae81 | [
"Zlib"
] | null | null | null | // ==================================================================================
// = NAS2D
// = Copyright © 2008 - 2020 New Age Software
// ==================================================================================
// = NAS2D is distributed under the terms of the zlib license. You are free to copy,
// = modify and distribute the software under the terms of the zlib license.
// =
// = Acknowledgement of your use of NAS2D is appriciated but is not required.
// ==================================================================================
#include "Renderer.h"
#include "Rectangle.h"
#include <iostream>
#include <algorithm>
using namespace NAS2D;
/**
* Internal constructor used by derived types to set the name of the Renderer.
*
* This c'tor is not public and can't be invoked externally.
*/
Renderer::Renderer(const std::string& appTitle) : mTitle(appTitle)
{}
Renderer::~Renderer()
{
fadeCompleteSignal.clear();
std::cout << "Renderer Terminated." << std::endl;
}
/**
* Returns the title of the application window.
*/
const std::string& Renderer::title() const
{
return mTitle;
}
/**
* Returns the name of the driver as named by the operating system.
*/
const std::string& Renderer::driverName() const
{
return mDriverName;
}
/**
* Sets the title of the application window.
*/
void Renderer::title(const std::string& title)
{
mTitle = title;
}
void Renderer::drawTextShadow(const Font& font, std::string_view text, Point<float> position, Vector<float> shadowOffset, Color textColor, Color shadowColor)
{
const auto shadowPosition = position + shadowOffset;
drawText(font, text, shadowPosition, shadowColor);
drawText(font, text, position, textColor);
}
/**
* Sets the color of the fade.
*
* \param color A Color.
*/
void Renderer::fadeColor(Color color)
{
mFadeColor = color;
}
/**
* Non-blocking screen fade.
*
* \param delay Time in miliseconds the fade should last. A value of 0
* will instantly fade the screen in.
*/
void Renderer::fadeIn(float delay)
{
if (delay == 0)
{
mCurrentFade = 0.0f;
mCurrentFadeType = FadeType::None;
return;
}
mCurrentFadeType = FadeType::In;
mFadeStep = 255.0f / delay;
fadeTimer.delta(); // clear timer
}
/**
* Non-blocking screen fade.
*
* \param delay Time in miliseconds the fade should last. A value of 0
* will instantly fade the screen in.
*/
void Renderer::fadeOut(float delay)
{
if (delay == 0)
{
mCurrentFade = 255.0f;
mCurrentFadeType = FadeType::None;
return;
}
mCurrentFadeType = FadeType::Out;
mFadeStep = 255.0f / delay;
fadeTimer.delta(); // clear timer
}
/**
* Gets whether or not a fade is in progress.
*/
bool Renderer::isFading() const
{
return (mCurrentFadeType != FadeType::None);
}
/**
* Gets whether the screen is faded or not.
*/
bool Renderer::isFaded() const
{
return (mCurrentFade == 255.0f);
}
/**
* Gets a refernece to the callback signal for fade transitions.
*/
Signals::SignalSource<>& Renderer::fadeComplete()
{
return fadeCompleteSignal;
}
/**
* Gets the center coordinates of the screen.
*/
Point<int> Renderer::center() const
{
return Point{0, 0} + mResolution / 2;
}
/**
* Updates the screen.
*
* \note All derived Renderer objects must call Renderer::update()
* before performing screen refreshes.
*/
void Renderer::update()
{
if (mCurrentFadeType != FadeType::None)
{
float fade = (fadeTimer.delta() * mFadeStep) * static_cast<int>(mCurrentFadeType);
mCurrentFade += fade;
if (mCurrentFade < 0.0f || mCurrentFade > 255.0f)
{
mCurrentFade = std::clamp(mCurrentFade, 0.0f, 255.0f);
mCurrentFadeType = FadeType::None;
fadeCompleteSignal();
}
}
if (mCurrentFade > 0.0f)
{
drawBoxFilled(Rectangle<float>::Create({0, 0}, size().to<float>()), mFadeColor.alphaFade(static_cast<uint8_t>(mCurrentFade)));
}
}
void Renderer::setResolution(Vector<int> newResolution)
{
if (!fullscreen())
{
mResolution = newResolution;
}
}
/**
* Sets the driver name.
*
* \note Internal function used only by derived
* renderer types.
*/
void Renderer::driverName(const std::string& name)
{
mDriverName = name;
}
| 19.672986 | 157 | 0.644664 | [
"vector"
] |
697f6c53043620790e81be57ebbe0e1cb945fc1c | 23,344 | cpp | C++ | paxoskv/comm/svrlist_config_base.cpp | shanbaoyin/paxosstore | d9969c102df9ea4ef11a95f94f40c63d9d12b354 | [
"BSD-3-Clause"
] | 1,567 | 2017-08-30T07:58:14.000Z | 2022-03-28T07:46:54.000Z | paxoskv/comm/svrlist_config_base.cpp | tomjobs/paxosstore | 120ce539ef4fef18b3bef512cec28e3e0e3b241c | [
"BSD-3-Clause"
] | 21 | 2017-08-31T01:21:30.000Z | 2021-08-31T12:55:39.000Z | paxoskv/comm/svrlist_config_base.cpp | tomjobs/paxosstore | 120ce539ef4fef18b3bef512cec28e3e0e3b241c | [
"BSD-3-Clause"
] | 352 | 2017-08-30T15:25:40.000Z | 2022-03-18T10:02:57.000Z |
/*
* Tencent is pleased to support the open source community by making PaxosStore available.
* Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* https://opensource.org/licenses/BSD-3-Clause
* 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 <netinet/in.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cassert>
#include "cutils/log_utils.h"
#include "conhash.h"
#include "svrlist_config_base.h"
#include "iconfig.h"
#include "kvsvrcomm.h"
#define _err_line -1000 - __LINE__
using namespace Comm;
template <class T>
class clsDelayFree
{
T * m_ptr;
public:
clsDelayFree()
{
m_ptr = NULL;
}
void Free( T * p )
{
if( m_ptr )
{
delete m_ptr;
m_ptr = 0;
}
m_ptr = p;
}
T *Take()
{
T * p = m_ptr;
m_ptr = NULL;
return p;
}
T * Get()
{
return m_ptr;
}
~clsDelayFree()
{
if( m_ptr ) delete m_ptr;
m_ptr = NULL;
}
};
class param
{
public:
/*
[Server]
ServerCount=
KvConsistentHash=
*/
uint32_t _iServerCount;// = 0;
uint32_t _iConsistentHash;// = 0;
/*
[General]
GroupCount=
FailPeriod=
FailCount=
TimeOut=
*/
uint32_t _iGroupCount;// = 6;
uint32_t _iFailPeriod;// = 60;
uint32_t _iFailCount;// = 60;
uint32_t _iTimeOut;// = 500;
clsConHash *_poConHash;// = NULL;
std::vector< SvrGroup_t * > *pvGroups;
SvrGroupList_t *pGroupList4SelfIP;
param()
{
memset( this,0,sizeof(*this) ); //WARNING !!!
}
~param()
{
if( _poConHash ) delete _poConHash;_poConHash = NULL;
if( pvGroups ) delete pvGroups;pvGroups = NULL;
if( pGroupList4SelfIP ) delete pGroupList4SelfIP;pGroupList4SelfIP = NULL;
}
void SetConnHash( clsConHash *p )
{
FreeConHash();
_poConHash = p;
}
void SetGroups( std::vector< SvrGroup_t *> *p )
{
FreeGroups();
pvGroups = p;
}
void SetGroupList4SelfIP( SvrGroupList_t *p )
{
FreeGroupList4SelfIP();
pGroupList4SelfIP = p;
}
void FreeConHash()
{
if( !_poConHash ) return;
delete _poConHash;
_poConHash = NULL;
}
void FreeGroups()
{
if( !pvGroups ) return;
for( size_t i=0;i<pvGroups->size();i++)
{
delete (*pvGroups)[i];
(*pvGroups)[i] = NULL;
}
pvGroups->clear();
delete pvGroups;
pvGroups = NULL;
}
void FreeGroupList4SelfIP()
{
if( !pGroupList4SelfIP ) return;
free( pGroupList4SelfIP );
pGroupList4SelfIP = NULL;
}
};
static bool s_bOpenTest = false;
static param s_param0;
static param s_param1;
//static param *s_o = &s_param1;
//static param *s_curr = &s_param0;
static int ReadUintItem(
CConfig & reader, const char * svrListPath,
const char * section, const char * item, uint32_t & result)
{
ConfigItemInfo_t infoArray [] =
{
CONFIG_ITEM_UIN(section, item, result),
CONFIG_ITEM_END
};
int ret = ConfigRead(&reader, infoArray);
if(0 != ret)
{
logdebug("ERR: %s:%d ConfigRead %s section %s item %s ret %d", __FILE__, __LINE__, svrListPath, section, item, ret);
return ret;
}
ConfigDump(infoArray);
return 0;
}
static int ReadBatchStrItem(
CConfig & reader, const char * svrListPath,
int count, const char * section, const char * itemPrefix,
std::vector<std::string> & results)
{
char item[32] = {0};
char value[256] = {0};
for(int index = 0; index < count; ++index)
{
snprintf(item, sizeof(item), "%s%d", itemPrefix, index);
ConfigItemInfo_t infoArray [] =
{
CONFIG_ITEM_STR(section, item, value),
CONFIG_ITEM_END
};
int ret = ConfigRead(&reader, infoArray);
if(0 != ret)
{
logerr("ERR: %s:%d ConfigRead %s section %s item %s ret %d", __FILE__, __LINE__,
svrListPath, section, item, ret);
return ret;
}
results.push_back(value);
ConfigDump(infoArray);
}
return 0;
}
static bool IsVectorContain(
const std::vector<std::string> & container, const char * target)
{
for(uint32_t index = 0; index < container.size(); ++index)
{
if(container[index] == target)
{
return true;
}
}
return false;
}
static void FillSvrAddr(
const std::vector<std::string> & ip, int port, SvrAddr_t * addrs)
{
for( uint32_t index = 0; index < ip.size(); ++index )
{
addrs[index].iPort = htons(port);
struct in_addr stIP;
inet_aton(ip[index].c_str(), &stIP); //net-order now
addrs[index].iIP = stIP.s_addr;
}
}
static int GetLCM(int a, int b)
{
int iMax = a>b ? a:b;
for(int i=iMax; i<=a*b; i++)
{
if(i%a==0 && i%b == 0)
{
return i;
}
}
return -1;
}
static void GenerateFakeIPC(
uint32_t countAB, uint32_t groupCount,
std::vector<std::string> & ipC)
{
if(countAB == 6 && groupCount == countAB)
{
return;
}
int iFakeCount = GetLCM(countAB, groupCount);
int iCCount = ipC.size();
for(int i=0; i< iFakeCount - iCCount; i++)
{
ipC.push_back(ipC[ i % iCCount]);
logerr("DEBUG: %s:%s:%d push_back index %d %s iFakeCount %u iCCount %u",
__FILE__, __func__, __LINE__, i % iCCount, ipC[ i % iCCount].c_str(), iFakeCount, iCCount);
}
//printf("countAB %u group %u fake %d ccount %d size %u\n", countAB, groupCount, iFakeCount, iCCount, (uint32_t)ipC.size());
}
clsSvrListConfigBase::clsSvrListConfigBase()
: _grouplist(NULL)
, _poConHash(NULL)
, _bOpenTest(false)
, _old(NULL)
, _curr(NULL)
{
memset(_selfIP, 0, sizeof(_selfIP));
memset(_svrListPath, 0, sizeof(_svrListPath));
Reset();
}
clsSvrListConfigBase::~clsSvrListConfigBase()
{
Reset();
if (NULL != _old)
{
delete _old;
_old = NULL;
}
if (NULL != _curr)
{
delete _curr;
_curr = NULL;
}
}
void clsSvrListConfigBase::Reset()
{
delete _poConHash;
_poConHash = NULL;
_iServerCount = 0;
_iConsistentHash = 0;
_iGroupCount = 6;
_iTimeOut = 500;
_iOssAttrID = 0;
_iFailCount = 60;
_iFailPeriod = 60;
free(_grouplist);
_grouplist = NULL;
}
class clsCmpSvrGroup
{
public:
inline bool operator()( const SvrGroup_t *a,const SvrGroup_t *b ) //for sort by begin
{
return a->iBegin < b->iBegin;
}
inline bool operator()( const SvrGroup_t *a,uint32_t b ) //for lower_bound
{
// printf("a->iEnd %u b %u\n",a->iEnd,b );
return a->iEnd < b;
}
};
static SvrGroup_t *GetSvrGroupBySect( std::vector< SvrGroup_t *> &v,uint32_t sect )
{
// printf("v.size %zu sect %u v[0]->iBegin %u\n",v.size(),sect,v[0]->iBegin );
if( v.empty() || sect < v[0]->iBegin ) return NULL;
clsCmpSvrGroup cmp;
std::vector< SvrGroup_t * >::iterator it = lower_bound( v.begin(),v.end(),sect,cmp );
// printf("it == end %d\n",it == v.end() );
// if( it != v.end() )
// {
// printf("begin %u end %u sect %u\n",(*it)->iBegin,(*it)->iEnd,sect );
// }
if( it != v.end() && (*it)->iBegin <= sect && sect <= (*it)->iEnd )
{
return *it;
}
return NULL;
}
static int SortAndCheckOverlapped( std::vector< SvrGroup_t * > & v )
{
if( v.size() < 2 ) return 0;
bool need_sort = false;
for( size_t i=1;i<v.size();i++ )
{
if( v[i]->iBegin < v[i - 1]->iBegin )
{
need_sort = true;
break;
}
}
if( need_sort )
{
clsCmpSvrGroup cmp;
std::sort( v.begin(),v.end(),cmp );
}
//check overlapped
for( size_t i=1;i<v.size();i++ )
{
if( v[i]->iBegin < v[i-1]->iEnd ) return _err_line;
}
return 0;
}
static int FillSvrGroupList( SvrGroupList_t *grouplist,
const std::vector< SvrGroup_t *> &v,
const char *_selfIP )
{
struct in_addr stIP;
inet_aton( _selfIP, &stIP ); //net-order now
int ip = stIP.s_addr;
grouplist->iGroupCnt = 0;
grouplist->iMachineC = 0;
for( size_t i=0;i<v.size();i++)
{
SvrGroup_t &g = *v[i];
bool ab = false;
bool c = false;
//check is ab
for( size_t j=0;j< sizeof(g.tAddrAB)/sizeof(g.tAddrAB[0]);j++ )
{
if( ip == g.tAddrAB[j].iIP )
{
ab = true;
break;
}
}
//check is c
for( size_t j=0;j< sizeof(g.tAddrC)/sizeof(g.tAddrC[0]);j++ )
{
if( ip == g.tAddrC[j].iIP )
{
c = true;
break;
}
}
//fill
if( ab || c )
{
int idx = grouplist->iGroupCnt++;
if( c )
{
grouplist->iMachineC = 1; //true or false
}
memcpy( grouplist->tSvrGroup + idx,&g,sizeof(g) ); //WARNING !!! may be out of bound
}
}
return 0;
}
static int LoadConfigFromCConfig_New( param &a,
uint32_t iOldConsistentHash,
uint32_t iOldServerCount,
clsConHash *pOldConHash,
Comm::CConfig& reader,char *_svrListPath,const char *_selfIP )
{
//-----------------------------------
std::vector< SvrGroup_t * > *pvGroups = new std::vector< SvrGroup_t* >();
std::unique_ptr< std::vector< SvrGroup_t* > > auto_groups( pvGroups );
std::vector< SvrGroup_t * > &m_vGroups = *pvGroups;
int ret = 0;
ret = ReadUintItem( reader, _svrListPath, "General", "GroupCount", a._iGroupCount );
if( ret < 0 )
{
a._iGroupCount = 6;
}
if( ReadUintItem(reader, _svrListPath, "General", "FailPeriod", a._iFailPeriod) < 0 ||
ReadUintItem(reader, _svrListPath, "General", "FailCount", a._iFailCount) < 0 ||
ReadUintItem(reader, _svrListPath, "General", "TimeOut", a._iTimeOut) < 0 )
{
a._iFailPeriod = 60;
a._iFailCount = 60;
a._iTimeOut = 500;
}
uint32_t iServerCount = 0;
ret = ReadUintItem( reader, _svrListPath, "Server", "ServerCount", iServerCount );
if( ret < 0 ) return _err_line;
ReadUintItem( reader, _svrListPath, "Server", "KvConsistentHash", a._iConsistentHash );
//server count of conhash changed, clsConHash should be reinit
if( a._iConsistentHash
&& ( !pOldConHash || !iOldConsistentHash || iOldServerCount != iServerCount ) )
{
clsConHash * poConHash = new clsConHash();
int ret = poConHash->Init( iServerCount );
if( ret < 0 )
{
logerr("ERR: clsConHash Init(%d) %d", iServerCount, ret);
return _err_line;
}
a._poConHash = poConHash;
a._iServerCount = iServerCount;
}
char section[16] = {0};
for(uint32_t index = 0; index < iServerCount; ++index)
{
snprintf(section, sizeof(section), "Server%d", index);
uint32_t svrCountAB = 0, svrCountC = 0, port = 0, begin = 0, end = 0;
{
int ret = ReadUintItem( reader, _svrListPath, section, "SVRCount", svrCountAB );
if( ret < 0 ) return _err_line;
ret = ReadUintItem( reader, _svrListPath, section, "SVR_C_Count", svrCountC );
if( ret < 0 ) return _err_line;
ret = ReadUintItem(reader, _svrListPath, section, "SVR_Port", port);
if( ret < 0 ) return _err_line;
// printf ( "section %s iPort %d\n", section, port );
//1.get sect [ begin,end ]
//
if( !a._iConsistentHash )
{
ret = ReadUintItem( reader, _svrListPath, section, "Sect_Begin", begin );
if( ret < 0 ) return _err_line;
ret = ReadUintItem( reader, _svrListPath, section, "Sect_End", end );
if( ret < 0 ) return _err_line;
if( begin > end ) return _err_line;
}
else
{
begin = index;
end = index;
}
}
//2.get ip
std::vector<std::string> ipAB, ipC;
ret = ReadBatchStrItem( reader, _svrListPath, svrCountAB, section, "SVR", ipAB );
if( ret < 0 ) return _err_line;
ret = ReadBatchStrItem( reader, _svrListPath, svrCountC, section, "SVR_C", ipC );
if( ret < 0 ) return _err_line;
if( svrCountAB != ipAB.size() )
{
return _err_line;
}
if( svrCountC != ipC.size() )
{
return _err_line;
}
//generate fake c ips
//
GenerateFakeIPC( svrCountAB, a._iGroupCount, ipC );
svrCountC = ipC.size();
SvrGroup_t * group = new SvrGroup_t();
std::unique_ptr< SvrGroup_t > x( group );
memset( group,0,sizeof(*group) );
{
group->iCountAB = svrCountAB;
group->iCountC = svrCountC;
group->iBegin = begin;
group->iEnd = end;
group->iGroupCount = a._iGroupCount;
}
//WARNING !!! may be out of bound
FillSvrAddr( ipAB, port, group->tAddrAB );
FillSvrAddr( ipC, port, group->tAddrC );
m_vGroups.push_back( x.release() );
}
ret = SortAndCheckOverlapped( m_vGroups );
if( ret ) return _err_line;
SvrGroupList_t *grouplist = (SvrGroupList_t*)calloc( sizeof( SvrGroupList_t ),1 );
{
std::unique_ptr< SvrGroupList_t > oo( grouplist );
FillSvrGroupList( grouplist, m_vGroups, _selfIP );
a.SetGroupList4SelfIP( oo.release() );
}
a.SetGroups( auto_groups.release() );
return 0;
}
int clsSvrListConfigBase::LoadConfigFromCConfig(Comm::CConfig& reader)
{
int ret = LoadConfigFromCConfigOld(reader);
logerr("LoadConfigFromCConfigOld ret %d", ret);
if (0 != ret)
{
return ret;
}
// only when LoadConfigFromCConfigOld == 0;
ret = LoadConfigFromCConfigNew(reader);
logerr("LoadConfigFromCConfigNew ret %d", ret);
return 0;
}
int clsSvrListConfigBase::LoadConfigFromCConfigNew(Comm::CConfig& reader)
{
if (false == _bOpenTest)
{
return 0; // do nothing;
}
assert(NULL != _old);
assert(NULL != _curr);
//1. clear old
if (_old->_poConHash != _curr->_poConHash)
{
_old->FreeConHash();
}
_old->FreeGroups();
_old->FreeGroupList4SelfIP();
//2. load config -> old
int ret = LoadConfigFromCConfig_New(
*_old, _old->_iConsistentHash, _old->_iServerCount,
_old->_poConHash, reader,
_svrListPath, _selfIP);
if (!ret)
{
if (_old->_iConsistentHash && !_old->_poConHash)
{
_old->_poConHash = _curr->_poConHash;
}
std::swap(_curr, _old);
}
return ret;
}
//int clsSvrListConfigBase::LoadConfigFromCConfigNew(Comm::CConfig& reader)
//{
// if (false == s_bOpenTest)
// {
// return 0;
// }
//
// //1. clear old
// //
//// printf("o->_poConHash %p curr->_poConHash %p\n",
//// s_o->_poConHash,s_curr->_poConHash );
//
// if( s_o->_poConHash != s_curr->_poConHash )
// {
// s_o->FreeConHash();
// }
//
//// printf("o->pvGroups %p\n",s_o->pvGroups );
//
// s_o->FreeGroups();
// s_o->FreeGroupList4SelfIP();
//
// //2. load config -> old
// //
// int ret = LoadConfigFromCConfig_New( *s_o, s_o->_iConsistentHash,
// s_o->_iServerCount,
// s_o->_poConHash,
// reader,
// _svrListPath,
// _selfIP );
//
//// printf("ret %d %p\n",ret,s_o->pvGroups );
// if( !ret )
// {
//
// if( s_o->_iConsistentHash && !s_o->_poConHash )
// {
// s_o->_poConHash = s_curr->_poConHash;
// }
//
// //swap s_curr <-> s_o
//// printf ( "before swap s_o %p s_curr %p\n", s_o, s_curr );
// param *n = s_curr; s_curr = s_o; s_o = n;
//// printf ( "after swap s_o %p s_curr %p\n", s_o, s_curr );
//
// }
// return ret;
//}
int clsSvrListConfigBase::LoadConfigFromCConfigOld( Comm::CConfig& reader )
{
// cp from clsNewSvrListConfig::LoadConfg(Comm::CConfig& reader)
// 1.
static SvrGroupList_t* pOldGroupList = NULL;
static clsConHash* pOldConHash = NULL;
{
free(pOldGroupList);
pOldGroupList = NULL;
free(pOldConHash);
pOldConHash = NULL;
}
if(ReadUintItem(reader, _svrListPath, "General", "GroupCount", _iGroupCount) < 0)
{
_iGroupCount = 6;
}
if(ReadUintItem(reader, _svrListPath, "General", "FailPeriod", _iFailPeriod) < 0 ||
ReadUintItem(reader, _svrListPath, "General", "FailCount", _iFailCount) < 0 ||
ReadUintItem(reader, _svrListPath, "General", "TimeOut", _iTimeOut) < 0)
{
_iFailPeriod=60;
_iFailCount=60;
_iTimeOut=500;
}
uint32_t iServerCount = 0;
if(ReadUintItem(reader, _svrListPath, "Server", "ServerCount", iServerCount) < 0)
{
return -1;
}
ReadUintItem(reader, _svrListPath, "Server", "KvConsistentHash", _iConsistentHash);
//server count of conhash changed, clsConHash should be reinit
if (_iServerCount != iServerCount && _iConsistentHash)
{
clsConHash * poConHash = new clsConHash();
int ret = poConHash->Init(iServerCount);
if (ret < 0)
{
logerr("ERR: clsConHash Init(%d) %d", iServerCount, ret);
return -1;
}
pOldConHash = _poConHash;
_poConHash = poConHash;
_iServerCount = iServerCount;
}
char section[16] = {0};
SvrGroupList_t * grouplist = (SvrGroupList_t*)calloc(sizeof(SvrGroupList_t), 1);
bzero(grouplist, sizeof(SvrGroupList_t));
for(uint32_t index = 0; index < iServerCount; ++index)
{
snprintf(section, sizeof(section), "Server%d", index);
uint32_t svrCountAB = 0, svrCountC = 0, port = 0, begin = 0, end = 0;
if(ReadUintItem(reader, _svrListPath, section, "SVRCount", svrCountAB) < 0 ||
ReadUintItem(reader, _svrListPath, section, "SVR_C_Count", svrCountC) < 0 ||
ReadUintItem(reader, _svrListPath, section, "SVR_Port", port) < 0)
{
return -1;
}
if (!_iConsistentHash)
{
if(ReadUintItem(reader, _svrListPath, section, "Sect_Begin", begin) < 0 ||
ReadUintItem(reader, _svrListPath, section, "Sect_End", end) < 0)
{
return -1;
}
}
std::vector<std::string> ipAB, ipC;
if(ReadBatchStrItem(reader, _svrListPath, svrCountAB, section, "SVR", ipAB) < 0 ||
ReadBatchStrItem(reader, _svrListPath, svrCountC, section, "SVR_C", ipC) < 0)
{
return -1;
}
bool bContainAB = IsVectorContain(ipAB, _selfIP);
bool bContainC = IsVectorContain(ipC, _selfIP);
if(!bContainAB && !bContainC)
{
continue;
}
//for consistenthash
if (_iConsistentHash)
{
begin = index;
end = index;
}
//generate fake c ips
GenerateFakeIPC(svrCountAB, _iGroupCount, ipC);
svrCountC = ipC.size();
SvrGroup_t * group = &(grouplist->tSvrGroup[grouplist->iGroupCnt]);
group->iCountAB = svrCountAB;
group->iCountC = svrCountC;
group->iBegin = begin;
group->iEnd = end;
group->iGroupCount = _iGroupCount;
FillSvrAddr(ipAB, port, group->tAddrAB);
FillSvrAddr(ipC, port, group->tAddrC);
if(bContainC)
{
grouplist->iMachineC = 1;
}
grouplist->iGroupCnt++;
assert(grouplist->iGroupCnt <= MAX_C_SHARE_GROUP);
if(bContainAB)
{
break;
}
}
//no changed
if(NULL != _grouplist && 0 == memcmp(grouplist, _grouplist, sizeof(SvrGroupList_t)))
{
free(grouplist);
grouplist = NULL;
return 0;
}
if(grouplist->iGroupCnt == 0)
{
return 1;
}
else
{
pOldGroupList = _grouplist;
_grouplist = grouplist;
logerr("\033[33m INFO: %s:%d kvsvr_list.conf changed\033[0m\n", __FILE__, __LINE__);
return 0;
}
return -1;
}
void clsSvrListConfigBase::SetSelfIP(const char* sIP)
{
snprintf(_selfIP, sizeof(_selfIP), "%s", sIP);
}
void clsSvrListConfigBase::SetSvrListPath(const char* sSvrListPath)
{
snprintf(_svrListPath, sizeof(_svrListPath), "%s", sSvrListPath);
}
void clsSvrListConfigBase::GetSvrGroupList(SvrGroupList_t& grouplist)
{
if (NULL == _grouplist)
{
memset(&grouplist, 0, sizeof(SvrGroupList_t));
return ;
}
assert(NULL != _grouplist);
grouplist.iGroupCnt = _grouplist->iGroupCnt;
grouplist.iMachineC = _grouplist->iMachineC;
memcpy(grouplist.tSvrGroup, _grouplist->tSvrGroup,
sizeof(SvrGroup_t) * grouplist.iGroupCnt);
}
clsConHash* clsSvrListConfigBase::GetConHash()
{
return _poConHash;
}
void clsSvrListConfigBase::PrintSvrList()
{
printf("SvrGroupList_t %p self %s path %s\n", _grouplist, _selfIP, _svrListPath);
if(_grouplist == NULL)
{
return;
}
printf("iGroupCnt %u iMachineC %u\n", _grouplist->iGroupCnt, _grouplist->iMachineC);
for(int index = 0; index < MAX_C_SHARE_GROUP; ++index)
{
printf("index %d\n", index);
SvrGroup_t & group = _grouplist->tSvrGroup[index];
printf("\tiCountAB %u iCountC %u iBegin %u iEnd %u iGroupCount %u\n",
group.iCountAB, group.iCountC, group.iBegin, group.iEnd, group.iGroupCount);
for(int cursor = 0; cursor < MAX_SVR_COUNT_AB_PER_GROUP; ++cursor)
{
printf("\tSVR%d %s\n", cursor, group.tAddrAB[cursor].GetIP());
}
for(int cursor = 0; cursor < MAX_SVR_COUNT_C_PER_GROUP; ++cursor)
{
printf("\tSVRC%d %s\n", cursor, group.tAddrC[cursor].GetIP());
}
}
}
int clsSvrListConfigBase::GetSelfIdx()
{
if( !_grouplist ) return -1;
for(size_t i=0;i < sizeof(_grouplist->tSvrGroup) / sizeof(_grouplist->tSvrGroup[0] );i++)
{
SvrGroup_t &g = _grouplist->tSvrGroup[i];
for( size_t j=0;j<sizeof(g.tAddrAB) / sizeof(g.tAddrAB[0]);j++ )
{
SvrAddr_t &a = g.tAddrAB[j];
if( !strcmp( _selfIP,a.GetIP() ) )
{
return j;
}
}
for( size_t j=0;j<sizeof(g.tAddrC) / sizeof(g.tAddrC[0]);j++ )
{
SvrAddr_t &a = g.tAddrC[j];
if( !strcmp( _selfIP,a.GetIP() ) )
{
return j + g.iCountAB;
}
}
}
return -1;
}
SvrGroup_t *clsSvrListConfigBase::GetBySect( uint32_t sect )
{
if (NULL == _curr)
{
return NULL;
}
assert(NULL != _curr);
return GetSvrGroupBySect(*(_curr->pvGroups), sect);
// if( !s_curr ) return NULL;
// return GetSvrGroupBySect( *s_curr->pvGroups,sect );
}
int clsSvrListConfigBase::GetSvrSetIdx(uint32_t sect)
{
if (NULL == _curr)
{
return -1;
}
assert(NULL != _curr);
const std::vector<SvrGroup_t*>& vecSvrGroup = *(_curr->pvGroups);
if (true == vecSvrGroup.empty() || sect < vecSvrGroup[0]->iBegin)
{
return -2;
}
clsCmpSvrGroup cmp;
std::vector<SvrGroup_t*>::const_iterator
iter = std::lower_bound(
vecSvrGroup.begin(), vecSvrGroup.end(), sect, cmp);
if (iter == vecSvrGroup.end() ||
(*iter)->iBegin > sect || (*iter)->iEnd < sect)
{
return -3;
}
assert(iter != vecSvrGroup.end());
return iter - vecSvrGroup.begin();
}
int clsSvrListConfigBase::GetAllDataSvr(std::vector<SvrAddr_t>& vecDataSvr)
{
if (NULL == _curr)
{
return -1;
}
assert(NULL != _curr);
vecDataSvr.clear();
std::vector<SvrGroup_t*>& vecSvrGroup = *(_curr->pvGroups);
for (size_t i = 0; i < vecSvrGroup.size(); ++i)
{
SvrGroup_t* pGrp = vecSvrGroup[i];
assert(NULL != pGrp);
vecDataSvr.reserve(vecDataSvr.size() + pGrp->iCountAB);
for (uint32_t k = 0; k < pGrp->iCountAB; ++k)
{
vecDataSvr.push_back(pGrp->tAddrAB[k]);
}
}
return 0;
// if (NULL == s_curr)
// {
// return -1;
// }
//
// vecDataSvr.clear();
// vector<SvrGroup_t*>& vecSvrGroup = *(s_curr->pvGroups);
// for (size_t i = 0; i < vecSvrGroup.size(); ++i)
// {
// SvrGroup_t* pGrp = vecSvrGroup[i];
// assert(NULL != pGrp);
// vecDataSvr.reserve(vecDataSvr.size() + pGrp->iCountAB);
// for (uint32_t k = 0; k < pGrp->iCountAB; ++k)
// {
// vecDataSvr.push_back(pGrp->tAddrAB[k]);
// }
// }
//
// return 0;
}
void clsSvrListConfigBase::OpenTest()
{
s_bOpenTest = true;
}
void clsSvrListConfigBase::OpenTestFlag()
{
if (_bOpenTest)
{
assert(NULL != _old);
assert(NULL != _curr);
return ;
}
_old = new param;
_curr = new param;
assert(NULL != _old);
assert(NULL != _curr);
_bOpenTest = true;
}
namespace {
void* UpdateConfigThread(void* arg)
{
BindToLastCpu();
clsSillySvrListConfig* poConfig =
reinterpret_cast<clsSillySvrListConfig*>(arg);
assert(NULL != poConfig);
while (true)
{
int ret = poConfig->UpdateConfig();
logerr("UpdateConfig ret %d", ret);
sleep(1);
}
return NULL;
}
} // namespace
clsSillySvrListConfig::clsSillySvrListConfig(const char* sSvrListConf)
{
assert(NULL != sSvrListConf);
SetSvrListPath(sSvrListConf);
// !!!
OpenTestFlag();
}
int clsSillySvrListConfig::UpdateConfig()
{
CConfig reader(GetSvrListPath());
int ret = reader.Init();
if (0 > ret)
{
logerr("ERR: %s[%d] CConfig::Init %s ret %d",
__FILE__, __LINE__, GetSvrListPath(), ret);
return ret;
}
LoadConfigFromCConfigOld(reader);
return LoadConfigFromCConfigNew(reader);
}
| 21.755825 | 307 | 0.649503 | [
"vector"
] |
698234d920cdc7f84fc41b8e8f43e52c739cf244 | 633 | cpp | C++ | Syl3D/entity/uvsphere.cpp | Vivekyadavgithub/Syl3D | 9533f69d4c96d7d7d9bcc4189b218a7a9138f12a | [
"MIT"
] | null | null | null | Syl3D/entity/uvsphere.cpp | Vivekyadavgithub/Syl3D | 9533f69d4c96d7d7d9bcc4189b218a7a9138f12a | [
"MIT"
] | null | null | null | Syl3D/entity/uvsphere.cpp | Vivekyadavgithub/Syl3D | 9533f69d4c96d7d7d9bcc4189b218a7a9138f12a | [
"MIT"
] | null | null | null | #include "uvsphere.h"
using namespace entity;
UVSphere::UVSphere(int parallels, int meridians, std::string shaderName)
:
Entity(shaderName),
_sphere(std::make_shared<mesh::UVSphereMesh>(parallels, meridians))
{
this->initialize({ std::static_pointer_cast<mesh::Mesh>(_sphere) });
}
UVSphere::UVSphere(math::Vec3 startingPos, int parallels, int meridians, std::string shaderName)
:
UVSphere(parallels, meridians, shaderName)
{
_pos = startingPos;
}
void UVSphere::draw() {
if (_usesEBO) {
glBindVertexArray(_VAOs[0]);
glDrawElements(GL_TRIANGLES, _sphere->numIndices() / sizeof(unsigned int), GL_UNSIGNED_INT, 0);
}
} | 25.32 | 97 | 0.744076 | [
"mesh"
] |
6983491fdfa07d3665399c7915332621e36a7d04 | 5,127 | cpp | C++ | src/main/resources/main/c++/DynamicRenderable.cpp | yildiz-online/module-graphic-ogre | 8f45fbfd3984d3f9f3143767de5b211e9a9c525f | [
"MIT"
] | null | null | null | src/main/resources/main/c++/DynamicRenderable.cpp | yildiz-online/module-graphic-ogre | 8f45fbfd3984d3f9f3143767de5b211e9a9c525f | [
"MIT"
] | 8 | 2018-11-19T20:41:21.000Z | 2021-12-03T03:03:51.000Z | src/main/resources/main/c++/DynamicRenderable.cpp | yildiz-online/module-graphic-ogre | 8f45fbfd3984d3f9f3143767de5b211e9a9c525f | [
"MIT"
] | null | null | null | /*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2019 Grégory Van den Borre
*
* More infos available: https://engine.yildiz-games.be
*
* 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 "../includes/DynamicRenderable.hpp"
using namespace Ogre;
DynamicRenderable::DynamicRenderable()
{
}
DynamicRenderable::~DynamicRenderable()
{
delete mRenderOp.vertexData;
delete mRenderOp.indexData;
}
void DynamicRenderable::initialize(RenderOperation::OperationType operationType,
bool useIndices)
{
// Initialize render operation
mRenderOp.operationType = operationType;
mRenderOp.useIndexes = useIndices;
mRenderOp.vertexData = new VertexData;
if (mRenderOp.useIndexes)
mRenderOp.indexData = new IndexData;
// Reset buffer capacities
mVertexBufferCapacity = 0;
mIndexBufferCapacity = 0;
// Create vertex declaration
createVertexDeclaration();
}
void DynamicRenderable::prepareHardwareBuffers(size_t vertexCount,
size_t indexCount)
{
// Prepare vertex buffer
size_t newVertCapacity = mVertexBufferCapacity;
if ((vertexCount > mVertexBufferCapacity) ||
(!mVertexBufferCapacity))
{
// vertexCount exceeds current capacity!
// It is necessary to reallocate the buffer.
// Check if this is the first call
if (!newVertCapacity)
newVertCapacity = 1;
// Make capacity the next power of two
while (newVertCapacity < vertexCount)
newVertCapacity <<= 1;
}
else if (vertexCount < mVertexBufferCapacity>>1) {
// Make capacity the previous power of two
while (vertexCount < newVertCapacity>>1)
newVertCapacity >>= 1;
}
if (newVertCapacity != mVertexBufferCapacity)
{
mVertexBufferCapacity = newVertCapacity;
// Create new vertex buffer
HardwareVertexBufferSharedPtr vbuf =
HardwareBufferManager::getSingleton().createVertexBuffer(
mRenderOp.vertexData->vertexDeclaration->getVertexSize(0),
mVertexBufferCapacity,
HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); // TODO: Custom HBU_?
// Bind buffer
mRenderOp.vertexData->vertexBufferBinding->setBinding(0, vbuf);
}
// Update vertex count in the render operation
mRenderOp.vertexData->vertexCount = vertexCount;
if (mRenderOp.useIndexes)
{
OgreAssert(indexCount <= std::numeric_limits<unsigned short>::max(), "indexCount exceeds 16 bit");
size_t newIndexCapacity = mIndexBufferCapacity;
// Prepare index buffer
if ((indexCount > newIndexCapacity) ||
(!newIndexCapacity))
{
// indexCount exceeds current capacity!
// It is necessary to reallocate the buffer.
// Check if this is the first call
if (!newIndexCapacity)
newIndexCapacity = 1;
// Make capacity the next power of two
while (newIndexCapacity < indexCount)
newIndexCapacity <<= 1;
}
else if (indexCount < newIndexCapacity>>1)
{
// Make capacity the previous power of two
while (indexCount < newIndexCapacity>>1)
newIndexCapacity >>= 1;
}
if (newIndexCapacity != mIndexBufferCapacity)
{
mIndexBufferCapacity = newIndexCapacity;
// Create new index buffer
mRenderOp.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_16BIT,
mIndexBufferCapacity,
HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); // TODO: Custom HBU_?
}
// Update index count in the render operation
mRenderOp.indexData->indexCount = indexCount;
}
}
Real DynamicRenderable::getBoundingRadius() const
{
return Math::Sqrt(std::max(mBox.getMaximum().squaredLength(), mBox.getMinimum().squaredLength()));
}
Real DynamicRenderable::getSquaredViewDepth(const Camera* cam) const
{
Vector3 vMin, vMax, vMid, vDist;
vMin = mBox.getMinimum();
vMax = mBox.getMaximum();
vMid = ((vMax - vMin) * 0.5) + vMin;
vDist = cam->getDerivedPosition() - vMid;
return vDist.squaredLength();
}
| 33.077419 | 119 | 0.707821 | [
"render"
] |
698b2389ff217abb00e39e222852ce1457ca8d7d | 674 | cpp | C++ | Leetcode/res/Find All Numbers Disappeared in an Array/1.cpp | AllanNozomu/CompetitiveProgramming | ac560ab5784d2e2861016434a97e6dcc44e26dc8 | [
"MIT"
] | 1 | 2022-03-04T16:06:41.000Z | 2022-03-04T16:06:41.000Z | Leetcode/res/Find All Numbers Disappeared in an Array/1.cpp | AllanNozomu/CompetitiveProgramming | ac560ab5784d2e2861016434a97e6dcc44e26dc8 | [
"MIT"
] | null | null | null | Leetcode/res/Find All Numbers Disappeared in an Array/1.cpp | AllanNozomu/CompetitiveProgramming | ac560ab5784d2e2861016434a97e6dcc44e26dc8 | [
"MIT"
] | null | null | null | \*
Author: allannozomu
Runtime: 116 ms
Memory: 14.7 MB*\
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int qty = nums.size();
int res_qty = qty;
for (int i = 0 ; i < qty; ++i){
int curr_index = nums[i] < 0 ? -(nums[i]) : nums[i];
curr_index--;
if (nums[curr_index] > 0){
nums[curr_index] *= -1;
res_qty--;
}
}
vector<int> res = vector<int>(res_qty);
for (int i = 0 ; i < qty; ++i){
if (nums[i] > 0){
res[--res_qty] = (i + 1);
}
}
return res;
}
}; | 24.962963 | 64 | 0.431751 | [
"vector"
] |
7e348caebdf131300f2e255ba9a0ad11814350b0 | 6,252 | cpp | C++ | ext/stub/java/awt/LinearGradientPaint-stub.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/stub/java/awt/LinearGradientPaint-stub.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/stub/java/awt/LinearGradientPaint-stub.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/awt/LinearGradientPaint.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace java
{
namespace awt
{
typedef ::SubArray< ::java::awt::Transparency, ::java::lang::ObjectArray > TransparencyArray;
typedef ::SubArray< ::java::awt::Paint, ::java::lang::ObjectArray, TransparencyArray > PaintArray;
} // awt
namespace io
{
typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray;
} // io
namespace awt
{
typedef ::SubArray< ::java::awt::Color, ::java::lang::ObjectArray, PaintArray, ::java::io::SerializableArray > ColorArray;
} // awt
} // java
extern void unimplemented_(const char16_t* name);
java::awt::LinearGradientPaint::LinearGradientPaint(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
java::awt::LinearGradientPaint::LinearGradientPaint(::java::awt::geom::Point2D* start, ::java::awt::geom::Point2D* end, ::floatArray* fractions, ColorArray* colors)
: LinearGradientPaint(*static_cast< ::default_init_tag* >(0))
{
ctor(start, end, fractions, colors);
}
java::awt::LinearGradientPaint::LinearGradientPaint(::java::awt::geom::Point2D* start, ::java::awt::geom::Point2D* end, ::floatArray* fractions, ColorArray* colors, MultipleGradientPaint_CycleMethod* cycleMethod)
: LinearGradientPaint(*static_cast< ::default_init_tag* >(0))
{
ctor(start, end, fractions, colors, cycleMethod);
}
java::awt::LinearGradientPaint::LinearGradientPaint(float startX, float startY, float endX, float endY, ::floatArray* fractions, ColorArray* colors)
: LinearGradientPaint(*static_cast< ::default_init_tag* >(0))
{
ctor(startX, startY, endX, endY, fractions, colors);
}
java::awt::LinearGradientPaint::LinearGradientPaint(float startX, float startY, float endX, float endY, ::floatArray* fractions, ColorArray* colors, MultipleGradientPaint_CycleMethod* cycleMethod)
: LinearGradientPaint(*static_cast< ::default_init_tag* >(0))
{
ctor(startX, startY, endX, endY, fractions, colors, cycleMethod);
}
java::awt::LinearGradientPaint::LinearGradientPaint(::java::awt::geom::Point2D* start, ::java::awt::geom::Point2D* end, ::floatArray* fractions, ColorArray* colors, MultipleGradientPaint_CycleMethod* cycleMethod, MultipleGradientPaint_ColorSpaceType* colorSpace, ::java::awt::geom::AffineTransform* gradientTransform)
: LinearGradientPaint(*static_cast< ::default_init_tag* >(0))
{
ctor(start, end, fractions, colors, cycleMethod, colorSpace, gradientTransform);
}
void ::java::awt::LinearGradientPaint::ctor(::java::awt::geom::Point2D* start, ::java::awt::geom::Point2D* end, ::floatArray* fractions, ColorArray* colors)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::awt::LinearGradientPaint::ctor(::java::awt::geom::Point2D* start, ::java::awt::geom::Point2D* end, ::floatArray* fractions, ColorArray* colors)");
}
void ::java::awt::LinearGradientPaint::ctor(::java::awt::geom::Point2D* start, ::java::awt::geom::Point2D* end, ::floatArray* fractions, ColorArray* colors, MultipleGradientPaint_CycleMethod* cycleMethod)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::awt::LinearGradientPaint::ctor(::java::awt::geom::Point2D* start, ::java::awt::geom::Point2D* end, ::floatArray* fractions, ColorArray* colors, MultipleGradientPaint_CycleMethod* cycleMethod)");
}
void ::java::awt::LinearGradientPaint::ctor(float startX, float startY, float endX, float endY, ::floatArray* fractions, ColorArray* colors)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::awt::LinearGradientPaint::ctor(float startX, float startY, float endX, float endY, ::floatArray* fractions, ColorArray* colors)");
}
void ::java::awt::LinearGradientPaint::ctor(float startX, float startY, float endX, float endY, ::floatArray* fractions, ColorArray* colors, MultipleGradientPaint_CycleMethod* cycleMethod)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::awt::LinearGradientPaint::ctor(float startX, float startY, float endX, float endY, ::floatArray* fractions, ColorArray* colors, MultipleGradientPaint_CycleMethod* cycleMethod)");
}
void ::java::awt::LinearGradientPaint::ctor(::java::awt::geom::Point2D* start, ::java::awt::geom::Point2D* end, ::floatArray* fractions, ColorArray* colors, MultipleGradientPaint_CycleMethod* cycleMethod, MultipleGradientPaint_ColorSpaceType* colorSpace, ::java::awt::geom::AffineTransform* gradientTransform)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::awt::LinearGradientPaint::ctor(::java::awt::geom::Point2D* start, ::java::awt::geom::Point2D* end, ::floatArray* fractions, ColorArray* colors, MultipleGradientPaint_CycleMethod* cycleMethod, MultipleGradientPaint_ColorSpaceType* colorSpace, ::java::awt::geom::AffineTransform* gradientTransform)");
}
java::awt::PaintContext* java::awt::LinearGradientPaint::createContext(::java::awt::image::ColorModel* cm, Rectangle* deviceBounds, ::java::awt::geom::Rectangle2D* userBounds, ::java::awt::geom::AffineTransform* transform, RenderingHints* hints)
{ /* stub */
unimplemented_(u"java::awt::PaintContext* java::awt::LinearGradientPaint::createContext(::java::awt::image::ColorModel* cm, Rectangle* deviceBounds, ::java::awt::geom::Rectangle2D* userBounds, ::java::awt::geom::AffineTransform* transform, RenderingHints* hints)");
return 0;
}
java::awt::geom::Point2D* java::awt::LinearGradientPaint::getEndPoint()
{ /* stub */
unimplemented_(u"java::awt::geom::Point2D* java::awt::LinearGradientPaint::getEndPoint()");
return 0;
}
java::awt::geom::Point2D* java::awt::LinearGradientPaint::getStartPoint()
{ /* stub */
unimplemented_(u"java::awt::geom::Point2D* java::awt::LinearGradientPaint::getStartPoint()");
return 0;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* java::awt::LinearGradientPaint::class_()
{
static ::java::lang::Class* c = ::class_(u"java.awt.LinearGradientPaint", 28);
return c;
}
java::lang::Class* java::awt::LinearGradientPaint::getClass0()
{
return class_();
}
| 50.829268 | 333 | 0.727927 | [
"transform"
] |
7e3af736c28f47fe6be0b20710519ac956396cab | 30,858 | cpp | C++ | src/distributed_paillier.cpp | fedlearnJDT/libfedlearn | 581dfeca7ba6c49c480b883a883001dce7922f76 | [
"Apache-2.0"
] | 8 | 2021-07-20T01:54:18.000Z | 2021-11-09T07:56:04.000Z | src/distributed_paillier.cpp | fedlearnJDT/libfedlearn | 581dfeca7ba6c49c480b883a883001dce7922f76 | [
"Apache-2.0"
] | null | null | null | src/distributed_paillier.cpp | fedlearnJDT/libfedlearn | 581dfeca7ba6c49c480b883a883001dce7922f76 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 The FedLearn 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 <distributed_paillier.h>
/***************************************
* Distributed Paillier key generation
***************************************/
LIST_OF_CHAR_LIST
distributed_paillier::create_prime_share(vector<long> &ret_char_size,
vector<bool> &is_negative_lst,
NTL::ZZ &s) {
NTL::GenPrime(s, bit_len);
ShamirSecretSharingScheme scheme = ShamirSecretSharingScheme(P, n, t);
ShamirShares share = scheme.share_secret(s);
// return shared points (a,b) to JAVA interface
// NB: a is always 1, 2, 3, ..., t+1
LIST_OF_CHAR_LIST ret;
ret.reserve(share.shares.length());
int i = 0;
for (const auto &each_point : share.shares) {
CHAR_LIST one_point;
bool is_negative;
ret_char_size[i] = ZZ_2_byte(one_point, each_point.b, is_negative);
is_negative_lst[i] = is_negative;
i++;
ret.push_back(one_point);
}
// check if share is constructed correctly
assert(s == share.reconstruct_secret(P));
std::cout << "s = " << s << " P = " << P << endl;
return ret;
}
LIST_OF_CHAR_LIST
distributed_paillier::create_lambda_share(CHAR_LIST &secret,
bool &is_neg_in,
vector<long> &ret_char_size,
vector<bool> &is_negative_lst) {
return __create_share_integer__(secret, is_neg_in, ret_char_size, is_negative_lst);
}
LIST_OF_CHAR_LIST
distributed_paillier::create_beta_share(CHAR_LIST &secret,
bool &is_neg_in,
vector<long> &ret_char_size,
vector<bool> &is_negative_lst) {
return __create_share_integer__(secret, is_neg_in, ret_char_size, is_negative_lst);
}
LIST_OF_CHAR_LIST
distributed_paillier::__create_share_integer__(CHAR_LIST &secret,
bool &is_neg_in,
vector<long> &ret_char_size,
vector<bool> &is_negative_lst) {
NTL::ZZ s;
distributed_paillier::char_list_2_ZZ(s, secret, is_neg_in);
if (s > P) {
std::cout << "secret is larger then P." << endl;
assert(s <= P);
}
NTL::Vec<NTL::Pair<long, NTL::ZZ>> shares = __create_share_integer__(s);
LIST_OF_CHAR_LIST ret;
ret.reserve(shares.length());
int i = 0;
for (const auto &each_point : shares) {
CHAR_LIST one_point;
bool is_negative;
ret_char_size[i] = ZZ_2_byte(one_point, each_point.b, is_negative);
is_negative_lst[i] = is_negative;
ret.push_back(one_point);
i++;
}
return ret;
}
NTL::Vec<NTL::Pair<long, NTL::ZZ>>
distributed_paillier::__create_share_integer__(ZZ &s) {
ShamirSecretSharingSchemeInteger scheme = ShamirSecretSharingSchemeInteger(P, n, t, kappa);
ShamirShares_integer share = scheme.share_secret(NTL::to_ZZ(s));
integer_share_scaling_fac = NTL::to_long(share.scaling);
return share.shares;
}
/**
* Re-share additive Shamir shares.
*
* Parameters:
* a: the first value of a point, i.e. a in point(a, b)
* in_lst: b_j from other shares, i.e. b_1, b_2, ..., b_t+1 in
* point(a, b_1), (a, b_2), ..., (a, b_t+1)
*/
NTL::Pair<long, NTL::ZZ>
distributed_paillier::__reshare__(NTL::Vec<NTL::Pair<long, NTL::ZZ>> in_lst,
const NTL::ZZ& modulu) {
NTL::ZZ b(0);
long a = in_lst[0].a;
for (const auto &pair : in_lst) {
NTL::add(b, b, pair.b);
if (a != pair.a) {
std::cout << "a in points(a, b) are not the same. a = " + to_string(a) + ", pair.a = " + to_string(pair.a)
<< endl;
assert(a == pair.a);
}
}
return NTL::Pair<long, NTL::ZZ>(a, b);
}
CHAR_LIST
distributed_paillier::reshare(const LIST_OF_CHAR_LIST& in_lst,
const vector<bool> &is_negative_lst_in,
bool &is_negative_out,
long &a,
vector<long> &ret_char_size,
const CHAR_LIST& modulu_char) {
NTL::Vec<NTL::Pair<long, NTL::ZZ>> share_part;
int i = 0;
for (const auto &char_list : in_lst) {
NTL::ZZ b;
char_list_2_ZZ(b, char_list, is_negative_lst_in[i]);
share_part.append(NTL::Pair<long, NTL::ZZ>(a, b));
i++;
}
NTL::ZZ modulu;
char_list_2_ZZ(modulu, modulu_char, false);
NTL::Pair<long, NTL::ZZ> res = __reshare__(share_part, modulu);
CHAR_LIST one_point;
ZZ_2_byte(one_point, res.b, is_negative_out);
return one_point;
}
NTL::Pair<long, NTL::ZZ>
distributed_paillier::reshare(const LIST_OF_CHAR_LIST& in_lst,
const vector<bool> &is_negative_lst_in,
long &a,
const NTL::ZZ& modulu) {
NTL::Vec<NTL::Pair<long, NTL::ZZ>> share_part;
int i = 0;
for (const auto &char_list : in_lst) {
NTL::ZZ b;
char_list_2_ZZ(b, char_list, is_negative_lst_in[i]);
share_part.append(NTL::Pair<long, NTL::ZZ>(a, b));
i++;
}
NTL::Pair<long, NTL::ZZ> res = __reshare__(share_part, modulu);
return res;
}
/** Compute share part of lambda*beta at point a
* Return:
* res[0] -- lambda_times_beta
* res[1] -- theta
* NB: 1. this would make the threshold increase to 2*t, which means
* that 2*t+1 points are needed for decryption. Original threshold is t.
* 2. we note that lambda_times_beta and theta must have the same sign
* this requires the scale factor to be positive.
*/
LIST_OF_CHAR_LIST
distributed_paillier::compute_lambda_times_beta_share(const LIST_OF_CHAR_LIST& in_lst_lambda,
const LIST_OF_CHAR_LIST& in_lst_beta,
const LIST_OF_BOOL &is_negative_lst_in_lam,
const LIST_OF_BOOL &is_negative_lst_in_beta,
const CHAR_LIST &modulu_char,
long &a,
vector<long> &ret_char_size,
bool &is_negative_out,
bool &theta_is_negative_out,
long const &scalar) {
NTL::ZZ modulu;
char_list_2_ZZ(modulu, modulu_char, false);
NTL::Pair<long, NTL::ZZ> lamd = reshare(in_lst_lambda, is_negative_lst_in_lam, a, modulu);
NTL::Pair<long, NTL::ZZ> beta = reshare(in_lst_beta, is_negative_lst_in_beta, a, modulu);
NTL::ZZ lambda_times_beta, theta_share;
NTL::mul(lambda_times_beta, lamd.b, beta.b);
theta_share = compute_theta_share(lambda_times_beta, modulu);
LIST_OF_CHAR_LIST res(2);
ZZ_2_byte(res[0], lambda_times_beta, is_negative_out);
ZZ_2_byte(res[1], theta_share, theta_is_negative_out);
// std::cout << lambda_times_beta << endl;
return res;
}
/**
* \brief adding shares of lambda and beta, then compute one share of sum(lambda)*sum(beta)
* @param in_lst_lambda shares of lambda_i for one party
* @param in_lst_beta shares of beta_i for one party
* @param modulu
* @param scalar ??
* @return
*/
std::vector<ZZ>
distributed_paillier::compute_lambda_times_beta_share(const NTL::Vec<NTL::Pair<long, NTL::ZZ>> & in_lst_lambda,
const NTL::Vec<NTL::Pair<long, NTL::ZZ>> & in_lst_beta,
const ZZ &modulu,
long const &scalar) {
NTL::Pair<long, NTL::ZZ> lamd = __reshare__(in_lst_lambda, modulu);
NTL::Pair<long, NTL::ZZ> beta = __reshare__(in_lst_beta, modulu);
NTL::ZZ lambda_times_beta, theta_share;
NTL::mul(lambda_times_beta, lamd.b, beta.b);
theta_share = compute_theta_share(lambda_times_beta, modulu);
std::vector<ZZ> res;
res.reserve(2);
res.emplace_back(lambda_times_beta);
res.emplace_back(theta_share);
return res;
}
/**
* \brief use all shares of theta to reconstruct theta
* @param theta_shares ALL shares of theta
* @param N modulo
* @return reconstructed theta
*/
NTL::ZZ
distributed_paillier::reveal_theta(const vector<NTL::ZZ> &theta_shares,
const NTL::ZZ &N,
const int & threshold,
const int & num_party) {
assert(theta_shares.size() >= 2 * threshold + 1);
NTL::ZZ nfct = factorial_small(num_party);
NTL::ZZ recon_theta(0);
for (long i = 1; i <= 2 * threshold + 1; i++) {
NTL::ZZ li, tmp;
NTL::ZZ enume = nfct;
NTL::ZZ denom = NTL::ZZ(1);
for (long j = 1; j <= 2 * threshold + 1; j++) {
if (i != j) {
enume *= j;
denom *= j - i;
}
}
NTL::div(li, enume, denom);
NTL::AddMod(recon_theta, recon_theta, li * theta_shares[i - 1], N);
}
NTL::ZZ scalar_inv;
NTL::InvMod(scalar_inv, nfct * sqr(nfct), N);
NTL::MulMod(recon_theta, recon_theta, scalar_inv, N);
NTL::MulMod(recon_theta, recon_theta, nfct * sqr(nfct), N);
return recon_theta;
}
/****************************
* Paillier arithmetic
****************************/
void distributed_paillier::add(cypher_text_t &res,
const cypher_text_t &a,
const cypher_text_t &b,
const dist_paillier_pubkey_t &pk) {
NTL::ZZ azz, bzz, reszz;
char_list_2_ZZ(azz, a.c, a.is_neg);
char_list_2_ZZ(bzz, b.c, b.is_neg);
NTL::MulMod(reszz, azz, bzz, pk.n_squared);
ZZ_2_byte(res.c, reszz, res.is_neg);
// cout << reszz <<" "
// << azz <<" "
// << bzz <<" "
// << endl;
}
void distributed_paillier::mul(cypher_text_t &res,
const cypher_text_t &a,
const plain_text_t &b,
const dist_paillier_pubkey_t &pk) {
NTL::ZZ azz, bzz, reszz;
char_list_2_ZZ(azz, a.c, a.is_neg);
char_list_2_ZZ(bzz, b.plain, b.is_negative);
// here azz should never be larger than pk.n_squared
assert(azz < pk.n_squared);
NTL::PowerMod(reszz, azz, bzz, pk.n_squared);
ZZ_2_byte(res.c, reszz, res.is_neg);
}
void distributed_paillier::mul(cypher_text_t &res,
const cypher_text_t &a,
const NTL::ZZ &b,
const dist_paillier_pubkey_t &pk) {
NTL::ZZ azz, reszz;
char_list_2_ZZ(azz, a.c, a.is_neg);
assert(azz < pk.n_squared);
NTL::PowerMod(reszz, azz, b, pk.n_squared);
ZZ_2_byte(res.c, reszz, res.is_neg);
}
void distributed_paillier::div(cypher_text_t &res,
const cypher_text_t &a,
const NTL::ZZ &b,
const dist_paillier_pubkey_t &pk) {
NTL::ZZ azz, reszz, b_inv;
char_list_2_ZZ(azz, a.c, a.is_neg);
assert(b != 0);
NTL::InvMod(b_inv, b, pk.n);
assert(azz < pk.n_squared);
NTL::PowerMod(reszz, azz, b_inv, pk.n_squared);
ZZ_2_byte(res.c, reszz, res.is_neg);
// cout << "reszz = " << reszz << endl;
}
/****************************
* Paillier Enc & Two-step Dec
****************************/
void distributed_paillier::enc(cypher_text_t &cypher_text,
const ZZ &plain,
const dist_paillier_pubkey_t &pb_key) {
NTL::ZZ c_zz, r;
do {
NTL::RandomBnd(r, pb_key.n);
// r = pb_key.n-1; // only for debug
} while (r == 0 || r == pb_key.n || (NTL::GCD(r, pb_key.n) != 1));
NTL::PowerMod(c_zz, pb_key.n_plusone, plain, pb_key.n_squared);
NTL::PowerMod(r, r, pb_key.n, pb_key.n_squared);
NTL::MulMod(c_zz, c_zz, r, pb_key.n_squared);
ZZ_2_byte(cypher_text.c, c_zz, cypher_text.is_neg);
}
void distributed_paillier::enc(cypher_text_t &cypher_text,
const plain_text_t &plain,
const dist_paillier_pubkey_t &pb_key) {
NTL::ZZ p_zz, c_zz, r;
do {
NTL::RandomBnd(r, pb_key.n);
// r = 1; // only for debug
} while (r == 0 || r == pb_key.n || (NTL::GCD(r, pb_key.n) != 1));
char_list_2_ZZ(p_zz, plain.plain, plain.is_negative);
NTL::PowerMod(c_zz, pb_key.n_plusone, p_zz, pb_key.n_squared);
NTL::PowerMod(r, r, pb_key.n, pb_key.n_squared);
NTL::MulMod(c_zz, c_zz, r, pb_key.n_squared);
ZZ_2_byte(cypher_text.c, c_zz, cypher_text.is_neg);
}
void distributed_paillier::dec_partial(const long i,
const long t,
cypher_text_t &partial_res,
const cypher_text_t &cypher_text,
const dist_paillier_privkey_t &priv_key) {
NTL::ZZ c, e;
char_list_2_ZZ(c, cypher_text.c, cypher_text.is_neg);
// compute li*hi
NTL::ZZ li;
long enume = priv_key.n_fat;
long denom = 1;
for (long j = 1; j <= 2 * t + 1; j++) {
if (i != j) {
enume *= j;
denom *= j - i;
}
}
li = enume / denom;
NTL::mul(c, li, priv_key.hi);
ZZ_2_byte(partial_res.c, c, partial_res.is_neg);
// std::cout << "li = " << li
// << endl;
}
void distributed_paillier::dec_final(plain_text_t &plain,
const cypher_text_t &cypher_text,
const std::vector<cypher_text_t> &lihi_lst,
const long &t,
const NTL::ZZ &max_negative_abs,
const dist_paillier_privkey_t &priv_key) {
NTL::ZZ res = dec_final(cypher_text, lihi_lst, t, max_negative_abs, priv_key);
ZZ_2_byte(plain.plain, res, plain.is_negative);
// std::cout << "res = " << res
// << " lihi_sum = " << lihi_sum
// << endl;
}
NTL::ZZ distributed_paillier::dec_final(const cypher_text_t &cypher_text,
const std::vector<cypher_text_t> &lihi_lst,
const long &t,
const NTL::ZZ &max_negative_abs,
const dist_paillier_privkey_t &priv_key) {
NTL::ZZ c, lihi_sum(0), res;
assert(lihi_lst.size() >= 2 * t + 1);
for (long i = 1; i <= 2 * t + 1; i++) {
NTL::ZZ tmp;
char_list_2_ZZ(tmp, lihi_lst[i - 1].c, lihi_lst[i - 1].is_neg);
NTL::add(lihi_sum, lihi_sum, tmp);
}
char_list_2_ZZ(c, cypher_text.c, cypher_text.is_neg);
NTL::PowerMod(res, c, lihi_sum, priv_key.n_squared);
NTL::add(res, res, -1);
if ((res % priv_key.n) != 0) {
std::cout << "res = " << res
<< " lihi_sum = " << lihi_sum
<< " c = " << c
<< " priv_key.n_squared = " << priv_key.n_squared
<< " priv_key.n = " << priv_key.n
<< endl;
assert(res % priv_key.n == 0);
}
NTL::div(res, res, priv_key.n);
NTL::MulMod(res, res, priv_key.theta_invmod, priv_key.n);
if (res > max_negative_abs) {
res = res - priv_key.n;
}
// std::cout << "res = " << res
// << " max_negative_abs = " << max_negative_abs
// << endl;
return res;
}
/****************************
* class utils
****************************/
long distributed_paillier::ZZ_2_byte(CHAR_LIST &out,
const NTL::ZZ &in,
bool &is_negative) {
// return shared points (a,b) to JAVA interface
// NB : a is always 1, 2, 3, ..., t+1
long char_size = NTL::NumBytes(in);
auto *pp = new unsigned char[char_size];
NTL::BytesFromZZ(pp, in, char_size); // pp = byte-representation
out.assign(pp, pp + char_size);
delete[] pp;
is_negative = (in < 0) != 0;
return char_size;
}
void distributed_paillier::char_list_2_ZZ(NTL::ZZ &out,
const CHAR_LIST &in,
const bool &is_negative) {
long char_size = in.size();
const unsigned char *in_pnt = in.data();
NTL::ZZFromBytes(out, in_pnt, char_size);
out = is_negative ? -1 * out : out;
}
bool distributed_paillier::check_points_in_order(const LIST_OF_LONG &input) {
long i = 1;
for (auto x : input) {
if (x != i) {
std::cout << "Input points are not in order of 1, 2, ..., t+1" << endl;
return false;
}
i += 1;
}
return true;
}
/**
* A standalone version priv-key generation. Should switch to
* distributed version
* ==========
* Parameters
* ...
* Return
* std::vector containing 2t+1 dist_paillier_privkey_t's.
*
* FIXME: NOTE that only 2t+1 keys are generated. This code does
* not work when n!=2t+1. Fixing is easy -- generating n shares
* of lambda*beta instead of 2t+1.
*/
std::vector<dist_paillier_privkey_t>
distributed_paillier::gene_privkey_standalone(const long &len,
const long &n,
const long &t) {
std::cout << "Generating priv-keys for all parties..." << endl;
// 2^N must be larger than sqr of the largest number in plain text
// assert( (long)2<<len > (plain_text_num*plain_text_num));
// NOTE that N is generated by one party here, thus bi-prime test is not done.
NTL::ZZ nfct = factorial_small(n);
NTL::ZZ p, q, P;
NTL::GenPrime(p, len);
NTL::GenPrime(q, len);
NTL::GenPrime(P, len);
const NTL::ZZ N = p * q;
// std::cout << "\np = " << p
// << "; q=" << q
// << "; N=" << N
// << "; P=" << P
// << ";"
// << endl;
NTL::Vec<NTL::ZZ> lambda_lst, beta_lst;
NTL::Vec<NTL::ZZ> pi_lst, qi_lst;
CHAR_LIST modulu_char;
bool modulu_char_isneg = false;
distributed_paillier::ZZ_2_byte(modulu_char, N, modulu_char_isneg);
std::vector<LIST_OF_CHAR_LIST> lambda_share, beta_share;
lambda_share.reserve(n);
beta_share.reserve(n);
LIST_OF_BOOL_LIST lambda_share_sign, beta_shares_sign;
lambda_share_sign.reserve(n);
beta_shares_sign.reserve(n);
std::vector<distributed_paillier> paillier_class_lst;
paillier_class_lst.reserve(n);
ZZ p_sum(0), q_sum(0);
for (long i = 1; i <= n; i++) {
paillier_class_lst.emplace_back(N, n, t, len);
}
for (long i = 1; i < n; i++) {
pi_lst.append(NTL::RandomBnd(p / n));
qi_lst.append(NTL::RandomBnd(q / n));
p_sum += pi_lst[i - 1];
q_sum += qi_lst[i - 1];
}
pi_lst.append(p - p_sum);
qi_lst.append(q - q_sum);
// check qi, pi correctness
p_sum = 0;
q_sum = 0;
for (long i = 0; i < n; i++) {
p_sum += pi_lst[i];
q_sum += qi_lst[i];
// cout << "pi_lst[" << i << "] = " << pi_lst[i]
// << "; qi_lst[" << i << "] = " << qi_lst[i] << ";"
// << endl;
assert((pi_lst[i] > 0) && (qi_lst[i] > 0));
}
assert(q_sum == q && p_sum == p);
for (long i = 1; i <= n; i++) {
NTL::ZZ tmp;
do {
tmp = NTL::RandomBnd(N);
// tmp = 1; // for debug
} while (tmp == 0);
beta_lst.append(tmp);
if (i == 1) {
lambda_lst.append(N - pi_lst[i - 1] - qi_lst[i - 1] + 1);
} else {
lambda_lst.append(-pi_lst[i - 1] - qi_lst[i - 1]);
}
JAVA_CHAR lam_char, beta_char;
std::vector<long> byte_arr_size_lambdai(n), byte_arr_size_betai((n));
LIST_OF_BOOL is_negative_lst_lambda(n);
LIST_OF_BOOL is_negative_lst_beta(n);
distributed_paillier::ZZ_2_byte(lam_char.byte_arr,
lambda_lst[i - 1],
lam_char.is_negative);
distributed_paillier::ZZ_2_byte(beta_char.byte_arr,
beta_lst[i - 1],
beta_char.is_negative);
lambda_share.push_back(
paillier_class_lst[i - 1].create_lambda_share(lam_char.byte_arr,
lam_char.is_negative,
byte_arr_size_lambdai,
is_negative_lst_lambda));
beta_share.push_back(
paillier_class_lst[i - 1].create_beta_share(beta_char.byte_arr,
beta_char.is_negative,
byte_arr_size_betai,
is_negative_lst_beta));
lambda_share_sign.push_back(is_negative_lst_lambda);
beta_shares_sign.push_back(is_negative_lst_beta);
}
// 1) simulate network transfer -- transferring shares to each party
// 2) compute Lambda*beta
// NB: be careful with the size of reconstruction party.
NTL::Vec<ZZ> theta_lst, hi;
for (long i = 1; i <= 2 * t + 1; i++) {
LIST_OF_CHAR_LIST tmp_res(2);
CHAR_LIST lamb_times_beta;
CHAR_LIST theta;
bool lamb_times_beta_isneg, theta_is_neg;
vector<long> ret_char_size(n);
// lambda recv
LIST_OF_CHAR_LIST reorganized_lambda_b;
LIST_OF_BOOL reorganized_lambda_b_neg;
LIST_OF_LONG reorganized_a;
__recv_and_reorganize__(lambda_share, lambda_share_sign,
reorganized_lambda_b, reorganized_lambda_b_neg,
reorganized_a, n, i);
// beta recv
LIST_OF_CHAR_LIST reorganized_beta_b;
LIST_OF_BOOL reorganized_beta_b_neg;
LIST_OF_LONG reorganized_abeta;
__recv_and_reorganize__(beta_share, beta_shares_sign,
reorganized_beta_b, reorganized_beta_b_neg,
reorganized_abeta, n, i);
long scalar = NTL::to_long(nfct);
tmp_res =
paillier_class_lst[i - 1].compute_lambda_times_beta_share(
reorganized_lambda_b, reorganized_beta_b,
reorganized_lambda_b_neg, reorganized_beta_b_neg,
modulu_char, i, ret_char_size, lamb_times_beta_isneg,
theta_is_neg, scalar);
lamb_times_beta = tmp_res[0];
// NOTE: the scaling factor is computed during secret sharing.
// this param should be passed out for computing theta here
theta = tmp_res[1];
// convert to zz type
NTL::ZZ tmp1, tmp2;
distributed_paillier::char_list_2_ZZ(tmp1, theta, theta_is_neg);
theta_lst.append(tmp1);
distributed_paillier::char_list_2_ZZ(tmp2, lamb_times_beta, lamb_times_beta_isneg);
hi.append(tmp2);
}
// 1) compute theta
// 2) check shares of lamb_times_beta can reconstruct rea l lamb_times_beta
NTL::ZZ recon_lamb_times_beta(0);
NTL::ZZ recon_theta(0);
for (long i = 1; i <= 2 * t + 1; i++) {
NTL::ZZ li, tmp;
NTL::ZZ enume = nfct;
NTL::ZZ denom = NTL::ZZ(1);
for (long j = 1; j <= 2 * t + 1; j++) {
if (i != j) {
enume *= j;
denom *= j - i;
}
}
NTL::div(li, enume, denom);
NTL::mul(tmp, li, hi[i - 1]);
NTL::add(recon_lamb_times_beta, recon_lamb_times_beta, tmp);
NTL::AddMod(recon_theta, recon_theta, li * theta_lst[i - 1], N);
}
NTL::ZZ scalar_inv;
NTL::InvMod(scalar_inv, nfct * sqr(nfct), N);
NTL::MulMod(recon_theta, recon_theta, scalar_inv, N);
NTL::MulMod(recon_theta, recon_theta, nfct * sqr(nfct), N);
NTL::ZZ lambda_lst_sum(0), beta_lst_sum(0);
for (int i = 0; i < lambda_lst.length(); i++) {
lambda_lst_sum += lambda_lst[i];
beta_lst_sum += beta_lst[i];
}
auto real_lamb_times_beta = lambda_lst_sum * beta_lst_sum;
// std::cout << "\nrecon_lamb_times_beta = " << recon_lamb_times_beta
// << "\n real_lamb_times_beta = " << real_lamb_times_beta * nfct * sqr(nfct)
// << "\nrecon_theta = " << recon_theta
// << "\nN = " << N
// << endl;
// NB: These two assertions are VERY IMPORTANT!
assert(lambda_lst_sum * beta_lst_sum * nfct * sqr(nfct) == recon_lamb_times_beta);
assert(recon_theta == recon_lamb_times_beta % N);
std::cout << "key generation finished. Correct\n"
<< endl;
// generate priv and pub key for each party
dist_paillier_pubkey_t pub_key;
std::vector<dist_paillier_privkey_t> pri_key_lst;
for (long i = 1; i <= 2 * t + 1; i++) {
dist_paillier_privkey_t pri_key;
pri_key.n = N;
pub_key.n = N;
pri_key.n_squared = NTL::sqr(N);
pub_key.n_squared = NTL::sqr(N);
pub_key.bits = len;
pub_key.n_plusone = N + 1;
pri_key.hi = hi[i - 1];
pri_key.t = t;
pri_key.n_fat = NTL::to_long(nfct);
NTL::InvMod(pri_key.theta_invmod, recon_theta, N);
pri_key_lst.push_back(pri_key);
}
return pri_key_lst;
}
void
distributed_paillier::__recv_and_reorganize__(const std::vector<LIST_OF_CHAR_LIST> &share_lst_b,
const LIST_OF_BOOL_LIST &share_lst_b_neg,
LIST_OF_CHAR_LIST &reorganized_b,
LIST_OF_BOOL &reorganized_b_neg,
LIST_OF_LONG &reorganized_a,
long num_party, long i) {
reorganized_a.reserve(num_party);
reorganized_b.reserve(num_party);
reorganized_b_neg.reserve(num_party);
for (long j = 1; j <= num_party; j++) {
reorganized_b.push_back(share_lst_b[j - 1][i - 1]);
reorganized_a.push_back(j);
reorganized_b_neg.push_back(share_lst_b_neg[j - 1][i - 1]);
}
}
// TODO: reconstruct __recv_and_reorganize__ functions
void
distributed_paillier::__recv_and_reorganize__(const std::vector<ShamirShares> &share_lst_b,
std::vector<ZZ> &reorganized_b,
LIST_OF_LONG &reorganized_a,
long num_party, long i) {
reorganized_a.reserve(num_party);
reorganized_b.reserve(num_party);
for (long j = 1; j <= num_party; j++) {
reorganized_b.push_back(share_lst_b[j - 1].shares.get(i - 1).b);
assert(share_lst_b[j - 1].shares.get(i - 1).a == i);
reorganized_a.push_back(i);
}
}
std::vector<NTL::ZZ>
distributed_paillier::gene_local_piqi_4_first_party(int bit_len, int n) {
std::vector<ZZ> ret;
ret.reserve(2);
long p_q_bit_len = bit_len;
// long n_copy = n;
// while(n_copy>1) {
// p_q_bit_len --;
// n_copy = n_copy >> 1;
// }
// p_q_bit_len--;
NTL::ZZ tmp;
do {
tmp = NTL::RandomBits_ZZ(p_q_bit_len);
// tmp = 1; // for debug
} while (tmp == 0 || ( (tmp%4)!=3) );
ret.emplace_back(tmp);
do {
tmp = NTL::RandomBits_ZZ(p_q_bit_len);
// tmp = 1; // for debug
} while (tmp == 0 || ( (tmp%4)!=3) );
ret.emplace_back(tmp);
return ret;
}
std::vector<NTL::ZZ>
distributed_paillier::gene_local_piqi_4_other_party(int bit_len, int n) {
std::vector<ZZ> ret;
ret.reserve(2);
long p_q_bit_len = bit_len;
long n_copy = n;
while(n_copy>1) {
p_q_bit_len --;
n_copy = n_copy >> 1;
}
p_q_bit_len--;
NTL::ZZ tmp;
do {
tmp = NTL::RandomBits_ZZ(p_q_bit_len);
// tmp = 1; // for debug
} while (tmp == 0 || ( (tmp%4)!=0) );
ret.emplace_back(tmp);
do {
tmp = NTL::RandomBits_ZZ(p_q_bit_len);
// tmp = 1; // for debug
} while (tmp == 0 || ( (tmp%4)!=0) );
ret.emplace_back(tmp);
return ret;
}
ZZ distributed_paillier::get_rand_4_biprimetest(const ZZ& N) {
ZZ tmp = NTL::RandomBnd(N);
while((NTL::Jacobi(tmp, N) != 1 ) || (tmp==0) ) {
tmp = NTL::RandomBnd(N);
}
// cout << "g = " << tmp << endl;
return tmp;
}
ZZ distributed_paillier::biprime_test_step1(int party_id, const ZZ& N, const ZZ& pi, const ZZ& qi, const ZZ& g) {
ZZ tmp(0);
if(party_id==1) {
tmp = (N-pi-qi+1);
assert(tmp % 4 == 0);
} else {
tmp = pi+qi;
assert(tmp % 4 == 0);
}
return NTL::PowerMod(g, tmp/4, N);
}
bool distributed_paillier::biprime_test_step2(const vector<ZZ>& other_v, const ZZ& v, const ZZ& N, const long &num_party ) {
ZZ tmp = ZZ(1);
ZZ product=ZZ(1);
//a mod b = (a % b + b) % b
assert(other_v.size() == num_party-1);
for(const auto& value : other_v) {
//NTL::MulMod(tmp, tmp, value, N);
product = product*value;
// cout <<"product = " << product <<"\n";
// cout <<" vi = " << value <<"\n";
}
tmp=(product% N+N)% N;
// ZZ v_mod_N = v % N;
ZZ v_mod_N=(v % N+ N) % N;
// cout << "v = " << v <<"\n"
// << "v_mod_N = " << v_mod_N << "\n"
// << "tmp = " << tmp
// << endl;
ZZ ans1=((product+v)%N + N)%N;
ZZ ans2=((product-v)%N + N)%N;
// cout << "ans1 = " << ans1 <<"\n"
// << "ans2 = " << ans2 << "\n"
// << endl;
// return ( (v_mod_N==tmp) || (v_mod_N==(-1*tmp)) );
return ( (ans1==0)||(ans2==0) );
}
| 36.648456 | 124 | 0.538888 | [
"vector"
] |
7e3f8834a68c8ede4f04cd77ce10217a29af4408 | 26,289 | cpp | C++ | source/Model.cpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 31 | 2015-03-19T08:44:48.000Z | 2021-12-15T20:52:31.000Z | source/Model.cpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 19 | 2015-07-09T09:02:44.000Z | 2016-06-09T03:51:03.000Z | source/Model.cpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 3 | 2017-10-04T23:38:18.000Z | 2022-03-07T08:27:13.000Z | // Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
#include <GTGE/Model.hpp>
#include <GTGE/VertexArrayLibrary.hpp>
#include <GTGE/CPUVertexShader_SimpleTransform.hpp>
#include <GTGE/Math.hpp>
#include <GTGE/GTEngine.hpp>
#include <GTGE/Core/Timing.hpp>
#include <cfloat>
#undef min
#undef max
namespace GT
{
//static ModelDefinition NullModelDefinition;
#if 0
Model::Model()
: definition(NullModelDefinition),
meshes(), bones(),
aabbMin(), aabbMax(), isAABBValid(false),
animation(), animationChannelBones(), animationKeyCache(),
animationPlaybackSpeed(1.0)
{
}
#endif
Model::Model(const ModelDefinition &definitionIn)
: definition(definitionIn),
meshes(), bones(),
aabbMin(), aabbMax(), isAABBValid(false),
animation(), animationChannelBones(), animationKeyCache(),
animationPlaybackSpeed(1.0)
{
// This will get the model into the correct state.
this->OnDefinitionChanged();
}
Model::~Model()
{
this->Clear();
}
Mesh* Model::AttachMesh(VertexArray* geometry, const char* materialFileName, DrawMode drawMode)
{
auto newMesh = new Mesh(definition.GetContext(), drawMode);
newMesh->SetGeometry(geometry);
newMesh->SetMaterial(materialFileName);
this->meshes.PushBack(newMesh);
// The AABB is no longer valid.
this->isAABBValid = false;
return newMesh;
}
Mesh* Model::AttachMesh(VertexArray* geometryIn, const char* materialFileName, const SkinningVertexAttribute* skinningVertexAttributes)
{
auto newMesh = this->AttachMesh(geometryIn, materialFileName);
if (newMesh != nullptr)
{
newMesh->SetSkinningData(this->bones.buffer, skinningVertexAttributes);
}
return newMesh;
}
void Model::CopyAndAttachBones(const Vector<Bone*> &inputBones)
{
// We do this in two passes. The first pass makes copies but does not link with parents. The second pass will link the bones together.
for (size_t i = 0; i < inputBones.count; ++i)
{
auto bone = inputBones[i];
assert(bone != nullptr);
this->bones.PushBack(new Bone(*bone));
}
// This is the second pass. We need to link the bones together to form their hierarchy.
for (size_t i = 0; i < inputBones.count; ++i)
{
auto inputBone = inputBones[i];
assert(inputBone != nullptr);
if (inputBone->GetParent() != nullptr)
{
auto bone = this->GetBoneByName(inputBone->GetName());
assert(bone != nullptr);
auto parentBone = this->GetBoneByName(inputBone->GetParent()->GetName());
assert(parentBone != nullptr);
parentBone->AttachChild(*bone);
}
}
}
void Model::CopyAnimation(const Animation &sourceAnimation, const Map<Bone*, AnimationChannel*> &sourceAnimationChannelBones)
{
// We first need to create all of the key frames.
for (size_t iKeyFrame = 0; iKeyFrame < sourceAnimation.GetKeyFrameCount(); ++iKeyFrame)
{
this->animation.AppendKeyFrame(sourceAnimation.GetKeyFrameTimeByIndex(iKeyFrame));
}
// Here we add all of our channels to the animation. They will be empty to begin with, but filled below.
for (size_t iChannel = 0; iChannel < sourceAnimationChannelBones.count; ++iChannel)
{
auto sourceChannel = sourceAnimationChannelBones.buffer[iChannel]->value;
auto sourceBone = sourceAnimationChannelBones.buffer[iChannel]->key;
auto bone = this->GetBoneByName(sourceBone->GetName());
assert(bone != nullptr);
auto &newChannel = this->animation.CreateChannel();
this->animationChannelBones.Add(bone, &newChannel);
// Now we loop through all the keys and add them.
auto &sourceKeys = sourceChannel->GetKeys();
for (size_t iKey = 0; iKey < sourceKeys.count; ++iKey)
{
auto sourceKey = static_cast<TransformAnimationKey*>(sourceKeys.buffer[iKey]->value);
auto newKey = new TransformAnimationKey(sourceKey->position, sourceKey->rotation, sourceKey->scale);
this->animationKeyCache.PushBack(newKey);
newChannel.SetKey(sourceKeys.buffer[iKey]->key, newKey);
}
}
// Here we add the named segments.
for (size_t iSegment = 0; iSegment < sourceAnimation.GetNamedSegmentCount(); ++iSegment)
{
auto name = sourceAnimation.GetNamedSegmentNameByIndex(iSegment);
auto segment = sourceAnimation.GetNamedSegmentByIndex(iSegment);
assert(name != nullptr);
assert(segment != nullptr);
this->animation.AddNamedSegment(name, segment->startKeyFrame, segment->endKeyFrame);
}
}
void Model::ApplyTransformation(const glm::mat4 &transform)
{
// We're going to use a CPU vertex shader here.
CPUVertexShader_SimpleTransform shader(transform);
// We need to execute the shader on all meshes.
for (size_t i = 0; i < this->meshes.count; ++i)
{
auto mesh = this->meshes[i];
assert(mesh != nullptr);
auto geometry = mesh->GetGeometry();
auto &format = geometry->GetFormat();
auto vertexCount = geometry->GetVertexCount();
auto vertexData = geometry->MapVertexData();
shader.Execute(vertexData, vertexCount, format, vertexData);
geometry->UnmapVertexData();
}
this->GenerateTangentsAndBitangents();
// The AABB is no longer valid.
this->isAABBValid = false;
}
void Model::GenerateTangentsAndBitangents()
{
for (size_t i = 0; i < this->meshes.count; ++i)
{
this->meshes[i]->GenerateTangentsAndBitangents();
}
}
void Model::GetAABB(glm::vec3 &aabbMinOut, glm::vec3 &aabbMaxOut) const
{
// We may need to update the AABB.
if (!this->isAABBValid)
{
if (this->meshes.count > 0)
{
// We need to iterate over the positions of every vertex of every mesh and find the bounds.
this->aabbMin = glm::vec3(FLT_MAX, FLT_MAX, FLT_MAX);
this->aabbMax = glm::vec3(FLT_MIN, FLT_MIN, FLT_MIN);
for (size_t i = 0; i < this->meshes.count; ++i)
{
glm::vec3 vaMin;
glm::vec3 vaMax;
this->meshes[i]->GetGeometry()->CalculateAABB(vaMin, vaMax);
if (vaMin.x < this->aabbMin.x) this->aabbMin.x = vaMin.x;
if (vaMin.y < this->aabbMin.y) this->aabbMin.y = vaMin.y;
if (vaMin.z < this->aabbMin.z) this->aabbMin.z = vaMin.z;
if (vaMax.x > this->aabbMax.x) this->aabbMax.x = vaMax.x;
if (vaMax.y > this->aabbMax.y) this->aabbMax.y = vaMax.y;
if (vaMax.z > this->aabbMax.z) this->aabbMax.z = vaMax.z;
}
this->isAABBValid = true;
}
if (this->aabbMax.x - this->aabbMin.x < glm::epsilon<float>()) this->aabbMax.x = this->aabbMin.x + glm::epsilon<float>();
if (this->aabbMax.y - this->aabbMin.y < glm::epsilon<float>()) this->aabbMax.y = this->aabbMin.y + glm::epsilon<float>();
if (this->aabbMax.z - this->aabbMin.z < glm::epsilon<float>()) this->aabbMax.z = this->aabbMin.z + glm::epsilon<float>();
}
aabbMinOut = this->aabbMin;
aabbMaxOut = this->aabbMax;
}
void Model::SetAABB(const glm::vec3 &aabbMinIn, const glm::vec3 &aabbMaxIn)
{
this->aabbMin = aabbMinIn;
this->aabbMax = aabbMaxIn;
this->isAABBValid = true;
}
void Model::OnDefinitionChanged()
{
this->Clear();
// We need to create copies of the bones. It is important that this is done before adding the meshes.
this->CopyAndAttachBones(this->definition.m_bones);
// Now the animation.
this->CopyAnimation(this->definition.m_animation, this->definition.animationChannelBones);
// Now we need to create the meshes. This must be done after adding the bones.
for (size_t i = 0; i < this->definition.meshes.count; ++i)
{
auto &definitionMesh = this->definition.meshes[i];
Mesh* newMesh = nullptr;
if (definitionMesh.skinningVertexAttributes != nullptr)
{
newMesh = this->AttachMesh(definitionMesh.geometry, definitionMesh.material->GetDefinition().relativePath.c_str(), definitionMesh.skinningVertexAttributes);
}
else
{
newMesh = this->AttachMesh(definitionMesh.geometry, definitionMesh.material->GetDefinition().relativePath.c_str());
}
// Material parameters.
if (newMesh != nullptr)
{
auto newMeshMaterial = newMesh->GetMaterial();
if (newMeshMaterial != nullptr)
{
if (definitionMesh.material != nullptr)
{
newMeshMaterial->SetParameters(definitionMesh.material->GetParameters());
}
newMeshMaterial->SetParameters(definitionMesh.defaultUniforms);
}
}
}
}
void Model::Serialize(Serializer &serializer) const
{
// A model has a fairly complex set of properties. Geometry, materials, bones, animation state, etc. We're going to have a null chunk
// at the end so we can do an iteration-based deserializer.
// The first chunk contains the mesh data. We save the mesh data differently depending on whether or not the model is procedural. If
// it is, we need to save the geometry data.
BasicSerializer meshesSerializer;
//bool serializeMeshGeometry = &this->definition == &NullModelDefinition;
bool serializeMeshGeometry = true;
meshesSerializer.Write(static_cast<uint32_t>(meshes.count));
for (size_t i = 0; i < meshes.count; ++i)
{
auto mesh = this->meshes[i];
assert(mesh != nullptr);
{
mesh->Serialize(meshesSerializer, serializeMeshGeometry);
// We need to write a boolean that specifies whether or not the material is the same as that specified by the definition.
bool usingSameMaterial = false;
//if (&this->definition != &NullModelDefinition && this->definition.meshes[i].material != nullptr && mesh->GetMaterial() != nullptr)
if (this->definition.meshes[i].material != nullptr && mesh->GetMaterial() != nullptr)
{
auto &definitionA = this->definition.meshes[i].material->GetDefinition();
auto &definitionB = mesh->GetMaterial()->GetDefinition();
usingSameMaterial = definitionA.relativePath == definitionB.relativePath;
}
meshesSerializer.Write(usingSameMaterial);
}
}
Serialization::ChunkHeader header;
header.id = Serialization::ChunkID_Model_Meshes;
header.version = 1;
header.sizeInBytes = meshesSerializer.GetBufferSizeInBytes();
serializer.Write(header);
serializer.Write(meshesSerializer.GetBuffer(), header.sizeInBytes);
// Now bones. We'll only write this chunk if we actually have bones.
if (this->bones.count > 0)
{
BasicSerializer bonesSerializer;
bonesSerializer.Write(static_cast<uint32_t>(bones.count));
for (size_t i = 0; i < this->bones.count; ++i)
{
auto bone = this->bones[i];
assert(bone != nullptr);
{
bone->Serialize(bonesSerializer);
}
}
header.id = Serialization::ChunkID_Model_Bones;
header.version = 1;
header.sizeInBytes = bonesSerializer.GetBufferSizeInBytes();
serializer.Write(header);
serializer.Write(bonesSerializer.GetBuffer(), header.sizeInBytes);
}
// Finally, the animation. We only write this chunk if we actually have animation key frames.
if (this->animation.GetKeyFrameCount() > 0)
{
BasicSerializer animationSerializer;
this->animation.Serialize(animationSerializer);
animationSerializer.Write(this->animationPlaybackSpeed);
header.id = Serialization::ChunkID_Model_Animation;
header.version = 1;
header.sizeInBytes = animationSerializer.GetBufferSizeInBytes();
serializer.Write(header);
serializer.Write(animationSerializer.GetBuffer(), header.sizeInBytes);
}
// Finally, the null terminator.
header.id = Serialization::ChunkID_Null;
header.version = 1;
header.sizeInBytes = 0;
serializer.Write(header);
}
void Model::Deserialize(Deserializer &deserializer)
{
// A model is tied to a definition. When a model is saved, it will be saved based on that definition. If the definition has changed
// it will mean the serialized data isn't really valid. Thus, if the definition is any different, we going to skip everything and
// just load up the model based on the definition.
bool isAbandoned = false;
// We're going to us a iteration based deserialization system here. Basically, we keep reading chunks until we hit the null terminator.
Serialization::ChunkHeader header;
do
{
deserializer.Read(header);
switch (header.id)
{
case Serialization::ChunkID_Model_Meshes:
{
if (isAbandoned)
{
deserializer.Seek(header.sizeInBytes);
break;
}
switch (header.version)
{
case 1:
{
uint32_t meshCount;
deserializer.Read(meshCount);
// We need to check if it's still possible to deserialize. If the mesh count is different, we can't reliably load anything, so
// we'll need to abandon everything. Note that we don't immediately return, because we want to maintain the integrity of the
// deserializer.
if (this->meshes.count != meshCount && this->meshes.count != 0)
{
isAbandoned = true;
this->OnDefinitionChanged();
deserializer.Seek(header.sizeInBytes - sizeof(meshCount));
break;
}
// Keeps track of whether or not we are allocating new meshes.
bool allocateNewMeshes = false;
// If we don't have any meshes, it probably means we're deserializing from an empty model. We'll create the meshes here.
if (this->meshes.count == 0)
{
allocateNewMeshes = true;
}
else
{
assert(this->meshes.count == meshCount);
// We don't want to allocate new meshes.
allocateNewMeshes = false;
}
for (uint32_t iMesh = 0; iMesh < meshCount; ++iMesh)
{
Mesh* mesh = nullptr;
if (allocateNewMeshes)
{
mesh = this->AttachMesh(nullptr, nullptr, nullptr);
}
else
{
mesh = this->meshes[iMesh];
}
assert(mesh != nullptr);
{
mesh->Deserialize(deserializer);
// The next byte should be a boolean specifying whether or not we are using the same material as that defined by the definition.
bool usingSameMaterial;
deserializer.Read(usingSameMaterial);
if (usingSameMaterial)
{
auto newMaterial = this->definition.meshes[iMesh].material;
if (newMaterial != nullptr)
{
mesh->SetMaterial(newMaterial->GetDefinition().relativePath.c_str());
mesh->GetMaterial()->SetParameters(this->definition.meshes[iMesh].defaultUniforms);
}
}
}
}
break;
}
default:
{
g_Context->Logf("Error deserializing model. Meshes chunk has an unsupported version (%d).", header.version);
break;
}
}
break;
}
case Serialization::ChunkID_Model_Bones:
{
if (isAbandoned)
{
deserializer.Seek(header.sizeInBytes);
break;
}
switch (header.version)
{
case 1:
{
uint32_t boneCount;
deserializer.Read(boneCount);
if (this->bones.count == boneCount)
{
for (size_t iBone = 0; iBone < this->bones.count; ++iBone)
{
this->bones[iBone]->Deserialize(deserializer);
}
}
else
{
isAbandoned = true;
this->OnDefinitionChanged();
deserializer.Seek(header.sizeInBytes - sizeof(boneCount));
break;
}
break;
}
default:
{
g_Context->Logf("Error deserializing model. Bones chunk has an unsupported version (%d).", header.version);
break;
}
}
break;
}
case Serialization::ChunkID_Model_Animation:
{
if (isAbandoned)
{
deserializer.Seek(header.sizeInBytes);
break;
}
switch (header.version)
{
case 1:
{
this->animation.Deserialize(deserializer);
deserializer.Read(this->animationPlaybackSpeed);
break;
}
default:
{
g_Context->Logf("Error deserializing model. Animation chunk has an unsupported version (%d).", header.version);
break;
}
}
break;
}
default:
{
// We don't know about the chunk so we'll just skip it.
deserializer.Seek(header.sizeInBytes);
break;
}
}
} while (header.id != Serialization::ChunkID_Null);
// The AABB is no longer valid after deserialization.
this->isAABBValid = false;
}
///////////////////////////////////////////////////////////////////
// Animation.
void Model::PlayAnimation(const AnimationSequence &sequence)
{
this->animation.Play(sequence);
}
void Model::StopAnimation()
{
this->animation.Stop();
}
void Model::PauseAnimation()
{
this->animation.Pause();
}
void Model::ResumeAnimation()
{
this->animation.Resume();
}
void Model::StepAnimation(double step)
{
this->animation.Step(step * this->animationPlaybackSpeed);
glm::vec3 boneAABBMin = glm::vec3( FLT_MAX);
glm::vec3 boneAABBMax = glm::vec3(-FLT_MAX);
// Now that we've stepped the animation, we need to update the bone positions.
size_t startKeyFrame;
size_t endKeyFrame;
auto interpolationFactor = this->animation.GetKeyFramesAtCurrentPlayback(startKeyFrame, endKeyFrame);
for (size_t i = 0; i < this->animationChannelBones.count; ++i)
{
auto iChannelBone = this->animationChannelBones.buffer[i];
auto firstKey = static_cast<TransformAnimationKey*>(iChannelBone->value->GetKey(startKeyFrame));
auto endKey = static_cast<TransformAnimationKey*>(iChannelBone->value->GetKey(endKeyFrame));
auto bone = iChannelBone->key;
if (firstKey != nullptr && endKey != nullptr)
{
glm::vec3 position = glm::mix( firstKey->position, endKey->position, interpolationFactor);
glm::quat rotation = glm::slerp(firstKey->rotation, endKey->rotation, interpolationFactor);
glm::vec3 scale = glm::mix( firstKey->scale, endKey->scale, interpolationFactor);
bone->SetPosition(position);
bone->SetRotation(rotation);
bone->SetScale(scale);
}
}
// Now we need to loop over each channel again and update the skinning transformations. It's important that this is done separately from the
// loop above to ensure all dependants have been updated beforehand.
for (size_t i = 0; i < this->animationChannelBones.count; ++i)
{
glm::vec3 position;
glm::quat devnull0;
glm::vec3 devnull1;
this->animationChannelBones.buffer[i]->key->UpdateSkinningTransform(position, devnull0, devnull1);
boneAABBMin = glm::min(boneAABBMin, position);
boneAABBMax = glm::max(boneAABBMax, position);
}
// The AABB needs to be set, but with bone AABB padding applied.
boneAABBMin -= this->definition.GetAnimationAABBPadding();
boneAABBMax += this->definition.GetAnimationAABBPadding();
this->SetAABB(boneAABBMin, boneAABBMax);
}
bool Model::IsAnimating() const
{
return this->animation.IsPlaying();
}
bool Model::IsAnimationPaused() const
{
return this->animation.IsPaused();
}
void Model::SetAnimationPlaybackSpeed(double speed)
{
this->animationPlaybackSpeed = speed;
}
Bone* Model::GetBoneByName(const char* name, size_t* indexOut)
{
for (size_t i = 0; i < this->bones.count; ++i)
{
if (Strings::Equal(name, this->bones[i]->GetName()))
{
if (indexOut != nullptr)
{
*indexOut = i;
}
return this->bones[i];
}
}
return nullptr;
}
Bone* Model::GetBoneByIndex(size_t boneIndex)
{
return this->bones[boneIndex];
}
}
// Private
namespace GT
{
void Model::Clear()
{
// Meshes.
for (size_t i = 0; i < this->meshes.count; ++i)
{
delete this->meshes[i];
}
this->meshes.Clear();
// Bones
for (size_t i = 0; i < this->bones.count; ++i)
{
delete this->bones.buffer[i];
}
this->bones.Clear();
// Animation keys.
for (size_t i = 0; i < this->animationKeyCache.count; ++i)
{
delete this->animationKeyCache[i];
}
this->animationKeyCache.Clear();
this->animationChannelBones.Clear();
// The AABB is no longer valid.
this->isAABBValid = false;
}
}
| 36.111264 | 173 | 0.503671 | [
"mesh",
"geometry",
"vector",
"model",
"transform"
] |
7e40e4ff233a2831696ca917ce4b9a9ee4da3ba7 | 15,788 | cpp | C++ | av/media/libmedia/IMediaSource.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 10 | 2020-04-17T04:02:36.000Z | 2021-11-23T11:38:42.000Z | av/media/libmedia/IMediaSource.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 3 | 2020-02-19T16:53:25.000Z | 2021-04-29T07:28:40.000Z | av/media/libmedia/IMediaSource.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 5 | 2019-12-25T04:05:02.000Z | 2022-01-14T16:57:55.000Z | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "BpMediaSource"
#include <utils/Log.h>
#include <inttypes.h>
#include <stdint.h>
#include <sys/types.h>
#include <binder/Parcel.h>
#include <media/IMediaSource.h>
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/MediaBufferGroup.h>
#include <media/stagefright/MediaSource.h>
#include <media/stagefright/MetaData.h>
namespace android {
enum {
START = IBinder::FIRST_CALL_TRANSACTION,
STOP,
PAUSE,
GETFORMAT,
READ,
READMULTIPLE,
RELEASE_BUFFER
};
enum {
NULL_BUFFER,
SHARED_BUFFER,
INLINE_BUFFER
};
class RemoteMediaBufferReleaser : public BBinder {
public:
RemoteMediaBufferReleaser(MediaBuffer *buf, sp<BnMediaSource> owner) {
mBuf = buf;
mOwner = owner;
}
~RemoteMediaBufferReleaser() {
if (mBuf) {
ALOGW("RemoteMediaBufferReleaser dtor called while still holding buffer");
mBuf->release();
}
}
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0) {
if (code == RELEASE_BUFFER) {
mBuf->release();
mBuf = NULL;
return OK;
} else {
return BBinder::onTransact(code, data, reply, flags);
}
}
private:
MediaBuffer *mBuf;
// Keep a ref to ensure MediaBuffer is released before the owner, i.e., BnMediaSource,
// because BnMediaSource needs to delete MediaBufferGroup in its dtor and
// MediaBufferGroup dtor requires all MediaBuffer's have 0 ref count.
sp<BnMediaSource> mOwner;
};
class RemoteMediaBufferWrapper : public MediaBuffer {
public:
RemoteMediaBufferWrapper(sp<IMemory> mem, sp<IBinder> source);
protected:
virtual ~RemoteMediaBufferWrapper();
private:
sp<IMemory> mMemory;
sp<IBinder> mRemoteSource;
};
RemoteMediaBufferWrapper::RemoteMediaBufferWrapper(sp<IMemory> mem, sp<IBinder> source)
: MediaBuffer(mem->pointer(), mem->size()) {
mMemory = mem;
mRemoteSource = source;
}
RemoteMediaBufferWrapper::~RemoteMediaBufferWrapper() {
mMemory.clear();
// Explicitly ask the remote side to release the buffer. We could also just clear
// mRemoteSource, but that doesn't immediately release the reference on the remote side.
Parcel data, reply;
mRemoteSource->transact(RELEASE_BUFFER, data, &reply);
mRemoteSource.clear();
}
class BpMediaSource : public BpInterface<IMediaSource> {
public:
BpMediaSource(const sp<IBinder>& impl)
: BpInterface<IMediaSource>(impl)
{
}
virtual status_t start(MetaData *params) {
ALOGV("start");
Parcel data, reply;
data.writeInterfaceToken(BpMediaSource::getInterfaceDescriptor());
if (params) {
params->writeToParcel(data);
}
status_t ret = remote()->transact(START, data, &reply);
if (ret == NO_ERROR && params) {
ALOGW("ignoring potentially modified MetaData from start");
ALOGW("input:");
params->dumpToLog();
sp<MetaData> meta = MetaData::createFromParcel(reply);
ALOGW("output:");
meta->dumpToLog();
}
return ret;
}
virtual status_t stop() {
ALOGV("stop");
Parcel data, reply;
data.writeInterfaceToken(BpMediaSource::getInterfaceDescriptor());
return remote()->transact(STOP, data, &reply);
}
virtual sp<MetaData> getFormat() {
ALOGV("getFormat");
Parcel data, reply;
data.writeInterfaceToken(BpMediaSource::getInterfaceDescriptor());
status_t ret = remote()->transact(GETFORMAT, data, &reply);
if (ret == NO_ERROR) {
mMetaData = MetaData::createFromParcel(reply);
return mMetaData;
}
return NULL;
}
virtual status_t read(MediaBuffer **buffer, const ReadOptions *options) {
ALOGV("read");
Parcel data, reply;
data.writeInterfaceToken(BpMediaSource::getInterfaceDescriptor());
if (options) {
data.writeByteArray(sizeof(*options), (uint8_t*) options);
}
status_t ret = remote()->transact(READ, data, &reply);
if (ret != NO_ERROR) {
return ret;
}
// wrap the returned data in a MediaBuffer
ret = reply.readInt32();
int32_t buftype = reply.readInt32();
if (buftype == SHARED_BUFFER) {
sp<IBinder> remote = reply.readStrongBinder();
sp<IBinder> binder = reply.readStrongBinder();
sp<IMemory> mem = interface_cast<IMemory>(binder);
if (mem == NULL) {
ALOGE("received NULL IMemory for shared buffer");
}
size_t offset = reply.readInt32();
size_t length = reply.readInt32();
MediaBuffer *buf = new RemoteMediaBufferWrapper(mem, remote);
buf->set_range(offset, length);
buf->meta_data()->updateFromParcel(reply);
*buffer = buf;
} else if (buftype == NULL_BUFFER) {
ALOGV("got status %d and NULL buffer", ret);
*buffer = NULL;
} else {
int32_t len = reply.readInt32();
ALOGV("got status %d and len %d", ret, len);
*buffer = new MediaBuffer(len);
reply.read((*buffer)->data(), len);
(*buffer)->meta_data()->updateFromParcel(reply);
}
return ret;
}
virtual status_t readMultiple(Vector<MediaBuffer *> *buffers, uint32_t maxNumBuffers) {
ALOGV("readMultiple");
if (buffers == NULL || !buffers->isEmpty()) {
return BAD_VALUE;
}
Parcel data, reply;
data.writeInterfaceToken(BpMediaSource::getInterfaceDescriptor());
data.writeUint32(maxNumBuffers);
status_t ret = remote()->transact(READMULTIPLE, data, &reply);
if (ret != NO_ERROR) {
return ret;
}
// wrap the returned data in a vector of MediaBuffers
int32_t bufCount = 0;
while (1) {
if (reply.readInt32() == 0) {
break;
}
int32_t len = reply.readInt32();
ALOGV("got len %d", len);
MediaBuffer *buf = new MediaBuffer(len);
reply.read(buf->data(), len);
buf->meta_data()->updateFromParcel(reply);
buffers->push_back(buf);
++bufCount;
}
ret = reply.readInt32();
ALOGV("got status %d, bufCount %d", ret, bufCount);
return ret;
}
virtual status_t pause() {
ALOGV("pause");
Parcel data, reply;
data.writeInterfaceToken(BpMediaSource::getInterfaceDescriptor());
return remote()->transact(PAUSE, data, &reply);
}
virtual status_t setBuffers(const Vector<MediaBuffer *> & buffers __unused) {
ALOGV("setBuffers NOT IMPLEMENTED");
return ERROR_UNSUPPORTED; // default
}
private:
// NuPlayer passes pointers-to-metadata around, so we use this to keep the metadata alive
// XXX: could we use this for caching, or does metadata change on the fly?
sp<MetaData> mMetaData;
};
IMPLEMENT_META_INTERFACE(MediaSource, "android.media.IMediaSource");
#undef LOG_TAG
#define LOG_TAG "BnMediaSource"
BnMediaSource::BnMediaSource()
: mGroup(NULL) {
}
BnMediaSource::~BnMediaSource() {
delete mGroup;
mGroup = NULL;
}
status_t BnMediaSource::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch (code) {
case START: {
ALOGV("start");
CHECK_INTERFACE(IMediaSource, data, reply);
sp<MetaData> meta;
if (data.dataAvail()) {
meta = MetaData::createFromParcel(data);
}
status_t ret = start(meta.get());
if (ret == NO_ERROR && meta != NULL) {
meta->writeToParcel(*reply);
}
return ret;
}
case STOP: {
ALOGV("stop");
CHECK_INTERFACE(IMediaSource, data, reply);
return stop();
}
case PAUSE: {
ALOGV("pause");
CHECK_INTERFACE(IMediaSource, data, reply);
return pause();
}
case GETFORMAT: {
ALOGV("getFormat");
CHECK_INTERFACE(IMediaSource, data, reply);
sp<MetaData> meta = getFormat();
if (meta != NULL) {
meta->writeToParcel(*reply);
return NO_ERROR;
}
return UNKNOWN_ERROR;
}
case READ: {
ALOGV("read");
CHECK_INTERFACE(IMediaSource, data, reply);
status_t ret;
MediaBuffer *buf = NULL;
ReadOptions opts;
uint32_t len;
if (data.readUint32(&len) == NO_ERROR &&
len == sizeof(opts) && data.read((void*)&opts, len) == NO_ERROR) {
ret = read(&buf, &opts);
} else {
ret = read(&buf, NULL);
}
reply->writeInt32(ret);
if (buf != NULL) {
size_t usedSize = buf->range_length();
// even if we're using shared memory, we might not want to use it, since for small
// sizes it's faster to copy data through the Binder transaction
// On the other hand, if the data size is large enough, it's better to use shared
// memory. When data is too large, binder can't handle it.
if (usedSize >= MediaBuffer::kSharedMemThreshold) {
ALOGV("use shared memory: %zu", usedSize);
MediaBuffer *transferBuf = buf;
size_t offset = buf->range_offset();
if (transferBuf->mMemory == NULL) {
if (mGroup == NULL) {
mGroup = new MediaBufferGroup;
size_t allocateSize = usedSize;
if (usedSize < SIZE_MAX / 3) {
allocateSize = usedSize * 3 / 2;
}
mGroup->add_buffer(new MediaBuffer(allocateSize));
}
MediaBuffer *newBuf = NULL;
ret = mGroup->acquire_buffer(
&newBuf, false /* nonBlocking */, usedSize);
if (ret != OK || newBuf == NULL || newBuf->mMemory == NULL) {
ALOGW("failed to acquire shared memory, ret %d", ret);
buf->release();
if (newBuf != NULL) {
newBuf->release();
}
reply->writeInt32(NULL_BUFFER);
return NO_ERROR;
}
transferBuf = newBuf;
memcpy(transferBuf->data(), (uint8_t*)buf->data() + buf->range_offset(),
buf->range_length());
offset = 0;
}
reply->writeInt32(SHARED_BUFFER);
RemoteMediaBufferReleaser *wrapper =
new RemoteMediaBufferReleaser(transferBuf, this);
reply->writeStrongBinder(wrapper);
reply->writeStrongBinder(IInterface::asBinder(transferBuf->mMemory));
reply->writeInt32(offset);
reply->writeInt32(usedSize);
buf->meta_data()->writeToParcel(*reply);
if (buf->mMemory == NULL) {
buf->release();
}
} else {
// buffer is small: copy it
if (buf->mMemory != NULL) {
ALOGV("%zu shared mem available, but only %zu used", buf->mMemory->size(), buf->range_length());
}
reply->writeInt32(INLINE_BUFFER);
reply->writeByteArray(buf->range_length(), (uint8_t*)buf->data() + buf->range_offset());
buf->meta_data()->writeToParcel(*reply);
buf->release();
}
} else {
ALOGV("ret %d, buf %p", ret, buf);
reply->writeInt32(NULL_BUFFER);
}
return NO_ERROR;
}
case READMULTIPLE: {
ALOGV("readmultiple");
CHECK_INTERFACE(IMediaSource, data, reply);
uint32_t maxNumBuffers;
data.readUint32(&maxNumBuffers);
status_t ret = NO_ERROR;
uint32_t bufferCount = 0;
if (maxNumBuffers > kMaxNumReadMultiple) {
maxNumBuffers = kMaxNumReadMultiple;
}
while (bufferCount < maxNumBuffers) {
if (reply->dataSize() >= MediaBuffer::kSharedMemThreshold) {
break;
}
MediaBuffer *buf = NULL;
ret = read(&buf, NULL);
if (ret != NO_ERROR || buf == NULL) {
break;
}
++bufferCount;
reply->writeInt32(1); // indicate one more MediaBuffer.
reply->writeByteArray(
buf->range_length(), (uint8_t*)buf->data() + buf->range_offset());
buf->meta_data()->writeToParcel(*reply);
buf->release();
}
reply->writeInt32(0); // indicate no more MediaBuffer.
reply->writeInt32(ret);
return NO_ERROR;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
////////////////////////////////////////////////////////////////////////////////
IMediaSource::ReadOptions::ReadOptions() {
reset();
}
void IMediaSource::ReadOptions::reset() {
mOptions = 0;
mSeekTimeUs = 0;
mLatenessUs = 0;
mNonBlocking = false;
}
void IMediaSource::ReadOptions::setNonBlocking() {
mNonBlocking = true;
}
void IMediaSource::ReadOptions::clearNonBlocking() {
mNonBlocking = false;
}
bool IMediaSource::ReadOptions::getNonBlocking() const {
return mNonBlocking;
}
void IMediaSource::ReadOptions::setSeekTo(int64_t time_us, SeekMode mode) {
mOptions |= kSeekTo_Option;
mSeekTimeUs = time_us;
mSeekMode = mode;
}
void IMediaSource::ReadOptions::clearSeekTo() {
mOptions &= ~kSeekTo_Option;
mSeekTimeUs = 0;
mSeekMode = SEEK_CLOSEST_SYNC;
}
bool IMediaSource::ReadOptions::getSeekTo(
int64_t *time_us, SeekMode *mode) const {
*time_us = mSeekTimeUs;
*mode = mSeekMode;
return (mOptions & kSeekTo_Option) != 0;
}
void IMediaSource::ReadOptions::setLateBy(int64_t lateness_us) {
mLatenessUs = lateness_us;
}
int64_t IMediaSource::ReadOptions::getLateBy() const {
return mLatenessUs;
}
} // namespace android
| 33.879828 | 120 | 0.550165 | [
"vector"
] |
7e4474bbaf72a6d94150064a168e557d92046269 | 2,052 | cpp | C++ | TG/bookcodes/ch5/uva10917.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | TG/bookcodes/ch5/uva10917.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | TG/bookcodes/ch5/uva10917.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // UVa10917 A Walk through the Forest
// Rujia Liu
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int INF = 1000000000;
const int maxn = 1000 + 10;
struct Edge {
int from, to, dist;
};
struct HeapNode {
int d, u;
bool operator < (const HeapNode& rhs) const {
return d > rhs.d;
}
};
struct Dijkstra {
int n, m;
vector<Edge> edges;
vector<int> G[maxn];
bool done[maxn]; // 是否已永久标号
int d[maxn]; // s到各个点的距离
int p[maxn]; // 最短路中的上一条弧
void init(int n) {
this->n = n;
for(int i = 0; i < n; i++) G[i].clear();
edges.clear();
}
void AddEdge(int from, int to, int dist) {
edges.push_back((Edge){from, to, dist});
m = edges.size();
G[from].push_back(m-1);
}
void dijkstra(int s) {
priority_queue<HeapNode> Q;
for(int i = 0; i < n; i++) d[i] = INF;
d[s] = 0;
memset(done, 0, sizeof(done));
Q.push((HeapNode){0, s});
while(!Q.empty()) {
HeapNode x = Q.top(); Q.pop();
int u = x.u;
if(done[u]) continue;
done[u] = true;
for(int i = 0; i < G[u].size(); i++) {
Edge& e = edges[G[u][i]];
if(d[e.to] > d[u] + e.dist) {
d[e.to] = d[u] + e.dist;
p[e.to] = G[u][i];
Q.push((HeapNode){d[e.to], e.to});
}
}
}
}
};
//////// 题目相关
Dijkstra solver;
int d[maxn]; // 到家距离
int dp(int u) {
if(u == 1) return 1; // 到家了
int& ans = d[u];
if(ans >= 0) return ans;
ans = 0;
for(int i = 0; i < solver.G[u].size(); i++) {
int v = solver.edges[solver.G[u][i]].to;
if(solver.d[v] < solver.d[u]) ans += dp(v);
}
return ans;
}
int main() {
int n, m;
while(scanf("%d%d", &n, &m) == 2) {
solver.init(n);
for(int i = 0; i < m; i++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c); a--; b--;
solver.AddEdge(a, b, c);
solver.AddEdge(b, a, c);
}
solver.dijkstra(1); // 家(1)到所有点的距离。因为道路都是双向的,所以把家看作起点也行
memset(d, -1, sizeof(d));
printf("%d\n", dp(0)); // 办公室(0)到家的符合条件的路径条数
}
return 0;
}
| 20.52 | 59 | 0.503411 | [
"vector"
] |
7e504d03f076cd290e79e9e9cab9ce9c15d4811f | 1,401 | cpp | C++ | tsplp/src/LinearConstraint.cpp | sebrockm/mtsp-vrp | 28955855d253f51fcb9397a0b22c6774f66f8d55 | [
"MIT"
] | null | null | null | tsplp/src/LinearConstraint.cpp | sebrockm/mtsp-vrp | 28955855d253f51fcb9397a0b22c6774f66f8d55 | [
"MIT"
] | null | null | null | tsplp/src/LinearConstraint.cpp | sebrockm/mtsp-vrp | 28955855d253f51fcb9397a0b22c6774f66f8d55 | [
"MIT"
] | null | null | null | #include "LinearConstraint.hpp"
#include "LinearVariableComposition.hpp"
#include <CoinFinite.hpp>
tsplp::LinearConstraint tsplp::operator<=(LinearVariableComposition lhs, LinearVariableComposition rhs)
{
LinearConstraint result = lhs - rhs;
result.m_upperBound *= -1;
result.m_lowerBound = -COIN_DBL_MAX;
return result;
}
tsplp::LinearConstraint tsplp::operator>=(LinearVariableComposition lhs, LinearVariableComposition rhs)
{
LinearConstraint result = lhs - rhs;
result.m_lowerBound = -result.m_upperBound;
result.m_upperBound = COIN_DBL_MAX;
return result;
}
tsplp::LinearConstraint tsplp::operator==(LinearVariableComposition lhs, LinearVariableComposition rhs)
{
LinearConstraint result = lhs - rhs;
result.m_upperBound *= -1;
result.m_lowerBound = result.m_upperBound;
return result;
}
tsplp::LinearConstraint::LinearConstraint(LinearVariableComposition&& convertee)
: m_variables(std::move(convertee.m_variables)), m_coefficients(std::move(convertee.m_coefficients)), m_upperBound(convertee.m_constant)
{
}
bool tsplp::LinearConstraint::Evaluate(const Model& model, double tolerance) const
{
double value = 0.0;
for (size_t i = 0; i < m_coefficients.size(); ++i)
value += m_coefficients[i] * m_variables[i].GetObjectiveValue(model);
return m_lowerBound <= value + tolerance && value - tolerance <= m_upperBound;
}
| 32.581395 | 140 | 0.748751 | [
"model"
] |
7e54742f9281e60bad640254daa0938c2aeed4d9 | 3,713 | cpp | C++ | evolve4src/src/evolve/ZoomHistory.cpp | ilyar/Evolve | f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88 | [
"EFL-2.0"
] | null | null | null | evolve4src/src/evolve/ZoomHistory.cpp | ilyar/Evolve | f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88 | [
"EFL-2.0"
] | null | null | null | evolve4src/src/evolve/ZoomHistory.cpp | ilyar/Evolve | f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88 | [
"EFL-2.0"
] | null | null | null | //
// ZoomHistory
//
#include "stdafx.h"
// AboutDialog dialog
ZoomHistory::ZoomHistory()
{
m_sp = 0;
tf = &m_stack[m_sp];
}
ZoomHistory::~ZoomHistory()
{
}
void ZoomHistory::set_world(UNIVERSE *u)
{
world.left = 0.0 - 0.5;
world.right = u->width + 0.5;
world.top = 0.0 - 0.5;
world.bottom = u->height + 0.5;
}
void ZoomHistory::set_window(CRect rect)
{
CPoint p1, p2;
p1 = rect.TopLeft();
p2 = rect.BottomRight();
win.left = p1.x;
win.top = p1.y;
win.right = p2.x;
win.bottom = p2.y;
window = win;
preserve_aspect_ratio();
}
void ZoomHistory::resize()
{
preserve_aspect_ratio();
TF_Set(tf, &win, &world);
}
void ZoomHistory::view_all()
{
m_sp = 0;
tf = &m_stack[ m_sp ];
world = tf->world;
win = tf->win;
}
/*
* Zoom in, but when no drag rectangle was specified
*
*/
void ZoomHistory::zoom_in()
{
double w, h;
CRect rect;
/*
* Create 'rect' as a 1/4 smaller rectangle inside of
* 'window'.
*/
w = (win.right - win.left) / 8.0;
h = (win.bottom - win.top) / 8.0;
rect.left = (int) (win.left + w);
rect.top = (int) (win.top + h);
rect.right = (int) (win.right - w);
rect.bottom = (int) (win.bottom - h);
zoom_in(rect);
}
void ZoomHistory::zoom_in(CRect rect)
{
TF_RECT zr, wr;
if( m_sp+1 >= sizeof(m_stack)/sizeof(m_stack[0]) )
return;
if( rect.right >= rect.left ) {
zr.left = rect.left;
zr.right = rect.right;
} else {
zr.left = rect.right;
zr.right = rect.left;
}
if( rect.bottom >= rect.top ) {
zr.top = rect.top;
zr.bottom = rect.bottom;
} else {
zr.top = rect.bottom;
zr.bottom = rect.top;
}
TF_WinToWorld(tf, zr.left, zr.top, &wr.left, &wr.top);
TF_WinToWorld(tf, zr.right, zr.bottom, &wr.right, &wr.bottom);
m_sp++;
tf = &m_stack[ m_sp ];
world = wr;
preserve_aspect_ratio();
TF_Set(tf, &win, &world);
pan(0, 0);
}
/*
* If we are popping the last transform, then
* restore that view. Otherwise pan the old view to be
* centered to where the window is currently viewing.
*
*/
void ZoomHistory::zoom_out()
{
double ax, ay;
double bx, by;
double cx, cy;
if( m_sp == 1 ) {
/*
* restore to top-level view (show all)
*/
m_sp -= 1;
tf = &m_stack[ m_sp ];
world = tf->world;
win = tf->win;
} else if( m_sp > 1 ) {
/*
* restore previous view, but pan to be centered where
* the we are currently positioned.
*/
ax = (world.right + world.left)/2.0;
ay = (world.bottom + world.top)/2.0;
m_sp -= 1;
tf = &m_stack[ m_sp ];
world = tf->world;
win = tf->win;
bx = (world.right + world.left)/2.0;
by = (world.bottom + world.top)/2.0;
cx = ax - bx;
cy = ay - by;
world.left += cx;
world.top += cy;
world.right += cx;
world.bottom += cy;
TF_Set(tf, &win, &world);
}
}
/*
* Pan display. (cx, cy) are values in window units
*/
void ZoomHistory::pan(int cx, int cy)
{
TF_RECT tmp_win;
TF_RECT new_world;
tmp_win = win;
tmp_win.left += cx;
tmp_win.top += cy;
tmp_win.right += cx;
tmp_win.bottom += cy;
TF_WinToWorld(tf, tmp_win.left, tmp_win.top, &new_world.left, &new_world.top);
TF_WinToWorld(tf, tmp_win.right, tmp_win.bottom, &new_world.right, &new_world.bottom);
world = new_world;
TF_Set(tf, &win, &world);
}
/*
* Change 'win' so its aspect ration matches the aspect ratio
* of the 'world' rectangle.
*
*/
void ZoomHistory::preserve_aspect_ratio()
{
double window_ratio;
double world_ratio;
window_ratio = (win.bottom - win.top) / (win.right - win.left);
world_ratio = (world.bottom - world.top) / (world.right - world.left);
if( world_ratio > window_ratio ) {
win.right = win.left +
(win.bottom - win.top) / world_ratio;
} else {
win.bottom = win.top +
(win.right - win.left) * world_ratio;
}
}
| 17.110599 | 87 | 0.618368 | [
"transform"
] |
7e556e50bd7762abfaf1a34dce03934dc94b74dd | 720 | cpp | C++ | AEngine/src/GameObject.cpp | JaymieX/AEngine | 660fb6e124f809f7c758bd49e1c3bc2ddf75df16 | [
"Unlicense"
] | null | null | null | AEngine/src/GameObject.cpp | JaymieX/AEngine | 660fb6e124f809f7c758bd49e1c3bc2ddf75df16 | [
"Unlicense"
] | null | null | null | AEngine/src/GameObject.cpp | JaymieX/AEngine | 660fb6e124f809f7c758bd49e1c3bc2ddf75df16 | [
"Unlicense"
] | null | null | null | #include <Core/AEpch.h>
#include "GameObject.h"
#include "Graphics/Model.h"
#include "Graphics/Shader.h"
GameObject::GameObject(Model* model, Shader* shader) :
model(model), shader(shader)
{
transformMatrixID = shader->getUniformID("modelMatrix");
normalMatrixID = shader->getUniformID("normalMatrix");
}
GameObject::~GameObject()
{
if (model) delete model, model = nullptr;
if (shader) delete shader, shader = nullptr;
}
void GameObject::Update(float dt)
{
}
void GameObject::Render() const
{
mat3 normalMatrix = transformMatrix;
glUniformMatrix4fv(transformMatrixID, 1, GL_FALSE, &transformMatrix[0][0]);
glUniformMatrix3fv(normalMatrixID, 1, GL_FALSE, &normalMatrix[0][0]);
if(model) model->Render();
} | 24 | 76 | 0.738889 | [
"render",
"model"
] |
7e6369269a0c99a4477c0aac4ab1320b0fdd6546 | 8,818 | hpp | C++ | openjdk11/src/hotspot/share/gc/g1/g1ParScanThreadState.hpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | openjdk11/src/hotspot/share/gc/g1/g1ParScanThreadState.hpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | openjdk11/src/hotspot/share/gc/g1/g1ParScanThreadState.hpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_GC_G1_G1PARSCANTHREADSTATE_HPP
#define SHARE_VM_GC_G1_G1PARSCANTHREADSTATE_HPP
#include "gc/g1/dirtyCardQueue.hpp"
#include "gc/g1/g1CardTable.hpp"
#include "gc/g1/g1CollectedHeap.hpp"
#include "gc/g1/g1OopClosures.hpp"
#include "gc/g1/g1Policy.hpp"
#include "gc/g1/g1RemSet.hpp"
#include "gc/g1/heapRegionRemSet.hpp"
#include "gc/shared/ageTable.hpp"
#include "memory/allocation.hpp"
#include "oops/oop.hpp"
#include "utilities/ticks.hpp"
class G1PLABAllocator;
class G1EvacuationRootClosures;
class HeapRegion;
class outputStream;
class G1ParScanThreadState : public CHeapObj<mtGC> {
G1CollectedHeap* _g1h;
RefToScanQueue* _refs;
DirtyCardQueue _dcq;
G1CardTable* _ct;
G1EvacuationRootClosures* _closures;
G1PLABAllocator* _plab_allocator;
AgeTable _age_table;
InCSetState _dest[InCSetState::Num];
// Local tenuring threshold.
uint _tenuring_threshold;
G1ScanEvacuatedObjClosure _scanner;
int _hash_seed;
uint _worker_id;
// Upper and lower threshold to start and end work queue draining.
uint const _stack_trim_upper_threshold;
uint const _stack_trim_lower_threshold;
Tickspan _trim_ticks;
// Map from young-age-index (0 == not young, 1 is youngest) to
// surviving words. base is what we get back from the malloc call
size_t* _surviving_young_words_base;
// this points into the array, as we use the first few entries for padding
size_t* _surviving_young_words;
// Indicates whether in the last generation (old) there is no more space
// available for allocation.
bool _old_gen_is_full;
#define PADDING_ELEM_NUM (DEFAULT_CACHE_LINE_SIZE / sizeof(size_t))
DirtyCardQueue& dirty_card_queue() { return _dcq; }
G1CardTable* ct() { return _ct; }
InCSetState dest(InCSetState original) const {
assert(original.is_valid(),
"Original state invalid: " CSETSTATE_FORMAT, original.value());
assert(_dest[original.value()].is_valid_gen(),
"Dest state is invalid: " CSETSTATE_FORMAT, _dest[original.value()].value());
return _dest[original.value()];
}
public:
G1ParScanThreadState(G1CollectedHeap* g1h, uint worker_id, size_t young_cset_length);
virtual ~G1ParScanThreadState();
void set_ref_discoverer(ReferenceDiscoverer* rd) { _scanner.set_ref_discoverer(rd); }
#ifdef ASSERT
bool queue_is_empty() const { return _refs->is_empty(); }
bool verify_ref(narrowOop* ref) const;
bool verify_ref(oop* ref) const;
bool verify_task(StarTask ref) const;
#endif // ASSERT
template <class T> void do_oop_ext(T* ref);
template <class T> void push_on_queue(T* ref);
template <class T> void update_rs(HeapRegion* from, T* p, oop o) {
assert(!HeapRegion::is_in_same_region(p, o), "Caller should have filtered out cross-region references already.");
// If the field originates from the to-space, we don't need to include it
// in the remembered set updates. Also, if we are not tracking the remembered
// set in the destination region, do not bother either.
if (!from->is_young() && _g1h->heap_region_containing((HeapWord*)o)->rem_set()->is_tracked()) {
size_t card_index = ct()->index_for(p);
// If the card hasn't been added to the buffer, do it.
if (ct()->mark_card_deferred(card_index)) {
dirty_card_queue().enqueue((jbyte*)ct()->byte_for_index(card_index));
}
}
}
G1EvacuationRootClosures* closures() { return _closures; }
uint worker_id() { return _worker_id; }
// Returns the current amount of waste due to alignment or not being able to fit
// objects within LABs and the undo waste.
virtual void waste(size_t& wasted, size_t& undo_wasted);
size_t* surviving_young_words() {
// We add one to hide entry 0 which accumulates surviving words for
// age -1 regions (i.e. non-young ones)
return _surviving_young_words + 1;
}
void flush(size_t* surviving_young_words);
private:
#define G1_PARTIAL_ARRAY_MASK 0x2
inline bool has_partial_array_mask(oop* ref) const {
return ((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) == G1_PARTIAL_ARRAY_MASK;
}
// We never encode partial array oops as narrowOop*, so return false immediately.
// This allows the compiler to create optimized code when popping references from
// the work queue.
inline bool has_partial_array_mask(narrowOop* ref) const {
assert(((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) != G1_PARTIAL_ARRAY_MASK, "Partial array oop reference encoded as narrowOop*");
return false;
}
// Only implement set_partial_array_mask() for regular oops, not for narrowOops.
// We always encode partial arrays as regular oop, to allow the
// specialization for has_partial_array_mask() for narrowOops above.
// This means that unintentional use of this method with narrowOops are caught
// by the compiler.
inline oop* set_partial_array_mask(oop obj) const {
assert(((uintptr_t)(void *)obj & G1_PARTIAL_ARRAY_MASK) == 0, "Information loss!");
return (oop*) ((uintptr_t)(void *)obj | G1_PARTIAL_ARRAY_MASK);
}
inline oop clear_partial_array_mask(oop* ref) const {
return cast_to_oop((intptr_t)ref & ~G1_PARTIAL_ARRAY_MASK);
}
inline void do_oop_partial_array(oop* p);
// This method is applied to the fields of the objects that have just been copied.
template <class T> inline void do_oop_evac(T* p);
inline void deal_with_reference(oop* ref_to_scan);
inline void deal_with_reference(narrowOop* ref_to_scan);
inline void dispatch_reference(StarTask ref);
// Tries to allocate word_sz in the PLAB of the next "generation" after trying to
// allocate into dest. State is the original (source) cset state for the object
// that is allocated for. Previous_plab_refill_failed indicates whether previously
// a PLAB refill into "state" failed.
// Returns a non-NULL pointer if successful, and updates dest if required.
// Also determines whether we should continue to try to allocate into the various
// generations or just end trying to allocate.
HeapWord* allocate_in_next_plab(InCSetState const state,
InCSetState* dest,
size_t word_sz,
bool previous_plab_refill_failed);
inline InCSetState next_state(InCSetState const state, markOop const m, uint& age);
void report_promotion_event(InCSetState const dest_state,
oop const old, size_t word_sz, uint age,
HeapWord * const obj_ptr) const;
inline bool needs_partial_trimming() const;
inline bool is_partially_trimmed() const;
inline void trim_queue_to_threshold(uint threshold);
public:
oop copy_to_survivor_space(InCSetState const state, oop const obj, markOop const old_mark);
void trim_queue();
void trim_queue_partially();
Tickspan trim_ticks() const;
void reset_trim_ticks();
inline void steal_and_trim_queue(RefToScanQueueSet *task_queues);
// An attempt to evacuate "obj" has failed; take necessary steps.
oop handle_evacuation_failure_par(oop obj, markOop m);
};
class G1ParScanThreadStateSet : public StackObj {
G1CollectedHeap* _g1h;
G1ParScanThreadState** _states;
size_t* _surviving_young_words_total;
size_t _young_cset_length;
uint _n_workers;
bool _flushed;
public:
G1ParScanThreadStateSet(G1CollectedHeap* g1h, uint n_workers, size_t young_cset_length);
~G1ParScanThreadStateSet();
void flush();
G1ParScanThreadState* state_for_worker(uint worker_id);
const size_t* surviving_young_words() const;
private:
G1ParScanThreadState* new_par_scan_state(uint worker_id, size_t young_cset_length);
};
#endif // SHARE_VM_GC_G1_G1PARSCANTHREADSTATE_HPP
| 37.364407 | 131 | 0.732139 | [
"object"
] |
7e67851014b2d27ee8c0c72b6a05de5798c8be9a | 2,881 | hpp | C++ | include/codegen/include/OVR/OpenVR/IVRSystem__PollNextEventWithPose.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/OVR/OpenVR/IVRSystem__PollNextEventWithPose.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/OVR/OpenVR/IVRSystem__PollNextEventWithPose.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:00 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
// Including type: OVR.OpenVR.IVRSystem
#include "OVR/OpenVR/IVRSystem.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Skipping declaration: IntPtr because it is already included!
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Forward declaring namespace: OVR::OpenVR
namespace OVR::OpenVR {
// Forward declaring type: ETrackingUniverseOrigin
struct ETrackingUniverseOrigin;
// Forward declaring type: VREvent_t
struct VREvent_t;
// Forward declaring type: TrackedDevicePose_t
struct TrackedDevicePose_t;
}
// Completed forward declares
// Type namespace: OVR.OpenVR
namespace OVR::OpenVR {
// Autogenerated type: OVR.OpenVR.IVRSystem/_PollNextEventWithPose
class IVRSystem::_PollNextEventWithPose : public System::MulticastDelegate {
public:
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0xCAAE28
static IVRSystem::_PollNextEventWithPose* New_ctor(::Il2CppObject* object, System::IntPtr method);
// public System.Boolean Invoke(OVR.OpenVR.ETrackingUniverseOrigin eOrigin, OVR.OpenVR.VREvent_t pEvent, System.UInt32 uncbVREvent, OVR.OpenVR.TrackedDevicePose_t pTrackedDevicePose)
// Offset: 0xCAAE3C
bool Invoke(OVR::OpenVR::ETrackingUniverseOrigin eOrigin, OVR::OpenVR::VREvent_t& pEvent, uint uncbVREvent, OVR::OpenVR::TrackedDevicePose_t& pTrackedDevicePose);
// public System.IAsyncResult BeginInvoke(OVR.OpenVR.ETrackingUniverseOrigin eOrigin, OVR.OpenVR.VREvent_t pEvent, System.UInt32 uncbVREvent, OVR.OpenVR.TrackedDevicePose_t pTrackedDevicePose, System.AsyncCallback callback, System.Object object)
// Offset: 0xCAB108
System::IAsyncResult* BeginInvoke(OVR::OpenVR::ETrackingUniverseOrigin eOrigin, OVR::OpenVR::VREvent_t& pEvent, uint uncbVREvent, OVR::OpenVR::TrackedDevicePose_t& pTrackedDevicePose, System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.Boolean EndInvoke(OVR.OpenVR.VREvent_t pEvent, OVR.OpenVR.TrackedDevicePose_t pTrackedDevicePose, System.IAsyncResult result)
// Offset: 0xCAB1F8
bool EndInvoke(OVR::OpenVR::VREvent_t& pEvent, OVR::OpenVR::TrackedDevicePose_t& pTrackedDevicePose, System::IAsyncResult* result);
}; // OVR.OpenVR.IVRSystem/_PollNextEventWithPose
}
DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::IVRSystem::_PollNextEventWithPose*, "OVR.OpenVR", "IVRSystem/_PollNextEventWithPose");
#pragma pack(pop)
| 53.351852 | 249 | 0.767789 | [
"object"
] |
7e6dbf0e2b30718ea1894a109637891ee33c1a77 | 683 | cpp | C++ | dynamic_programming/triangle.cpp | jaswantcoder/C-Plus-Plus | 3501c124743dfc4be437f0ecad5e4e8d7d81fbba | [
"MIT"
] | null | null | null | dynamic_programming/triangle.cpp | jaswantcoder/C-Plus-Plus | 3501c124743dfc4be437f0ecad5e4e8d7d81fbba | [
"MIT"
] | null | null | null | dynamic_programming/triangle.cpp | jaswantcoder/C-Plus-Plus | 3501c124743dfc4be437f0ecad5e4e8d7d81fbba | [
"MIT"
] | null | null | null | /*Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
*/
class Solution {
public:
int minimumTotal(vector<vector<int>>& tri) {
int i,j,n=tri.size();
vector<int> dp(n,0);
for(i=n-1;i>=0;i--)
for(j=0;j<=i;j++)
{
if(i+1<n)
{
dp[j]=min(dp[j],dp[j+1]);
}
dp[j]+=tri[i][j];
}
return dp[0];
}
};
| 19.514286 | 126 | 0.464129 | [
"vector"
] |
7e77ccba1cb59bd482e58e533bb6c10f5e067e1e | 5,835 | cpp | C++ | hw2/src/main.cpp | kungcn/Teamwork_of_Algorithm | 55ed4785896aae7876b4ef34c73c4fed2111d187 | [
"MIT"
] | null | null | null | hw2/src/main.cpp | kungcn/Teamwork_of_Algorithm | 55ed4785896aae7876b4ef34c73c4fed2111d187 | [
"MIT"
] | null | null | null | hw2/src/main.cpp | kungcn/Teamwork_of_Algorithm | 55ed4785896aae7876b4ef34c73c4fed2111d187 | [
"MIT"
] | null | null | null | #include "header.h"
#include "def.h"
int main(int argc, char *argv[]) {
// dateFile path
char MNIST_DS[MAX_ARRAY_NUMBER] = "./Mnist.ds";
// decode command line
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-n") == 0) {
number_of_dataset = atoi(argv[i+1]);
cout << "number_of_dataset = " << number_of_dataset <<endl;
} else if (strcmp(argv[i], "-d") == 0) {
number_of_pixel = atoi(argv[i+1]);
cout << "number_of_pixel = " << number_of_pixel <<endl;
} else if (strcmp(argv[i], "-f") == 0) {
memcpy(MNIST_DS, argv[i+1], strlen(argv[i + 1]));
cout << "MNIST_DS: " << MNIST_DS << endl;
}
}
// set the present time as the time seed
srand((unsigned)time(NULL));
// record the start time to run the algorithm
double start_time = (double)clock();
//PART 1: read data from mnist.ds
float** dataset = createArray(number_of_dataset, number_of_pixel);
readFromMinst(MNIST_DS, dataset, number_of_dataset);
//PART2: create 100 random vector
float** random_vector = createArray(number_of_random, number_of_pixel);
Create_random(random_vector, number_of_random, number_of_pixel);
//PART3: project dataset to 100 random vector
vector<vector<pair<int, double> > > S = Random_Projection(dataset, random_vector,
number_of_dataset, number_of_random, number_of_pixel);
double part3_time = (double)clock();
//PART4: find the closest pair with algorithm 3
double min = INIT_VALUE_FOR_DISTANCE;
Node closest_pair;
for(vector<vector<pair<int, double> > >::iterator it = S.begin(); it != S.end(); ++it) {
vector<pair<int, double> > s_temp = (*it);
close_pair_pivot x;
x.set(s_temp, s_temp.size());
vector<pair<int, typeOfVector> > y = x.get();
vector<pair<int, typeOfVector> > &X = y;
Node n = x.closestPairMedian(y);
if (n.distance < min) {
min = n.distance;
closest_pair.distance = min;
closest_pair.cp.first.first = n.cp.first.first;
closest_pair.cp.first.second = n.cp.first.second;
closest_pair.cp.second.first = n.cp.second.first;
closest_pair.cp.second.second = n.cp.second.second;
}
}
// Eucildean Distance of the vector represented by the closest pair
double powerSumFirst = 0.0;
double EucildeanDistanceFirst = 0.0;
double distanceMin = dataset[closest_pair.cp.first.first][0] - dataset[closest_pair.cp.second.first][0];
for (int j = 0; j < number_of_pixel; j++) {
powerSumFirst += (dataset[closest_pair.cp.first.first][j] - dataset[closest_pair.cp.second.first][j]) * (dataset[closest_pair.cp.first.first][j] - dataset[closest_pair.cp.second.first][j]);
}
EucildeanDistanceFirst = sqrt(powerSumFirst);
for (int j = 0; j < number_of_pixel; j++) {
double tmp = dataset[closest_pair.cp.first.first][j] - dataset[closest_pair.cp.second.first][j];
if (tmp < distanceMin) {
distanceMin = tmp;
}
}
cout <<"the closest distance count with algorithm 3 is " << closest_pair.distance
<< " with the " << closest_pair.cp.first.first << "st node whose value is "
<< closest_pair.cp.first.second << " and the " <<
closest_pair.cp.second.first << " node whose value is " << closest_pair.cp.second.second << ". The Eucildean Distance is " << EucildeanDistanceFirst << ". The smallest pair is : " << abs(distanceMin) << endl;
double part4_time = (double)clock();
cout << "the cost time with algorithm 3 is " << (part4_time - start_time) / CLOCKS_PER_SEC << "s" << endl;
//PART5: find the closest pair with algorithm4
min = INIT_VALUE_FOR_DISTANCE;
Node closest_pair_;
for(vector<vector<pair<int, double> > >::iterator it = S.begin(); it != S.end(); ++it) {
vector<pair<int, double> > s_temp = (*it);
close_pair_pivot x;
x.set(s_temp, s_temp.size());
vector<pair<int, typeOfVector> > y = x.get();
vector<pair<int, typeOfVector> > &X = y;
Node n = x.closestPairRandom(y);
if (n.distance < min) {
min = n.distance;
closest_pair_.distance = min;
closest_pair_.cp.first.first = n.cp.first.first;
closest_pair_.cp.first.second = n.cp.first.second;
closest_pair_.cp.second.first = n.cp.second.first;
closest_pair_.cp.second.second = n.cp.second.second;
}
}
// Eucildean Distance of the vector represented by the closest pair
double powerSumSecond = 0.0;
double EucildeanDistanceSecond = 0.0;
double distanceMin_ = dataset[closest_pair.cp.first.first][0] - dataset[closest_pair.cp.second.first][0];
for (int j = 0; j < number_of_pixel; j++) {
powerSumSecond += (dataset[closest_pair_.cp.first.first][j] - dataset[closest_pair_.cp.second.first][j]) * (dataset[closest_pair_.cp.first.first][j] - dataset[closest_pair_.cp.second.first][j]);
}
EucildeanDistanceSecond = sqrt(powerSumSecond);
for (int j = 0; j < number_of_pixel; j++) {
double tmp = dataset[closest_pair_.cp.first.first][j] - dataset[closest_pair_.cp.second.first][j];
if (tmp < distanceMin_) {
distanceMin_ = tmp;
}
}
cout <<"the closest distance count with algorithm 4 is " << closest_pair_.distance
<< " with the " << closest_pair_.cp.first.first << "st node whose value is "
<< closest_pair_.cp.first.second << " and the " <<
closest_pair_.cp.second.first << " node whose value is " << closest_pair_.cp.second.second << ". The Eucildean Distance is " << EucildeanDistanceSecond << ". The smallest pair is : " << abs(distanceMin_) << endl;
double part5_time = (double)clock();
cout << "the cost time with algorithm 4 is " << (part5_time - part4_time + part3_time - start_time) / CLOCKS_PER_SEC << "s" << endl;
freeArray(dataset, number_of_dataset);
freeArray(random_vector, number_of_random);
}
| 43.87218 | 215 | 0.655698 | [
"vector"
] |
7e7de481e4d8c3ec37743b03c9777503eb1e3507 | 18,021 | cpp | C++ | Src/CreatureEditor/creature/glink.cpp | jjuiddong/Creature-Editor | ee68cc71b8b93bcc164318344d1a0f87b3ebef4f | [
"MIT"
] | 1 | 2020-01-19T08:45:16.000Z | 2020-01-19T08:45:16.000Z | Src/CreatureEditor/creature/glink.cpp | jjuiddong/Creature-Editor | ee68cc71b8b93bcc164318344d1a0f87b3ebef4f | [
"MIT"
] | null | null | null | Src/CreatureEditor/creature/glink.cpp | jjuiddong/Creature-Editor | ee68cc71b8b93bcc164318344d1a0f87b3ebef4f | [
"MIT"
] | 1 | 2020-11-26T11:52:37.000Z | 2020-11-26T11:52:37.000Z |
#include "stdafx.h"
#include "glink.h"
using namespace evc;
cGLink::cGLink()
: graphic::cNode(common::GenerateId(), "glink")
, m_autoDelete(true)
, m_gnode0(nullptr)
, m_gnode1(nullptr)
, m_highlightRevoluteAxis(false)
{
m_prop.type = phys::eJointType::Fixed;
m_prop.isAngularSensor = false;
m_prop.isLimitSensor = false;
m_prop.isVelocitySensor = false;
m_prop.isAccelSensor = false;
m_prop.isContactSensor = false;
m_prop.revoluteAxis = Vector3(1, 0, 0);
}
cGLink::~cGLink()
{
Clear();
}
// create genotype link from genotype struct
bool cGLink::Create(const sGenotypeLink &glink, cGNode *gnode0, cGNode *gnode1)
{
const Vector3 pivot0 = glink.pivots[0].dir * glink.nodeLocal0.rot * glink.pivots[0].len
+ glink.nodeLocal0.pos;
const Vector3 pivot1 = glink.pivots[1].dir * glink.nodeLocal1.rot * glink.pivots[1].len
+ glink.nodeLocal1.pos;
bool result = false;
switch (glink.type)
{
case phys::eJointType::Fixed:
result = CreateFixed(gnode0, pivot0, gnode1, pivot1);
break;
case phys::eJointType::Spherical:
result = CreateSpherical(gnode0, pivot0, gnode1, pivot1);
break;
case phys::eJointType::Revolute:
result = CreateRevolute(gnode0, pivot0, gnode1, pivot1, glink.revoluteAxis);
break;
case phys::eJointType::Prismatic:
result = CreatePrismatic(gnode0, pivot0, gnode1, pivot1, glink.revoluteAxis);
break;
case phys::eJointType::Distance:
result = CreateDistance(gnode0, pivot0, gnode1, pivot1);
break;
case phys::eJointType::D6:
result = CreateD6(gnode0, pivot0, gnode1, pivot1);
break;
}
if (!result)
return false;
m_prop = glink;
return true;
}
bool cGLink::CreateFixed(cGNode *gnode0 , const Vector3 &pivot0
, cGNode *gnode1, const Vector3 &pivot1)
{
const Transform &worldTfm0 = gnode0->m_transform;
const Transform &worldTfm1 = gnode1->m_transform;
const Vector3 linkPos = (pivot0 + pivot1) / 2.f;
m_prop.type = phys::eJointType::Fixed;
m_gnode0 = gnode0;
m_gnode1 = gnode1;
gnode0->AddLink(this);
gnode1->AddLink(this);
SetRevoluteAxis(Vector3(1, 0, 0));
m_prop.origPos = linkPos - worldTfm0.pos;
m_prop.nodeLocal0 = worldTfm0;
m_prop.nodeLocal1 = worldTfm1;
// world -> local space
m_prop.pivots[0].dir = (pivot0 - worldTfm0.pos).Normal() * worldTfm0.rot.Inverse();
m_prop.pivots[0].len = (pivot0 - worldTfm0.pos).Length();
m_prop.pivots[1].dir = (pivot1 - worldTfm1.pos).Normal() * worldTfm1.rot.Inverse();
m_prop.pivots[1].len = (pivot1 - worldTfm1.pos).Length();
return true;
}
bool cGLink::CreateSpherical(cGNode *gnode0, const Vector3 &pivot0
, cGNode *gnode1, const Vector3 &pivot1)
{
const Transform &worldTfm0 = gnode0->m_transform;
const Transform &worldTfm1 = gnode1->m_transform;
const Vector3 linkPos = (pivot0 + pivot1) / 2.f;
m_prop.type = phys::eJointType::Spherical;
m_gnode0 = gnode0;
m_gnode1 = gnode1;
gnode0->AddLink(this);
gnode1->AddLink(this);
SetRevoluteAxis(Vector3(1, 0, 0));
m_prop.origPos = linkPos - worldTfm0.pos;
m_prop.nodeLocal0 = worldTfm0;
m_prop.nodeLocal1 = worldTfm1;
// world -> local space
m_prop.pivots[0].dir = (pivot0 - worldTfm0.pos).Normal() * worldTfm0.rot.Inverse();
m_prop.pivots[0].len = (pivot0 - worldTfm0.pos).Length();
m_prop.pivots[1].dir = (pivot1 - worldTfm1.pos).Normal() * worldTfm1.rot.Inverse();
m_prop.pivots[1].len = (pivot1 - worldTfm1.pos).Length();
return true;
}
bool cGLink::CreateRevolute(cGNode *gnode0, const Vector3 &pivot0
, cGNode *gnode1, const Vector3 &pivot1, const Vector3 &revoluteAxis)
{
const Transform &worldTfm0 = gnode0->m_transform;
const Transform &worldTfm1 = gnode1->m_transform;
const Vector3 linkPos = (pivot0 + pivot1) / 2.f;
m_prop.type = phys::eJointType::Revolute;
m_gnode0 = gnode0;
m_gnode1 = gnode1;
gnode0->AddLink(this);
gnode1->AddLink(this);
SetRevoluteAxis(revoluteAxis);
m_prop.origPos = linkPos - worldTfm0.pos;
m_prop.nodeLocal0 = worldTfm0;
m_prop.nodeLocal1 = worldTfm1;
// world -> local space
m_prop.pivots[0].dir = (pivot0 - worldTfm0.pos).Normal() * worldTfm0.rot.Inverse();
m_prop.pivots[0].len = (pivot0 - worldTfm0.pos).Length();
m_prop.pivots[1].dir = (pivot1 - worldTfm1.pos).Normal() * worldTfm1.rot.Inverse();
m_prop.pivots[1].len = (pivot1 - worldTfm1.pos).Length();
return true;
}
bool cGLink::CreatePrismatic(cGNode *gnode0, const Vector3 &pivot0
, cGNode *gnode1, const Vector3 &pivot1, const Vector3 &revoluteAxis)
{
const Transform &worldTfm0 = gnode0->m_transform;
const Transform &worldTfm1 = gnode1->m_transform;
const Vector3 linkPos = (pivot0 + pivot1) / 2.f;
m_prop.type = phys::eJointType::Prismatic;
m_gnode0 = gnode0;
m_gnode1 = gnode1;
gnode0->AddLink(this);
gnode1->AddLink(this);
SetRevoluteAxis(revoluteAxis);
m_prop.origPos = linkPos - worldTfm0.pos;
m_prop.nodeLocal0 = worldTfm0;
m_prop.nodeLocal1 = worldTfm1;
// world -> local space
m_prop.pivots[0].dir = (pivot0 - worldTfm0.pos).Normal() * worldTfm0.rot.Inverse();
m_prop.pivots[0].len = (pivot0 - worldTfm0.pos).Length();
m_prop.pivots[1].dir = (pivot1 - worldTfm1.pos).Normal() * worldTfm1.rot.Inverse();
m_prop.pivots[1].len = (pivot1 - worldTfm1.pos).Length();
return true;
}
bool cGLink::CreateDistance(cGNode *gnode0, const Vector3 &pivot0
, cGNode *gnode1, const Vector3 &pivot1)
{
const Transform &worldTfm0 = gnode0->m_transform;
const Transform &worldTfm1 = gnode1->m_transform;
const Vector3 linkPos = (pivot0 + pivot1) / 2.f;
m_prop.type = phys::eJointType::Distance;
m_gnode0 = gnode0;
m_gnode1 = gnode1;
gnode0->AddLink(this);
gnode1->AddLink(this);
SetRevoluteAxis(Vector3(1, 0, 0));
m_prop.origPos = linkPos - worldTfm0.pos;
m_prop.nodeLocal0 = worldTfm0;
m_prop.nodeLocal1 = worldTfm1;
// world -> local space
m_prop.pivots[0].dir = (pivot0 - worldTfm0.pos).Normal() * worldTfm0.rot.Inverse();
m_prop.pivots[0].len = (pivot0 - worldTfm0.pos).Length();
m_prop.pivots[1].dir = (pivot1 - worldTfm1.pos).Normal() * worldTfm1.rot.Inverse();
m_prop.pivots[1].len = (pivot1 - worldTfm1.pos).Length();
return true;
}
bool cGLink::CreateD6(cGNode *gnode0, const Vector3 &pivot0
, cGNode *gnode1, const Vector3 &pivot1)
{
const Transform &worldTfm0 = gnode0->m_transform;
const Transform &worldTfm1 = gnode1->m_transform;
const Vector3 linkPos = (pivot0 + pivot1) / 2.f;
m_prop.type = phys::eJointType::D6;
m_gnode0 = gnode0;
m_gnode1 = gnode1;
gnode0->AddLink(this);
gnode1->AddLink(this);
SetRevoluteAxis(Vector3(1, 0, 0));
m_prop.origPos = linkPos - worldTfm0.pos;
m_prop.nodeLocal0 = worldTfm0;
m_prop.nodeLocal1 = worldTfm1;
// world -> local space
m_prop.pivots[0].dir = (pivot0 - worldTfm0.pos).Normal() * worldTfm0.rot.Inverse();
m_prop.pivots[0].len = (pivot0 - worldTfm0.pos).Length();
m_prop.pivots[1].dir = (pivot1 - worldTfm1.pos).Normal() * worldTfm1.rot.Inverse();
m_prop.pivots[1].len = (pivot1 - worldTfm1.pos).Length();
return true;
}
bool cGLink::CreateCompound(cGNode *gnode0, const Vector3 &pivot0
, cGNode *gnode1, const Vector3 &pivot1)
{
const Transform &worldTfm0 = gnode0->m_transform;
const Transform &worldTfm1 = gnode1->m_transform;
const Vector3 linkPos = (pivot0 + pivot1) / 2.f;
m_prop.type = phys::eJointType::Compound;
m_gnode0 = gnode0;
m_gnode1 = gnode1;
gnode0->AddLink(this);
gnode1->AddLink(this);
SetRevoluteAxis(Vector3(1, 0, 0));
m_prop.origPos = linkPos - worldTfm0.pos;
m_prop.nodeLocal0 = worldTfm0;
m_prop.nodeLocal1 = worldTfm1;
// world -> local space
m_prop.pivots[0].dir = (pivot0 - worldTfm0.pos).Normal() * worldTfm0.rot.Inverse();
m_prop.pivots[0].len = (pivot0 - worldTfm0.pos).Length();
m_prop.pivots[1].dir = (pivot1 - worldTfm1.pos).Normal() * worldTfm1.rot.Inverse();
m_prop.pivots[1].len = (pivot1 - worldTfm1.pos).Length();
return true;
}
bool cGLink::Render(graphic::cRenderer &renderer
, const XMMATRIX &parentTm //= XMIdentity
, const int flags //= 1
)
{
using namespace graphic;
Vector3 pivotPos0 = GetPivotPos(0);
Vector3 pivotPos1 = GetPivotPos(1);
//Vector3 linkPos = (pivotPos0 + pivotPos1) / 2.f;
Vector3 linkPos = m_prop.origPos + m_gnode0->m_transform.pos;
// render link position
Transform tfm;
tfm.pos = linkPos;
tfm.scale = Vector3::Ones * 0.05f;
renderer.m_dbgBox.SetColor(cColor::GREEN);
renderer.m_dbgBox.SetBox(tfm);
renderer.m_dbgBox.Render(renderer);
//~render link position
// render pivot - link pos
if (1)
{
renderer.m_dbgLine.SetColor(cColor(0.f, 1.f, 0.f, 0.5f));
renderer.m_dbgLine.m_isSolid = true;
renderer.m_dbgLine.SetLine(pivotPos0, linkPos, 0.01f);
renderer.m_dbgLine.Render(renderer);
renderer.m_dbgLine.SetLine(pivotPos1, linkPos, 0.01f);
renderer.m_dbgLine.Render(renderer);
}
//~
// render revolution axis
if ((phys::eJointType::Revolute == m_prop.type)
|| (phys::eJointType::Prismatic == m_prop.type))
{
m_transform.pos = linkPos;
Vector3 p0, p1;
GetRevoluteAxis(p0, p1);
renderer.m_dbgLine.SetColor(m_highlightRevoluteAxis ?
cColor(0.f, 0.f, 1.f, 0.9f) : cColor(0.f, 0.f, 1.f, 0.7f));
renderer.m_dbgLine.m_isSolid = true;
renderer.m_dbgLine.SetLine(p0, p1, m_highlightRevoluteAxis? 0.03f : 0.01f);
renderer.m_dbgLine.Render(renderer);
}
// render pivot - revolution axis
if ((phys::eJointType::Revolute == m_prop.type)
|| (phys::eJointType::Prismatic == m_prop.type))
{
Vector3 p0, p1;
GetRevoluteAxis(p0, p1);
const Line line(p0, p1);
const Vector3 p2 = line.Projection(m_gnode0->m_transform.pos);
const Vector3 p3 = line.Projection(m_gnode1->m_transform.pos);
renderer.m_dbgLine.SetColor(cColor::YELLOW);
renderer.m_dbgLine.SetLine(m_gnode0->m_transform.pos, p2, 0.02f);
renderer.m_dbgLine.Render(renderer);
renderer.m_dbgLine.SetLine(m_gnode1->m_transform.pos, p3, 0.02f);
renderer.m_dbgLine.Render(renderer);
}
// render angular limit (origin axis)
if (0 && (phys::eJointType::Revolute == m_prop.type))
{
const float axisLen = 0.2f;
const float axisSize = 0.01f;
Vector3 r0, r1;
GetRevoluteAxis(r0, r1);
const Vector3 dir = (r1 - r0).Normal();
const Quaternion rot(Vector3(1, 0, 0), dir);
Vector3 dirOrig = Vector3(0, 1, 0) * rot;
const Vector3 b0 = Vector3(-0.2f, 0, 0) * rot + linkPos;
const Vector3 b1 = Vector3(0.2f, 0, 0) * rot + linkPos;
const Vector3 p0 = dirOrig * axisLen + b0;
const Vector3 p1 = dirOrig * axisLen + b1;
renderer.m_dbgLine.SetColor(cColor::BLUE);
renderer.m_dbgLine.SetLine(b0, p0, axisSize);
renderer.m_dbgLine.Render(renderer);
renderer.m_dbgLine.SetLine(b1, p1, axisSize);
renderer.m_dbgLine.Render(renderer);
}
// render cone limit (y,z angle)
if ((phys::eJointType::Spherical == m_prop.type) && (m_prop.limit.cone.isLimit))
{
const float r = 0.2f;
const float ry = (float)sin(m_prop.limit.cone.yAngle) * r;
const float hy = (float)cos(m_prop.limit.cone.yAngle) * r;
const float rz = (float)sin(m_prop.limit.cone.zAngle) * r;
const float hz = (float)cos(m_prop.limit.cone.zAngle) * r;
const float h = max(max(hy, hz), 0.1f);
renderer.m_cone.SetDimension(r, h);
renderer.m_cone.SetRadiusXZ(ry, rz);
Quaternion q;
q.SetRotationArc(Vector3(0, -1, 0), m_prop.revoluteAxis);
renderer.m_cone.m_transform.pos = m_prop.origPos + m_prop.nodeLocal0.pos
+ m_prop.revoluteAxis * h;
renderer.m_cone.m_transform.rot = q;
renderer.m_cone.Render(renderer, XMIdentity, eRenderFlag::WIREFRAME);
q.SetRotationArc(Vector3(0, -1, 0), -m_prop.revoluteAxis);
renderer.m_cone.m_transform.pos = m_prop.origPos + m_prop.nodeLocal0.pos
+ -m_prop.revoluteAxis * h;
renderer.m_cone.m_transform.rot = q;
renderer.m_cone.Render(renderer, XMIdentity, eRenderFlag::WIREFRAME);
}
// render linear limit (lower, upper)
if ((phys::eJointType::Prismatic == m_prop.type) && (m_prop.limit.linear.isLimit))
{
Vector3 r0, r1;
GetRevoluteAxis(r0, r1);
const Vector3 dir = (r1 - r0).Normal();
const Quaternion rot(Vector3(1, 0, 0), dir);
const float distance = abs(m_prop.revoluteAxis.DotProduct(
m_gnode1->m_transform.pos - m_gnode0->m_transform.pos));
const float lower = distance + m_prop.limit.linear.lower;
const float upper = distance + m_prop.limit.linear.upper;
const Vector3 p0 = Vector3(1, 0, 0) * lower * rot + m_gnode0->m_transform.pos;
const Vector3 p1 = Vector3(1, 0, 0) * upper * rot + m_gnode0->m_transform.pos;
Transform tfm;
tfm.pos = p0;
tfm.scale = Vector3::Ones * 0.02f;
renderer.m_dbgBox.SetColor(cColor::YELLOW);
renderer.m_dbgBox.SetBox(tfm);
renderer.m_dbgBox.Render(renderer);
tfm.pos = p1;
renderer.m_dbgBox.SetBox(tfm);
renderer.m_dbgBox.SetColor(cColor::RED);
renderer.m_dbgBox.Render(renderer);
}
__super::Render(renderer, parentTm, flags);
return true;
}
// revolute axis picking
graphic::cNode* cGLink::Picking(const Ray &ray, const graphic::eNodeType::Enum type
, const bool isSpherePicking //= true
, OUT float *dist //= NULL
)
{
if (phys::eJointType::Revolute != m_prop.type)
return nullptr;
Vector3 p0, p1;
GetRevoluteAxis(p0, p1);
const Vector3 linkPos = (p0 + p1) / 2.f;
cBoundingBox bbox;
bbox.SetLineBoundingBox(p0, p1, 0.05f);
if (bbox.Pick(ray))
{
if (dist)
*dist = linkPos.Distance(ray.orig);
return this;
}
return nullptr;
}
// update link information if genotype node moving or rotation
// update pivot position, local transform
bool cGLink::UpdateLinkInfo()
{
SetPivotPosByRevoluteAxis(m_prop.revoluteAxis, m_prop.origPos + m_prop.nodeLocal0.pos);
m_prop.nodeLocal0 = m_gnode0->m_transform;
m_prop.nodeLocal1 = m_gnode1->m_transform;
return true;
}
// nodeIndex: 0=node0, 1=node1
// pos : pivot global pos
void cGLink::SetPivotPos(const int nodeIndex, const Vector3 &pos)
{
if ((nodeIndex != 0) && (nodeIndex != 1))
{
assert(0);
return;
}
// change local coordinate system
const Transform tfm = (nodeIndex == 0) ? m_prop.nodeLocal0 : m_prop.nodeLocal1;
const Vector3 dir = (pos - tfm.pos);
m_prop.pivots[nodeIndex].dir = dir.Normal() * tfm.rot.Inverse();
m_prop.pivots[nodeIndex].len = dir.Length();
}
// return pivot world transform
// nodeIndex: 0=node0, 1=node1
Transform cGLink::GetPivotWorldTransform(const int nodeIndex)
{
if ((nodeIndex != 0) && (nodeIndex != 1))
{
assert(0);
return Transform();
}
const Transform tfm = (nodeIndex == 0) ? m_prop.nodeLocal0 : m_prop.nodeLocal1;
Transform ret;
ret.pos = GetPivotPos(nodeIndex);
ret.scale = tfm.scale;
ret.rot = tfm.rot;
return ret;
}
// return pivot pos
Vector3 cGLink::GetPivotPos(const int nodeIndex)
{
if ((nodeIndex != 0) && (nodeIndex != 1))
return Vector3::Zeroes;
Vector3 pivotPos;
cGNode *gnode = (nodeIndex == 0) ? m_gnode0 : m_gnode1;
if (m_prop.pivots[nodeIndex].len != 0.f)
{
const Vector3 localPos = m_prop.pivots[nodeIndex].dir * gnode->m_transform.rot
* m_prop.pivots[nodeIndex].len;
pivotPos = gnode->m_transform.pos + localPos;
}
else
{
pivotPos = gnode->m_transform.pos;
}
return pivotPos;
}
// revoluteAxis: revolute axis direction
void cGLink::SetRevoluteAxis(const Vector3 &revoluteAxis)
{
m_prop.revoluteAxis = revoluteAxis;
m_prop.rotRevolute.SetRotationArc(Vector3(1, 0, 0), revoluteAxis);
}
// update pivot position
// revoluteAxis : revolute axis direction
// aixsPos : revolute axis position (world space position)
void cGLink::SetPivotPosByRevoluteAxis(const Vector3 &revoluteAxis, const Vector3 &axisPos)
{
const Vector3 r0 = revoluteAxis * 2.f + axisPos;
const Vector3 r1 = revoluteAxis * -2.f + axisPos;
const Vector3 pos = axisPos;
const Line line(r0, r1);
// update actor0 pivot pos
const Vector3 p0 = line.Projection(m_prop.nodeLocal0.pos);
const float len0 = pos.Distance(p0);
const Vector3 toP0 = (p0 - pos).Normal();
const Vector3 newPivotPos0 = toP0 * len0 + pos;
// update actor1 pivot pos
const Vector3 p1 = line.Projection(m_prop.nodeLocal1.pos);
const float len1 = pos.Distance(p1);
const Vector3 toP1 = (p1 - pos).Normal();
const Vector3 newPivotPos1 = toP1 * len1 + pos;
SetPivotPos(0, newPivotPos0);
SetPivotPos(1, newPivotPos1);
m_prop.origPos = axisPos - m_prop.nodeLocal0.pos;
}
// pos : revolute axis world pos (world space position)
// revolute axis pos store relative center pos
void cGLink::SetPivotPosByRevolutePos(const Vector3 &pos)
{
Vector3 r0, r1;
if (!GetRevoluteAxis(r0, r1, pos))
return;
const Line line(r0, r1);
// update actor0 pivot pos
const Vector3 p0 = line.Projection(m_prop.nodeLocal0.pos);
const float len0 = pos.Distance(p0);
const Vector3 toP0 = (p0 - pos).Normal();
const Vector3 newPivotPos0 = toP0 * len0 + pos;
// update actor1 pivot pos
const Vector3 p1 = line.Projection(m_prop.nodeLocal1.pos);
const float len1 = pos.Distance(p1);
const Vector3 toP1 = (p1 - pos).Normal();
const Vector3 newPivotPos1 = toP1 * len1 + pos;
SetPivotPos(0, newPivotPos0);
SetPivotPos(1, newPivotPos1);
m_prop.origPos = pos - m_prop.nodeLocal0.pos;
}
// calc revolute axis from pivot0,1
// axisPos : revolute axis position if update
// if empty, default setting joint position
// return revolute axis position p0, p1
bool cGLink::GetRevoluteAxis(OUT Vector3 &out0, OUT Vector3 &out1
, const Vector3 &axisPos //= Vector3::Zeroes
)
{
if (!m_gnode0 || !m_gnode1)
return false;
const Vector3 pivotPos0 = GetPivotPos(0);
const Vector3 pivotPos1 = GetPivotPos(1);
const Vector3 jointPos = axisPos.IsEmpty() ? ((pivotPos0 + pivotPos1) / 2.f) : axisPos;
Vector3 dir;
if (pivotPos1.Distance(pivotPos0) < 0.2f)
{
const Quaternion rot = m_prop.nodeLocal0.rot.Inverse() * m_gnode0->m_transform.rot;
dir = m_prop.revoluteAxis * rot;
}
else
{
dir = (pivotPos1 - pivotPos0).Normal();
}
const Vector3 p0 = dir * 2.f + jointPos;
const Vector3 p1 = dir * -2.f + jointPos;
const common::Line line(p0, p1);
const Vector3 p2 = line.Projection(m_gnode0->m_transform.pos);
const Vector3 p3 = line.Projection(m_gnode1->m_transform.pos);
if (p2.Distance(p3) < 2.f)
{
out0 = dir * 0.5f + jointPos;
out1 = -dir * 0.5f + jointPos;
}
else
{
out0 = p2;
out1 = p3;
}
return true;
}
void cGLink::Clear()
{
m_gnode0 = nullptr;
m_gnode1 = nullptr;
}
| 29.786777 | 91 | 0.711448 | [
"render",
"transform"
] |
7e893975fca0ed8028b7439867975c673dececa6 | 3,533 | hpp | C++ | libff/common/utils.hpp | FardeenFindora/libff | 9be5f23075f9723840eb2ceb0016d24d69dfea8f | [
"MIT"
] | null | null | null | libff/common/utils.hpp | FardeenFindora/libff | 9be5f23075f9723840eb2ceb0016d24d69dfea8f | [
"MIT"
] | null | null | null | libff/common/utils.hpp | FardeenFindora/libff | 9be5f23075f9723840eb2ceb0016d24d69dfea8f | [
"MIT"
] | null | null | null | /** @file
*****************************************************************************
Declaration of miscellaneous math, serialization, and other common utility
functions.
*****************************************************************************
* @author This file is part of libff, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef UTILS_HPP_
#define UTILS_HPP_
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace libff {
typedef std::vector<bool> bit_vector;
template<bool B, class T = void>
struct enable_if { typedef void* type; };
template<class T>
struct enable_if<true, T> { typedef T type; };
std::size_t get_power_of_two(std::size_t n);
std::size_t round_to_next_power_of_2(const std::size_t n);
bool is_power_of_2(const std::size_t n);
/// returns ceil(log2(n)), so 1ul<<log2(n) is the smallest power of 2, that is not less than n
std::size_t log2(std::size_t n);
inline std::size_t exp2(std::size_t k) { return std::size_t(1) << k; }
std::size_t to_twos_complement(int i, std::size_t w);
int from_twos_complement(std::size_t i, std::size_t w);
std::size_t bitreverse(std::size_t n, const std::size_t l);
bit_vector int_list_to_bits(const std::initializer_list<unsigned long> &l, const std::size_t wordsize);
/* throws error if y = 0 */
long long div_ceil(long long x, long long y);
bool is_little_endian();
std::string FORMAT(const std::string &prefix, const char* format, ...);
/* A variadic template to suppress unused argument warnings */
template<typename ... Types>
void UNUSED(Types&&...) {}
#ifdef DEBUG
#define FMT libff::FORMAT
#else
#define FMT(...) (libff::UNUSED(__VA_ARGS__), "")
#endif
void serialize_bit_vector(std::ostream &out, const bit_vector &v);
void deserialize_bit_vector(std::istream &in, bit_vector &v);
template<typename T>
std::size_t ceil_size_in_bits(const std::vector<T> &v);
/* Print a vector in the form { elem0 elem1 elem2 ... }, with a newline at the end
template<typename T>
void print_vector(std::vector<T> &vec);
template<typename T>
void print_vector(std::vector<T> vec);*/
template<typename T>
void print_vector(std::vector<T> &vec)
{
printf("{ ");
for (auto const& elem : vec)
{
std::cout << elem << " ";
}
printf("}\n");
}
template<typename T>
void print_vector(std::vector<T> vec)
{
printf("{ ");
for (auto const& elem : vec)
{
std::cout << elem << " ";
}
printf("}\n");
}
/**
* Returns a random element of T that is not zero or one.
* T can be a field or elliptic curve group.
* Used for testing to generate a test example that doesn't error.
*/
template<typename T>
T random_element_non_zero_one();
/**
* Returns a random element of T that is not zero.
* T can be a field or elliptic curve group.
* Used for testing to generate a test example that doesn't error.
*/
template<typename T>
T random_element_non_zero();
/**
* Returns a random element of T that is not equal to y.
* T can be a field or elliptic curve group.
* Used for testing to generate a test example that doesn't error.
*/
template<typename T>
T random_element_exclude(T y);
#define ARRAY_SIZE(arr) (sizeof(arr)/sizeof(arr[0]))
} // namespace libff
#include <libff/common/utils.tcc> /* note that utils has a templatized part (utils.tcc) and non-templatized part (utils.cpp) */
#endif // UTILS_HPP_
| 28.723577 | 127 | 0.652986 | [
"vector"
] |
7e8cb4fa1135fb1c606ac1d50551aee3242fa3f8 | 480 | cpp | C++ | 1029. Two City Scheduling.cpp | MadanParth786/LeetcodeSolutions_PracticeQuestions | 8a9c1eb88a6d5214abdb2becf2115a51e317a5c4 | [
"MIT"
] | 1 | 2022-01-19T14:25:36.000Z | 2022-01-19T14:25:36.000Z | 1029. Two City Scheduling.cpp | MadanParth786/LeetcodeSolutions_PracticeQuestions | 8a9c1eb88a6d5214abdb2becf2115a51e317a5c4 | [
"MIT"
] | null | null | null | 1029. Two City Scheduling.cpp | MadanParth786/LeetcodeSolutions_PracticeQuestions | 8a9c1eb88a6d5214abdb2becf2115a51e317a5c4 | [
"MIT"
] | null | null | null | class Solution {
public:
int TwocitySchedCost(vector<vector<int>>& costs) {
vector<int> refund;
int N = costs.size()/2;
int minCost = 0;
for(vector<int> cost : costs){
minCost += cost[0];
refund.push_back(cost[1] - cost[0]);
}
sort(refund.begin(), refund.end());
for(int i = 0; i < N; i++){
minCost += refund[i];
}
return minCost;
}
};
| 25.263158 | 55 | 0.454167 | [
"vector"
] |
7e8eff53b4b0d722555d59a799f7b818ec6a7e24 | 513 | hpp | C++ | SniperCommander.hpp | talcome/WarGame | 1af9cba399cae255d95618814881f06021f5a239 | [
"MIT"
] | null | null | null | SniperCommander.hpp | talcome/WarGame | 1af9cba399cae255d95618814881f06021f5a239 | [
"MIT"
] | null | null | null | SniperCommander.hpp | talcome/WarGame | 1af9cba399cae255d95618814881f06021f5a239 | [
"MIT"
] | null | null | null | #pragma once
#include "Sniper.hpp"
namespace WarGame
{
class SniperCommander : public Sniper{
public:
explicit SniperCommander(uint playerID): Sniper(playerID,120,120,100){}
~SniperCommander() override= default;
std::pair<int,int> getEnemyLoc(std::vector<std::vector<Soldier*>> &board) override ;
void attack(std::vector<std::vector<Soldier *>> &board, std::pair<int, int> source) override;
void heal() override;
};
} // end namespace WarGame
| 27 | 101 | 0.647173 | [
"vector"
] |
7e8f59132328c7f91c7b4afcaf61f08bc7fe8ac4 | 9,502 | cpp | C++ | tests/src/runtimeApi/module/hipModuleLoadMultProcessOnMultGPU.cpp | krishoza/HIP | f83315ac3b62801c61098e7f2604ce07e79b633c | [
"MIT"
] | 7 | 2022-03-23T07:04:20.000Z | 2022-03-30T02:44:42.000Z | tests/src/runtimeApi/module/hipModuleLoadMultProcessOnMultGPU.cpp | krishoza/HIP | f83315ac3b62801c61098e7f2604ce07e79b633c | [
"MIT"
] | null | null | null | tests/src/runtimeApi/module/hipModuleLoadMultProcessOnMultGPU.cpp | krishoza/HIP | f83315ac3b62801c61098e7f2604ce07e79b633c | [
"MIT"
] | null | null | null | /*
Copyright (c) 2020-Present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, 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.
*/
/* HIT_START
* BUILD_CMD: kernel_composite_test.code %hc --genco %S/kernel_composite_test.cpp -o kernel_composite_test.code
* BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS -std=c++11
* TEST: %t --tests 0x1
* TEST: %t --tests 0x2
* TEST: %t --tests 0x3
* HIT_END
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef __linux__
#include <unistd.h>
#include <sys/wait.h>
#endif
#include <iostream>
#include <fstream>
#include <cstddef>
#include <vector>
#include "test_common.h"
#define TEST_ITERATIONS 1000
#define CODEOBJ_FILE "kernel_composite_test.code"
#define CODEOBJ_GLOB_KERNEL1 "testWeightedCopy"
#define CODEOBJ_GLOB_KERNEL2 "getAvg"
#define BLOCKSPERCULDULD 6
#define THREADSPERBLOCKLDULD 256
unsigned int globTestID = 0;
/**
* Fetches Gpu device count
*/
void getDeviceCount(int *pdevCnt) {
#ifdef __linux__
int fd[2], val = 0;
pid_t childpid;
// create pipe descriptors
pipe(fd);
// disable visible_devices env from shell
unsetenv("ROCR_VISIBLE_DEVICES");
unsetenv("HIP_VISIBLE_DEVICES");
childpid = fork();
if (childpid > 0) { // Parent
close(fd[1]);
// parent will wait to read the device cnt
read(fd[0], &val, sizeof(val));
// close the read-descriptor
close(fd[0]);
// wait for child exit
wait(NULL);
*pdevCnt = val;
} else if (!childpid) { // Child
int devCnt = 1;
// writing only, no need for read-descriptor
close(fd[0]);
HIPCHECK(hipGetDeviceCount(&devCnt));
// send the value on the write-descriptor:
write(fd[1], &devCnt, sizeof(devCnt));
// close the write descriptor:
close(fd[1]);
exit(0);
} else { // failure
*pdevCnt = 1;
return;
}
#else
HIPCHECK(hipGetDeviceCount(pdevCnt));
#endif
}
/**
* Validates hipModuleLoadUnload if globTestID = 1
* Validates hipModuleLoadDataUnload if globTestID = 2
* Validates hipModuleLoadDataExUnload if globTestID = 3
*/
bool testhipModuleLoadUnloadFunc(const std::vector<char>& buffer) {
size_t N = 16*16;
size_t Nbytes = N * sizeof(int);
int *A_d, *B_d;
int *A_h, *B_h;
unsigned blocks = HipTest::setNumBlocks(BLOCKSPERCULDULD,
THREADSPERBLOCKLDULD, N);
int deviceid;
hipGetDevice(&deviceid);
printf("pid = %u deviceid = %d\n", getpid(), deviceid);
// allocate host and device buffer
HIPCHECK(hipMalloc(&A_d, Nbytes));
HIPCHECK(hipMalloc(&B_d, Nbytes));
A_h = reinterpret_cast<int *>(malloc(Nbytes));
if (NULL == A_h) {
failed("Failed to allocate using malloc");
}
B_h = reinterpret_cast<int *>(malloc(Nbytes));
if (NULL == B_h) {
failed("Failed to allocate using malloc");
}
// set host buffers
for (int idx = 0; idx < N; idx++) {
A_h[idx] = deviceid;
}
// Copy buffer from host to device
HIPCHECK(hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice));
hipModule_t Module;
hipFunction_t Function;
if (1 == globTestID) {
HIPCHECK(hipModuleLoad(&Module, CODEOBJ_FILE));
} else if (2 == globTestID) {
HIPCHECK(hipModuleLoadData(&Module, &buffer[0]));
} else if (3 == globTestID) {
HIPCHECK(hipModuleLoadDataEx(&Module,
&buffer[0], 0, nullptr, nullptr));
}
HIPCHECK(hipModuleGetFunction(&Function, Module,
CODEOBJ_GLOB_KERNEL1));
float deviceGlobalFloatH = 3.14;
int deviceGlobalInt1H = 100*deviceid;
int deviceGlobalInt2H = 50*deviceid;
short deviceGlobalShortH = 25*deviceid;
char deviceGlobalCharH = 13*deviceid;
hipDeviceptr_t deviceGlobal;
size_t deviceGlobalSize;
HIPCHECK(hipModuleGetGlobal(&deviceGlobal,
&deviceGlobalSize,
Module, "deviceGlobalFloat"));
HIPCHECK(hipMemcpyHtoD(hipDeviceptr_t(deviceGlobal),
&deviceGlobalFloatH,
deviceGlobalSize));
HIPCHECK(hipModuleGetGlobal(&deviceGlobal,
&deviceGlobalSize,
Module, "deviceGlobalInt1"));
HIPCHECK(hipMemcpyHtoD(hipDeviceptr_t(deviceGlobal),
&deviceGlobalInt1H,
deviceGlobalSize));
HIPCHECK(hipModuleGetGlobal(&deviceGlobal,
&deviceGlobalSize,
Module,
"deviceGlobalInt2"));
HIPCHECK(hipMemcpyHtoD(hipDeviceptr_t(deviceGlobal),
&deviceGlobalInt2H, deviceGlobalSize));
HIPCHECK(hipModuleGetGlobal(&deviceGlobal,
&deviceGlobalSize,
Module, "deviceGlobalShort"));
HIPCHECK(hipMemcpyHtoD(hipDeviceptr_t(deviceGlobal),
&deviceGlobalShortH, deviceGlobalSize));
HIPCHECK(hipModuleGetGlobal(&deviceGlobal,
&deviceGlobalSize, Module, "deviceGlobalChar"));
HIPCHECK(hipMemcpyHtoD(hipDeviceptr_t(deviceGlobal),
&deviceGlobalCharH, deviceGlobalSize));
// Launch Function kernel function
hipStream_t stream;
HIPCHECK(hipStreamCreate(&stream));
struct {
void* _Ad;
void* _Bd;
} args;
args._Ad = reinterpret_cast<void*>(A_d);
args._Bd = reinterpret_cast<void*>(B_d);
size_t size = sizeof(args);
void* config[] = {HIP_LAUNCH_PARAM_BUFFER_POINTER, &args,
HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
HIP_LAUNCH_PARAM_END};
HIPCHECK(hipModuleLaunchKernel(Function, 1, 1, 1,
N, 1, 1, 0, stream, NULL,
reinterpret_cast<void**>(&config)));
// Copy buffer from decice to host
HIPCHECK(hipMemcpyAsync(B_h, B_d, Nbytes, hipMemcpyDeviceToHost, stream));
HIPCHECK(hipDeviceSynchronize());
HIPCHECK(hipStreamDestroy(stream));
// Check the results
for (int idx = 0; idx < N; idx++) {
if (B_h[idx] != (deviceGlobalInt1H*A_h[idx]
+ deviceGlobalInt2H
+ static_cast<int>(deviceGlobalShortH) +
+ static_cast<int>(deviceGlobalCharH)
+ static_cast<int>(deviceGlobalFloatH*deviceGlobalFloatH))) {
printf("Matrix Addition Failed\n");
// exit the current process with failure
return false;
}
}
HIPCHECK(hipModuleUnload(Module));
// free memory
HIPCHECK(hipFree(B_d));
HIPCHECK(hipFree(A_d));
free(B_h);
free(A_h);
printf("pid:%u PASSED\n", getpid());
return true;
}
/**
* Spawn 1 Process for each device
*
*/
void spawnProc(int deviceCount, const std::vector<char>& buffer) {
int numDevices = deviceCount;
bool TestPassed = true;
#ifdef __linux__
pid_t pid = 0;
// spawn a process for each device
for (int deviceNo = 0; deviceNo < numDevices; deviceNo++) {
if ((pid = fork()) < 0) {
printf("Child_Concurrency_MultiGpu : fork() returned error %d\n",
pid);
failed("Test Failed!");
} else if (!pid) { // Child process
bool TestPassedChild = true;
// set the device id for the current process
HIPCHECK(hipSetDevice(deviceNo));
TestPassedChild = testhipModuleLoadUnloadFunc(buffer);
if (TestPassedChild) {
exit(0); // child exit with success status
} else {
printf("Child_Concurrency_MultiGpu : childpid %d failed\n",
getpid());
exit(1); // child exit with failure status
}
}
}
int cumStatus = 0;
// Parent shall wait for child to complete
for (int i = 0; i < numDevices; i++) {
int pidwait = 0, exitStatus;
pidwait = wait(&exitStatus);
cumStatus |= WEXITSTATUS(exitStatus);
}
if (cumStatus) {
TestPassed &= false;
}
#else
for (int deviceNo = 0; deviceNo < numDevices; deviceNo++) {
// set the device id for the current process
HIPCHECK(hipSetDevice(deviceNo));
TestPassed &= testhipModuleLoadUnloadFunc(buffer);
}
#endif
if (TestPassed) {
passed();
} else {
failed("hipMallocChild_Concurrency_MultiGpu Failed!");
}
}
int main(int argc, char* argv[]) {
HipTest::parseStandardArguments(argc, argv, true);
int numDevices = 0;
getDeviceCount(&numDevices);
if (1 == numDevices) {
printf("Testing on Single GPU machine.\n");
}
std::ifstream file(CODEOBJ_FILE,
std::ios::binary | std::ios::ate);
std::streamsize fsize = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(fsize);
if (!file.read(buffer.data(), fsize)) {
failed("could not open code object '%s'\n", CODEOBJ_FILE);
}
file.close();
if (p_tests == 0x1) {
globTestID = 1;
spawnProc(numDevices, buffer);
} else if (p_tests == 0x2) {
globTestID = 2;
spawnProc(numDevices, buffer);
} else if (p_tests == 0x3) {
globTestID = 3;
spawnProc(numDevices, buffer);
}
}
| 30.357827 | 111 | 0.67228 | [
"object",
"vector"
] |
7e955e31e68d28f123276bf002dfb8b0f6a015c4 | 557 | cpp | C++ | Acmicpc/C++/BOJ13333.cpp | sungmen/Acmicpc_Solve | 0298a6aec84993a4d8767bd2c00490b7201e06a4 | [
"MIT"
] | 1 | 2020-07-08T23:16:19.000Z | 2020-07-08T23:16:19.000Z | Acmicpc/C++/BOJ13333.cpp | sungmen/Acmicpc_Solve | 0298a6aec84993a4d8767bd2c00490b7201e06a4 | [
"MIT"
] | 1 | 2020-05-16T03:12:24.000Z | 2020-05-16T03:14:42.000Z | Acmicpc/C++/BOJ13333.cpp | sungmen/Acmicpc_Solve | 0298a6aec84993a4d8767bd2c00490b7201e06a4 | [
"MIT"
] | 2 | 2020-05-16T03:25:16.000Z | 2021-02-10T16:51:25.000Z | #include <iostream>
#include <vector>
#include <algorithm>
int main() {
int n;
scanf("%d", &n);
std::vector<int> v(n);
for(int i = 0; i < n; i++)
scanf("%d", &v[i]);
std::sort(v.begin(), v.end());
for(int i = n; i >= int(n/2); i--) {
int cnt = 0;
for(int j = 0; j < n; j++) {
if (v[j] >= i)
++cnt;
}
if(cnt >= i && n - cnt <= i){
printf("%d", i);
return 0;
}
}
printf("%d", v[0]);
return 0;
} | 20.62963 | 41 | 0.35009 | [
"vector"
] |
7e988c89940fca4b49f63f046b822a52fc1a9e42 | 2,250 | hpp | C++ | storage/storage_builder.hpp | mapsme/travelguide | 26dd50b93f55ef731175c19d12514da5bace9fa4 | [
"Apache-2.0"
] | 61 | 2015-12-05T19:34:20.000Z | 2021-06-25T09:07:09.000Z | storage/storage_builder.hpp | mapsme/travelguide | 26dd50b93f55ef731175c19d12514da5bace9fa4 | [
"Apache-2.0"
] | 9 | 2016-02-19T23:22:20.000Z | 2017-01-03T18:41:04.000Z | storage/storage_builder.hpp | mapsme/travelguide | 26dd50b93f55ef731175c19d12514da5bace9fa4 | [
"Apache-2.0"
] | 35 | 2015-12-17T00:09:14.000Z | 2021-01-27T10:47:11.000Z | #pragma once
#include "storage.hpp"
#include "article_info.hpp"
#include "../std/map.hpp"
#include "../std/stdint.hpp"
class ArticleInfoBuilder : public ArticleInfo
{
public:
explicit ArticleInfoBuilder(string const & title) : ArticleInfo(title)
{
}
ArticleInfoBuilder(ArticleInfo const & info) : ArticleInfo(info)
{
}
ArticleInfoBuilder(string const & title, ArticleInfoBuilder const & src, bool redirect)
: ArticleInfo(title, src, redirect), m_parentUrl(src.m_parentUrl)
{
}
void SetParams(vector<string> const & entries);
void SetLatLon(double lat, double lon)
{
m_lat = lat;
m_lon = lon;
}
/// @name Used for tests.
//@{
ArticleInfoBuilder(string const & title, string const & url, double lat, double lon)
: ArticleInfo(title)
{
m_url = url;
SetLatLon(lat, lon);
}
ArticleInfoBuilder(string const & title, double lat, double lon, uint32_t length)
: ArticleInfo(title)
{
m_length = length;
SetLatLon(lat, lon);
}
//@}
string m_parentUrl;
void Swap(ArticleInfoBuilder & b)
{
m_parentUrl.swap(b.m_parentUrl);
ArticleInfo::Swap(b);
}
string const & Title() const { return m_title; }
double Lat() const { return m_lat; }
double Lon() const { return m_lon; }
};
inline void swap(ArticleInfoBuilder & b1, ArticleInfoBuilder & b2)
{
b1.Swap(b2);
}
class StorageBuilder
{
vector<ArticleInfoBuilder> m_info;
map<string, size_t> m_url2info;
void ProcessArticles();
public:
void ParseEntries(string const & path);
void ParseRedirects(string const & path);
void ParseGeocodes(string const & path);
void Add(ArticleInfoBuilder const & info);
void Save(string const & path);
void Load(string const & path);
void Assign(Storage & storage);
bool operator == (Storage const & s) const;
ArticleInfoBuilder * GetArticle(string const & url)
{
map<string, size_t>::const_iterator i = m_url2info.find(url);
return (i == m_url2info.end() ? 0 : &m_info[i->second]);
}
size_t GetSize() const { return m_info.size(); }
ArticleInfoBuilder const & GetArticle(size_t i) const { return m_info[i]; }
/// For tests only.
void InitMock();
};
class StorageMock : public Storage
{
public:
StorageMock();
};
| 20.833333 | 89 | 0.679111 | [
"vector"
] |
7ea55f9cecbf0f96335197b63f3a197457e2fe9d | 3,787 | cpp | C++ | csapex_vision/src/matrix_operations/convert_type.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 2 | 2016-09-02T15:33:22.000Z | 2019-05-06T22:09:33.000Z | csapex_vision/src/matrix_operations/convert_type.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 1 | 2021-02-14T19:53:30.000Z | 2021-02-14T19:53:30.000Z | csapex_vision/src/matrix_operations/convert_type.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 6 | 2016-10-12T00:55:23.000Z | 2021-02-10T17:49:25.000Z | #include "convert_type.h"
/// PROJECT
#include <csapex/model/node_modifier.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_opencv/cv_mat_message.h>
using namespace csapex;
using namespace csapex::connection_types;
using namespace csapex;
CSAPEX_REGISTER_CLASS(csapex::ConvertType, csapex::Node)
namespace
{
template <typename Tp>
inline void normalize(cv::Mat& mat)
{
double min;
double max;
cv::minMaxLoc(mat, &min, &max);
mat = mat - min;
max -= min;
mat = mat / max;
Tp fac = std::numeric_limits<Tp>::max();
mat = mat * fac;
}
} // namespace
ConvertType::ConvertType() : mode_(CV_8U)
{
}
void ConvertType::process()
{
CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
CvMatMessage::Ptr out(new connection_types::CvMatMessage(in->getEncoding(), in->frame_id, in->stamp_micro_seconds));
switch (mode_) {
case CV_8U:
if (normalize_)
normalize<unsigned char>(out->value);
in->value.convertTo(out->value, CV_8UC(in->value.channels()), alpha_, beta_);
break;
case CV_8S:
if (normalize_)
normalize<signed char>(out->value);
in->value.convertTo(out->value, CV_8SC(in->value.channels()), alpha_, beta_);
break;
case CV_16U:
if (normalize_)
normalize<unsigned short int>(out->value);
in->value.convertTo(out->value, CV_16UC(in->value.channels()), alpha_, beta_);
break;
case CV_16S:
if (normalize_)
normalize<signed short int>(out->value);
in->value.convertTo(out->value, CV_16SC(in->value.channels()), alpha_, beta_);
break;
case CV_32S:
if (normalize_)
normalize<signed int>(out->value);
in->value.convertTo(out->value, CV_32SC(in->value.channels()), alpha_, beta_);
break;
case CV_32F:
if (normalize_)
normalize<float>(out->value);
in->value.convertTo(out->value, CV_32FC(in->value.channels()), alpha_, beta_);
break;
case CV_64F:
if (normalize_)
normalize<double>(out->value);
in->value.convertTo(out->value, CV_64FC(in->value.channels()), alpha_, beta_);
break;
default:
throw std::runtime_error("Unknown conversion goal type!");
break;
}
msg::publish(output_, out);
}
void ConvertType::setup(NodeModifier& node_modifier)
{
input_ = node_modifier.addInput<CvMatMessage>("original");
output_ = node_modifier.addOutput<CvMatMessage>("converted");
update();
}
void ConvertType::setupParameters(Parameterizable& parameters)
{
std::map<std::string, int> types = { { " 8 Bit unsigned", CV_8U }, { " 8 Bit signed", CV_8S }, { "16 Bit usigned", CV_16U }, { "16 Bit signed", CV_16S },
{ "32 Bit signed", CV_32S }, { "32 Bit floating", CV_32F }, { "64 Bit floating", CV_64F } };
parameters.addParameter(csapex::param::factory::declareParameterSet("convert to", types, CV_8U), std::bind(&ConvertType::update, this));
parameters.addParameter(csapex::param::factory::declareBool("normalize", false), std::bind(&ConvertType::update, this));
parameters.addParameter(csapex::param::factory::declareRange("alpha", 0.0, 255.0, 1.0, 0.01),
alpha_);
parameters.addParameter(csapex::param::factory::declareRange("beta", 0.0, 255.0, 0.0, 0.01),
beta_);
}
void ConvertType::update()
{
mode_ = readParameter<int>("convert to");
}
| 34.117117 | 160 | 0.607077 | [
"model"
] |
7eb2b5485a471b35c9d6c52ed711a90674a4b766 | 14,952 | cpp | C++ | PICam/code/kinetics.cpp | sliakat/SpeReadPy | f57e4eeaf3759de3fc01bc5c7712d0f8a12b71c2 | [
"MIT"
] | 2 | 2021-02-11T18:15:33.000Z | 2021-06-06T22:14:36.000Z | PICam/code/kinetics.cpp | sliakat/SpeReadPy | f57e4eeaf3759de3fc01bc5c7712d0f8a12b71c2 | [
"MIT"
] | 1 | 2020-12-30T16:04:09.000Z | 2020-12-30T16:04:09.000Z | PICam/code/kinetics.cpp | sliakat/SpeReadPy | f57e4eeaf3759de3fc01bc5c7712d0f8a12b71c2 | [
"MIT"
] | 1 | 2021-06-02T01:05:10.000Z | 2021-06-02T01:05:10.000Z | //---------------------------------------------------------------------------
// Kinetics.cpp Sample Code to demonstrate Kinetics Capture using PI API
// This source defaults to produce a set of free-running kinetics acquisitions
// See notes below to produce code for manually triggered acquisition
//---------------------------------------------------------------------------
#include "picam.h" // Teledyne Princeton Instruments API Header
#include "stdio.h"
// Name, location of Raw Data output file
const char* TargetFileName="fileoutput.dat";
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// to have source produce code for manually triggered acquisition,
// #define one of these: (BUT NOT BOTH)
// manually trigger each kinetics window frame acquisition
//#define DO_KINETICS_WITH_SHIFT_PER_TRIGGER
// manually trigger each kinetics window frame expose
//#define DO_KINETICS_WITH_EXPOSE_DURING_TRIGGER_PULSE
// manually trigger each Readout acquisition
//#define DO_KINETICS_WITH_READOUT_PER_TRIGGER
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Kinetics Example Code
void DoKineticsCapture(PicamHandle camera);
// Show error code helper routine
void DisplayError(PicamError errCode);
// sample function to show how to write captured pixel data to binary file
// returns true for success, false if failed
// DOES NOT HANDLE MetaData
pibool myWriteDataToFile(void *buffer, piint pixelBitDepth, pi64s numreadouts,
piint pixelsWide, piint pixelsHigh, const char* TargetFileName);
//---------------------------------------------------------------------------
// Teledyne Princeton Instruments Kinetics Capture example.
//
// Main is a generic stub, calling specially written functions
//
//---------------------------------------------------------------------------
int main()
{
PicamError errCode = PicamError_None; // Error Code
PicamHandle camera = NULL; // Camera Handle
// ensure that only ONE Trigger condition was #defined:
piint DefineTest = 0;
#ifdef DO_KINETICS_WITH_SHIFT_PER_TRIGGER
DefineTest++;
#endif
#ifdef DO_KINETICS_WITH_EXPOSE_DURING_TRIGGER_PULSE
DefineTest++;
#endif
#ifdef DO_KINETICS_WITH_READOUT_PER_TRIGGER
DefineTest++;
#endif
if (DefineTest>1)
{
printf("\n\n ! ! ERROR- %d TRIGGER conditions #defined, can have only one ! ! \n",(int)DefineTest);
return 1;
}
// Initialize the library
errCode = Picam_InitializeLibrary();
// Check error code
if (errCode == PicamError_None)
{
// Open the first camera
errCode = Picam_OpenFirstCamera( &camera );
// If the camera open succeeded
if (errCode == PicamError_None)
{
// Setup and acquire for a Kinetics Capture
DoKineticsCapture(camera);
// We are done with the camera so close it
Picam_CloseCamera(camera);
}
// Show error string if a problem occurred
else
DisplayError(errCode);
}
// Show error string if a problem occurred
else
DisplayError(errCode);
// Uninitialize the library
Picam_UninitializeLibrary();
printf("\n\n ! ! ! Finished- Press Any Key To Exit ! ! ! !\n");
//!! _getch();
return 0;
}
//---------------------------------------------------------------------------
// DisplayError helper routine, prints out the message for the associated
// error code.
//
//---------------------------------------------------------------------------
void DisplayError(PicamError errCode)
{
// Get the error string, the called function allocates the memory
const pichar *errString;
Picam_GetEnumerationString( PicamEnumeratedType_Error,
(piint)errCode,
&errString);
// Print the error
printf("%s\n", errString);
// Since the called function allocated the memory it must free it
Picam_DestroyString(errString);
}
//---------------------------------------------------------------------------
// myWriteDataToFile( ) returns true for success, false if failed
// sample function to show how to write captured pixel data to binary file
// WARNING: This is JUST a sample how to handle image data after capture
// This will NOT Work as written if metadata is present
//---------------------------------------------------------------------------
pibool myWriteDataToFile(void *buffer, piint pixelBitDepth, pi64s numreadouts,
piint pixelsWide, piint pixelsHigh, const char* TargetFileName)
{
pibool returnOK = false;
piint imagePixels = pixelsWide * pixelsHigh;
piint bytesInReadout = 0;
// simple dump of raw data into binary file
FILE* fs = fopen(TargetFileName, "wb");
if (!fs)
{
printf("\n ! ! Could not open datafile %s for output\n", TargetFileName);
return returnOK;
}
// Conversion of numpixels in readout to numbytes
// currently we recognize only 16 bit image pixel size
switch (pixelBitDepth)
{
case 16:
bytesInReadout = 2 * imagePixels;
break;
default:
bytesInReadout = 0;
break;
}
// write out numreadouts * readoutSize worth of data to file
// each readout data blob is contiguously stored
// ! ! THIS LOGIC WILL NOT CORRECTLY OUTPUT READOUT WITH METADATA ! ! !
if (fwrite(buffer, bytesInReadout, (size_t)numreadouts, fs) == (size_t)numreadouts)
returnOK = true;
fclose(fs);
if (returnOK)
printf("\n ! ! Successfully wrote %d bytes to %s \n",
(int)(bytesInReadout * numreadouts), TargetFileName);
else
printf("\n ! ! Could not write data to %s \n", TargetFileName);
return returnOK;
}
//---------------------------------------------------------------------------
// Teledyne Princeton Instruments Kinetics example.
//
// Sets up the camera and acquires a kinetics image set.
//
//---------------------------------------------------------------------------
void DoKineticsCapture(PicamHandle camera)
{
PicamError err; // Error Code
PicamAvailableData acquisitionData; // Data Struct
PicamAcquisitionErrorsMask acqErrors; // Errors
const PicamParameter *paramsFailed; // Failed to commit
piint failCount; // Count of failed
const PicamRoisConstraint *ptrConstraint; // Constraints
PicamRois roiSetup; // region of interest setup
PicamRoi theKineticsROI;
piint framesPerReadout = 0;
// Variables to compute data blob sizes
piint readoutHeight = 0; // Height of Readout (in pixels)
piint readoutWidth = 0; // Width of Readout (in pixels)
piint singleFrameHeight= 0; // Height of single Kinetics frame (in pixels)
// Inputs into this experiment:
// Acquire 3 readout of data with a 10000 ms timeout
// Using kinetics mode, with window height of 128 pixels
PicamReadoutControlMode ReadoutMode = PicamReadoutControlMode_Kinetics;
piint acquireTimoutMillisecs = 10000; // Ten second timeout for normal kinetics
// is disabled by logic if trigger mode
piint kineticsWindowHeight = 10;
piint exposureTimeMillisecs = 20;
pi64s numReadoutsRequested = 3;
PicamTriggerResponse TriggerResponse = PicamTriggerResponse_NoResponse;
pibool usingTrigger = false;
PicamTriggerDetermination TriggerDetermination = PicamTriggerDetermination_PositivePolarity;
printf("..STARTING KINETICS EXPERIMENT..\n\n");
#ifdef DO_KINETICS_WITH_EXPOSE_DURING_TRIGGER_PULSE
TriggerResponse = PicamTriggerResponse_ExposeDuringTriggerPulse;
TriggerDetermination = PicamTriggerDetermination_PositivePolarity;
acquireTimoutMillisecs = -1; // Disable timeout on acquisition
usingTrigger = true;
printf(" with Expose During Trigger Pulse Hardware mode\n\n");
#endif
#ifdef DO_KINETICS_WITH_SHIFT_PER_TRIGGER
TriggerResponse = PicamTriggerResponse_ShiftPerTrigger;
TriggerDetermination = PicamTriggerDetermination_PositivePolarity;
usingTrigger = true;
acquireTimoutMillisecs = -1; // Disable timeout on acquisition
printf(" with Shift Per Trigger Hardware mode\n\n");
#endif
#ifdef DO_KINETICS_WITH_READOUT_PER_TRIGGER
TriggerResponse = PicamTriggerResponse_ReadoutPerTrigger;
TriggerDetermination = PicamTriggerDetermination_NegativePolarity;
usingTrigger = true;
acquireTimoutMillisecs = -1; // Disable timeout on acquisition
printf(" with Readout Per Trigger Hardware mode\n\n");
#endif
err = Picam_SetParameterIntegerValue(camera,
PicamParameter_ReadoutControlMode, ReadoutMode);
if (err != PicamError_None)
{
printf("ERROR SetParameter PicamParameter_ReadoutControlMode");
return;
}
err = Picam_SetParameterFloatingPointValue(
camera,PicamParameter_ExposureTime, exposureTimeMillisecs );
if (err != PicamError_None)
{
printf("ERROR SetParameter PicamParameter_ExposureTime");
return;
}
err = Picam_SetParameterIntegerValue( camera,
PicamParameter_KineticsWindowHeight, kineticsWindowHeight);
if (err != PicamError_None)
{
printf("ERROR SetParameter PicamParameter_KineticsWindowHeight");
return;
}
// If using a triggered kinetics acquisition, set type of trigger response
if (usingTrigger)
{
// trigger each image or each frame/shift
err = Picam_SetParameterIntegerValue( camera,
PicamParameter_TriggerResponse, TriggerResponse);
if (err != PicamError_None)
{
printf("ERROR SetParameter PicamParameter_TriggerResponse");
return;
}
// Positive or negative edge of trigger pulse
err = Picam_SetParameterIntegerValue( camera,
PicamParameter_TriggerDetermination, TriggerDetermination);
if (err != PicamError_None)
{
printf("ERROR SetParameter PicamParameter_TriggerDetermination");
return;
}
} // if (usingTrigger)
// Get dimensional constraints (ptrConstraint must be deallocated)
err = Picam_GetParameterRoisConstraint( camera, PicamParameter_Rois,
PicamConstraintCategory_Required, &ptrConstraint);
if (err != PicamError_None)
{
printf("ERROR GetParameter PicamParameter_Rois");
return;
}
// Get width and height of accessible region from current constraints
readoutWidth = (piint)ptrConstraint->width_constraint.maximum;
singleFrameHeight = (piint)ptrConstraint->height_constraint.maximum;
// Deallocate constraints after using access
Picam_DestroyRoisConstraints(ptrConstraint);
// Get number of frames that are returned in a single readout,
// given this kinetics window size
err = Picam_GetParameterIntegerValue( camera,
PicamParameter_FramesPerReadout, &framesPerReadout);
if (err != PicamError_None)
{
printf("ERROR GetParameter PicamParameter_FramesPerReadout");
return;
}
// calculate height of full readout
readoutHeight = singleFrameHeight * framesPerReadout;
// setup the roiSetup object count and pointer
roiSetup.roi_count = 1;
roiSetup.roi_array = &theKineticsROI;
// The ROI structure should hold the size of a single kinetics capture ROI
theKineticsROI.height = singleFrameHeight;
theKineticsROI.width = readoutWidth;
// The ROI structure should hold the location of this ROI (upper left corner of window)
theKineticsROI.x = 0;
theKineticsROI.y = 0;
// The vertical and horizontal binning
theKineticsROI.x_binning = 1;
theKineticsROI.y_binning = 1;
// Set the roiSetup of interest
err = Picam_SetParameterRoisValue( camera, PicamParameter_Rois, &roiSetup);
// Commit to hardware
err = Picam_CommitParameters( camera, ¶msFailed, &failCount);
if (err == PicamError_None)
{
printf("\nStart Picam_Acquire():\n %d frames of Kinetics data (%d pix high), in %d readouts\n",
(int)(framesPerReadout * numReadoutsRequested),(int) kineticsWindowHeight,(int)numReadoutsRequested);
// Prompt if Triggered mode is requested
#ifdef DO_KINETICS_WITH_SHIFT_PER_TRIGGER
printf("\n Press Trigger for each Kinetics Window frame requested....\n");
#endif
#ifdef DO_KINETICS_WITH_EXPOSE_PER_TRIGGERPAIR
printf("\n Press Trigger for each Kinetics Window frame expose requested....\n");
#endif
#ifdef DO_KINETICS_WITH_READOUT_PER_TRIGGER
printf("\n Press Trigger to begin Kinetics capture for each readout requested....\n");
#endif
if (acquireTimoutMillisecs != -1)
printf(" .... %d msec Timeout ....\n",(int)acquireTimoutMillisecs);
if (Picam_Acquire(camera, numReadoutsRequested, acquireTimoutMillisecs,
&acquisitionData, &acqErrors) == PicamError_None)
{
printf("..Picam_Acquire() successfully returned\n");
// Get the pixel BitDepth
piint pixelBitDepth;
Picam_GetParameterIntegerValue( camera, PicamParameter_PixelBitDepth, &pixelBitDepth);
// sample function to show how to write out this data to file
// returns boolean true if success, else false
myWriteDataToFile(acquisitionData.initial_readout,
pixelBitDepth, numReadoutsRequested,
readoutHeight, readoutWidth, TargetFileName);
}
else // Error returned from Picam_Acquire(
{
printf("\n! ! Error returned from Picam_Acquire() = %d ! !\n",(int)err);
DisplayError(err);
}
} // after Picam_CommitParameters( )
else // Error returned from Picam_CommitParameters(
{
printf("\n ! ! Error returned from Picam_CommitParameters() = %d: %d failures:\n",(int)err, (int)failCount);
DisplayError(err);
const PicamParameter *ptrErr = paramsFailed;
for (int n=0; n < failCount; n++)
{
printf(" %2d: %d\n",(int)n+1,(int) *ptrErr);
ptrErr++;
}
// free failed parameter array allocated by picam
Picam_DestroyParameters(paramsFailed);
} //if (err == PicamError_None)
} //DoKineticsCapture( )
| 37.19403 | 117 | 0.619382 | [
"object"
] |
9d1b5e4fa6e3f71d09ba7770740bf28fe7fbe72b | 1,808 | cpp | C++ | backup/2/interviewbit/c++/fraction.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 21 | 2019-11-16T19:08:35.000Z | 2021-11-12T12:26:01.000Z | backup/2/interviewbit/c++/fraction.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 1 | 2022-02-04T16:02:53.000Z | 2022-02-04T16:02:53.000Z | backup/2/interviewbit/c++/fraction.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 4 | 2020-05-15T19:39:41.000Z | 2021-10-30T06:40:31.000Z | // Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/interviewbit/fraction.html .
string Solution::fractionToDecimal(int numerator, int denominator) {
long long a = numerator, b = denominator;
if (a == 0)
return "0";
if (b == 0)
return "";
bool nonNegative = a * b >= 0;
if (a < 0) {
a = -a;
}
if (b < 0) {
b = -b;
}
long long intPart = a / b;
stringstream ss;
ss << intPart;
if (a % b != 0) {
ss << ".";
map<long long, long long> mapping;
vector<long long> nums;
a = (a % b) * 10;
while (mapping.find(a) == mapping.end()) {
mapping[a] = nums.size();
nums.push_back(a / b);
a = (a % b) * 10;
if (a == 0) {
break;
}
}
if (a == 0) {
for (long long i = 0; i < nums.size(); i++) {
ss << nums[i];
}
} else {
long long n = nums.size(), k = mapping[a];
for (long long i = 0; i < k; i++) {
ss << nums[i];
}
ss << "(";
for (long long i = k; i < n; i++) {
ss << nums[i];
}
ss << ")";
}
}
return (nonNegative ? "" : "-") + ss.str();
}
| 34.113208 | 345 | 0.489491 | [
"vector"
] |
9d1cdca2d9fc5d6d87b3b9677fd9c0dbeeeb3a48 | 18,168 | cpp | C++ | src/ADP/AnotherDangParser.cpp | Stephen-Seo/AnotherDangParser | 59d9d27e47efc2e4d4f061ad3b80cbf13060bdfc | [
"MIT"
] | null | null | null | src/ADP/AnotherDangParser.cpp | Stephen-Seo/AnotherDangParser | 59d9d27e47efc2e4d4f061ad3b80cbf13060bdfc | [
"MIT"
] | null | null | null | src/ADP/AnotherDangParser.cpp | Stephen-Seo/AnotherDangParser | 59d9d27e47efc2e4d4f061ad3b80cbf13060bdfc | [
"MIT"
] | null | null | null |
#include "AnotherDangParser.hpp"
#include <cstring>
#include <queue>
#include <vector>
#include <stdexcept>
#include "OptionFlag.hpp"
using namespace ADP;
const std::regex AnotherDangParser::dashRegex("^-[^-].*$");
const std::regex AnotherDangParser::dashFullRegex("^-([a-zA-Z])$");
const std::regex AnotherDangParser::longRegex("^--([a-zA-Z][a-zA-Z_-]*)$");
const std::regex AnotherDangParser::longFullRegex("^--([a-zA-Z][a-zA-Z_-]*)=(.+)$");
AnotherDangParser::AnotherDangParser() :
isDirty(true)
{}
void AnotherDangParser::addFlag(std::string flag, std::function<void()> callback, std::string helpText)
{
if(!checkIsValidShort("-" + flag))
{
throw std::invalid_argument("Invalid short flag cannot be registered!");
}
callbacks.insert(std::make_pair(flag, CallbackHolder<void>(callback, helpText)));
isDirty = true;
}
void AnotherDangParser::addOptionFlag(std::string flag, std::function<void(std::string)> callback, std::string helpText)
{
if(!checkIsValidShort("-" + flag))
{
throw std::invalid_argument("Invalid short flag cannot be registered!");
}
optionCallbacks.insert(std::make_pair(flag, CallbackHolder<void, std::string>(callback, helpText)));
isDirty = true;
}
void AnotherDangParser::addLongFlag(std::string lflag, std::function<void()> callback, std::string helpText)
{
if(!checkIsValidLong("--" + lflag))
{
throw std::invalid_argument("Invalid long flag cannot be registered!");
}
longCallbacks.insert(std::make_pair(lflag, CallbackHolder<void>(callback, helpText)));
isDirty = true;
}
void AnotherDangParser::addLongOptionFlag(std::string lflag, std::function<void(std::string)> callback, std::string helpText)
{
if(!checkIsValidLong("--" + lflag))
{
throw std::invalid_argument("Invalid long flag cannot be registered!");
}
longOptionCallbacks.insert(std::make_pair(lflag, CallbackHolder<void, std::string>(callback, helpText)));
isDirty = true;
}
void AnotherDangParser::aliasFlag(std::string existingFlag, std::string newFlag)
{
std::smatch eMatch, nMatch;
bool eIsLong, nIsLong;
if(std::regex_match(existingFlag, eMatch, AnotherDangParser::dashFullRegex))
{
eIsLong = false;
}
else if(std::regex_match(existingFlag, eMatch, AnotherDangParser::longRegex))
{
eIsLong = true;
}
else
{
throw std::invalid_argument("Existing flag is invalid!");
}
if(std::regex_match(newFlag, nMatch, AnotherDangParser::dashFullRegex))
{
nIsLong = false;
}
else if(std::regex_match(newFlag, nMatch, AnotherDangParser::longRegex))
{
nIsLong = true;
}
else
{
throw std::invalid_argument("New flag is invalid!");
}
if(callbacks.find(nMatch[1]) != callbacks.end() ||
optionCallbacks.find(nMatch[1]) != optionCallbacks.end() ||
longCallbacks.find(nMatch[1]) != longCallbacks.end() ||
longOptionCallbacks.find(nMatch[1]) != longOptionCallbacks.end() ||
aliases.find(nMatch[1]) != aliases.end() ||
optionAliases.find(nMatch[1]) != optionAliases.end())
{
throw std::invalid_argument("New flag already exists!");
}
bool eIsOption;
if(eIsLong)
{
auto eiter = longCallbacks.find(eMatch[1]);
auto eoiter = longOptionCallbacks.find(eMatch[1]);
if(eiter != longCallbacks.end())
{
eIsOption = false;
}
else if(eoiter != longOptionCallbacks.end())
{
eIsOption = true;
}
else
{
throw std::invalid_argument("Existing flag does not exist!");
}
}
else
{
auto eiter = callbacks.find(eMatch[1]);
auto eoiter = optionCallbacks.find(eMatch[1]);
if(eiter != callbacks.end())
{
eIsOption = false;
}
else if(eoiter != optionCallbacks.end())
{
eIsOption = true;
}
else
{
throw std::invalid_argument("Existing flag does not exist!");
}
}
if(eIsOption)
{
if(nIsLong)
{
longOptionAliases.insert(std::make_pair(nMatch[1], eMatch[1]));
}
else
{
optionAliases.insert(std::make_pair(nMatch[1], eMatch[1]));
}
}
else
{
if(nIsLong)
{
longAliases.insert(std::make_pair(nMatch[1], eMatch[1]));
}
else
{
aliases.insert(std::make_pair(nMatch[1], eMatch[1]));
}
}
isDirty = true;
}
bool AnotherDangParser::parse(int argc, char** argv, bool stopOnInvalidInput)
{
// ignore first parameter which is typically the name of the program
// with the relative/abosulte path to it
--argc;
++argv;
bool gotInvalidInput = false;
std::priority_queue<OptionFlag, std::vector<OptionFlag>, std::greater<OptionFlag> > optionFlagQueue;
while(argc > 0)
{
if(optionFlagQueue.empty())
{
if(std::regex_match(argv[0], AnotherDangParser::dashRegex))
{
unsigned int i = 0;
std::string flag;
// iterate through all short flags clumped together
for(char* arg = argv[0] + 1; arg[0] != '\0'; ++arg)
{
flag.assign(1, arg[0]);
auto iter = callbacks.find(flag);
auto oiter = optionCallbacks.find(flag);
auto aiter = aliases.find(flag);
auto oaiter = optionAliases.find(flag);
if(iter != callbacks.end())
{
iter->second.callback();
}
else if(oiter != optionCallbacks.end())
{
optionFlagQueue.push(OptionFlag(flag, i++));
}
else if(aiter != aliases.end())
{
auto a2c = callbacks.find(aiter->second);
auto a2lc = longCallbacks.find(aiter->second);
if(a2c != callbacks.end())
{
a2c->second.callback();
}
else if(a2lc != longCallbacks.end())
{
a2lc->second.callback();
}
else
{
throw std::runtime_error("ERROR: Failed to find matching alias!");
}
}
else if(oaiter != optionAliases.end())
{
auto oa2o = optionCallbacks.find(oaiter->second);
auto oa2lo = longOptionCallbacks.find(oaiter->second);
if(oa2o != optionCallbacks.end())
{
optionFlagQueue.push(OptionFlag(oa2o->first, i++));
}
else if(oa2lo != longOptionCallbacks.end())
{
optionFlagQueue.push(OptionFlag(oa2lo->first, i++));
}
else
{
throw std::runtime_error("ERROR: Failed to find matching alias!");
}
}
else
{
#ifndef NDEBUG
std::cout << "Got invalid input with " << flag << std::endl;
#endif
if(stopOnInvalidInput)
{
return false;
}
gotInvalidInput = true;
}
}
}
else // did not match dashRegex
{
std::cmatch match;
if(std::regex_match(argv[0], match, AnotherDangParser::longRegex))
{
std::string longName = match[1];
auto iter = longCallbacks.find(longName);
auto laiter = longAliases.find(longName);
if(iter != longCallbacks.end())
{
iter->second.callback();
}
else if(laiter != longAliases.end())
{
auto la2c = callbacks.find(laiter->second);
auto la2lc = longCallbacks.find(laiter->second);
if(la2c != callbacks.end())
{
la2c->second.callback();
}
else if(la2lc != longCallbacks.end())
{
la2lc->second.callback();
}
else
{
throw std::runtime_error("ERROR: Failed to find matching alias!");
}
}
else
{
#ifndef NDEBUG
std::cout << "Got invalid input with " << longName << std::endl;
#endif
if(stopOnInvalidInput)
{
return false;
}
gotInvalidInput = true;
}
}
else if(std::regex_match(argv[0], match, AnotherDangParser::longFullRegex))
{
std::string longName = match[1];
auto iter = longOptionCallbacks.find(longName);
auto loaiter = longOptionAliases.find(longName);
if(iter != longOptionCallbacks.end())
{
iter->second.callback(match[2]);
}
else if(loaiter != longOptionAliases.end())
{
auto loa2oc = optionCallbacks.find(loaiter->second);
auto loa2loc = longOptionCallbacks.find(loaiter->second);
if(loa2oc != optionCallbacks.end())
{
loa2oc->second.callback(match[2]);
}
else if(loa2loc != longOptionCallbacks.end())
{
loa2loc->second.callback(match[2]);
}
else
{
throw std::runtime_error("ERROR: Failed to find matching alias!");
}
}
else
{
#ifndef NDEBUG
std::cout << "Got invalid input with " << longName << std::endl;
#endif
if(stopOnInvalidInput)
{
return false;
}
gotInvalidInput = true;
}
}
else
{
if(stopOnInvalidInput)
{
return false;
}
gotInvalidInput = true;
}
}
}
else // optionFlagQueue not empty
{
OptionFlag of = optionFlagQueue.top();
optionFlagQueue.pop();
auto oc = optionCallbacks.find(of.optionFlag);
auto loc = longOptionCallbacks.find(of.optionFlag);
if(oc != optionCallbacks.end())
{
oc->second.callback(std::string(argv[0]));
}
else if(loc != longOptionCallbacks.end())
{
loc->second.callback(std::string(argv[0]));
}
else
{
throw std::runtime_error("Invalid flag in OptionQueue!");
}
}
--argc;
++argv;
}
if(!optionFlagQueue.empty())
{
#ifndef NDEBUG
std::cout << "Got invalid input because optionFlagQueue was not empty" << std::endl;
#endif
gotInvalidInput = true;
}
return !gotInvalidInput;
}
void AnotherDangParser::printHelp(std::ostream& ostream)
{
if(isDirty)
{
helpCache.clear();
for(auto iter = callbacks.begin(); iter != callbacks.end(); ++iter)
{
HelpInfo helpInfo(iter->first, false, false, iter->second.helpText);
for(auto aiter = aliases.begin(); aiter != aliases.end(); ++aiter)
{
if(aiter->second == iter->first)
{
helpInfo.aliases.push_back("-" + aiter->first);
}
}
for(auto aiter = longAliases.begin(); aiter != longAliases.end(); ++aiter)
{
if(aiter->second == iter->first)
{
helpInfo.aliases.push_back("--" + aiter->first);
}
}
helpCache.insert(helpInfo);
}
for(auto iter = optionCallbacks.begin(); iter != optionCallbacks.end(); ++iter)
{
HelpInfo helpInfo(iter->first, false, true, iter->second.helpText);
for(auto aiter = optionAliases.begin(); aiter != optionAliases.end(); ++aiter)
{
if(aiter->second == iter->first)
{
helpInfo.aliases.push_back("-" + aiter->first);
}
}
for(auto aiter = longOptionAliases.begin(); aiter != longOptionAliases.end(); ++aiter)
{
if(aiter->second == iter->first)
{
helpInfo.aliases.push_back("--" + aiter->first);
}
}
helpCache.insert(helpInfo);
}
for(auto iter = longCallbacks.begin(); iter != longCallbacks.end(); ++iter)
{
HelpInfo helpInfo(iter->first, true, false, iter->second.helpText);
for(auto aiter = aliases.begin(); aiter != aliases.end(); ++aiter)
{
if(aiter->second == iter->first)
{
helpInfo.aliases.push_back("-" + aiter->first);
}
}
for(auto aiter = longAliases.begin(); aiter != longAliases.end(); ++aiter)
{
if(aiter->second == iter->first)
{
helpInfo.aliases.push_back("--" + aiter->first);
}
}
helpCache.insert(helpInfo);
}
for(auto iter = longOptionCallbacks.begin(); iter != longOptionCallbacks.end(); ++iter)
{
HelpInfo helpInfo(iter->first, true, true, iter->second.helpText);
for(auto aiter = optionAliases.begin(); aiter != optionAliases.end(); ++aiter)
{
if(aiter->second == iter->first)
{
helpInfo.aliases.push_back("-" + aiter->first);
}
}
for(auto aiter = longOptionAliases.begin(); aiter != longOptionAliases.end(); ++aiter)
{
if(aiter->second == iter->first)
{
helpInfo.aliases.push_back("--" + aiter->first);
}
}
helpCache.insert(helpInfo);
}
isDirty = false;
}
ostream << "Usage:\n";
for(auto iter = helpCache.begin(); iter != helpCache.end(); ++iter)
{
if(iter->isLong)
{
ostream << " --";
}
else
{
ostream << " -";
}
ostream << iter->flag;
if(!iter->aliases.empty())
{
ostream << "\n Aliases:\n ";
for(auto aiter = iter->aliases.begin(); aiter != iter->aliases.end(); ++aiter)
{
ostream << *aiter << " ";
}
}
ostream << "\n ";
if(iter->helpText.empty())
{
ostream << "(No help text provided.)";
}
else
{
ostream << iter->helpText;
}
ostream << "\n Example(s):\n";
if(iter->isLong)
{
if(iter->requiresOption)
{
ostream << " --" << iter->flag << "=<parameter>";
}
else
{
ostream << " --" << iter->flag;
}
}
else
{
if(iter->requiresOption)
{
ostream << " -" << iter->flag << " <parameter>";
}
else
{
ostream << " -" << iter->flag;
}
}
ostream << '\n';
// alias examples
std::smatch smatch;
for(auto aiter = iter->aliases.begin(); aiter != iter->aliases.end(); ++aiter)
{
if(iter->requiresOption)
{
if(std::regex_match(*aiter, smatch, AnotherDangParser::dashFullRegex))
{
// Is short flag
ostream << " " << *aiter << " <parameter>\n";
}
else
{
// Is long flag
ostream << " " << *aiter << "=<parameter>\n";
}
}
else
{
// Either flag, similar output
ostream << " " << *aiter << '\n';
}
}
ostream << '\n';
}
ostream << std::flush;
}
bool AnotherDangParser::checkIsValidShort(std::string shortFlag)
{
if(std::regex_match(shortFlag, AnotherDangParser::dashFullRegex))
{
return true;
}
else
{
return false;
}
}
bool AnotherDangParser::checkIsValidLong(std::string longFlag)
{
if(std::regex_match(longFlag, AnotherDangParser::longRegex))
{
return true;
}
else
{
return false;
}
}
| 31.817863 | 125 | 0.455746 | [
"vector"
] |
9d220e2effd6f20bcd832798fdde3c8fad102a01 | 7,353 | cpp | C++ | src/backend/llvm/IRGen.cpp | google/ohmu | 33991d1bb655ab26ce1f172fdea0fd7eef32e763 | [
"Apache-2.0"
] | 79 | 2015-01-08T11:43:59.000Z | 2022-02-13T23:39:27.000Z | src/backend/llvm/IRGen.cpp | google/ohmu | 33991d1bb655ab26ce1f172fdea0fd7eef32e763 | [
"Apache-2.0"
] | null | null | null | src/backend/llvm/IRGen.cpp | google/ohmu | 33991d1bb655ab26ce1f172fdea0fd7eef32e763 | [
"Apache-2.0"
] | 22 | 2015-01-03T07:31:58.000Z | 2021-10-13T09:08:31.000Z | //===- IRGen.cpp -----------------------------------------------*- C++ --*-===//
// Copyright 2014 Google
//
// 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 "backend/llvm/IRGen.h"
#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
#include <cstddef>
namespace ohmu {
namespace backend_llvm {
// Map SExpr* to llvm::Value* in general.
template <class T> struct LLVMTypeMap { typedef llvm::Value* Ty; };
// Map other types, e.g. BasicBlock* to llvm::BasicBlock*.
// We define these here b/c template specializations cannot be class members.
template<> struct LLVMTypeMap<Phi> { typedef llvm::PHINode* Ty; };
template<> struct LLVMTypeMap<BasicBlock> { typedef llvm::BasicBlock* Ty; };
template<> struct LLVMTypeMap<SCFG> { typedef llvm::Function* Ty; };
class LLVMReducerMap {
public:
template <class T> struct TypeMap : public LLVMTypeMap<T> { };
typedef std::nullptr_t NullType;
// default result of all undefined reduce methods.
static NullType reduceNull() { return nullptr; }
};
class LLVMReducer : public Traversal<LLVMReducer, LLVMReducerMap>,
public DefaultReducer<LLVMReducer, LLVMReducerMap>,
public DefaultScopeHandler<LLVMReducerMap> {
public:
LLVMReducer() : currentFunction_(nullptr), builder_(ctx()) {
// The module holds all of the llvm output.
outModule_ = new llvm::Module("ohmu_output", ctx());
}
~LLVMReducer() {
delete outModule_;
}
static llvm::LLVMContext& ctx() { return llvm::getGlobalContext(); }
llvm::Module* module() { return outModule_; }
public:
/*
* FIXME -- move into traverse
*
template <class T>
llvm::Value* exitSubExpr(T *e, llvm::Value* v, TraversalKind K) {
if (Instruction *inst = e->asCFGInstruction())
currentValues_[inst->instrID()] = v;
return v;
}
llvm::PHINode* exitSubExpr(Phi *e, llvm::Value* v, TraversalKind K) {
return llvm::cast<llvm::PHINode>(v);
}
llvm::BasicBlock* exitSubExpr(BasicBlock *e, llvm::BasicBlock* v,
TraversalKind K) {
return v;
}
*/
llvm::Value* reduceWeak(Instruction* e) {
return currentValues_[e->instrID()];
}
llvm::BasicBlock* reduceWeak(BasicBlock* b) {
auto *lbb = currentBlocks_[b->blockID()];
if (!lbb) {
if (!currentFunction_)
return nullptr;
lbb = llvm::BasicBlock::Create(ctx(), "", currentFunction_);
currentBlocks_[b->blockID()] = lbb;
}
return lbb;
}
std::nullptr_t reduceWeak(VarDecl *vd) { return nullptr; }
llvm::Value* reduceVarDecl(VarDecl& orig, llvm::Value* v) {
// Eliminate vardecls -- just return the definition.
return v;
}
llvm::Value* reduceLiteral(Literal& e) { return nullptr; }
template <class T>
llvm::Value* reduceLiteralT(LiteralT<T>& e) { return nullptr; }
llvm::Value* reduceLiteralT(LiteralT<int32_t>& e) {
llvm::Constant* c =
llvm::ConstantInt::getSigned(llvm::Type::getInt32Ty(ctx()), e.value());
// return builder_.Insert(c);
return c;
}
llvm::Value* reduceUnaryOp(UnaryOp& orig, llvm::Value* e0) {
if (!e0)
return nullptr;
switch (orig.unaryOpcode()) {
case UOP_Minus:
return builder_.CreateNeg(e0);
case UOP_BitNot:
return builder_.CreateNot(e0);
case UOP_LogicNot:
return builder_.CreateNot(e0);
}
return nullptr;
}
llvm::Value* reduceBinaryOp(BinaryOp& orig, llvm::Value* e0, llvm::Value* e1) {
if (!e0 || !e1)
return nullptr;
switch (orig.binaryOpcode()) {
case BOP_Add:
return builder_.CreateAdd(e0, e1);
case BOP_Sub:
return builder_.CreateSub(e0, e1);
case BOP_Mul:
return builder_.CreateMul(e0, e1);
case BOP_Div:
return builder_.CreateSDiv(e0, e1);
case BOP_Rem:
return builder_.CreateSRem(e0, e1);
case BOP_Shl:
return builder_.CreateShl(e0, e1);
case BOP_Shr:
return builder_.CreateLShr(e0, e1);
case BOP_BitAnd:
return builder_.CreateAnd(e0, e1);
case BOP_BitXor:
return builder_.CreateXor(e0, e1);
case BOP_BitOr:
return builder_.CreateOr(e0, e1);
case BOP_Eq:
return builder_.CreateICmpEQ(e0, e1);
case BOP_Neq:
return builder_.CreateICmpNE(e0, e1);
case BOP_Lt:
return builder_.CreateICmpSLT(e0, e1);
case BOP_Leq:
return builder_.CreateICmpSLE(e0, e1);
case BOP_LogicAnd:
return builder_.CreateAnd(e0, e1);
case BOP_LogicOr:
return builder_.CreateOr(e0, e1);
}
return nullptr;
}
llvm::PHINode* reducePhiBegin(Phi& orig) {
llvm::Type* ty = llvm::Type::getInt32Ty(ctx());
llvm::PHINode* lph = builder_.CreatePHI(ty, orig.values().size());
return lph;
}
void reducePhiArg(Phi& orig, llvm::PHINode* lph, unsigned i, llvm::Value *v) {
if (!v)
return;
BasicBlock* bb = orig.block();
auto* lbb = reduceWeak(bb->predecessors()[i]);
lph->addIncoming(v, lbb);
}
llvm::Value* reduceGoto(Goto& orig, llvm::BasicBlock* lbb) {
builder_.CreateBr(lbb);
return nullptr;
}
llvm::Value* reduceBranch(Branch& orig, llvm::Value* c,
llvm::Value* ntb, llvm::Value* neb) {
return nullptr;
}
llvm::Value* reduceReturn(Return& orig, llvm::Value *rv) {
if (!rv)
return nullptr;
return builder_.CreateRet(rv);
}
llvm::BasicBlock* reduceBasicBlockBegin(BasicBlock &orig) {
auto* lbb = reduceWeak(&orig);
builder_.SetInsertPoint(lbb);
return lbb;
}
llvm::Function* reduceSCFG_Begin(SCFG& orig) {
currentBlocks_.clear();
currentBlocks_.resize(orig.numBlocks(), nullptr);
currentValues_.clear();
currentValues_.resize(orig.numInstructions(), nullptr);
// Create a new function in outModule_
std::vector<llvm::Type*> argTypes;
llvm::FunctionType *ft =
llvm::FunctionType::get(llvm::Type::getVoidTy(ctx()), argTypes, false);
currentFunction_ =
llvm::Function::Create(ft, llvm::Function::ExternalLinkage, "ohmu_main",
outModule_);
// The current CFG is implicit.
return currentFunction_;
}
llvm::Function* reduceSCFG_End(llvm::Function* cfg) {
llvm::verifyFunction(*currentFunction_);
currentFunction_->dump();
return cfg;
}
private:
llvm::Module* outModule_;
llvm::Function* currentFunction_;
llvm::IRBuilder<> builder_;
std::vector<llvm::BasicBlock*> currentBlocks_;
std::vector<llvm::Value*> currentValues_;
};
void generate_LLVM_IR(SExpr* E) {
LLVMReducer Reducer;
Reducer.traverseAll(E);
// Reducer.module()->dump();
}
} // end namespace backend_llvm
} // end namespace ohmu
| 28.948819 | 81 | 0.637699 | [
"vector"
] |
9d22b216d8200b733b6624a74b8fecd59af172a6 | 24,439 | cc | C++ | py_mini_racer/extension/mini_racer_extension.cc | studyhub-co/PyMiniRacer | ada7f86a03bb1b387315d0635027ccab3fd8f6b8 | [
"ISC"
] | 569 | 2016-08-02T14:43:21.000Z | 2022-03-30T09:20:20.000Z | py_mini_racer/extension/mini_racer_extension.cc | studyhub-co/PyMiniRacer | ada7f86a03bb1b387315d0635027ccab3fd8f6b8 | [
"ISC"
] | 63 | 2016-08-02T14:40:04.000Z | 2022-01-24T12:53:55.000Z | py_mini_racer/extension/mini_racer_extension.cc | sqreen/PyMiniRacer | f7b9da0d4987ca7d1982af7f24da423f06da9894 | [
"0BSD"
] | 52 | 2016-08-03T12:10:25.000Z | 2021-11-20T17:58:01.000Z | #include <libplatform/libplatform.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <v8-profiler.h>
#include <v8-version-string.h>
#include <v8.h>
#include <chrono>
#include <map>
#include <mutex>
#include <thread>
#ifdef V8_OS_WIN
#define LIB_EXPORT __declspec(dllexport)
#else // V8_OS_WIN
#define LIB_EXPORT __attribute__((visibility("default")))
#endif
template <class T>
static inline T* xalloc(T*& ptr, size_t x = sizeof(T)) {
void* tmp = malloc(x);
if (tmp == NULL) {
fprintf(stderr, "malloc failed. Aborting");
abort();
}
ptr = static_cast<T*>(tmp);
return static_cast<T*>(ptr);
}
using namespace v8;
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
virtual void* Allocate(size_t length) {
void* data = AllocateUninitialized(length);
return data == NULL ? data : memset(data, 0, length);
}
virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
virtual void Free(void* data, size_t) { free(data); }
};
struct ContextInfo {
Isolate* isolate;
Persistent<Context>* context;
ArrayBufferAllocator* allocator;
std::map<void*, std::shared_ptr<BackingStore>> backing_stores;
bool interrupted;
size_t soft_memory_limit;
bool soft_memory_limit_reached;
size_t hard_memory_limit;
bool hard_memory_limit_reached;
};
struct EvalResult {
bool parsed;
bool executed;
bool terminated;
bool timed_out;
Persistent<Value>* value;
Persistent<Value>* message;
Persistent<Value>* backtrace;
~EvalResult() {
kill_value(value);
kill_value(message);
kill_value(backtrace);
}
private:
static void kill_value(Persistent<Value>* val) {
if (!val) {
return;
}
val->Reset();
delete val;
}
};
typedef struct {
ContextInfo* context_info;
const char* eval;
int eval_len;
unsigned long timeout;
EvalResult* result;
size_t max_memory;
} EvalParams;
enum BinaryTypes {
type_invalid = 0,
type_null = 1,
type_bool = 2,
type_integer = 3,
type_double = 4,
type_str_utf8 = 5,
// type_array = 6, // deprecated
// type_hash = 7, // deprecated
type_date = 8,
type_symbol = 9,
type_object = 10,
type_function = 100,
type_shared_array_buffer = 101,
type_array_buffer = 102,
type_execute_exception = 200,
type_parse_exception = 201,
type_oom_exception = 202,
type_timeout_exception = 203,
};
struct BinaryValue {
union {
void* ptr_val;
char* str_val;
uint32_t int_val;
double double_val;
};
enum BinaryTypes type = type_invalid;
size_t len;
};
void BinaryValueFree(ContextInfo* context_info, BinaryValue* v) {
if (!v) {
return;
}
switch (v->type) {
case type_execute_exception:
case type_parse_exception:
case type_oom_exception:
case type_timeout_exception:
case type_str_utf8:
free(v->str_val);
break;
case type_bool:
case type_double:
case type_date:
case type_null:
case type_integer:
case type_function: // no value implemented
case type_symbol:
case type_object:
case type_invalid:
// the other types are scalar values
break;
case type_shared_array_buffer:
case type_array_buffer:
context_info->backing_stores.erase(v);
break;
}
free(v);
}
enum IsolateData {
CONTEXT_INFO,
};
static std::unique_ptr<Platform> current_platform = NULL;
static std::mutex platform_lock;
static void gc_callback(Isolate* isolate, GCType type, GCCallbackFlags flags) {
ContextInfo* context_info = (ContextInfo*)isolate->GetData(CONTEXT_INFO);
if (context_info == nullptr) {
return;
}
HeapStatistics stats;
isolate->GetHeapStatistics(&stats);
size_t used = stats.used_heap_size();
context_info->soft_memory_limit_reached =
(used > context_info->soft_memory_limit);
isolate->MemoryPressureNotification((context_info->soft_memory_limit_reached)
? v8::MemoryPressureLevel::kModerate
: v8::MemoryPressureLevel::kNone);
if (used > context_info->hard_memory_limit) {
context_info->hard_memory_limit_reached = true;
isolate->TerminateExecution();
}
}
static void init_v8(char const* flags) {
// no need to wait for the lock if already initialized
if (current_platform != NULL)
return;
platform_lock.lock();
if (current_platform == NULL) {
V8::InitializeICU();
if (flags != NULL) {
V8::SetFlagsFromString(flags);
}
if (flags != NULL && strstr(flags, "--single-threaded") != NULL) {
current_platform = platform::NewSingleThreadedDefaultPlatform();
} else {
current_platform = platform::NewDefaultPlatform();
}
V8::InitializePlatform(current_platform.get());
V8::Initialize();
}
platform_lock.unlock();
}
static void breaker(std::timed_mutex& breaker_mutex, void* d) {
EvalParams* data = (EvalParams*)d;
if (!breaker_mutex.try_lock_for(std::chrono::milliseconds(data->timeout))) {
data->result->timed_out = true;
data->context_info->isolate->TerminateExecution();
}
}
static void set_hard_memory_limit(ContextInfo* context_info, size_t limit) {
context_info->hard_memory_limit = limit;
context_info->hard_memory_limit_reached = false;
}
static bool maybe_fast_call(const char* eval, int eval_len) {
// Does the eval string ends with '()'?
// TODO check if the string is an identifier
return (eval_len > 2 && eval[eval_len - 2] == '(' &&
eval[eval_len - 1] == ')');
}
static void* nogvl_context_eval(void* arg) {
EvalParams* eval_params = (EvalParams*)arg;
EvalResult* result = eval_params->result;
Isolate* isolate = eval_params->context_info->isolate;
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
TryCatch trycatch(isolate);
Local<Context> context = eval_params->context_info->context->Get(isolate);
Context::Scope context_scope(context);
set_hard_memory_limit(eval_params->context_info, eval_params->max_memory);
result->parsed = false;
result->executed = false;
result->terminated = false;
result->timed_out = false;
result->value = NULL;
std::timed_mutex breaker_mutex;
std::thread breaker_thread;
// timeout limit
auto timeout = eval_params->timeout;
if (timeout > 0) {
breaker_mutex.lock();
breaker_thread =
std::thread(&breaker, std::ref(breaker_mutex), (void*)eval_params);
}
// memory limit
if (eval_params->max_memory > 0) {
isolate->AddGCEpilogueCallback(gc_callback);
}
MaybeLocal<Value> maybe_value;
// Is it a single function call?
if (maybe_fast_call(eval_params->eval, eval_params->eval_len)) {
Local<String> identifier;
Local<Value> func;
// Let's check if the value is a callable identifier
result->parsed =
String::NewFromUtf8(isolate, eval_params->eval, NewStringType::kNormal,
eval_params->eval_len - 2)
.ToLocal(&identifier) &&
context->Global()->Get(context, identifier).ToLocal(&func) &&
func->IsFunction();
if (result->parsed) {
// Call the identifier
maybe_value = Local<Function>::Cast(func)->Call(
context, v8::Undefined(isolate), 0, {});
result->executed = !maybe_value.IsEmpty();
}
}
// Fallback on a slower full eval
if (!result->executed) {
Local<String> eval;
Local<Script> script;
result->parsed =
String::NewFromUtf8(isolate, eval_params->eval, NewStringType::kNormal,
eval_params->eval_len)
.ToLocal(&eval) &&
Script::Compile(context, eval).ToLocal(&script) && !script.IsEmpty();
if (!result->parsed) {
result->message = new Persistent<Value>();
result->message->Reset(isolate, trycatch.Exception());
return NULL;
}
maybe_value = script->Run(context);
result->executed = !maybe_value.IsEmpty();
}
if (result->executed) {
// Execute all pending tasks
while (!result->timed_out &&
!eval_params->context_info->hard_memory_limit_reached) {
bool wait =
isolate->HasPendingBackgroundTasks(); // Only wait when needed
// otherwise it waits forever.
if (!platform::PumpMessageLoop(
current_platform.get(), isolate,
(wait) ? v8::platform::MessageLoopBehavior::kWaitForWork
: v8::platform::MessageLoopBehavior::kDoNotWait)) {
break;
}
isolate->PerformMicrotaskCheckpoint();
}
}
if (timeout > 0) {
breaker_mutex.unlock();
breaker_thread.join();
}
if (!result->executed) {
if (trycatch.HasCaught()) {
if (!trycatch.Exception()->IsNull()) {
result->message = new Persistent<Value>();
Local<Message> message = trycatch.Message();
char buf[1000];
int len, line, column;
if (!message->GetLineNumber(context).To(&line)) {
line = 0;
}
if (!message->GetStartColumn(context).To(&column)) {
column = 0;
}
len = snprintf(
buf, sizeof(buf), "%s at %s:%i:%i",
*String::Utf8Value(isolate, message->Get()),
*String::Utf8Value(isolate, message->GetScriptResourceName()
->ToString(context)
.ToLocalChecked()),
line, column);
if ((size_t)len >= sizeof(buf)) {
len = sizeof(buf) - 1;
buf[len] = '\0';
}
Local<String> v8_message =
String::NewFromUtf8(isolate, buf, NewStringType::kNormal, len)
.ToLocalChecked();
result->message->Reset(isolate, v8_message);
} else if (trycatch.HasTerminated()) {
result->terminated = true;
result->message = new Persistent<Value>();
Local<String> tmp;
if (result->timed_out) {
tmp = String::NewFromUtf8(isolate,
"JavaScript was terminated by timeout")
.ToLocalChecked();
} else {
tmp = String::NewFromUtf8(isolate, "JavaScript was terminated")
.ToLocalChecked();
}
result->message->Reset(isolate, tmp);
}
if (!trycatch.StackTrace(context).IsEmpty()) {
Local<Value> stacktrace;
if (trycatch.StackTrace(context).ToLocal(&stacktrace)) {
Local<Value> tmp;
if (stacktrace->ToString(context).ToLocal(&tmp)) {
result->backtrace = new Persistent<Value>();
result->backtrace->Reset(isolate, tmp);
}
}
}
}
} else {
Local<Value> tmp;
if (maybe_value.ToLocal(&tmp)) {
result->value = new Persistent<Value>();
result->value->Reset(isolate, tmp);
}
}
return NULL;
}
static BinaryValue* convert_v8_to_binary(ContextInfo* context_info,
Local<Context> context,
Local<Value> value) {
Isolate::Scope isolate_scope(context_info->isolate);
HandleScope scope(context_info->isolate);
BinaryValue* res = new (xalloc(res)) BinaryValue();
if (value->IsNull() || value->IsUndefined()) {
res->type = type_null;
} else if (value->IsInt32()) {
res->type = type_integer;
auto val = value->Uint32Value(context).ToChecked();
res->int_val = val;
}
// ECMA-262, 4.3.20
// http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.19
else if (value->IsNumber()) {
res->type = type_double;
double val = value->NumberValue(context).ToChecked();
res->double_val = val;
} else if (value->IsBoolean()) {
res->type = type_bool;
res->int_val = (value->IsTrue() ? 1 : 0);
} else if (value->IsFunction()) {
res->type = type_function;
} else if (value->IsSymbol()) {
res->type = type_symbol;
} else if (value->IsDate()) {
res->type = type_date;
Local<Date> date = Local<Date>::Cast(value);
double timestamp = date->ValueOf();
res->double_val = timestamp;
} else if (value->IsString()) {
Local<String> rstr = value->ToString(context).ToLocalChecked();
res->type = type_str_utf8;
res->len = size_t(rstr->Utf8Length(context_info->isolate)); // in bytes
size_t capacity = res->len + 1;
res->str_val = xalloc(res->str_val, capacity);
rstr->WriteUtf8(context_info->isolate, res->str_val);
} else if (value->IsSharedArrayBuffer() || value->IsArrayBuffer() ||
value->IsArrayBufferView()) {
std::shared_ptr<BackingStore> backing_store;
size_t offset = 0;
size_t size = 0;
if (value->IsArrayBufferView()) {
Local<ArrayBufferView> view = Local<ArrayBufferView>::Cast(value);
backing_store = view->Buffer()->GetBackingStore();
offset = view->ByteOffset();
size = view->ByteLength();
} else if (value->IsSharedArrayBuffer()) {
backing_store = Local<SharedArrayBuffer>::Cast(value)->GetBackingStore();
size = backing_store->ByteLength();
} else {
backing_store = Local<ArrayBuffer>::Cast(value)->GetBackingStore();
size = backing_store->ByteLength();
}
context_info->backing_stores[res] = backing_store;
res->type = value->IsSharedArrayBuffer() ? type_shared_array_buffer
: type_array_buffer;
res->ptr_val = static_cast<char*>(backing_store->Data()) + offset;
res->len = size;
} else if (value->IsObject()) {
res->type = type_object;
res->int_val = value->ToObject(context).ToLocalChecked()->GetIdentityHash();
} else {
BinaryValueFree(context_info, res);
res = nullptr;
}
return res;
}
static BinaryValue* convert_v8_to_binary(ContextInfo* context_info,
const Persistent<Context>& context,
Local<Value> value) {
HandleScope scope(context_info->isolate);
return convert_v8_to_binary(
context_info, Local<Context>::New(context_info->isolate, context), value);
}
static void deallocate(void* data) {
ContextInfo* context_info = static_cast<ContextInfo*>(data);
if (context_info == NULL || context_info->isolate == NULL) {
return;
}
if (context_info->context) {
Locker lock(context_info->isolate);
Isolate::Scope isolate_scope(context_info->isolate);
context_info->backing_stores.clear();
context_info->context->Reset();
delete context_info->context;
context_info->context = NULL;
}
if (context_info->interrupted) {
fprintf(stderr,
"WARNING: V8 isolate was interrupted by Python, "
"it can not be disposed and memory will not be "
"reclaimed till the Python process exits.");
} else {
context_info->isolate->Dispose();
context_info->isolate = NULL;
}
delete context_info->allocator;
delete context_info;
}
ContextInfo* MiniRacer_init_context(char const* v8_flags) {
init_v8(v8_flags);
ContextInfo* context_info = new (xalloc(context_info)) ContextInfo();
context_info->allocator = new ArrayBufferAllocator();
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = context_info->allocator;
context_info->isolate = Isolate::New(create_params);
Locker lock(context_info->isolate);
Isolate::Scope isolate_scope(context_info->isolate);
HandleScope handle_scope(context_info->isolate);
Local<Context> context = Context::New(context_info->isolate);
context_info->context = new Persistent<Context>();
context_info->context->Reset(context_info->isolate, context);
context_info->isolate->SetData(CONTEXT_INFO, (void*)context_info);
return context_info;
}
static BinaryValue* MiniRacer_eval_context_unsafe(ContextInfo* context_info,
const char* eval,
size_t eval_len,
unsigned long timeout,
size_t max_memory) {
EvalParams eval_params;
EvalResult eval_result{};
BinaryValue* result = NULL;
BinaryValue* bmessage = NULL;
BinaryValue* bbacktrace = NULL;
if (context_info == NULL || eval == NULL || static_cast<int>(eval_len) < 0) {
return NULL;
}
{
Locker lock(context_info->isolate);
Isolate::Scope isolate_scope(context_info->isolate);
HandleScope handle_scope(context_info->isolate);
eval_params.context_info = context_info;
eval_params.eval = eval;
eval_params.eval_len = static_cast<int>(eval_len);
eval_params.result = &eval_result;
eval_params.timeout = timeout;
eval_params.max_memory = max_memory;
nogvl_context_eval(&eval_params);
if (eval_result.message) {
Local<Value> tmp =
Local<Value>::New(context_info->isolate, *eval_result.message);
bmessage =
convert_v8_to_binary(context_info, *context_info->context, tmp);
}
if (eval_result.backtrace) {
Local<Value> tmp =
Local<Value>::New(context_info->isolate, *eval_result.backtrace);
bbacktrace =
convert_v8_to_binary(context_info, *context_info->context, tmp);
}
}
// bmessage and bbacktrace are now potentially allocated
// they are always freed at the end of the function
// NOTE: this is very important, we can not do an raise from within
// a v8 scope, if we do the scope is never cleaned up properly and we leak
if (!eval_result.parsed) {
result = xalloc(result);
result->type = type_parse_exception;
if (bmessage && bmessage->type == type_str_utf8) {
// canibalize bmessage
result->str_val = bmessage->str_val;
result->len = bmessage->len;
free(bmessage);
bmessage = NULL;
} else {
result->str_val = strdup("Unknown JavaScript error during parse");
result->len = result->str_val ? strlen(result->str_val) : 0;
}
}
else if (!eval_result.executed) {
result = xalloc(result);
result->str_val = nullptr;
if (context_info->hard_memory_limit_reached) {
result->type = type_oom_exception;
} else {
if (eval_result.timed_out) {
result->type = type_timeout_exception;
} else {
result->type = type_execute_exception;
}
}
if (bmessage && bmessage->type == type_str_utf8 && bbacktrace &&
bbacktrace->type == type_str_utf8) {
// +1 for \n, +1 for NUL terminator
size_t dest_size = bmessage->len + bbacktrace->len + 1 + 1;
char* dest = xalloc(dest, dest_size);
memcpy(dest, bmessage->str_val, bmessage->len);
dest[bmessage->len] = '\n';
memcpy(dest + bmessage->len + 1, bbacktrace->str_val, bbacktrace->len);
dest[dest_size - 1] = '\0';
result->str_val = dest;
result->len = dest_size - 1;
} else if (bmessage && bmessage->type == type_str_utf8) {
// canibalize bmessage
result->str_val = bmessage->str_val;
result->len = bmessage->len;
free(bmessage);
bmessage = NULL;
} else {
result->str_val = strdup("Unknown JavaScript error during execution");
result->len = result->str_val ? strlen(result->str_val) : 0;
}
}
else if (eval_result.value) {
Locker lock(context_info->isolate);
Isolate::Scope isolate_scope(context_info->isolate);
HandleScope handle_scope(context_info->isolate);
Local<Value> tmp =
Local<Value>::New(context_info->isolate, *eval_result.value);
result = convert_v8_to_binary(context_info, *context_info->context, tmp);
}
BinaryValueFree(context_info, bmessage);
BinaryValueFree(context_info, bbacktrace);
return result;
}
static BinaryValue* heap_stats(ContextInfo* context_info) {
v8::HeapStatistics stats;
if (!context_info || !context_info->isolate) {
return NULL;
}
Locker lock(context_info->isolate);
Isolate::Scope isolate_scope(context_info->isolate);
HandleScope handle_scope(context_info->isolate);
TryCatch trycatch(context_info->isolate);
Local<Context> context = context_info->context->Get(context_info->isolate);
Context::Scope context_scope(context);
context_info->isolate->GetHeapStatistics(&stats);
Local<Object> stats_obj = Object::New(context_info->isolate);
stats_obj
->Set(context,
String::NewFromUtf8Literal(context_info->isolate,
"total_physical_size"),
Number::New(context_info->isolate,
(double)stats.total_physical_size()))
.Check();
stats_obj
->Set(context,
String::NewFromUtf8Literal(context_info->isolate,
"total_heap_size_executable"),
Number::New(context_info->isolate,
(double)stats.total_heap_size_executable()))
.Check();
stats_obj
->Set(
context,
String::NewFromUtf8Literal(context_info->isolate, "total_heap_size"),
Number::New(context_info->isolate, (double)stats.total_heap_size()))
.Check();
stats_obj
->Set(context,
String::NewFromUtf8Literal(context_info->isolate, "used_heap_size"),
Number::New(context_info->isolate, (double)stats.used_heap_size()))
.Check();
stats_obj
->Set(
context,
String::NewFromUtf8Literal(context_info->isolate, "heap_size_limit"),
Number::New(context_info->isolate, (double)stats.heap_size_limit()))
.Check();
Local<String> output;
if (!JSON::Stringify(context, stats_obj).ToLocal(&output) ||
output.IsEmpty()) {
return NULL;
}
return convert_v8_to_binary(context_info, context, output);
}
class BufferOutputStream : public OutputStream {
public:
BinaryValue* bv;
BufferOutputStream() {
bv = xalloc(bv);
bv->len = 0;
bv->type = type_str_utf8;
bv->str_val = nullptr;
}
virtual ~BufferOutputStream() {} // don't destroy the stuff
virtual void EndOfStream() {}
virtual int GetChunkSize() { return 1000000; }
virtual WriteResult WriteAsciiChunk(char* data, int size) {
size_t oldlen = bv->len;
bv->len = oldlen + size_t(size);
bv->str_val = static_cast<char*>(realloc(bv->str_val, bv->len));
if (!bv->str_val) {
return kAbort;
}
memcpy(bv->str_val + oldlen, data, (size_t)size);
return kContinue;
}
};
extern "C" {
LIB_EXPORT BinaryValue* mr_eval_context(ContextInfo* context_info,
char* str,
int len,
unsigned long timeout,
size_t max_memory) {
BinaryValue* res = MiniRacer_eval_context_unsafe(context_info, str, len,
timeout, max_memory);
return res;
}
LIB_EXPORT ContextInfo* mr_init_context(const char* v8_flags) {
return MiniRacer_init_context(v8_flags);
}
LIB_EXPORT void mr_free_value(ContextInfo* context_info, BinaryValue* val) {
BinaryValueFree(context_info, val);
}
LIB_EXPORT void mr_free_context(ContextInfo* context_info) {
deallocate(context_info);
}
LIB_EXPORT BinaryValue* mr_heap_stats(ContextInfo* context_info) {
return heap_stats(context_info);
}
LIB_EXPORT void mr_set_hard_memory_limit(ContextInfo* context_info,
size_t limit) {
set_hard_memory_limit(context_info, limit);
}
LIB_EXPORT void mr_set_soft_memory_limit(ContextInfo* context_info,
size_t limit) {
context_info->soft_memory_limit = limit;
context_info->soft_memory_limit_reached = false;
}
LIB_EXPORT bool mr_soft_memory_limit_reached(ContextInfo* context_info) {
return context_info->soft_memory_limit_reached;
}
LIB_EXPORT void mr_low_memory_notification(ContextInfo* context_info) {
context_info->isolate->LowMemoryNotification();
}
LIB_EXPORT char const* mr_v8_version() {
return V8_VERSION_STRING;
}
// FOR DEBUGGING ONLY
LIB_EXPORT BinaryValue* mr_heap_snapshot(ContextInfo* context_info) {
Isolate* isolate = context_info->isolate;
Locker lock(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
auto snap = isolate->GetHeapProfiler()->TakeHeapSnapshot();
BufferOutputStream bos{};
snap->Serialize(&bos);
return bos.bv;
}
}
| 30.060271 | 80 | 0.641802 | [
"object"
] |
9d2857e44747f8cf8fcbcee1190d485960d4c925 | 3,952 | cpp | C++ | kwj1270/3월 2주/13460_구슬탈출.cpp | kwj1270/Algorithm_AlgoGaZa | 91286b7f06f4031da3d7476f9091058c825f8542 | [
"MIT"
] | 1 | 2021-01-26T09:11:01.000Z | 2021-01-26T09:11:01.000Z | kwj1270/3월 2주/13460_구슬탈출.cpp | kwj1270/Algorithm_AlgoGaZa | 91286b7f06f4031da3d7476f9091058c825f8542 | [
"MIT"
] | null | null | null | kwj1270/3월 2주/13460_구슬탈출.cpp | kwj1270/Algorithm_AlgoGaZa | 91286b7f06f4031da3d7476f9091058c825f8542 | [
"MIT"
] | 1 | 2021-01-26T09:14:52.000Z | 2021-01-26T09:14:52.000Z | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int dx[] = {0,0,1,-1}; // 4방향
int dy[] = {1,-1,0,0}; // 4방향
const int LIMIT = 10; // 10 제한
vector<int> gen(int k) { // 정수 k를 길이가 10인 4진법으로 나타내는 것
vector<int> a(LIMIT);
for (int i=0; i<LIMIT; i++) {
a[i] = (k&3);
k >>= 2;
}
return a;
}
pair<bool,bool> simulate(vector<string> &a, int k, int &x, int &y) {
if (a[x][y] == '.') return make_pair(false, false); // 두 구슬중 하나가 빠지더라도 계속 이동시키자 했으니 빈칸이 있을 수 있다. -> 그때 리턴
int n = a.size(); // 세로
int m = a[0].size(); // 가로.
bool moved = false; // 움직였다.
while (true) {
int nx = x+dx[k]; // 다음 이동
int ny = y+dy[k]; // 다음 이동.
if (nx < 0 || nx >= n || ny < 0 || ny >= m) { // 범위를 벗어나면
return make_pair(moved, false); // 여태 저장된 움직임 가능/ 구멍에 안들어감 리턴
}
if (a[nx][ny] == '#') { // # 일 경우
return make_pair(moved, false); // 여태 저장된 움직임 가능/ 구멍에 안들어감 리턴.
} else if (a[nx][ny] == 'R' || a[nx][ny] == 'B') { // 서로 다른 구슬들일 경우도
return make_pair(moved, false); // 여태 저장된 움직임 가능/ 구멍에 안들어감 리턴.
} else if (a[nx][ny] == '.') { // 빈칸일 경우
swap(a[nx][ny], a[x][y]); // 값 스왑. -> 구슬이랑 빈칸 바꾸기
x = nx;
y = ny;
moved = true; // 한번이라도 움직였으니 true
} else if (a[nx][ny] == 'O') { // 구멍일 경우
a[x][y] = '.'; // 현재 위치 . 만들기 -> 구슬 하나 사라짐.
moved = true; // 움직였다 체크
return make_pair(moved, true); // 움직였다랑 / 구슬 빠졌다 리턴
}
}
return make_pair(false, false); // 아무것도 실행 안되었다면 둘다 false
}
int check(vector<string> a, vector<int> &dir) {
int n = a.size(); // 세로 크기
int m = a[0].size(); // 가로 크기.
int hx,hy,rx,ry,bx,by;
for (int i=0; i<n; i++) { // 세로 반복
for (int j=0; j<m; j++) { // 가로 반복
if (a[i][j] == 'O') { // O 일 경우
hx = i; hy = j; // 위치 저장
} else if (a[i][j] == 'R') { // 빨강 구슬 R 일 경우
rx = i; ry = j; // 위치 저장
} else if (a[i][j] == 'B') { // 파랑 구슬 B 일 경우
bx = i; by = j; // 위치 저장
}
}
}
int cnt = 0; // 카운트는 0 부터 시작.
for (int k : dir) {
cnt += 1; // 반복당 카운트 증가.
bool hole1=false, hole2=false; // 둘다 안 들어 왔다.
while (true) { // 무한 루프.
auto p1 = simulate(a, k, rx, ry); // 빨강 구슬을 방향 k로 이동시키는 시뮬레이션 시작
auto p2 = simulate(a, k, bx, by); // 파랑 구슬을 방향 k로 이동시키는 시뮬레이션 시작
if (p1.first == false && p2.first == false) { // 둘다 이동 안함
break; // b r 일 경우 문제가 된다. br 되어야 하므로 무한루프 및 둘 다 이동 못할 경우를 만들어 놓은 것.
}
if (p1.second) hole1 = true; // 구멍에 빠짐
if (p2.second) hole2 = true; // 구멍에 빠짐
}
if (hole2) return -1; // 파랑 구슬이 빠졌다면 -1
if (hole1) return cnt; // 파랑이 안빠졌고 빨강이 빠졌다는 뜻이므로 카운트 리턴
}
return -1;
}
bool valid(vector<int> &dir) {
int l = dir.size();
for (int i=0; i+1<l; i++) {
if (dir[i] == 0 && dir[i+1] == 1) return false; // 반대
if (dir[i] == 1 && dir[i+1] == 0) return false; // 반대
if (dir[i] == 2 && dir[i+1] == 3) return false; // 반대
if (dir[i] == 3 && dir[i+1] == 2) return false; // 반대.
if (dir[i] == dir[i+1]) return false; // 같은 방향 의미가 없는 것.
}
return true;
}
int main() {
// 초기화.
int n, m;
cin >> n >> m;
vector<string> a(n);
for (int i=0; i<n; i++) {
cin >> a[i];
}
// 정답 저장.
int ans = -1;
// 이동방법 k를 비트마스크로 만들기 위해서 LIMIT *2
for (int k=0; k<(1<<(LIMIT*2)); k++) {
vector<int> dir = gen(k); // dir 를 이용해서 방법으로 바꿔준다. -> 크기가 10인 4진법 수를 만드는 것.
if (!valid(dir)) continue; // 의미가 없는 방법은 빼고 시뮬레이션 해보자.
int cur = check(a, dir); // 보드 a 를 dir 방향으로 이동하는 것
if (cur == -1) continue; // 가능하지 않다면 넘기기
if (ans == -1 || ans > cur) ans = cur; // 가능하면 이동하기.
}
cout << ans << '\n'; // 결과.
return 0;
}
| 34.666667 | 109 | 0.446609 | [
"vector"
] |
9d2b02b9e7398dfa7ab62460c9500a53bb50a4d8 | 4,282 | cpp | C++ | svntrunk/src/BlueMatter/util/src/basicblocks.cpp | Bhaskers-Blu-Org1/BlueMatter | 1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e | [
"BSD-2-Clause"
] | 7 | 2020-02-25T15:46:18.000Z | 2022-02-25T07:04:47.000Z | svntrunk/src/BlueMatter/util/src/basicblocks.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | null | null | null | svntrunk/src/BlueMatter/util/src/basicblocks.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | 5 | 2019-06-06T16:30:21.000Z | 2020-11-16T19:43:01.000Z | /* Copyright 2001, 2019 IBM Corporation
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <fstream>
#include <mpi.h>
#include <algorithm>
#include <vector>
#include "TimeHelper.hpp"
using namespace std;
#define MAXSITES 100000
#define DOUBLES_PER_SITE 3
static double SendBuffer[ MAXSITES * DOUBLES_PER_SITE ];
static double RecieveBuffer[ MAXSITES * DOUBLES_PER_SITE ];
int main(int argc, char **argv, char **envp)
{
int myRank = 0;
MPI_Init( &argc, &argv ); /* initialize MPI environment */
MPI_Comm_rank(MPI_COMM_WORLD, &myRank );
int doublesPerSite = 3;
vector<double> bcastTimes;
vector<double> allReduceTimes;
vector<int> sitesVector;
for(int sites=1; sites <= MAXSITES; sites+=1000 )
{
int numDoubles = sites * DOUBLES_PER_SITE;
// cout << "Number Of Doubles: " << numDoubles << endl;
sitesVector.push_back( sites );
TimeHelper startTime = TimeHelper::GetTimeValue();
MPI_Bcast( SendBuffer, numDoubles, MPI_DOUBLE, 0, MPI_COMM_WORLD );
TimeHelper finishTime = TimeHelper::GetTimeValue();
TimeHelper difference = finishTime - startTime;
double timeDiff = TimeHelper::ConvertTimeValueToDouble(difference);
bcastTimes.push_back( timeDiff );
startTime = TimeHelper::GetTimeValue();
MPI_Allreduce(SendBuffer, RecieveBuffer , numDoubles , MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
finishTime = TimeHelper::GetTimeValue();
difference = finishTime - startTime;
timeDiff = TimeHelper::ConvertTimeValueToDouble(difference);
allReduceTimes.push_back( timeDiff );
// cout << "Number Of Sites: " << sites << endl;
}
if( myRank == 0 )
{
// cout << "Got here" << endl;
ofstream os;
os.open("basicblocktimes.plot");
for ( int i=0; i < bcastTimes.size(); i++)
{
// cout << i << endl;
os << sitesVector[ i ] << "\t"
<< bcastTimes[ i ] << "\t"
<< allReduceTimes[ i ]
<< endl;
}
os.close();
ofstream os1;
os1.open("bcastbasic.gplot", ios::out);
os1 << "set xlabel 'Number of Sites'" << endl;
os1 << "set ylabel 'Bcast Elapsed Time'" << endl;
os1 << "plot \"basicblocktimes.plot\" using 1:2 with points" << endl;
os1.close();
ofstream os2;
os2.open("allreducebasic.gplot", ios::out);
os2 << "set xlabel 'Number of Sites'" << endl;
os2 << "set ylabel 'AllReduce Elapsed Time'" << endl;
os2 << "plot \"basicblocktimes.plot\" using 1:3 with points" << endl;
os2.close();
}
MPI_Finalize();
return 0;
}
| 38.576577 | 118 | 0.6149 | [
"vector"
] |
9d34a0b9032269440adad060f406bde3b74e16f0 | 293 | cpp | C++ | src/SvgLib/Region.cpp | steneva/svg-lib | 47a754f71be923bd75bfef35ab529c61702b93ae | [
"MIT"
] | 2 | 2020-08-11T20:46:31.000Z | 2020-08-14T09:51:02.000Z | src/SvgLib/Region.cpp | steneva/svg-lib | 47a754f71be923bd75bfef35ab529c61702b93ae | [
"MIT"
] | null | null | null | src/SvgLib/Region.cpp | steneva/svg-lib | 47a754f71be923bd75bfef35ab529c61702b93ae | [
"MIT"
] | null | null | null | #include "Region.h"
Region::Region(Coordinate x, Coordinate y)
{
this->x = x;
this->y = y;
}
bool Region::contains(const Shape& shape) const
{
for (const Point& point : shape.boundary())
{
if (!this->contains(point))
return false;
}
return true;
}
Region::~Region() = default;
| 13.952381 | 47 | 0.641638 | [
"shape"
] |
9d483ebde60cfa3cc285451b543ce41b4aad42fc | 5,338 | hh | C++ | core/test/UtGunnsFluidConductor.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | core/test/UtGunnsFluidConductor.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | core/test/UtGunnsFluidConductor.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | #ifndef UtGunnsFluidConductor_EXISTS
#define UtGunnsFluidConductor_EXISTS
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @defgroup UT_FLUID_CONDUCTOR Gunns Fluid Conductor Unit Test
/// @ingroup UT_GUNNS
///
/// @copyright Copyright 2021 United States Government as represented by the Administrator of the
/// National Aeronautics and Space Administration. All Rights Reserved.
///
/// @details Unit Tests for the Gunns Fluid Conductor
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestFixture.h>
#include <iostream>
#include "core/GunnsFluidConductor.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Inherit from GunnsFluidConductor and befriend UtGunnsFluidConductor.
///
/// @details Class derived from the unit under test. It just has a constructor with the same
/// arguments as the parent and a default destructor, but it befriends the unit test case
/// driver class to allow it access to protected data members.
////////////////////////////////////////////////////////////////////////////////////////////////////
class FriendlyGunnsFluidConductor : public GunnsFluidConductor
{
public:
FriendlyGunnsFluidConductor();
virtual ~FriendlyGunnsFluidConductor();
friend class UtGunnsFluidConductor;
};
inline FriendlyGunnsFluidConductor::FriendlyGunnsFluidConductor() : GunnsFluidConductor() {};
inline FriendlyGunnsFluidConductor::~FriendlyGunnsFluidConductor() {}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Gunns Basis Conductor unit tests.
////
/// @details This class provides the unit tests for the Base Valve within the CPPUnit framework.
////////////////////////////////////////////////////////////////////////////////////////////////////
class UtGunnsFluidConductor: public CppUnit::TestFixture
{
private:
/// @brief Copy constructor unavailable since declared private and not implemented.
UtGunnsFluidConductor(const UtGunnsFluidConductor& that);
/// @brief Assignment operator unavailable since declared private and not implemented.
UtGunnsFluidConductor& operator =(const UtGunnsFluidConductor& that);
CPPUNIT_TEST_SUITE(UtGunnsFluidConductor);
CPPUNIT_TEST(testConfig);
CPPUNIT_TEST(testInput);
CPPUNIT_TEST(testDefaultConstruction);
CPPUNIT_TEST(testNominalInitialization);
CPPUNIT_TEST(testInitializationExceptions);
CPPUNIT_TEST(testStep);
CPPUNIT_TEST(testComputeFlows);
CPPUNIT_TEST(testComputeFlowsWithInternalFluid);
CPPUNIT_TEST(testTuning);
CPPUNIT_TEST(testAccessMethods);
CPPUNIT_TEST_SUITE_END();
GunnsFluidConductorConfigData* mConfigData; /**< (--) Pointer to nominal configuration data. */
GunnsFluidConductorInputData* mInputData; /**< (--) Pointer to nominal input data. */
FriendlyGunnsFluidConductor* mArticle; /**< (--) Test Article. */
std::string mLinkName; /**< (--) Conductor Name. */
double mMaxConductivity; /**< (m2) Link Max Conductivity. */
double mExpansionScaleFactor; /**< (--) Link Expansion Scale Factor. */
double mPressureExponent; /**< (--) Pressure exponent. */
GunnsFluidNode mNodes[3]; /**< (--) Network Nodes. */
GunnsNodeList mNodeList; /**< (--) Node List. */
std::vector<GunnsBasicLink*> mLinks; /**< (--) Network Links. */
int mPort0; /**< (--) Nominal inlet port index. */
int mPort1; /**< (--) Nominal outlet port index. */
double mTimeStep; /**< (s) Nominal time step. */
double mTolerance; /**< (--) Nominal tolerance for comparison of expected and returned values. */
DefinedFluidProperties* mFluidProperties; /**< (--) Predefined fluid properties. */
PolyFluidConfigData* mFluidConfig; /**< (--) Fluid 1 config data. */
PolyFluidInputData* mFluidInput1; /**< (--) Fluid 1 input data. */
PolyFluidInputData* mFluidInput2; /**< (--) Fluid 2input data. */
double* fractions; /**< (--) Fluid Fractions. */
public:
UtGunnsFluidConductor();
virtual ~UtGunnsFluidConductor();
void tearDown();
void setUp();
void testConfig();
void testInput();
void testDefaultConstruction();
void testNominalInitialization();
void testInitializationExceptions();
void testStep();
void testComputeFlows();
void testComputeFlowsWithInternalFluid();
void testTuning();
void testAccessMethods();
};
///@}
#endif
| 51.326923 | 140 | 0.542151 | [
"vector"
] |
9d59b7b8be827c3e5b85a570f174046c657ba284 | 981 | cpp | C++ | leetcode/cpp/546-Remove-Boxes.cpp | liu-chunhou/OnlineJudge | b79c8e05acf05411d8cf172214aa42e49cc20867 | [
"MIT"
] | null | null | null | leetcode/cpp/546-Remove-Boxes.cpp | liu-chunhou/OnlineJudge | b79c8e05acf05411d8cf172214aa42e49cc20867 | [
"MIT"
] | null | null | null | leetcode/cpp/546-Remove-Boxes.cpp | liu-chunhou/OnlineJudge | b79c8e05acf05411d8cf172214aa42e49cc20867 | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
class Solution {
public:
int removeBoxes(vector<int>& boxes) {
int n = boxes.size();
int dp[n][n][n+1];
// dp[i][j][k]: max score we can get from boxes[i] to boxes[j] with boxes[i] repeat k times on the left
for(int i=0;i<n;++i){
for(int k=0;k<=n;++k)
dp[i][i][k]=k*k;
for(int j=0; j<i; ++j)
for(int k=0; k<=n; ++k)
dp[i][j][k] = 0;
}
for(int i=n-1; i>=0; --i){
for(int j=i+1; j<n; ++j){
for(int k=0; k<=i+1; ++k){
dp[i][j][k] = k*k + dp[i+1][j][1];
for(int p=i+1; p<=j; ++p){
if(boxes[p]==boxes[i]){
dp[i][j][k] = max(dp[i][j][k], dp[i+1][p-1][1]+dp[p][j][k+1]);
}
}
}
}
}
return dp[0][n-1][1];
}
}; | 30.65625 | 111 | 0.345566 | [
"vector"
] |
9d5a1e841b1529994423be379dbd12c136128284 | 4,619 | cpp | C++ | src/logdensity.cpp | Jonghyun-Yun/LSA | 359934190e2f7e3852781f90e15d62575436618b | [
"MIT"
] | null | null | null | src/logdensity.cpp | Jonghyun-Yun/LSA | 359934190e2f7e3852781f90e15d62575436618b | [
"MIT"
] | null | null | null | src/logdensity.cpp | Jonghyun-Yun/LSA | 359934190e2f7e3852781f90e15d62575436618b | [
"MIT"
] | null | null | null | #include "logdensity.h"
#include <cmath>
#include <stan/math.hpp>
#include "tbb/blocked_range2d.h"
using namespace std;
// PoissonLogNormal implementation
PoissonLogNormal::PoissonLogNormal(double y, double mu, double sigma) :
y(y), mu(mu), sigma(sigma) {}
vector<double> PoissonLogNormal::clean(vector<double> x) {
// ensure x is below 700 (max value for which we can compute exp)
for (int i = 0; i < x.size(); ++i) {
if (x.at(i) > 700) {
x.at(i) = 700;
}
}
return x;
}
vector<double> PoissonLogNormal::h(vector<double> x) {
x = clean(x);
vector<double> rv(x.size());
for (int i = 0; i < x.size(); ++i) {
rv.at(i) = h(x.at(i));
}
return rv;
}
vector<double> PoissonLogNormal::h_prime(vector<double> x) {
x = clean(x);
vector<double> rv(x.size());
for (int i = 0; i < x.size(); ++i) {
rv.at(i) = h_prime(x.at(i));
}
return rv;
}
double PoissonLogNormal::h(double x) {
double rv = x*y - exp(x) - 0.5*pow(sigma, -2)*pow(x - mu, 2);
return rv;
}
double PoissonLogNormal::h_prime(double x) {
double rv = y - exp(x) - pow(sigma, -2) * (x - mu);
return rv;
}
// PoissonLogNormal implementation
gamma_full_conditional::gamma_full_conditional(const int ONE_FREE_GAMMA_, Eigen::VectorXd &gamma_, Eigen::VectorXd &acc_gamma_,
const Eigen::VectorXd &mu_gamma_, const Eigen::VectorXd &sigma_gamma_,
const Eigen::VectorXd &jump_gamma_, const Eigen::MatrixXd &cum_lambda_,
const Eigen::MatrixXd &beta_, const Eigen::MatrixXd &theta_,
const Eigen::MatrixXd &z_, const Eigen::MatrixXd &w_, const int &I_,
const int &N_, const Eigen::MatrixXi &NA_,
const Eigen::MatrixXi &Y_, boost::ecuyer1988 &rng_) :
c(ONE_FREE_GAMMA_),
gamma(gamma_),
mu_gamma(mu_gamma_),
sigma_gamma(sigma_gamma_),
jump_gamma(jump_gamma_),
cum_lambda(cum_lambda_),
beta(beta_),
theta(theta_),
z(z_),
w(w_),
I(I_),
N(N_),
NA(NA_),
Y(Y_),
rng(rng_) {}
double gamma_full_conditional::h(double gamma_s) {
double rv = stan::math::lognormal_lpdf(gamma_s, mu_gamma(c), sigma_gamma(c));
rv += tbb::parallel_reduce(
tbb::blocked_range2d<int>(0, I, 0, N), 0.0,
[&](tbb::blocked_range2d<int> r, double running_total) {
for (int i = r.rows().begin(); i < r.rows().end(); ++i) {
for (int k = r.cols().begin(); k < r.cols().end(); ++k) {
if (NA(i, k) == 1) {
running_total -=
cum_lambda(c * I + i, k) *
exp(beta(i, c) + theta(k, c) -
gamma_s * stan::math::distance(z.row(c * N + k),
w.row(c * I + i)));
if (Y(i, k) == c) {
running_total -=
gamma_s * stan::math::distance(z.row(c * N + k), w.row(c * I + i));
}
}
}
}
return running_total;
},
std::plus<double>());
return rv;
}
double gamma_full_conditional::h_prime(double gamma_s) {
double rv = - 1.0 * (1.0 + (log(gamma_s) - mu_gamma(c)) / pow(sigma_gamma(c), 2)) / gamma_s; // lognormal_lpdf derivative
rv += tbb::parallel_reduce(
tbb::blocked_range2d<int>(0, I, 0, N), 0.0,
[&](tbb::blocked_range2d<int> r, double running_total) {
for (int i = r.rows().begin(); i < r.rows().end(); ++i) {
for (int k = r.cols().begin(); k < r.cols().end(); ++k) {
if (NA(i, k) == 1) {
running_total +=
cum_lambda(c * I + i, k) *
exp(beta(i, c) + theta(k, c) -
gamma_s * stan::math::distance(z.row(c * N + k),
w.row(c * I + i))) * stan::math::distance(z.row(c * N + k),
w.row(c * I + i));
if (Y(i, k) == c) {
running_total -= stan::math::distance(z.row(c * N + k), w.row(c * I + i));
}
}
}
}
return running_total;
},
std::plus<double>());
return rv;
}
vector<double> gamma_full_conditional::h(vector<double> gamma_s) {
vector<double> rv(gamma_s.size());
for (int i = 0; i < gamma_s.size(); ++i) {
rv.at(i) = h(gamma_s.at(i));
}
return rv;
}
vector<double> gamma_full_conditional::h_prime(vector<double> gamma_s) {
vector<double> rv(gamma_s.size());
for (int i = 0; i < gamma_s.size(); ++i) {
rv.at(i) = h_prime(gamma_s.at(i));
}
return rv;
}
| 31.421769 | 127 | 0.523057 | [
"vector"
] |
9d5a2b17476bb0eebd4038fed232abd9195cba45 | 3,229 | cpp | C++ | freq/appname_manager.cpp | mehrdad-shokri/libwxfreq | 8281a2d530588f44661b42ea9be9474ba9316014 | [
"BSD-3-Clause"
] | 195 | 2018-01-01T01:54:14.000Z | 2021-11-30T09:52:16.000Z | freq/appname_manager.cpp | mehrdad-shokri/libwxfreq | 8281a2d530588f44661b42ea9be9474ba9316014 | [
"BSD-3-Clause"
] | 2 | 2018-03-12T04:41:03.000Z | 2018-05-14T08:52:48.000Z | freq/appname_manager.cpp | mehrdad-shokri/libwxfreq | 8281a2d530588f44661b42ea9be9474ba9316014 | [
"BSD-3-Clause"
] | 50 | 2018-01-02T00:54:16.000Z | 2022-01-13T09:31:15.000Z | /*
* Tencent is pleased to support the open source community by making libwxfreq available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 "appname_manager.h"
#include <unistd.h>
#include <stdio.h>
#include <vector>
#include "config.h"
#include "log.h"
namespace libwxfreq {
static AppNameMeta dummymeta;
AppanmeMapVecAppnameMeta AppnameManager::appname_map_[2];
unsigned char AppnameManager::index_ = 0;
void AppnameManager::UpdateAppNameMeta(const Config& config) {
int ret = 0;
unsigned int appid = 0, interval = 0;
std::string appname, interval_key;
unsigned char new_index = (index_ + 1) % 2;
AppanmeMapVecAppnameMeta& tmp_appname = appname_map_[new_index];
tmp_appname.clear();
std::vector<std::string> keys;
config.GetKeysBySection("appname", keys);
for (std::vector<std::string>::iterator it = keys.begin();
it != keys.end(); ++it) {
appid = 0;
std::size_t pos = it->find(":");
if (pos == std::string::npos) {
ret = config.ReadItem("appname", *it, 0, appid);
if (ret != 0 || appid == 0) {
gLog("[%s][%d]: read %s appid %d failed\n", __FILE__, __LINE__,
it->c_str(), appid);
continue;
}
tmp_appname[*it].set_appname(*it);
tmp_appname[*it].set_appid(appid);
} else {
appname = it->substr(0, pos);
interval_key = it->substr(pos + 1);
AppNameMeta& meta = tmp_appname[appname];
ret = config.ReadItem("appname", *it, 0, interval);
if (ret != 0) {
gLog("[%s][%d]: read %s %s failed\n", __FILE__, __LINE__,
appname.c_str(), interval_key.c_str());
continue;
}
if (interval_key == "min_interval") {
meta.set_min_interval(interval);
} else if (interval_key == "mid_interval") {
meta.set_mid_interval(interval);
} else if (interval_key == "max_interval") {
meta.set_max_interval(interval);
}
}
}
index_ = new_index;
gLog("[%s][%d]: index = %d\n", __FILE__, __LINE__, index_);
for (AppanmeMapVecAppnameMeta::iterator it = appname_map_[index_].begin();
it != appname_map_[index_].end(); ++it) {
gLog("[%s][%d]: appname = %s, meta = %s\n", __FILE__, __LINE__,
it->first.c_str(), it->second.DebugString().c_str());
}
}
const AppNameMeta* AppnameManager::GetAppNameMeta(const std::string& appname) {
AppanmeMapVecAppnameMeta::iterator it = appname_map_[index_].find(appname);
if (it == appname_map_[index_].end()) {
gLog("[%s][%d]: can't find appname %s meta\n", __FILE__, __LINE__,
appname.c_str());
return NULL;
}
return &(it->second);
}
} // namespace libwxfreq
| 33.635417 | 88 | 0.650666 | [
"vector"
] |
9d5f5712297302b1dfb045ed5a9b49c1303a2792 | 382 | cpp | C++ | code/jump-game-2.cpp | tqgy/interview | 1f51a70fd6b86ba15a900aed072a138524e84609 | [
"CC0-1.0"
] | 4 | 2018-04-09T12:57:46.000Z | 2019-07-30T00:25:40.000Z | code/jump-game-2.cpp | tqgy/interview | 1f51a70fd6b86ba15a900aed072a138524e84609 | [
"CC0-1.0"
] | null | null | null | code/jump-game-2.cpp | tqgy/interview | 1f51a70fd6b86ba15a900aed072a138524e84609 | [
"CC0-1.0"
] | 3 | 2018-11-19T03:11:15.000Z | 2021-07-28T11:48:30.000Z | // Jump Game
// 思路2,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
bool canJump (const vector<int>& nums) {
if (nums.empty()) return true;
// 逆向下楼梯,最左能下降到第几层
int left_most = nums.size() - 1;
for (int i = nums.size() - 2; i >= 0; --i)
if (i + nums[i] >= left_most)
left_most = i;
return left_most == 0;
}
}; | 23.875 | 50 | 0.5 | [
"vector"
] |
9d644d63e22795509712704ab438eea47e234f1f | 14,722 | hpp | C++ | Source/AllProjects/WndUtils/CIDCtrls/CIDCtrls_MColListBox.hpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | 1 | 2019-05-28T06:33:01.000Z | 2019-05-28T06:33:01.000Z | Source/AllProjects/WndUtils/CIDCtrls/CIDCtrls_MColListBox.hpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | Source/AllProjects/WndUtils/CIDCtrls/CIDCtrls_MColListBox.hpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | //
// FILE NAME: CIDCtrls_MCColListBox.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 11/28/2017
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// The list view control, if you want to custom draw it and if you are using buffered
// drawing, which mostly all client applications will for performance, is just a huge
// piece of crap. It's almost impossible to get it working without major drawing artifacts
// and it's just one hack on top of another.
//
// So, after suffering for a year or so with that dog, I decided to just create my own.
// It's a bit complicated but ultimately worth it because this multi-column list box
// type interface is used all over the place, with in-place editing often to create
// a very simple but convenient configuration or settings interface.
//
// To make things gigantically simpler, we create two child controls, one that displays
// the headers and one that display sthe grid of items, plus h/v scroll bars. So, at the
// highest level we just create those and size and position them accoringly within ourself.
// They handle their own affairs.
//
// Data:
//
// We store the data ourself, as text. So we have a vector of vectors of strings basically.
// The outer vector is the rows, and the inner vector is the columns. We keep more than
// just the text. Each row object can indicate a background color and bold/normal text
// style. A row can also be marked as a label row, in which case only the first column
// is used, and is assumed to be label text, which is drawn bold and isn't limited to the
// width of the actual first column.
//
// Justification of the column text is driven by the header control. So each column matches
// the justification of the assocated header slot.
//
// We provide a simple class to describe a column. The client code sets up a collection of
// these and calls SetColumns() to set up our columns and tell us how to draw them.
//
// Header:
//
// The header control sends us notifications about resizing of columns and selection of
// columns (which is used in sortable lists to select a new sort column.) We use a generic
// header object (which is also one of our custom classes.)
//
// Sorting:
//
// For sorting we use a simple abstract class that client code can create derivatives
// of as desired. We provide a default one that just sorts (using the raw column text) of
// a single column. They can create ones that understand what the underlying data represents
// and sort by non-textual ordering, and also they can sort by main and sub-column for two
// level sorting, and whatever else they choose.
//
// Drawing:
//
// Obviously we have way more text than we can show. So we have a 'virtual drawing space' the
// actual size required and just store an origin that controls how far up and left that
// virtual space is shifted. So drawing means finding the row/column that first is visible in
// the upper left (often partially) and the one in the lower right. That provides a rectangle
// of cells that could possibly be visible. We then redraw the ones of those that have been
// invalidated.
//
// So we have core helpers that calculate those LF/LR visible cells, that calculate the area
// of a given cell, figure out the row/column of the cell (if any) that falls under a given
// point (for hit testing), calculate the visible area of a whole row or column, and so forth.
//
// As mentioned above we have two children, a header and the display window. We don't draw
// into our own area because it vastly complicates things. Doing it this way, we don't have to
// deal with the fact that not all our window is visible (header and scroll bars), the area of
// the displary window is the display area. To further simplify things, we keep the scroll bars
// visible all the time, and they are part of the main window, not the display window. So the
// size of the display window doesn't have to change if we move from too much too much to display
// at once to too little, or vice versa. And of course it also means that we again don't have
// to deal with the fact that not all of the display area is actually available.
//
// The scroll bars are just enabled when needed and disabled whend not. We keep our scroll
// position in the actual scroll bars, so that we don't have two copies of it to keep in sync.
// If a bar is disabled, then we know the scroll position is zero. If not, then we take the
// values of the two scroll bars and invert them to negative values and that is our virtual
// display space origin relative to the display window.
//
// Management:
//
// The main window really doesn't do much other than enable/disable the scroll bars and pass
// on incoming commands as required. The display window handles all of the real work, and we
// can keep it internal which vastly reduces our public API footprint and need for rebuilds.
// It means all our row and column classes can be internal as well.
//
// We just have to be careful to make it look like our main window is the actual control to
// the outside world. So the display window tells our main window about what is happening, and
// the main window sends out notifications as necessary. It also handles events from the header
// and passes them to the display window. And it provides the public API most of which is just
// passthroughs to the display window.
//
// Since the display window is pretty complicated and we want to keep a very clean separation
// we have a separate internal only header/implementation file for that. We just forward ref
// the display window class here.
//
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
class TMColListBox;
class TMColListBoxImpl;
// ---------------------------------------------------------------------------
// CLASS: TMCLBColDef
// PREFIX: mclbcd
// ---------------------------------------------------------------------------
class CIDCTRLSEXP TMCLBColDef
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TMCLBColDef();
TMCLBColDef
(
const TString& strTitle
, const tCIDLib::EHJustify eHJustify
, const tCIDLib::TCard4 c4Width = 24
, const tCIDLib::TBoolean bBold = kCIDLib::False
);
TMCLBColDef
(
const TString& strTitle
, const tCIDLib::EHJustify eHJustify
, const TRGBClr& rgbBgnClr
, const TRGBClr& rgbTextClr
, const tCIDLib::TCard4 c4Width = 24
, const tCIDLib::TBoolean bBold = kCIDLib::False
);
TMCLBColDef
(
const TMCLBColDef& mclbcdSrc
);
~TMCLBColDef();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TMCLBColDef& operator=
(
const TMCLBColDef& mclbcdSrc
);
protected :
// -------------------------------------------------------------------
// The public and impl classes are our friends so that they can see the members
// -------------------------------------------------------------------
friend class TMColListBoxImpl;
friend class TMColListBox;
private :
// -------------------------------------------------------------------
// Private data members
// -------------------------------------------------------------------
tCIDLib::TBoolean m_bBold;
tCIDLib::TCard4 m_c4Width;
tCIDLib::EHJustify m_eHJustify;
TRGBClr* m_prgbBgnClr;
TRGBClr* m_prgbTextClr;
TString m_strTitle;
};
// ---------------------------------------------------------------------------
// CLASS: TMColListBox
// PREFIX: wnd
// ---------------------------------------------------------------------------
class CIDCTRLSEXP TMColListBox : public TCtrlWnd
{
public :
// -------------------------------------------------------------------
// Public class types
// -------------------------------------------------------------------
typedef TVector<TMCLBColDef> TColDefs;
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TMColListBox();
TMColListBox(const TMColListBox&) = delete;
~TMColListBox();
// -------------------------------------------------------------------
// Public oeprators
// -------------------------------------------------------------------
TMColListBox& operator=(const TMColListBox&) = delete;
// -------------------------------------------------------------------
// Public, inherited methods
// -------------------------------------------------------------------
tCIDLib::TVoid InitFromDesc
(
const TWindow& wndParent
, const TDlgItem& dlgiSrc
, const tCIDCtrls::EWndThemes eTheme
) override;
tCIDLib::TVoid QueryHints
(
tCIDLib::TStrCollect& colToFill
) const override;
TSize szDefault() const override;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid CreateMColLB
(
const TWindow& wndParent
, const tCIDCtrls::TWndId widThis
, const TArea& areaInit
, const tCIDCtrls::EWndStyles eStyles
, const tCIDCtrls::EMCLBStyles eMCLBStyles = tCIDCtrls::EMCLBStyles::None
, const tCIDCtrls::EExWndStyles eExStyles = tCIDCtrls::EExWndStyles::None
);
tCIDLib::TVoid SetColumns
(
const TColDefs& colToSet
);
protected :
// -------------------------------------------------------------------
// Protected, inherited methods
// -------------------------------------------------------------------
tCIDLib::TVoid AreaChanged
(
const TArea& areaPrev
, const TArea& areaNew
, const tCIDCtrls::EPosStates ePosState
, const tCIDLib::TBoolean bOrgChanged
, const tCIDLib::TBoolean bSizeChanged
, const tCIDLib::TBoolean bStateChanged
) override;
tCIDLib::TBoolean bCreated() override;
tCIDLib::TBoolean bEraseBgn
(
TGraphDrawDev& gdevToUse
) override;
tCIDLib::TBoolean bPaint
(
TGraphDrawDev& gdevToUse
, const TArea& areaUpdate
) override;
tCIDLib::TVoid Destroyed() override;
private :
// -------------------------------------------------------------------
// Private types and constants
// -------------------------------------------------------------------
const tCIDCtrls::TWndId kWndId_Hdr = kCIDCtrls::widFirstCtrl;
const tCIDCtrls::TWndId kWndId_Display = kCIDCtrls::widFirstCtrl + 1;
const tCIDCtrls::TWndId kWndId_HScroll = kCIDCtrls::widFirstCtrl + 2;
const tCIDCtrls::TWndId kWndId_VScroll = kCIDCtrls::widFirstCtrl + 3;
// -------------------------------------------------------------------
// Private, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid CalcChildAreas
(
const TArea& areaAvail
, TArea& areaHdr
, TArea& areaDisplay
, TArea& areaHScroll
, TArea& areaVScroll
);
tCIDLib::TVoid SetHorzScroll();
// -------------------------------------------------------------------
// Private data members
//
// m_areaLRCorner
// The only part of our window that is covered by other stuff is the lower right
// corner where the two scroll bars come together. So any time we calc the child
// areas this is set to that, so we can fill it when neeed.
//
// m_c4FontHeight
// A lot of stuff is drivn by the font height, so we get it up front. We pass it
// to the display window as well since he will use it even more.
//
// m_eMCLBStyles
// Our class specific styles.
//
// m_pwndDisplay
// Our private implementation window that handles the actual management and
// display of the list cells.
//
// m_pwndHeader
// Our column header control.
//
// m_pwndScrollH
// m_pwndScrollV
// Our h/v scroll bars which we do as separate controls, not as the built in
// ones because these we can keep visible.
// -------------------------------------------------------------------
TArea m_areaLRCorner;
tCIDLib::TCard4 m_c4FontHeight;
tCIDCtrls::EMCLBStyles m_eMCLBStyles;
TMColListBoxImpl* m_pwndDisplay;
TColHeader* m_pwndHeader;
TScrollBar* m_pwndScrollH;
TScrollBar* m_pwndScrollV;
// -------------------------------------------------------------------
// Do any needed magic macros
// -------------------------------------------------------------------
RTTIDefs(TMColListBox, TCtrlWnd)
};
#pragma CIDLIB_POPPACK
| 41.122905 | 98 | 0.520581 | [
"object",
"vector"
] |
9d6931281a5ad7ab7ba1c2248556f99e6818ea20 | 2,514 | hpp | C++ | include/boost/numpy/dstream/wiring/detail/nd_accessor.hpp | IceCube-SPNO/BoostNumpy | 66538c0b6e38e2f985e0b44d8191c878cea0332d | [
"BSL-1.0"
] | 6 | 2015-01-07T17:29:40.000Z | 2019-03-28T15:18:27.000Z | include/boost/numpy/dstream/wiring/detail/nd_accessor.hpp | IceCube-SPNO/BoostNumpy | 66538c0b6e38e2f985e0b44d8191c878cea0332d | [
"BSL-1.0"
] | 2 | 2017-04-12T19:01:21.000Z | 2017-04-14T16:18:38.000Z | include/boost/numpy/dstream/wiring/detail/nd_accessor.hpp | IceCube-SPNO/BoostNumpy | 66538c0b6e38e2f985e0b44d8191c878cea0332d | [
"BSL-1.0"
] | 2 | 2018-01-15T07:32:24.000Z | 2020-10-14T02:55:55.000Z | /**
* $Id$
*
* Copyright (C)
* 2014 - $Date$
* Martin Wolf <boostnumpy@martin-wolf.org>
*
* \file boost/numpy/dstream/wiring/detail/nd_accessor.hpp
* \version $Revision$
* \date $Date$
* \author Martin Wolf <boostnumpy@martin-wolf.org>
*
* \brief This file defines the nd_accessor template to access a value
* of a multi-dimensional object which implements the []-operator for
* each dimension.
*
* This file is distributed under the Boost Software License,
* Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt).
*/
#if !BOOST_PP_IS_ITERATING
#ifndef BOOST_NUMPY_DSTREAM_WIRING_ND_ACCESSOR_HPP_INCLUDED
#define BOOST_NUMPY_DSTREAM_WIRING_ND_ACCESSOR_HPP_INCLUDED
#include <stdint.h>
#include <vector>
#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
namespace boost {
namespace numpy {
namespace dstream {
namespace wiring {
namespace detail {
template <class T, class ValueT, unsigned nd>
struct nd_accessor;
#define BOOST_PP_ITERATION_PARAMS_1 \
(4, (1, 18, <boost/numpy/dstream/wiring/detail/nd_accessor.hpp>, 1))
#include BOOST_PP_ITERATE()
}// namespace detail
}// namespace wiring
}// namespace dstream
}// namespace numpy
}// namespace boost
#endif // ! BOOST_NUMPY_DSTREAM_WIRING_ND_ACCESSOR_HPP_INCLUDED
#else
#if BOOST_PP_ITERATION_FLAGS() == 1
#define ND BOOST_PP_ITERATION()
#define BOOST_NUMPY_DSTREAM_dim_indices_def(z, n, data) \
intptr_t & BOOST_PP_CAT(dim_index,n);
#define BOOST_NUMPY_DSTREAM_dim_indices_init(z, n, data) \
BOOST_PP_COMMA_IF(n) BOOST_PP_CAT(dim_index,n)(dim_indices[n])
#define BOOST_NUMPY_DSTREAM_access(z, n, data) \
[ BOOST_PP_CAT(dim_index,n) ]
template <class T, class ValueT>
struct nd_accessor<T, ValueT, ND>
{
nd_accessor(std::vector<intptr_t> & dim_indices)
: BOOST_PP_REPEAT(ND, BOOST_NUMPY_DSTREAM_dim_indices_init, ~)
{}
inline
ValueT
operator()(T const & nd_obj)
{
return nd_obj BOOST_PP_REPEAT(ND, BOOST_NUMPY_DSTREAM_access, ~) ;
}
BOOST_PP_REPEAT(ND, BOOST_NUMPY_DSTREAM_dim_indices_def, ~)
};
#undef BOOST_NUMPY_DSTREAM_access
#undef BOOST_NUMPY_DSTREAM_dim_indices_init
#undef BOOST_NUMPY_DSTREAM_dim_indices_def
#undef ND
#endif // BOOST_PP_ITERATION_FLAGS() == 1
#endif // BOOST_PP_IS_ITERATING
| 26.744681 | 80 | 0.702068 | [
"object",
"vector"
] |
9d6d4081c086bba43e6e3232b3bbd0f6e29458bf | 2,050 | cpp | C++ | src/discordpp/commands/CommandManager.cpp | Devincf/Discordpp | 0166773f378ed4aa15389133ebee283a8287c07a | [
"Apache-2.0"
] | 2 | 2019-02-15T16:32:48.000Z | 2019-04-02T11:29:38.000Z | src/discordpp/commands/CommandManager.cpp | Devincf/Discordpp | 0166773f378ed4aa15389133ebee283a8287c07a | [
"Apache-2.0"
] | null | null | null | src/discordpp/commands/CommandManager.cpp | Devincf/Discordpp | 0166773f378ed4aa15389133ebee283a8287c07a | [
"Apache-2.0"
] | null | null | null | /**
* @file CommandManager.cpp
* @author Devin-Can Firat (devinc.firat@gmail.com)
* @brief
* @version 0.1
* @date 2019-04-02 01:06
*
* @copyright Copyright (c) 2019
*
*/
#include "CommandManager.hpp"
#include "util/constants.hpp"
#include "boost/algorithm/string.hpp"
namespace discordpp
{
bool CommandManager::addCommand(const std::string &cmdStr, Command *cmdPtr)
{
return addCommand({0}, cmdStr, cmdPtr);
}
bool CommandManager::addCommand(Snowflake guildId, const std::string &cmdStr, Command *cmdPtr)
{
auto guildit = m_commandMap.find(guildId);
if (guildit == m_commandMap.end())
{
m_commandMap.insert({guildId, std::map<std::string,std::shared_ptr<Command>>()});
m_commandMap[guildId].insert({cmdStr, std::shared_ptr<Command>(cmdPtr)});
return true;
}
else
{
auto ret = (*guildit).second.insert({cmdStr, std::shared_ptr<Command>(cmdPtr)});
if (!ret.second)
{
DEBUG("element already existed");
return false;
}
return true;
}
}
std::shared_ptr<Command> CommandManager::findCommand(const Snowflake & guild_id, const std::string & cmdStr)
{
std::vector<std::string> split_cmdStr;
boost::split(split_cmdStr, cmdStr, boost::is_any_of(" "));
auto cmdit = m_commandMap[0].find(split_cmdStr[0]);
if(cmdit != m_commandMap[0].end())
{
//return global command
return cmdit->second;
}else
{
auto guildit = m_commandMap.find(guild_id);
if(guildit == m_commandMap.end())
{
//command not in global list and guild doesnt exist
return nullptr;
}else{
cmdit = guildit->second.find(split_cmdStr[0]);
if(cmdit != guildit->second.end())
{
//return guild local command
return cmdit->second;
}else{
//command neither in global nor in guild list
return nullptr;
}
}
}
}
} // namespace discordpp | 26.973684 | 108 | 0.598049 | [
"vector"
] |
9d7191d94f4dd13201cec74f948ae3fc6d39ad50 | 706 | cpp | C++ | LeetCode/Tag/Array/cpp/581.shortest-unsorted-continuous-subarray.cpp | pakosel/competitive-coding-problems | 187a2f13725e06ab3301ae2be37f16fbec0c0588 | [
"MIT"
] | 17 | 2017-08-12T14:42:46.000Z | 2022-02-26T16:35:44.000Z | LeetCode/Tag/Array/cpp/581.shortest-unsorted-continuous-subarray.cpp | pakosel/competitive-coding-problems | 187a2f13725e06ab3301ae2be37f16fbec0c0588 | [
"MIT"
] | 21 | 2019-09-20T07:06:27.000Z | 2021-11-02T10:30:50.000Z | LeetCode/Tag/Array/cpp/581.shortest-unsorted-continuous-subarray.cpp | pakosel/competitive-coding-problems | 187a2f13725e06ab3301ae2be37f16fbec0c0588 | [
"MIT"
] | 21 | 2017-05-28T10:15:07.000Z | 2021-07-20T07:19:58.000Z | class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size();
vector<int> maxLeft(n, -1e5-1), minRight(n, 1e5+1);
maxLeft[0] = nums[0];
minRight.back() = nums.back();
for (int i = 1, j = n-2; i < n; ++i, --j) {
maxLeft[i] = max(nums[i], maxLeft[i-1]);
minRight[j] = min(nums[j], minRight[j+1]);
}
int start = 0, end = n-1;
for (int i = 0; i+1 < n && maxLeft[i] <= minRight[i+1]; ++i, ++start);
for (int j = n-1; j-1 >= 0 && maxLeft[j-1] <= minRight[j] && start < end; --j, --end);
int result = end - start + 1;
return result > 1 ? result : 0;
}
}; | 37.157895 | 94 | 0.467422 | [
"vector"
] |
9d7416c19c6162da6123165a1ffe5285d1de6943 | 3,343 | cpp | C++ | Source/ArcadeSHMUP/EnemyAndAI/EnemyBlinker.cpp | DawgDaPoog/ArcadeSHMUP | 07b5fb31af008fbdf7b27ee8fe70423537207f99 | [
"MIT"
] | null | null | null | Source/ArcadeSHMUP/EnemyAndAI/EnemyBlinker.cpp | DawgDaPoog/ArcadeSHMUP | 07b5fb31af008fbdf7b27ee8fe70423537207f99 | [
"MIT"
] | null | null | null | Source/ArcadeSHMUP/EnemyAndAI/EnemyBlinker.cpp | DawgDaPoog/ArcadeSHMUP | 07b5fb31af008fbdf7b27ee8fe70423537207f99 | [
"MIT"
] | null | null | null | // Copyright Vladyslav Kulinych 2018. All Rights Reserved.
#include "EnemyBlinker.h"
#include "Particles/ParticleSystem.h"
#include "Particles/ParticleSystemComponent.h"
#include "Kismet/GameplayStatics.h"
#include "Kismet/KismetMathLibrary.h"
#include "Engine/World.h"
#include "TimerManager.h"
#include "BlinkerRay.h"
#include "Components/StaticMeshComponent.h"
#include "EnemyBlinkerAI.h"
#include "TimerManager.h"
AEnemyBlinker::AEnemyBlinker()
{
HitPoints = 60.f;
WeaponDropPriority = 3;
PointsAwardedOnKill = 200;
}
void AEnemyBlinker::BeginPlay()
{
Super::BeginPlay();
// Find our controller
MyController = Cast<AEnemyBlinkerAI>(GetController());
// Ask for blink as we spawn
if (MyController)
{
MyController->AskForBlink();
}
}
void AEnemyBlinker::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// If we are focused set the rotation focus
if (bIsFocused)
{
SetActorRotation(RotationFocus);
}
// If we have a spawned ray, set it's location and rotation to that of it's owner
if (CurrentlySpawnedRay && this)
{
CurrentlySpawnedRay->SetActorLocation(GetActorLocation());
}
if (CurrentlySpawnedRay && this)
{
CurrentlySpawnedRay->SetActorRotation(GetActorRotation());
}
// Clamp our movement speed if we have too much velocity on mesh
if (GetVelocity().Size() > 300.f)
{
Mesh->SetPhysicsLinearVelocity(GetVelocity().GetSafeNormal()*300.f);
}
}
void AEnemyBlinker::BlinkTo(FVector Location)
{
// Destroying the ray that we have spawned if we did
if (CurrentlySpawnedRay)
{
CurrentlySpawnedRay->Destroy();
}
// Unfocus
bIsFocused = false;
// Spawn particles when we teleport from the place
if (ParticlesOnTeleportBefore)
{
UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ParticlesOnTeleportBefore, GetActorLocation());
}
// Set actor location to the new, that has been set by the ai
SetActorLocation(Location);
// Spawn particles that play when we land at a new location
if (ParticlesOnTeleportAfter)
{
UGameplayStatics::SpawnEmitterAttached(ParticlesOnTeleportAfter, RootComponent);
}
}
void AEnemyBlinker::InitialiseRayAt(FVector Location)
{
if (CurrentlySpawnedRay)
{
CurrentlySpawnedRay->Destroy();
}
if (RayToShoot)
{
// Find rotation to our target
FRotator RotationToTarget = UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), Location);
// Setting the rotation to target and telling blinker to focus
RotationFocus = RotationToTarget;
bIsFocused = true;
// Spawn the inactive ray
CurrentlySpawnedRay = GetWorld()->SpawnActor<AEnemyProjectile>(RayToShoot, GetActorLocation(), RotationToTarget, FActorSpawnParameters());
// Set a timer to activate the ray after 1 sec
FTimerHandle TimerHandle;
FTimerDelegate TimerDelegate;
TimerDelegate.BindLambda([this]()
{
if (CurrentlySpawnedRay)
{
Cast<ABlinkerRay>(CurrentlySpawnedRay)->ActivateRay();
}
});
GetWorldTimerManager().SetTimer(TimerHandle, TimerDelegate, 1.f, false);
}
}
void AEnemyBlinker::TakeDamage(float Damage)
{
Super::TakeDamage(Damage);
// If we are not invincible, request the AI controller to blink
if (!bIsInvincible)
{
if (MyController)
{
MyController->AskForBlink();
}
}
}
void AEnemyBlinker::SequenceDestroy()
{
if (CurrentlySpawnedRay)
{
CurrentlySpawnedRay->Destroy();
}
Super::SequenceDestroy();
}
| 22.587838 | 140 | 0.744541 | [
"mesh"
] |
9d7e04f3b592be6a055bdf973992d6d932544181 | 1,545 | cpp | C++ | src/FluidCinderApp.cpp | kotsoft/FluidCinder | 3cd10cf75cd7e8df080e82428483764b8045cc50 | [
"MIT"
] | 44 | 2015-01-20T09:43:31.000Z | 2022-01-23T06:18:13.000Z | src/FluidCinderApp.cpp | YangTrees/FluidCinder | 3cd10cf75cd7e8df080e82428483764b8045cc50 | [
"MIT"
] | 2 | 2016-05-19T06:41:34.000Z | 2016-07-24T13:39:30.000Z | src/FluidCinderApp.cpp | YangTrees/FluidCinder | 3cd10cf75cd7e8df080e82428483764b8045cc50 | [
"MIT"
] | 9 | 2016-02-06T22:41:09.000Z | 2021-12-11T23:07:29.000Z | #include "cinder/app/AppBasic.h"
#include "cinder/gl/gl.h"
#include "Simulator.cpp"
#include <vector>
#include "cinder/gl/Vbo.h"
//#include <omp.h>
using namespace ci;
using namespace ci::app;
using namespace std;
class FluidCinderApp : public AppBasic {
Simulator s;
int n;
GLfloat* vertices;
public:
void setup();
void mouseDown( MouseEvent event );
void update();
void draw();
void prepareSettings(Settings *settings);
};
void FluidCinderApp::setup()
{
s.initializeGrid(400,200);
s.addParticles();
n = s.particles.size();
gl::VboMesh::Layout layout;
layout.setDynamicPositions();
vertices = new GLfloat[n*4];
}
void FluidCinderApp::mouseDown( MouseEvent event )
{
}
void FluidCinderApp::update()
{
s.update();
}
void FluidCinderApp::draw()
{
// clear out the window with black
gl::clear( Color( 0, 0, 0 ) );
gl::color(.1,.5,1);
vector<Particle>& particles = s.particles;
int nParticles = particles.size();
float* vi = vertices;
for (int i = 0; i < nParticles; i++) {
Particle& p = particles[i];
*(vi++) = p.x*4;
*(vi++) = p.y*4;
*(vi++) = (p.x-p.gu)*4;
*(vi++) = (p.y-p.gv)*4;
}
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vertices);
glDrawArrays(GL_LINES, 0, n*2);
glDisableClientState(GL_VERTEX_ARRAY);
}
void FluidCinderApp::prepareSettings( Settings *settings ) {
settings->setWindowSize( 1600, 800 );
settings->setFrameRate(60.0f);
}
CINDER_APP_BASIC( FluidCinderApp, RendererGl )
| 19.556962 | 60 | 0.686084 | [
"vector"
] |
9d7ff1bc4ec4f1b6127a54cbf50a618afa8038ae | 2,207 | hxx | C++ | main/editeng/inc/editeng/unoviwou.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/editeng/inc/editeng/unoviwou.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/editeng/inc/editeng/unoviwou.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _SVX_UNOVIWOU_HXX
#define _SVX_UNOVIWOU_HXX
#include <editeng/unoedsrc.hxx>
#include <editeng/editengdllapi.h>
class OutlinerView;
/// Specialization for Draw/Impress
class EDITENG_DLLPUBLIC SvxDrawOutlinerViewForwarder : public SvxEditViewForwarder
{
private:
OutlinerView& mrOutlinerView;
Point maTextShapeTopLeft;
EDITENG_DLLPRIVATE Point GetTextOffset() const;
public:
explicit SvxDrawOutlinerViewForwarder( OutlinerView& rOutl );
SvxDrawOutlinerViewForwarder( OutlinerView& rOutl, const Point& rShapePosTopLeft );
virtual ~SvxDrawOutlinerViewForwarder();
virtual sal_Bool IsValid() const;
virtual Rectangle GetVisArea() const;
virtual Point LogicToPixel( const Point& rPoint, const MapMode& rMapMode ) const;
virtual Point PixelToLogic( const Point& rPoint, const MapMode& rMapMode ) const;
virtual sal_Bool GetSelection( ESelection& rSelection ) const;
virtual sal_Bool SetSelection( const ESelection& rSelection );
virtual sal_Bool Copy();
virtual sal_Bool Cut();
virtual sal_Bool Paste();
/// Set the top, left position of the underlying draw shape, to
/// allow EditEngine offset calculations
void SetShapePos( const Point& rShapePosTopLeft );
};
#endif
| 33.953846 | 92 | 0.708654 | [
"shape"
] |
9d83f7c6c050806fba638c3c0b43706d8a946f88 | 28,885 | hpp | C++ | include/System/Linq/Expressions/Interpreter/InterpretedFrame.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Linq/Expressions/Interpreter/InterpretedFrame.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Linq/Expressions/Interpreter/InterpretedFrame.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrameInfo
#include "System/Linq/Expressions/Interpreter/InterpretedFrameInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Linq::Expressions::Interpreter
namespace System::Linq::Expressions::Interpreter {
// Forward declaring type: Interpreter
class Interpreter;
// Forward declaring type: DebugInfo
class DebugInfo;
}
// Forward declaring namespace: System::Runtime::CompilerServices
namespace System::Runtime::CompilerServices {
// Forward declaring type: IStrongBox
class IStrongBox;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Exception
class Exception;
}
// Completed forward declares
// Type namespace: System.Linq.Expressions.Interpreter
namespace System::Linq::Expressions::Interpreter {
// Forward declaring type: InterpretedFrame
class InterpretedFrame;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Linq::Expressions::Interpreter::InterpretedFrame);
DEFINE_IL2CPP_ARG_TYPE(::System::Linq::Expressions::Interpreter::InterpretedFrame*, "System.Linq.Expressions.Interpreter", "InterpretedFrame");
// Type namespace: System.Linq.Expressions.Interpreter
namespace System::Linq::Expressions::Interpreter {
// Size: 0x50
#pragma pack(push, 1)
// Autogenerated type: System.Linq.Expressions.Interpreter.InterpretedFrame
// [TokenAttribute] Offset: FFFFFFFF
class InterpretedFrame : public ::Il2CppObject {
public:
// Nested type: ::System::Linq::Expressions::Interpreter::InterpretedFrame::$GetStackTraceDebugInfo$d__29
class $GetStackTraceDebugInfo$d__29;
public:
// readonly System.Linq.Expressions.Interpreter.Interpreter Interpreter
// Size: 0x8
// Offset: 0x10
::System::Linq::Expressions::Interpreter::Interpreter* Interpreter;
// Field size check
static_assert(sizeof(::System::Linq::Expressions::Interpreter::Interpreter*) == 0x8);
// System.Linq.Expressions.Interpreter.InterpretedFrame _parent
// Size: 0x8
// Offset: 0x18
::System::Linq::Expressions::Interpreter::InterpretedFrame* parent;
// Field size check
static_assert(sizeof(::System::Linq::Expressions::Interpreter::InterpretedFrame*) == 0x8);
// private readonly System.Int32[] _continuations
// Size: 0x8
// Offset: 0x20
::ArrayW<int> continuations;
// Field size check
static_assert(sizeof(::ArrayW<int>) == 0x8);
// private System.Int32 _continuationIndex
// Size: 0x4
// Offset: 0x28
int continuationIndex;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int32 _pendingContinuation
// Size: 0x4
// Offset: 0x2C
int pendingContinuation;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Object _pendingValue
// Size: 0x8
// Offset: 0x30
::Il2CppObject* pendingValue;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
// public readonly System.Object[] Data
// Size: 0x8
// Offset: 0x38
::ArrayW<::Il2CppObject*> Data;
// Field size check
static_assert(sizeof(::ArrayW<::Il2CppObject*>) == 0x8);
// public readonly System.Runtime.CompilerServices.IStrongBox[] Closure
// Size: 0x8
// Offset: 0x40
::ArrayW<::System::Runtime::CompilerServices::IStrongBox*> Closure;
// Field size check
static_assert(sizeof(::ArrayW<::System::Runtime::CompilerServices::IStrongBox*>) == 0x8);
// public System.Int32 StackIndex
// Size: 0x4
// Offset: 0x48
int StackIndex;
// Field size check
static_assert(sizeof(int) == 0x4);
// public System.Int32 InstructionIndex
// Size: 0x4
// Offset: 0x4C
int InstructionIndex;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Get static field: static private System.Linq.Expressions.Interpreter.InterpretedFrame s_currentFrame
static ::System::Linq::Expressions::Interpreter::InterpretedFrame* _get_s_currentFrame();
// Set static field: static private System.Linq.Expressions.Interpreter.InterpretedFrame s_currentFrame
static void _set_s_currentFrame(::System::Linq::Expressions::Interpreter::InterpretedFrame* value);
// Get instance field reference: readonly System.Linq.Expressions.Interpreter.Interpreter Interpreter
[[deprecated("Use field access instead!")]] ::System::Linq::Expressions::Interpreter::Interpreter*& dyn_Interpreter();
// Get instance field reference: System.Linq.Expressions.Interpreter.InterpretedFrame _parent
[[deprecated("Use field access instead!")]] ::System::Linq::Expressions::Interpreter::InterpretedFrame*& dyn__parent();
// Get instance field reference: private readonly System.Int32[] _continuations
[[deprecated("Use field access instead!")]] ::ArrayW<int>& dyn__continuations();
// Get instance field reference: private System.Int32 _continuationIndex
[[deprecated("Use field access instead!")]] int& dyn__continuationIndex();
// Get instance field reference: private System.Int32 _pendingContinuation
[[deprecated("Use field access instead!")]] int& dyn__pendingContinuation();
// Get instance field reference: private System.Object _pendingValue
[[deprecated("Use field access instead!")]] ::Il2CppObject*& dyn__pendingValue();
// Get instance field reference: public readonly System.Object[] Data
[[deprecated("Use field access instead!")]] ::ArrayW<::Il2CppObject*>& dyn_Data();
// Get instance field reference: public readonly System.Runtime.CompilerServices.IStrongBox[] Closure
[[deprecated("Use field access instead!")]] ::ArrayW<::System::Runtime::CompilerServices::IStrongBox*>& dyn_Closure();
// Get instance field reference: public System.Int32 StackIndex
[[deprecated("Use field access instead!")]] int& dyn_StackIndex();
// Get instance field reference: public System.Int32 InstructionIndex
[[deprecated("Use field access instead!")]] int& dyn_InstructionIndex();
// public System.String get_Name()
// Offset: 0xF1E1AC
::StringW get_Name();
// public System.Linq.Expressions.Interpreter.InterpretedFrame get_Parent()
// Offset: 0xF1E76C
::System::Linq::Expressions::Interpreter::InterpretedFrame* get_Parent();
// System.Void .ctor(System.Linq.Expressions.Interpreter.Interpreter interpreter, System.Runtime.CompilerServices.IStrongBox[] closure)
// Offset: 0xF1E02C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static InterpretedFrame* New_ctor(::System::Linq::Expressions::Interpreter::Interpreter* interpreter, ::ArrayW<::System::Runtime::CompilerServices::IStrongBox*> closure) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::InterpretedFrame::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<InterpretedFrame*, creationType>(interpreter, closure)));
}
// public System.Linq.Expressions.Interpreter.DebugInfo GetDebugInfo(System.Int32 instructionIndex)
// Offset: 0xF1E128
::System::Linq::Expressions::Interpreter::DebugInfo* GetDebugInfo(int instructionIndex);
// public System.Void Push(System.Object value)
// Offset: 0xF14A80
void Push(::Il2CppObject* value);
// public System.Void Push(System.Boolean value)
// Offset: 0xF1E1C8
void Push(bool value);
// public System.Void Push(System.Int32 value)
// Offset: 0xF1E2C0
void Push(int value);
// public System.Void Push(System.Byte value)
// Offset: 0xF1E34C
void Push(uint8_t value);
// public System.Void Push(System.SByte value)
// Offset: 0xF1E414
void Push(int8_t value);
// public System.Void Push(System.Int16 value)
// Offset: 0xF1E4DC
void Push(int16_t value);
// public System.Void Push(System.UInt16 value)
// Offset: 0xF1E5A4
void Push(uint16_t value);
// public System.Object Pop()
// Offset: 0xF14A38
::Il2CppObject* Pop();
// System.Void SetStackDepth(System.Int32 depth)
// Offset: 0xF1E66C
void SetStackDepth(int depth);
// public System.Object Peek()
// Offset: 0xF1E690
::Il2CppObject* Peek();
// public System.Void Dup()
// Offset: 0xF1E6D4
void Dup();
// public System.Collections.Generic.IEnumerable`1<System.Linq.Expressions.Interpreter.InterpretedFrameInfo> GetStackTraceDebugInfo()
// Offset: 0xF1E774
::System::Collections::Generic::IEnumerable_1<::System::Linq::Expressions::Interpreter::InterpretedFrameInfo>* GetStackTraceDebugInfo();
// System.Void SaveTraceToException(System.Exception exception)
// Offset: 0xF1E7E0
void SaveTraceToException(::System::Exception* exception);
// System.Linq.Expressions.Interpreter.InterpretedFrame Enter()
// Offset: 0xF1EA60
::System::Linq::Expressions::Interpreter::InterpretedFrame* Enter();
// System.Void Leave(System.Linq.Expressions.Interpreter.InterpretedFrame prevFrame)
// Offset: 0xF1EACC
void Leave(::System::Linq::Expressions::Interpreter::InterpretedFrame* prevFrame);
// System.Boolean IsJumpHappened()
// Offset: 0xF1EB1C
bool IsJumpHappened();
// public System.Void RemoveContinuation()
// Offset: 0xF1EB2C
void RemoveContinuation();
// public System.Void PushContinuation(System.Int32 continuation)
// Offset: 0xF1EB3C
void PushContinuation(int continuation);
// public System.Int32 YieldToCurrentContinuation()
// Offset: 0xF1EB84
int YieldToCurrentContinuation();
// public System.Int32 YieldToPendingContinuation()
// Offset: 0xF1EC08
int YieldToPendingContinuation();
// System.Void PushPendingContinuation()
// Offset: 0xF1EDB4
void PushPendingContinuation();
// System.Void PopPendingContinuation()
// Offset: 0xF1EE40
void PopPendingContinuation();
// public System.Int32 Goto(System.Int32 labelIndex, System.Object value, System.Boolean gotoExceptionHandler)
// Offset: 0xF15250
int Goto(int labelIndex, ::Il2CppObject* value, bool gotoExceptionHandler);
}; // System.Linq.Expressions.Interpreter.InterpretedFrame
#pragma pack(pop)
static check_size<sizeof(InterpretedFrame), 76 + sizeof(int)> __System_Linq_Expressions_Interpreter_InterpretedFrameSizeCheck;
static_assert(sizeof(InterpretedFrame) == 0x50);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::get_Name
// Il2CppName: get_Name
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::get_Name)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "get_Name", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::get_Parent
// Il2CppName: get_Parent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Linq::Expressions::Interpreter::InterpretedFrame* (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::get_Parent)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "get_Parent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::GetDebugInfo
// Il2CppName: GetDebugInfo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Linq::Expressions::Interpreter::DebugInfo* (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(int)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::GetDebugInfo)> {
static const MethodInfo* get() {
static auto* instructionIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "GetDebugInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instructionIndex});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Push
// Il2CppName: Push
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(::Il2CppObject*)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Push)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Push", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Push
// Il2CppName: Push
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(bool)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Push)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Push", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Push
// Il2CppName: Push
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(int)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Push)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Push", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Push
// Il2CppName: Push
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(uint8_t)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Push)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Byte")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Push", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Push
// Il2CppName: Push
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(int8_t)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Push)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "SByte")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Push", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Push
// Il2CppName: Push
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(int16_t)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Push)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int16")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Push", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Push
// Il2CppName: Push
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(uint16_t)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Push)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "UInt16")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Push", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Pop
// Il2CppName: Pop
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Pop)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Pop", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::SetStackDepth
// Il2CppName: SetStackDepth
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(int)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::SetStackDepth)> {
static const MethodInfo* get() {
static auto* depth = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "SetStackDepth", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{depth});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Peek
// Il2CppName: Peek
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Peek)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Peek", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Dup
// Il2CppName: Dup
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Dup)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Dup", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::GetStackTraceDebugInfo
// Il2CppName: GetStackTraceDebugInfo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::IEnumerable_1<::System::Linq::Expressions::Interpreter::InterpretedFrameInfo>* (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::GetStackTraceDebugInfo)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "GetStackTraceDebugInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::SaveTraceToException
// Il2CppName: SaveTraceToException
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(::System::Exception*)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::SaveTraceToException)> {
static const MethodInfo* get() {
static auto* exception = &::il2cpp_utils::GetClassFromName("System", "Exception")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "SaveTraceToException", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{exception});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Enter
// Il2CppName: Enter
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Linq::Expressions::Interpreter::InterpretedFrame* (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Enter)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Enter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Leave
// Il2CppName: Leave
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(::System::Linq::Expressions::Interpreter::InterpretedFrame*)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Leave)> {
static const MethodInfo* get() {
static auto* prevFrame = &::il2cpp_utils::GetClassFromName("System.Linq.Expressions.Interpreter", "InterpretedFrame")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Leave", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{prevFrame});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::IsJumpHappened
// Il2CppName: IsJumpHappened
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::IsJumpHappened)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "IsJumpHappened", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::RemoveContinuation
// Il2CppName: RemoveContinuation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::RemoveContinuation)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "RemoveContinuation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::PushContinuation
// Il2CppName: PushContinuation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(int)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::PushContinuation)> {
static const MethodInfo* get() {
static auto* continuation = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "PushContinuation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{continuation});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::YieldToCurrentContinuation
// Il2CppName: YieldToCurrentContinuation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::YieldToCurrentContinuation)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "YieldToCurrentContinuation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::YieldToPendingContinuation
// Il2CppName: YieldToPendingContinuation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::YieldToPendingContinuation)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "YieldToPendingContinuation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::PushPendingContinuation
// Il2CppName: PushPendingContinuation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::PushPendingContinuation)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "PushPendingContinuation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::PopPendingContinuation
// Il2CppName: PopPendingContinuation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Expressions::Interpreter::InterpretedFrame::*)()>(&System::Linq::Expressions::Interpreter::InterpretedFrame::PopPendingContinuation)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "PopPendingContinuation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::InterpretedFrame::Goto
// Il2CppName: Goto
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::InterpretedFrame::*)(int, ::Il2CppObject*, bool)>(&System::Linq::Expressions::Interpreter::InterpretedFrame::Goto)> {
static const MethodInfo* get() {
static auto* labelIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* gotoExceptionHandler = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::InterpretedFrame*), "Goto", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{labelIndex, value, gotoExceptionHandler});
}
};
| 62.252155 | 330 | 0.749836 | [
"object",
"vector"
] |
9d863fc5d8d2ce44d4c96a401496438f76849b9b | 1,488 | cpp | C++ | higan/fc/ppu/ppu.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | 10 | 2019-12-19T01:19:41.000Z | 2021-02-18T16:30:29.000Z | higan/fc/ppu/ppu.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | null | null | null | higan/fc/ppu/ppu.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | null | null | null | #include <fc/fc.hpp>
namespace Famicom {
PPU ppu;
#include "memory.cpp"
#include "render.cpp"
#include "serialization.cpp"
auto PPU::Enter() -> void {
while(true) scheduler.synchronize(), ppu.main();
}
auto PPU::main() -> void {
renderScanline();
}
auto PPU::step(uint clocks) -> void {
uint L = vlines();
while(clocks--) {
if(io.ly == 240 && io.lx == 340) io.nmiHold = 1;
if(io.ly == 241 && io.lx == 0) io.nmiFlag = io.nmiHold;
if(io.ly == 241 && io.lx == 2) cpu.nmiLine(io.nmiEnable && io.nmiFlag);
if(io.ly == L-2 && io.lx == 340) io.spriteZeroHit = 0, io.spriteOverflow = 0;
if(io.ly == L-2 && io.lx == 340) io.nmiHold = 0;
if(io.ly == L-1 && io.lx == 0) io.nmiFlag = io.nmiHold;
if(io.ly == L-1 && io.lx == 2) cpu.nmiLine(io.nmiEnable && io.nmiFlag);
Thread::step(rate());
synchronize(cpu);
io.lx++;
}
}
auto PPU::scanline() -> void {
io.lx = 0;
if(++io.ly == vlines()) {
io.ly = 0;
frame();
}
cartridge.scanline(io.ly);
}
auto PPU::frame() -> void {
io.field++;
scheduler.exit(Scheduler::Event::Frame);
}
auto PPU::refresh() -> void {
Emulator::video.refresh(buffer, 256 * sizeof(uint32), 256, 240);
}
auto PPU::power(bool reset) -> void {
create(PPU::Enter, system.frequency());
io = {};
latch = {};
if(!reset) {
for(auto& data : ciram ) data = 0;
for(auto& data : cgram ) data = 0;
for(auto& data : oam ) data = 0;
}
for(auto& data : buffer) data = 0;
}
}
| 20.383562 | 81 | 0.563172 | [
"render"
] |
9d8be2b7a3dd3ac6ab292ddce8ea2c81463b4e24 | 456 | hpp | C++ | libraries/protocol/include/futurepia/protocol/block.hpp | futurepia/futurepia | 31163047b18082223a86ec4f95a820748275ceaa | [
"MIT"
] | 3 | 2019-12-24T13:49:22.000Z | 2021-01-02T08:26:13.000Z | libraries/protocol/include/futurepia/protocol/block.hpp | futurepia/futurepia | 31163047b18082223a86ec4f95a820748275ceaa | [
"MIT"
] | 4 | 2020-01-01T20:41:39.000Z | 2021-11-30T16:31:10.000Z | libraries/protocol/include/futurepia/protocol/block.hpp | futurepia/futurepia | 31163047b18082223a86ec4f95a820748275ceaa | [
"MIT"
] | 5 | 2019-03-30T12:53:31.000Z | 2021-06-10T16:22:11.000Z | #pragma once
#include <futurepia/protocol/block_header.hpp>
#include <futurepia/protocol/transaction.hpp>
namespace futurepia { namespace protocol {
struct signed_block : public signed_block_header
{
checksum_type calculate_merkle_root()const;
vector<signed_transaction> transactions;
};
} } // futurepia::protocol
FC_REFLECT_DERIVED( futurepia::protocol::signed_block, (futurepia::protocol::signed_block_header), (transactions) )
| 28.5 | 115 | 0.77193 | [
"vector"
] |
9da5b64f659bd75b0f69da722cda74c7f88e201f | 2,256 | cpp | C++ | 1023 CamelCase Matching.cpp | think-start/Leetcode-Solutions | 6b0870d10cf02c3e285fa9b9e603fc4ca25db575 | [
"BSD-3-Clause-Attribution"
] | 7 | 2021-05-28T21:28:26.000Z | 2021-09-20T13:14:22.000Z | 1023 CamelCase Matching.cpp | think-start/Leetcode-Solutions | 6b0870d10cf02c3e285fa9b9e603fc4ca25db575 | [
"BSD-3-Clause-Attribution"
] | null | null | null | 1023 CamelCase Matching.cpp | think-start/Leetcode-Solutions | 6b0870d10cf02c3e285fa9b9e603fc4ca25db575 | [
"BSD-3-Clause-Attribution"
] | 5 | 2021-05-28T13:43:33.000Z | 2022-02-18T09:14:45.000Z | // problem 1023 Camelcase Matching
// A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query.
// (We may insert each character at any position, and may insert 0 characters.)
// Given a list of queries, and a pattern.
// return an answer list of booleans, where answer[i] is true if and only if queries[i] matches the pattern.
// Example 1:
// Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"
// Output: [true,false,true,true,false]
// Explanation:
// "FooBar" can be generated like this "F" + "oo" + "B" + "ar".
// "FootBall" can be generated like this "F" + "oot" + "B" + "all".
// "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer".
// Example 2:
// Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"
// Output: [true,false,true,false,false]
// Explanation:
// "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r".
// "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll".
// Example 3:
// Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"
// Output: [false,true,false,false,false]
// Explanation:
// "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".
// Note:
// 1 <= queries.length <= 100
// 1 <= queries[i].length <= 100
// 1 <= pattern.length <= 100
// All strings consists only of lower and upper case English letters
class Solution {
public:
vector<bool> camelMatch(vector<string>& queries, string pattern) {
vector<bool>v;
for(int i=0;i<queries.size();i++){
int k=0,j=0;
while(k<queries[i].size()){
if(j<pattern.length() && queries[i][k] == pattern[j] ){
k++; j++;
}
else if(queries[i][k]<='z' && queries[i][k]>='a'){
k++;
}
else {
v.push_back(0); break;
}
if(k==queries[i].length())
{ if(j==pattern.length()) v.push_back(1);
else v.push_back(0);}
}
}
return v;
}
};
| 34.707692 | 124 | 0.562943 | [
"vector"
] |
9dc3e9094779cbf0f8bfe7388386219846c0c63d | 11,714 | hpp | C++ | lib/utils/ArgumentParser.hpp | maldicion069/monkeybrush- | 2bccca097402ff1f5344e356f06de19c8c70065b | [
"MIT"
] | 1 | 2016-11-15T09:04:12.000Z | 2016-11-15T09:04:12.000Z | lib/utils/ArgumentParser.hpp | maldicion069/monkeybrush- | 2bccca097402ff1f5344e356f06de19c8c70065b | [
"MIT"
] | null | null | null | lib/utils/ArgumentParser.hpp | maldicion069/monkeybrush- | 2bccca097402ff1f5344e356f06de19c8c70065b | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2016 maldicion069
*
* Authors: Cristian Rodríguez Bernal <ccrisrober@gmail.com>
*
* This file is part of MonkeyBrushPlusPlus
* <https://github.com/maldicion069/monkeybrushplusplus>
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License version 3.0 as published
* by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
// Code based on https://github.com/weisslj/cpp-optparse
#ifndef __MB__ARGUMENT_PARSER__
#define __MB__ARGUMENT_PARSER__
#include <mb/api.h>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <iostream>
#include <sstream>
namespace mb
{
class ArgumentParser;
class OptionGroup;
class Option;
class Values;
class Value;
class Callback;
typedef std::map<std::string, std::string> strMap;
typedef std::map<std::string, std::list<std::string> > lstMap;
typedef std::map<std::string, Option const*> optMap;
const char* const SUPPRESS_HELP = "SUPPRESS" "HELP";
const char* const SUPPRESS_USAGE = "SUPPRESS" "USAGE";
//! Class for automatic conversion from string -> anytype
class Value {
public:
MB_API
Value() : str(), valid(false) {}
MB_API
Value(const std::string& v) : str(v), valid(true) {}
MB_API
operator const char*() { return str.c_str(); }
MB_API
operator bool() { bool t; return (valid && (std::istringstream(str) >> t)) ? t : false; }
MB_API
operator short() { short t; return (valid && (std::istringstream(str) >> t)) ? t : 0; }
MB_API
operator unsigned short() { unsigned short t; return (valid && (std::istringstream(str) >> t)) ? t : 0; }
MB_API
operator int() { int t; return (valid && (std::istringstream(str) >> t)) ? t : 0; }
MB_API
operator unsigned int() { unsigned int t; return (valid && (std::istringstream(str) >> t)) ? t : 0; }
MB_API
operator long() { long t; return (valid && (std::istringstream(str) >> t)) ? t : 0; }
MB_API
operator unsigned long() { unsigned long t; return (valid && (std::istringstream(str) >> t)) ? t : 0; }
MB_API
operator float() { float t; return (valid && (std::istringstream(str) >> t)) ? t : 0; }
MB_API
operator double() { double t; return (valid && (std::istringstream(str) >> t)) ? t : 0; }
MB_API
operator long double() { long double t; return (valid && (std::istringstream(str) >> t)) ? t : 0; }
private:
const std::string str;
bool valid;
};
class Values {
public:
MB_API
Values() : _map() {}
MB_API
const std::string& operator[] (const std::string& d) const;
MB_API
std::string& operator[] (const std::string& d) { return _map[d]; }
MB_API
bool is_set(const std::string& d) const { return _map.find(d) != _map.end(); }
MB_API
bool is_set_by_user(const std::string& d) const { return _userSet.find(d) != _userSet.end(); }
MB_API
void is_set_by_user(const std::string& d, bool yes);
MB_API
Value get(const std::string& d) const { return (is_set(d)) ? Value((*this)[d]) : Value(); }
typedef std::list<std::string>::iterator iterator;
typedef std::list<std::string>::const_iterator const_iterator;
std::list<std::string>& all(const std::string& d) { return _appendMap[d]; }
const std::list<std::string>& all(const std::string& d) const { return _appendMap.find(d)->second; }
private:
strMap _map;
lstMap _appendMap;
std::set<std::string> _userSet;
};
class OptionContainer {
public:
MB_API
OptionContainer(const std::string& d = "") : _description(d) {}
MB_API
virtual ~OptionContainer() {}
MB_API
virtual OptionContainer& description(const std::string& d) { _description = d; return *this; }
MB_API
virtual const std::string& description() const { return _description; }
MB_API
Option& add_option(const std::string& opt);
MB_API
Option& add_option(const std::string& opt1, const std::string& opt2);
MB_API
Option& add_option(const std::string& opt1, const std::string& opt2, const std::string& opt3);
MB_API
Option& add_option(const std::vector<std::string>& opt);
MB_API
std::string format_option_help(unsigned int indent = 2) const;
protected:
std::string _description;
std::list<Option> _opts;
optMap _optmap_s;
optMap _optmap_l;
private:
virtual const ArgumentParser& get_parser() = 0;
};
class ArgumentParser : public OptionContainer {
public:
MB_API
ArgumentParser();
MB_API
virtual ~ArgumentParser() {}
MB_API
ArgumentParser& usage(const std::string& u) { set_usage(u); return *this; }
MB_API
ArgumentParser& version(const std::string& v) { _version = v; return *this; }
MB_API
ArgumentParser& description(const std::string& d) { _description = d; return *this; }
MB_API
ArgumentParser& add_help_option(bool h) { _add_help_option = h; return *this; }
MB_API
ArgumentParser& add_version_option(bool v) { _add_version_option = v; return *this; }
MB_API
ArgumentParser& prog(const std::string& p) { _prog = p; return *this; }
MB_API
ArgumentParser& epilog(const std::string& e) { _epilog = e; return *this; }
MB_API
ArgumentParser& set_defaults(const std::string& dest, const std::string& val) {
_defaults[dest] = val; return *this;
}
template<typename T>
ArgumentParser& set_defaults(const std::string& dest, T t) { std::ostringstream ss; ss << t; _defaults[dest] = ss.str(); return *this; }
ArgumentParser& enable_interspersed_args() { _interspersed_args = true; return *this; }
ArgumentParser& disable_interspersed_args() { _interspersed_args = false; return *this; }
ArgumentParser& add_option_group(const OptionGroup& group);
MB_API
const std::string& usage() const { return _usage; }
MB_API
const std::string& version() const { return _version; }
MB_API
const std::string& description() const { return _description; }
MB_API
bool add_help_option() const { return _add_help_option; }
MB_API
bool add_version_option() const { return _add_version_option; }
MB_API
const std::string& prog() const { return _prog; }
MB_API
const std::string& epilog() const { return _epilog; }
MB_API
bool interspersed_args() const { return _interspersed_args; }
MB_API
Values& parse_args(int argc, char const* const* argv);
MB_API
Values& parse_args(const std::vector<std::string>& args);
template<typename InputIterator>
Values& parse_args(InputIterator begin, InputIterator end) {
return parse_args(std::vector<std::string>(begin, end));
}
MB_API
const std::list<std::string>& args() const { return _leftover; }
MB_API
std::vector<std::string> args() {
return std::vector<std::string>(_leftover.begin(), _leftover.end());
}
MB_API
std::string format_help() const;
MB_API
void print_help() const;
MB_API
void set_usage(const std::string& u);
MB_API
std::string get_usage() const;
MB_API
void print_usage(std::ostream& out) const;
MB_API
void print_usage() const;
MB_API
std::string get_version() const;
MB_API
void print_version(std::ostream& out) const;
MB_API
void print_version() const;
MB_API
void error(const std::string& msg) const;
MB_API
void exit() const;
private:
const ArgumentParser& get_parser() { return *this; }
const Option& lookup_short_opt(const std::string& opt) const;
const Option& lookup_long_opt(const std::string& opt) const;
void handle_short_opt(const std::string& opt, const std::string& arg);
void handle_long_opt(const std::string& optstr);
void process_opt(const Option& option, const std::string& opt, const std::string& value);
std::string format_usage(const std::string& u) const;
std::string _usage;
std::string _version;
bool _add_help_option;
bool _add_version_option;
std::string _prog;
std::string _epilog;
bool _interspersed_args;
Values _values;
strMap _defaults;
std::list<OptionGroup const*> _groups;
std::list<std::string> _remaining;
std::list<std::string> _leftover;
friend class Option;
};
class OptionGroup : public OptionContainer {
public:
MB_API
OptionGroup(const ArgumentParser& p, const std::string& t, const std::string& d = "") :
OptionContainer(d), _parser(p), _title(t) {}
MB_API
virtual ~OptionGroup() {}
MB_API
OptionGroup& title(const std::string& t) { _title = t; return *this; }
MB_API
const std::string& title() const { return _title; }
private:
const ArgumentParser& get_parser() { return _parser; }
const ArgumentParser& _parser;
std::string _title;
friend class ArgumentParser;
};
class Option {
public:
MB_API
Option(const ArgumentParser& p) :
_parser(p), _action("store"), _type("string"), _nargs(1), _callback(0) {}
MB_API
virtual ~Option() {}
MB_API
Option& action(const std::string& a);
MB_API
Option& type(const std::string& t);
MB_API
Option& dest(const std::string& d) { _dest = d; return *this; }
MB_API
Option& set_default(const std::string& d) { _default = d; return *this; }
template<typename T>
Option& set_default(T t) { std::ostringstream ss; ss << t; _default = ss.str(); return *this; }
MB_API
Option& nargs(size_t n) { _nargs = n; return *this; }
MB_API
Option& set_const(const std::string& c) { _const = c; return *this; }
template<typename InputIterator>
Option& choices(InputIterator begin, InputIterator end) {
_choices.assign(begin, end); type("choice"); return *this;
}
#if __cplusplus >= 201103L
MB_API
Option& choices(std::initializer_list<std::string> ilist) {
_choices.assign(ilist); type("choice"); return *this;
}
#endif
MB_API
Option& help(const std::string& h) { _help = h; return *this; }
MB_API
Option& metavar(const std::string& m) { _metavar = m; return *this; }
MB_API
Option& callback(Callback& c) { _callback = &c; return *this; }
const std::string& action() const { return _action; }
MB_API
const std::string& type() const { return _type; }
MB_API
const std::string& dest() const { return _dest; }
MB_API
const std::string& get_default() const;
MB_API
size_t nargs() const { return _nargs; }
MB_API
const std::string& get_const() const { return _const; }
MB_API
const std::list<std::string>& choices() const { return _choices; }
MB_API
const std::string& help() const { return _help; }
MB_API
const std::string& metavar() const { return _metavar; }
MB_API
Callback* callback() const { return _callback; }
private:
std::string check_type(const std::string& opt, const std::string& val) const;
std::string format_option_help(unsigned int indent = 2) const;
std::string format_help(unsigned int indent = 2) const;
const ArgumentParser& _parser;
std::set<std::string> _short_opts;
std::set<std::string> _long_opts;
std::string _action;
std::string _type;
std::string _dest;
std::string _default;
size_t _nargs;
std::string _const;
std::list<std::string> _choices;
std::string _help;
std::string _metavar;
Callback* _callback;
friend class OptionContainer;
friend class ArgumentParser;
};
class Callback {
public:
MB_API
virtual void operator() (const Option& option, const std::string& opt, const std::string& val, const ArgumentParser& parser) = 0;
MB_API
virtual ~Callback() {}
};
}
#endif /* __MB__ARGUMENT_PARSER__ */
| 30.035897 | 138 | 0.693188 | [
"vector"
] |
e386e35337ba6f4a8643b7be8b1941126b70ae34 | 7,454 | cpp | C++ | src/ConstraintFactory.cpp | nandofioretto/gpuMPE | 875fcae5eb37194fef6bc36441296dc7f67c9439 | [
"MIT"
] | 1 | 2018-06-27T11:39:41.000Z | 2018-06-27T11:39:41.000Z | src/ConstraintFactory.cpp | nandofioretto/gpuMPE | 875fcae5eb37194fef6bc36441296dc7f67c9439 | [
"MIT"
] | null | null | null | src/ConstraintFactory.cpp | nandofioretto/gpuMPE | 875fcae5eb37194fef6bc36441296dc7f67c9439 | [
"MIT"
] | null | null | null | #include <string>
#include <sstream>
#include <rapidxml.hpp>
#include <iterator>
#include <vector>
#include "string_utils.hpp"
#include "ConstraintFactory.hpp"
#include "Assert.hpp"
#include "Types.hpp"
#include "Agent.hpp"
#include "Variable.hpp"
#include "TableConstraint.hpp"
#include "Utils/Permutation.hpp" // used in UAI parsing
using namespace rapidxml;
using namespace misc_utils;
using namespace std;
// Initializes static members
int ConstraintFactory::constraintsCt = 0;
// It constructs and returns a new constraint.
Constraint::ptr ConstraintFactory::create(xml_node<>* conXML,
xml_node<>* relsXML,
vector<Agent::ptr> agents,
vector<Variable::ptr> variables)
{
string name = conXML->first_attribute("name")->value();
string rel = conXML->first_attribute("reference")->value();
// Retrieve the relation associated to this constraint:
int size = atoi(relsXML->first_attribute("nbRelations")->value());
ASSERT(size > 0, "No Relation associated to constraint " << name);
xml_node<>* relXML = relsXML->first_node("relation");
while (rel.compare(relXML->first_attribute("name")->value()) != 0)
{
relXML = relXML->next_sibling();
ASSERT(relXML, "No Relation associated to constraint " << name);
}
// Proces constraints according to their type.
string semantics = relXML->first_attribute("semantics")->value();
auto c = createTableConstraint(conXML, relXML, variables);
setProperties(c, name, agents);
++constraintsCt;
return c;
}
// Jul 5, ok
void ConstraintFactory::setProperties
(Constraint::ptr c, string name, vector<Agent::ptr> agents)
{
c->setID(constraintsCt);
c->setName(name);
// Registers this constraint in the agents owning the variables of the
// constraint scope.
for (auto v : c->getScope())
{
Agent::ptr v_owner = nullptr;
for (auto a : agents) if( a->getID() == v->getAgtID() ) { v_owner = a; }
ASSERT(v_owner, "Error in finding variable owner\n");
v_owner->addConstraint( c );
}
}
// Jul 5, ok
std::vector<Variable::ptr> ConstraintFactory::getScope
(xml_node<>* conXML, std::vector<Variable::ptr> variables)
{
int arity = atoi(conXML->first_attribute("arity")->value());
// Read constraint scope
string p_scope = conXML->first_attribute("scope")->value();
std::vector<Variable::ptr> scope(arity, nullptr);
stringstream ss(p_scope); int c = 0; string var;
while( c < arity )
{
ss >> var;
Variable::ptr v_target = nullptr;
for (auto& v : variables)
if( v->getName().compare(var) == 0 )
v_target = v;
ASSERT(v_target, "Error in retrieving scope of constraint\n");
scope[ c++ ] = v_target;
}
return scope;
}
// Jul 5, ok
TableConstraint::ptr ConstraintFactory::createTableConstraint
(xml_node<>* conXML, xml_node<>* relXML,
std::vector<Variable::ptr> variables)
{
// Read Relation Properties
string name = relXML->first_attribute("name")->value();
int arity = atoi( relXML->first_attribute("arity")->value() );
size_t nb_tuples = atoi( relXML->first_attribute("nbTuples")->value() );
ASSERT( nb_tuples > 0, "Extensional Soft Constraint " << name << " is empty");
// Okey works
std::vector<Variable::ptr> scope = getScope( conXML, variables );
// Get the default cost
util_t def_cost = Constants::worstvalue;
if (relXML->first_attribute("defaultCost"))
{
string cost = relXML->first_attribute("defaultCost")->value();
if (cost.compare("infinity") == 0 )
def_cost = Constants::inf;
else if( cost.compare("-infinity") == 0 )
def_cost = -Constants::inf;
else
def_cost = std::stod(cost);
}
auto con = std::make_shared<TableConstraint>(scope, def_cost);
string content = relXML->value();
size_t lhs = 0, rhs = 0;
// replace all the occurrences of 'infinity' with a 'INFTY'
while (true)
{
rhs = content.find("infinity", lhs);
if (rhs != string::npos)
content.replace( rhs, 8, to_string(Constants::inf) );
else break;
};
// replace all the occurrences of ':' with a '\b'
// cost_t best_bound = Constants::worstvalue;
// cost_t worst_bound = Constants::bestvalue;
util_t m_cost; bool multiple_cost;
int* tuple = new int[ arity ];
int trim_s, trim_e;
size_t count = 0;
string str_tuples;
lhs = 0;
while (count < nb_tuples)
{
//multiple_cost = true;
rhs = content.find(":", lhs);
if (rhs < content.find("|", lhs))
{
if (rhs != string::npos)
{
m_cost = atoi( content.substr(lhs, rhs).c_str() );
// Keep track of the best/worst bounds
// best_bound = Utils::getBest(m_cost, best_bound);
// worst_bound = Utils::getWorst(m_cost, worst_bound);
lhs = rhs + 1;
}
}
rhs = content.find("|", lhs);
trim_s = lhs, trim_e = rhs;
lhs = trim_e+1;
if (trim_e == string::npos) trim_e = content.size();
else while (content[ trim_e-1 ] == ' ') trim_e--;
str_tuples = content.substr( trim_s, trim_e - trim_s );
str_tuples = strutils::rtrim(str_tuples);
stringstream ss( str_tuples );
//int tmp;
while( ss.good() )
{
for (int i = 0; i < arity; ++i) {
// ss >> tmp;
// tuple[ i ] = scope[ i ]->getDomain().get_pos( tmp );
ss >> tuple[ i ];
}
std::vector<value_t> v(tuple, tuple + arity);
con->setUtil( v, m_cost );
count++;
}
}
// con->setBestCost(best_bound);
// con->setWorstCost(worst_bound);
delete[] tuple;
return con;
}
// For WCSPs
Constraint::ptr
ConstraintFactory::create(size_t nTuples, util_t defCost, util_t ub,
string content,
vector<int> scopeIDs,
vector<Agent::ptr> agents,
vector<Variable::ptr> variables)
{
vector<Variable::ptr> scope = getScope(scopeIDs, variables);
auto con = make_shared<TableConstraint>(scope, defCost);
int arity = scopeIDs.size();
util_t util;
std::stringstream data(content);
// Read tuples
for (int l=0; l<nTuples; l++) { // lines
std::vector<value_t> tuple(arity);
for (int i=0; i<arity; i++)
data >> tuple[i];
data >> util;
// if (util >= ub) util = Constants::unsat;
con->setUtil(tuple, util);
}
string name = "c_";
for (auto id : scopeIDs) name += to_string(id);
setProperties(con, name, agents);
++constraintsCt;
return con;
}
// For UAI
Constraint::ptr ConstraintFactory::create(std::vector<util_t> entries,
vector<int> scopeIDs,
vector<Agent::ptr> agents,
vector<Variable::ptr> variables)
{
vector<Variable::ptr> scope = getScope(scopeIDs, variables);
auto con = make_shared<TableConstraint>(scope, 0);
int arity = scopeIDs.size();
util_t util;
std::vector<value_t> domMax;
for (auto v : scope) {
domMax.push_back(v->getMax());
}
combinatorics::Permutation<value_t> perm(domMax);
ASSERT(entries.size() == perm.size(), "Probability values and scope size differ: "
<< entries.size() << " / " << perm.size() << " constr NO: " << constraintsCt );
for (int e = 0; e < entries.size(); e++) { // entries
auto tuple = perm.getPermutations()[e];
con->setUtil(tuple, entries[e]);
}
string name = "c_";
for (auto id : scopeIDs) name += to_string(id);
setProperties(con, name, agents);
++constraintsCt;
return con;
}
std::vector<Variable::ptr>
ConstraintFactory::getScope(vector<int> scopeIDs,
vector<Variable::ptr> variables)
{
vector<Variable::ptr> ret;
for (auto id : scopeIDs) {
for (auto vptr : variables) {
if (vptr->getAgtID() == id) {
ret.push_back(vptr);
break;
}
}
}
return ret;
}
| 25.972125 | 88 | 0.653743 | [
"vector"
] |
e38ec80f474397039c3a06d8cfc7bb9c14f5b548 | 530 | cc | C++ | poj/2/2218.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | poj/2/2218.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | poj/2/2218.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string msg;
while (cin >> msg) {
vector<pair<int,string> > v;
string name;
while (cin >> name && name != "END") {
int days, weight;
cin >> days >> weight;
v.push_back(make_pair(weight-days, name));
}
sort(v.rbegin(), v.rend());
for (vector<pair<int,string> >::const_iterator it = v.begin(); it != v.end(); ++it) {
cout << it->second << endl;
}
cout << endl;
}
return 0;
}
| 21.2 | 89 | 0.556604 | [
"vector"
] |
e3912149a6e3cb6f5758f4b693c2973817614d9b | 2,901 | cpp | C++ | test/test-from-sources.cpp | mindastray/lincxx | 13fa45b9c6bc77ed77c0e5ae7b6cdffa937ace1f | [
"MIT"
] | null | null | null | test/test-from-sources.cpp | mindastray/lincxx | 13fa45b9c6bc77ed77c0e5ae7b6cdffa937ace1f | [
"MIT"
] | null | null | null | test/test-from-sources.cpp | mindastray/lincxx | 13fa45b9c6bc77ed77c0e5ae7b6cdffa937ace1f | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <lincxx.hpp>
#include <vector>
#include "test_tools.h"
class test_from_sources : public ::testing::Test {
protected:
struct test_struct_deep {
std::string x;
};
struct test_struct {
int id;
bool select;
test_struct_deep ref;
inline int calculate_stuffs() { return id * 2; }
inline bool operator == (const test_struct & v) const {
return
id == v.id &&
select == v.select &&
ref.x == v.ref.x;
}
};
// data ---
static int source_array_int [];
static test_struct source_array_struct [];
static std::vector < int > source_vector_int;
static const int source_const_array_int [];
static const test_struct source_const_array_struct[];
static const std::vector < int > source_const_vector_int;
// --------
virtual void SetUp () {}
virtual void TearDown () {}
};
int test_from_sources::source_array_int [] = { 8, 5, 7, 8, 2, 5, 6, 3, 3, 7, 2, 4, 1 };
test_from_sources::test_struct test_from_sources::source_array_struct [] = { { 2, true, { "A" } }, { 7, false, { "A" } }, { 12, false, { "A" } }, { 5, true, { "B" } }, { 1, true, { "A" } }, { 2, false, { "A" } }, { 72, false, { "A" } }, { 1, true, { "B" } }, { 5, true, { "A" } }, { 8, true, { "A" } }, { 1, true, { "A" } } };
std::vector < int > test_from_sources::source_vector_int = { 8, 5, 7, 8, 2, 5, 6, 3, 3, 7, 2, 4, 1 };
const int test_from_sources::source_const_array_int[] = { 8, 5, 7, 8, 2, 5, 6, 3, 3, 7, 2, 4, 1 };
const test_from_sources::test_struct test_from_sources::source_const_array_struct[] = { { 2, true, { "A" } }, { 7, false, { "A" } }, { 12, false, { "A" } }, { 5, true, { "B" } }, { 1, true, { "A" } }, { 2, false, { "A" } }, { 72, false, { "A" } }, { 1, true, { "B" } }, { 5, true, { "A" } }, { 8, true, { "A" } }, { 1, true, { "A" } } };
const std::vector < int > test_from_sources::source_const_vector_int = { 8, 5, 7, 8, 2, 5, 6, 3, 3, 7, 2, 4, 1 };
template < class source_type >
inline void test_source (source_type & source) {
using namespace lincxx;
using namespace lincxx_test;
auto query = from (source);
size_t query_count = 0;
for (auto v : query) {
ASSERT_EQ (v, source [query_count]);
++query_count;
}
ASSERT_EQ (source_size (source), query_count);
}
TEST_F (test_from_sources, from_array_fundamental_type) {
test_source (source_array_int);
}
TEST_F(test_from_sources, from_array_structs) {
test_source (source_array_struct);
}
TEST_F(test_from_sources, from_vector_fundamental_type) {
test_source (source_vector_int);
}
TEST_F(test_from_sources, from_const_array_fundamental_type) {
test_source (source_const_array_int);
}
TEST_F(test_from_sources, from_const_array_structs) {
test_source (source_const_array_struct);
}
TEST_F(test_from_sources, from_const_vector_fundamental_type) {
test_source (source_const_vector_int);
}
TEST_F(test_from_sources, from_query) {
test_source (source_vector_int);
} | 30.21875 | 337 | 0.64495 | [
"vector"
] |
e392dc9ab9a6c3200956262c1f47babd3f4fef50 | 481 | cpp | C++ | src/treedelegate.cpp | alechaka/cognat | affd9f41cd1517eaf85c7c1860673e78685b15e1 | [
"MIT"
] | null | null | null | src/treedelegate.cpp | alechaka/cognat | affd9f41cd1517eaf85c7c1860673e78685b15e1 | [
"MIT"
] | null | null | null | src/treedelegate.cpp | alechaka/cognat | affd9f41cd1517eaf85c7c1860673e78685b15e1 | [
"MIT"
] | null | null | null | #include "treedelegate.h"
TreeDelegate::TreeDelegate(const int &width, const int &height, QObject *parent)
: QItemDelegate(parent)
{
this->width = width;
this->height = height;
}
QSize TreeDelegate::sizeHint(const QStyleOptionViewItem & /*option*/, const QModelIndex &index) const
{
bool DomainOrGi = index.model()->data(index, Qt::SizeHintRole).toBool();
if (DomainOrGi) {
return QSize(width, height);
}
return QSize(width, height * 0.55);
}
| 26.722222 | 101 | 0.679834 | [
"model"
] |
e3937cbe319cccb5125d39e633142c68d338beb3 | 2,121 | cpp | C++ | blockware/curvy-snake/lib/CurvySnake/CurvySnake.cpp | jcasts/blocks-with-screens | 024e8336905bb41a56b943ce137b324d397d9dc7 | [
"MIT"
] | 24 | 2020-11-18T19:16:06.000Z | 2022-02-24T05:27:59.000Z | blockware/curvy-snake/lib/CurvySnake/CurvySnake.cpp | jcasts/blocks-with-screens | 024e8336905bb41a56b943ce137b324d397d9dc7 | [
"MIT"
] | 8 | 2021-11-14T16:18:52.000Z | 2021-11-29T19:56:05.000Z | blockware/curvy-snake/lib/CurvySnake/CurvySnake.cpp | jcasts/blocks-with-screens | 024e8336905bb41a56b943ce137b324d397d9dc7 | [
"MIT"
] | 6 | 2021-03-16T23:13:10.000Z | 2021-11-24T01:40:48.000Z | #include <Adafruit_SSD1351.h>
#include <algorithm>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include "CurvySnake.h"
#include <Colors.h>
#include <Entity.h>
#include <Random.h>
extern Adafruit_SSD1351 tft;
// in-memory 16-bit canvas
GFXcanvas16* canvas;
int screenWidth = -1;
int screenHeight = -1;
// used by CurvySnake_loop for tick frequency
const int FPS = floor(1000 / 60); // every ~16ms (60fps)
// track last run time in ms for CurvySnake_loop
uint16_t lastLoop = millis() - FPS + 1;
const int TOTAL_ENTITIES = 5;
// state
std::vector<Entity> entities;
void flush()
{
tft.drawRGBBitmap(0, 0, (uint16_t*)canvas->getBuffer(), screenWidth, screenHeight);
// tft.startWrite();
// SPI.writeBytes((uint8_t *)canvas->getBuffer(), 128 * 128 * 2);
// tft.endWrite();
}
void tick()
{
// reset screen to black
canvas->fillScreen(BLACK);
// canvas->drawPixel(pos.x, pos.y, BLACK);
// for all entities
for (std::size_t i = 0, max = entities.size(); i != max; i++) {
Entity* e = &entities[i];
e->tick();
// e->debug();
e->draw(canvas);
}
}
void CurvySnake_setup()
{
// save dimensions
screenWidth = tft.width();
screenHeight = tft.height();
// initialize canvas to all black
canvas = new GFXcanvas16(screenWidth, screenHeight);
canvas->fillScreen(BLACK);
flush();
// create entities
for (int i = 0; i != TOTAL_ENTITIES; i++) {
entities.push_back(Entity(screenWidth, screenHeight));
}
Serial.printf("\nFPS=%d", FPS);
Serial.printf("\nEntities[%d]", entities.size());
Serial.printf("\nEntity sizeof=%d", sizeof(entities[0]));
Serial.printf("\n");
// Serial.printf("\n%d -- %d\n", RGB565(255, 0, 0), RED);
// Serial.printf("\n%d -- %d\n", RGB565(0, 255, 0), GREEN);
// Serial.printf("\n%d -- %d\n", RGB565(0, 0, 255), BLUE);
}
void CurvySnake_loop()
{
uint16_t now = millis();
uint16_t time = now - lastLoop;
if (time > FPS) {
// track loop millis to keep steady fps
lastLoop = now;
// run!
tick();
// flush our in-memory canvas to the screen
flush();
}
}
| 22.09375 | 85 | 0.637435 | [
"vector"
] |
e398236c6e87ee4c44542eac338ebf9e5d91a396 | 15,734 | cpp | C++ | DemoApps/GLES3/ParticleSystem/source/ParticleSystemBasicScene.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 3 | 2019-01-19T20:21:24.000Z | 2021-08-10T02:11:32.000Z | DemoApps/GLES3/ParticleSystem/source/ParticleSystemBasicScene.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoApps/GLES3/ParticleSystem/source/ParticleSystemBasicScene.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2021-08-10T02:11:33.000Z | 2021-08-10T02:11:33.000Z | /****************************************************************************************************************************************************
* Copyright (c) 2015 Freescale Semiconductor, 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 Freescale Semiconductor, 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************************************************************************************/
#include <FslDemoApp/Base/Service/Graphics/IGraphicsService.hpp>
#include <FslBase/Math/MathHelper.hpp>
#include <FslGraphics/Vertices/VertexPositionTexture.hpp>
#include <FslGraphics/Vertices/VertexPositionColorTexture.hpp>
#include <FslGraphics/Font/BasicFontKerning.hpp>
#include <FslGraphics/Render/AtlasFont.hpp>
#include <FslGraphics/TextureAtlas/BasicTextureAtlas.hpp>
#include <FslGraphics/TextureAtlas/TextureAtlasHelper.hpp>
#include <FslUtil/OpenGLES3/GLUtil.hpp>
#include <FslUtil/OpenGLES3/Exceptions.hpp>
#include <FslUtil/OpenGLES3/GLCheck.hpp>
#include <FslUtil/OpenGLES3/NativeBatch2D.hpp>
#include <FslSimpleUI/Base/IWindowManager.hpp>
#include <FslSimpleUI/Base/WindowContext.hpp>
#include <FslSimpleUI/Base/Control/CheckBox.hpp>
#include <FslSimpleUI/Base/Control/Label.hpp>
#include <FslSimpleUI/Base/Control/SliderAndValueLabel.hpp>
#include <FslSimpleUI/Base/Control/ValueLabel.hpp>
#include <FslSimpleUI/Base/Event/WindowContentChangedEvent.hpp>
#include <FslSimpleUI/Base/Event/WindowSelectEvent.hpp>
#include <FslSimpleUI/Base/Layout/FillLayout.hpp>
#include <FslSimpleUI/Base/Layout/StackLayout.hpp>
#include "ParticleSystemBasicScene.hpp"
#include "PS/Draw/ParticleDrawPointsGLES3.hpp"
#include "PS/Draw/ParticleDrawQuadsGLES3.hpp"
#include "PS/Draw/ParticleDrawGeometryShaderGLES3.hpp"
#include "PS/Emit/BoxEmitter.hpp"
#include "PS/ParticleSystemOneArray.hpp"
#include "PS/ParticleSystemTwoArrays.hpp"
#include "PSGpu/ParticleSystemGLES3.hpp"
#include "PSGpu/ParticleSystemSnow.hpp"
#include <GLES3/gl3.h>
#include <iostream>
namespace Fsl
{
using namespace GLES3;
using namespace UI;
namespace
{
const uint32_t PARTICLE_CAPACITY = 4;
const float DEFAULT_ZOOM = 32;
void BuildCube(GLVertexBuffer& rDst, const Vector3 dimensions)
{
// 0-3 0 0-3
// |\| |\ \|
// 1-2 1-2 2
const float x = dimensions.X * 0.5f;
const float y = dimensions.Y * 0.5f;
const float z = dimensions.Z * 0.5f;
VertexPositionColorTexture vertices[6 * 6] =
{
// Front
VertexPositionColorTexture(Vector3(-x, +y, +z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(-x, -y, +z), Color::White(), Vector2(0, 0)),
VertexPositionColorTexture(Vector3(+x, -y, +z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(-x, +y, +z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(+x, -y, +z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(+x, +y, +z), Color::White(), Vector2(1, 1)),
// Back
VertexPositionColorTexture(Vector3(-x, +y, -z), Color::White(), Vector2(1, 1)),
VertexPositionColorTexture(Vector3(+x, -y, -z), Color::White(), Vector2(0, 0)),
VertexPositionColorTexture(Vector3(-x, -y, -z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(-x, +y, -z), Color::White(), Vector2(1, 1)),
VertexPositionColorTexture(Vector3(+x, +y, -z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(+x, -y, -z), Color::White(), Vector2(0, 0)),
// Right
VertexPositionColorTexture(Vector3(+x, +y, +z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(+x, -y, +z), Color::White(), Vector2(0, 0)),
VertexPositionColorTexture(Vector3(+x, -y, -z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(+x, +y, +z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(+x, -y, -z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(+x, +y, -z), Color::White(), Vector2(1, 1)),
// Left
VertexPositionColorTexture(Vector3(-x, +y, -z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(-x, -y, -z), Color::White(), Vector2(0, 0)),
VertexPositionColorTexture(Vector3(-x, -y, +z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(-x, +y, -z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(-x, -y, +z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(-x, +y, +z), Color::White(), Vector2(1, 1)),
// Top
VertexPositionColorTexture(Vector3(-x, +y, -z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(-x, +y, +z), Color::White(), Vector2(0, 0)),
VertexPositionColorTexture(Vector3(+x, +y, +z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(-x, +y, -z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(+x, +y, +z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(+x, +y, -z), Color::White(), Vector2(1, 1)),
// Bottom
VertexPositionColorTexture(Vector3(-x, -y, +z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(-x, -y, -z), Color::White(), Vector2(0, 0)),
VertexPositionColorTexture(Vector3(+x, -y, -z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(-x, -y, +z), Color::White(), Vector2(0, 1)),
VertexPositionColorTexture(Vector3(+x, -y, -z), Color::White(), Vector2(1, 0)),
VertexPositionColorTexture(Vector3(+x, -y, +z), Color::White(), Vector2(1, 1)),
};
rDst.Reset(vertices, 6 * 6, GL_STATIC_DRAW);
}
}
ParticleSystemBasicScene::ParticleSystemBasicScene(const DemoAppConfig& config, const std::shared_ptr<UIDemoAppExtension>& uiExtension)
: AScene(config)
, m_graphics(config.DemoServiceProvider.Get<IGraphicsService>())
, m_allowAdvancedTechniques(false)
, m_camera(config.ScreenResolution)
, m_program()
, m_vbCube()
, m_texParticle()
, m_texCube()
, m_particleSystem()
, m_locWorldViewMatrix(GLValues::INVALID_LOCATION)
, m_locProjMatrix(GLValues::INVALID_LOCATION)
, m_particleDrawContext()
, m_rotation()
, m_rotationSpeed(0.0f, 0.5f, 0.0f)
, m_rotate(false)
, m_particleSystemType(ParticleSystemType::GeometryShader)
{
m_camera.SetZoom(DEFAULT_ZOOM);
auto contentManager = GetContentManager();
m_allowAdvancedTechniques = GLUtil::HasExtension("GL_EXT_geometry_shader");
if (m_allowAdvancedTechniques)
{
m_particleSystemGpu2 = std::make_shared<ParticleSystemSnow>(PARTICLE_CAPACITY, contentManager, Vector3(5, 5, 5), 0.8f);
}
SetParticleSystem(m_particleSystemType, true);
BuildCube(m_vbCube, Vector3(1, 1, 1));
{ // Load the textures
GLTextureParameters textureParams(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT);
Bitmap bitmap;
contentManager->Read(bitmap, "Particle.png", PixelFormat::R8G8B8A8_UNORM);
m_texParticle.Reset(bitmap, textureParams, TextureFlags::GenerateMipMaps);
contentManager->Read(bitmap, "ParticleSnow.png", PixelFormat::R8G8B8_UNORM);
m_texParticleSnow.Reset(bitmap, textureParams, TextureFlags::GenerateMipMaps);
contentManager->Read(bitmap, "GTEC.png", PixelFormat::R8G8B8_UNORM);
m_texCube.Reset(bitmap, textureParams, TextureFlags::GenerateMipMaps);
}
{ // Prepare the default program
m_program.Reset(contentManager->ReadAllText("Shader.vert"), contentManager->ReadAllText("Shader.frag"));
const GLuint hProgram = m_program.Get();
auto vertexDecl = VertexPositionColorTexture::GetVertexDeclaration();
m_cubeAttribLink[0] = GLVertexAttribLink(glGetAttribLocation(hProgram, "VertexPosition"), vertexDecl.VertexElementGetIndexOf(VertexElementUsage::Position, 0));
m_cubeAttribLink[1] = GLVertexAttribLink(glGetAttribLocation(hProgram, "VertexColor"), vertexDecl.VertexElementGetIndexOf(VertexElementUsage::Color, 0));
m_cubeAttribLink[2] = GLVertexAttribLink(glGetAttribLocation(hProgram, "VertexTexCoord"), vertexDecl.VertexElementGetIndexOf(VertexElementUsage::TextureCoordinate, 0));
m_locWorldViewMatrix = glGetUniformLocation(hProgram, "WorldView");
m_locProjMatrix = glGetUniformLocation(hProgram, "Projection");
}
}
ParticleSystemBasicScene::~ParticleSystemBasicScene()
{
}
void ParticleSystemBasicScene::OnMouseButtonEvent(const MouseButtonEvent& event)
{
if ( event.IsHandled() )
return;
switch (event.GetButton())
{
case VirtualMouseButton::Left:
{
if (event.IsPressed())
m_camera.BeginDrag(event.GetPosition());
else if (m_camera.IsDragging())
m_camera.EndDrag(event.GetPosition());
event.Handled();
}
break;
case VirtualMouseButton::Right:
if (event.IsPressed())
{
m_camera.ResetRotation();
m_camera.SetZoom(DEFAULT_ZOOM);
m_rotation = Vector3();
event.Handled();
}
break;
default:
AScene::OnMouseButtonEvent(event);
break;
}
}
void ParticleSystemBasicScene::OnMouseMoveEvent(const MouseMoveEvent& event)
{
if ( event.IsHandled() )
return;
if (m_camera.IsDragging())
{
m_camera.Drag(event.GetPosition());
event.Handled();
}
}
void ParticleSystemBasicScene::OnMouseWheelEvent(const MouseWheelEvent& event)
{
m_camera.AddZoom(event.GetDelta() * -0.001f);
}
void ParticleSystemBasicScene::Update(const DemoTime& demoTime)
{
if (m_particleSystem)
m_particleSystem->Update(demoTime);
if (m_particleSystemGpu)
m_particleSystemGpu->Update(demoTime);
if (m_particleSystemGpu2)
m_particleSystemGpu2->Update(demoTime);
const Point2 screenResolution = GetScreenResolution();
if (m_rotate)
m_rotation += m_rotationSpeed * demoTime.DeltaTime;
m_particleDrawContext.MatrixWorld = Matrix::CreateRotationX(m_rotation.X) * Matrix::CreateRotationY(m_rotation.Y) * Matrix::CreateRotationZ(m_rotation.Z);
m_particleDrawContext.MatrixView = m_camera.GetViewMatrix();
m_particleDrawContext.MatrixProjection = Matrix::CreatePerspectiveFieldOfView(MathHelper::ToRadians(45.0f), screenResolution.X / (float)screenResolution.Y, 1, 1000.0f);
m_particleDrawContext.MatrixWorldView = m_particleDrawContext.MatrixWorld * m_particleDrawContext.MatrixView;
m_particleDrawContext.MatrixWorldViewProjection = m_particleDrawContext.MatrixWorldView * m_particleDrawContext.MatrixProjection;
m_particleDrawContext.ScreenAspectRatio = GetScreenResolution().X / static_cast<float>(GetScreenResolution().Y);
}
void ParticleSystemBasicScene::Draw()
{
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
//glDisable(GL_CULL_FACE);
glClearColor(0.5f, 0.5f, 0.5f, 0.5f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
DrawCube();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE);
//glBlendFunc(GL_ONE, GL_ONE);
DrawParticles();
glDisable(GL_DEPTH_TEST);
if (m_particleSystemGpu)
m_particleSystemGpu->Draw(m_particleDrawContext);
if (m_particleSystemGpu2)
{
//glBlendFunc(GL_ONE, GL_ONE);
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, m_texParticleSnow.Get());
glBlendFunc(GL_ONE, GL_ONE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_texParticleSnow.Get());
m_particleSystemGpu2->Draw(m_particleDrawContext);
}
}
void ParticleSystemBasicScene::DrawCube()
{
const GLuint hProgram = m_program.Get();
// Set the shader program
glUseProgram(hProgram);
// Load the matrices
glUniformMatrix4fv(m_locWorldViewMatrix, 1, 0, m_particleDrawContext.MatrixWorldView.DirectAccess());
glUniformMatrix4fv(m_locProjMatrix, 1, 0, m_particleDrawContext.MatrixProjection.DirectAccess());
// Select Our Texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_texCube.Get());
// bind the vertex buffer and enable the attrib array
glBindBuffer(m_vbCube.GetTarget(), m_vbCube.Get());
m_vbCube.EnableAttribArrays(m_cubeAttribLink, sizeof(m_cubeAttribLink) / sizeof(GLES3::GLVertexAttribLink));
glDrawArrays(GL_TRIANGLES, 0, m_vbCube.GetCapacity());
}
void ParticleSystemBasicScene::DrawParticles()
{
// Select Our Texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_texParticle.Get());
//glBindTexture(GL_TEXTURE_2D, m_texCube.Get());
if (m_particleSystem)
{
glDepthMask(false);
m_particleSystem->Draw(m_particleDrawContext);
glDepthMask(true);
}
}
void ParticleSystemBasicScene::SetParticleSystem(const ParticleSystemType type, const bool force)
{
if (type == m_particleSystemType && !force)
return;
m_particleSystemType = type;
m_particleSystem.reset();
std::shared_ptr<IParticleDraw> particleDraw;
auto typeEx = type;
if (typeEx == ParticleSystemType::GeometryShader && !m_allowAdvancedTechniques)
typeEx = ParticleSystemType::Instancing;
switch (typeEx)
{
case ParticleSystemType::Points:
particleDraw = std::make_shared<ParticleDrawPointsGLES3>(GetContentManager(), PARTICLE_CAPACITY, ParticleSystemOneArray::SIZE_PARTICLE_RECORD);
break;
case ParticleSystemType::GeometryShader:
particleDraw = std::make_shared<ParticleDrawGeometryShaderGLES3>(GetContentManager(), PARTICLE_CAPACITY, ParticleSystemOneArray::SIZE_PARTICLE_RECORD);
break;
case ParticleSystemType::Instancing:
default:
particleDraw = std::make_shared<ParticleDrawQuadsGLES3>(GetContentManager(), PARTICLE_CAPACITY);
break;
}
if (particleDraw)
{
m_particleSystem = std::make_shared<ParticleSystemOneArray>(particleDraw, PARTICLE_CAPACITY);
m_boxEmitter.reset(new BoxEmitter());
m_particleSystem->AddEmitter(m_boxEmitter);
}
}
}
| 39.732323 | 174 | 0.698742 | [
"render"
] |
e39883a12c6d11ff914fcf5e54f6a5370b365c01 | 683 | cpp | C++ | pgm07_17.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | 1 | 2021-07-13T03:58:36.000Z | 2021-07-13T03:58:36.000Z | pgm07_17.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | pgm07_17.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | //
// This file contains the C++ code from Program 7.17 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm07_17.cpp
//
void ListAsLinkedList::Withdraw (Position const& arg)
{
Pos const& position = dynamic_cast<Pos const&> (arg);
if (count == 0)
throw domain_error ("list is empty");
if (&position.list != this || position.element == 0)
throw invalid_argument ("invalid position");
linkedList.Extract (position.element->Datum ());
--count;
}
| 29.695652 | 80 | 0.670571 | [
"object"
] |
e39b531fea7ef9442f98c29393853faa8fd3ce3a | 15,585 | hpp | C++ | modules/umfcore/include/umf/metadatastream.hpp | intel/umf | 3103e3b0ab63a0f60f4d8d83ebf4dc39a61552aa | [
"Apache-2.0"
] | 13 | 2018-01-23T22:05:21.000Z | 2020-04-21T15:19:29.000Z | modules/umfcore/include/umf/metadatastream.hpp | intel/umf | 3103e3b0ab63a0f60f4d8d83ebf4dc39a61552aa | [
"Apache-2.0"
] | 10 | 2015-08-25T22:20:23.000Z | 2016-06-08T10:13:26.000Z | modules/umfcore/include/umf/metadatastream.hpp | 01org/vmf | 3103e3b0ab63a0f60f4d8d83ebf4dc39a61552aa | [
"Apache-2.0"
] | 10 | 2015-11-16T14:19:31.000Z | 2016-08-18T21:44:07.000Z | /*
* Copyright 2015 Intel(r) Corporation
*
* 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 metadatastream.hpp
* \brief %MetadataStream class header file
*/
#pragma once
#ifndef __METADATA_STREAM_H__
#define __METADATA_STREAM_H__
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4251)
#endif
#include "umf/global.hpp"
#include "umf/metadatainternal.hpp"
#include "umf/metadataset.hpp"
#include "umf/metadataschema.hpp"
#include "umf/compressor.hpp"
#include "umf/encryptor.hpp"
#include "umf/iquery.hpp"
#include "umf/statistics.hpp"
#include <map>
#include <memory>
#include <vector>
#include <algorithm>
namespace umf
{
class IDataSource;
class IReader;
class IWriter;
class Format;
/*!
* \class MetadataStream
* \brief %MetadataStream provides functionality to read/write
* metadata to media file
*/
class UMF_EXPORT MetadataStream : public IQuery
{
public:
/*!
* \brief File open mode flags
*/
enum OpenModeFlags
{
InMemory = 0, /**< Stream data are in-memory */
ReadOnly = 1, /**< Open file for read only */
Update = 2, /**< Open file for read and write */
IgnoreUnknownCompressor = 4, /**< Represent compressed data as UMF metadata if decompressor is unknown*/
IgnoreUnknownEncryptor = 8 /**< Represent encrypted data as UMF metadata if decryptor is unknown*/
};
typedef int OpenMode;
//static umf::MetadataStream::OpenMode ReadWrite;
/*!
* \class VideoSegment
* \brief The class representing a video segment
*/
class UMF_EXPORT VideoSegment
{
public:
/*!
* \brief Default constructor
*/
VideoSegment();
/*!
* \brief Constructor with all fields
* \param title
* \param fps
* \param timeStart
* \param duration
* \param width
* \param height
*/
VideoSegment( const std::string& title, double fps, long long timeStart,
long long duration = 0, long width = 0, long height = 0 );
~VideoSegment();
std::string getTitle() const;
void setTitle(const std::string& _title);
double getFPS() const;
void setFPS(double fps);
long long getDuration() const;
void setDuration(long long duration);
long long getTime() const;
void setTime(long long timeStart);
void getResolution(long& width, long& height) const;
void setResolution(long width, long height);
private:
std::string title;
double fps;
long long timeStart;
long long duration;
long width;
long height;
};
/*!
* \brief Default class constructor
* \throw NotInitializedException if Video metadata framework library is no initialized
*/
MetadataStream(void);
/*!
* \brief Class destructor
*/
virtual ~MetadataStream(void);
/*!
* \brief Open metadata stream
* \param sFilePath [in] path to media file
* \param eMode [in] open mode
* \return Open result
*/
bool open( const std::string& sFilePath, OpenMode eMode = ReadOnly );
/*!
* \brief Reopen a previously closed metadata stream.
* \param eMode [in] open mode
* \return Open result
*/
bool reopen( OpenMode eMode = ReadOnly );
/*!
* \brief Load metadata with specified scheme
* \param sSchemaName [in] schema name
* \return operation result
* \details The function loads metadata with specified scheme
* or all metadata if schema name is empty string
*/
bool load( const std::string& sSchemaName = "" );
/*!
* \brief Load metadata with specified name from selected schema
* \param sSchemaName [in] schema name
* \param sMetadataName [in] metadata item name
*/
bool load( const std::string& sSchemaName, const std::string& sMetadataName );
/*!
* \brief Save loaded data to media file
* \param compressorId String identifying compression to be used at saving
* (empty string means no compression)
* \return Save operation result
*/
bool save(const umf_string& compressorId = umf_string());
/*!
* \brief Save the in-memory metadata to a different video file.
* \param sFilePath the path of the new file.
* \param compressorId String identifying compression to be used at saving
* (empty string means no compression)
* \return true if succeed.
*/
bool saveTo(const std::string& sFilePath, const umf_string& compressorId = umf_string() );
/*!
* \brief Close previously opened media file
*/
void close();
/*!
* \brief Get metadata by its identifier
* \param id [in] metadata identifier
* \details The function return pointer to metadata with specified id or null pointer if identifier not found
*/
std::shared_ptr< Metadata > getById( const IdType& id ) const;
/*!
* \brief Add new metadata item
* \param spMetadata [in] pointer to metadata object
* \return identifier of added metadata object
* \throw ValidateException if metadata is not valid to selected scheme or description
*/
IdType add( std::shared_ptr< Metadata > spMetadata);
/*!
* \brief Add new metadata item
* \param mdi [in] reference to a MetadataInternal object
* \return ID of added metadata object
* \throw ValidateException if metadata is not valid to selected scheme or description
* \throw IncorrectParamException if metadata with such id is already exists
*/
IdType add(MetadataInternal& mdi);
/*!
* \brief Remove metadata by their id
* \param id [in] metadata identifier
* \return operation result
*/
bool remove( const IdType& id );
/*!
* \brief Remove set of metadata objects
* \param set [in] set of metadata objects
*/
void remove( const MetadataSet& set );
/*!
* \brief Remove schema and all objects in it.
*/
void remove( std::shared_ptr< MetadataSchema > schema );
/*!
* \brief Remove all metadata.
*/
void remove();
/*!
* \brief Add new schema
* \throw NullPointerException if schema pointer is null
* \throw IncorrectParamException if schema name is empty or
* schema already exists
*/
void addSchema( std::shared_ptr< MetadataSchema > spSchema );
/*!
* \brief Alias for %addSchema
*/
void add(std::shared_ptr< MetadataSchema > spSchema)
{ addSchema(spSchema); }
/*!
* \brief Get metadata schema by its name
* \param sSchemaName [in] schema name
* \return pointer to schema object or null if schema not found
*/
const std::shared_ptr< MetadataSchema > getSchema( const std::string& sSchemaName ) const;
/*!
* \brief Get the names of all schemas available in the stream
* \return vector of names of all schemas
*/
std::vector< std::string > getAllSchemaNames() const;
/*!
* \brief Import a set of metadata from a source stream.
* \param srcStream [in] The source stream that contains the source metadata
* \param srcSet [in] The source metadata set to be imported
* \param nTarFrameIndex [in] The frame index in the new video referenced by nSrcFrameIndex
* \param nSrcFrameIndex [in] The frame index of the first video frame to be imported from the source video.
* \param nNumOfFrames [in] Number of video frames that has been imported. If this is FRAME_COUNT_ALL, metadata associated to all video
* frames since nSrcFrameIndex will be imported
* \param pSetFailure [out] Set to receive metadata that failed to import, due to losing of associated frame. If this is null, no
* information about failed metadata will be returned.
* \details This routine should be called after importing a video sequence from a source video. The nTarFrameIndex, nSrcFrameIndex
* and nNumOfFrames parameters should reflect the way how the video was imported.
*/
bool import( MetadataStream& srcStream, MetadataSet& srcSet, long long nTarFrameIndex, long long nSrcFrameIndex, long long nNumOfFrames = FRAME_COUNT_ALL, MetadataSet* pSetFailure = NULL );
/*!
* \brief Get all metadata
* \return set of metadata objects
*/
MetadataSet getAll() const;
/*!
* \brief Unload all metadata from the stream
*/
void clear();
// Assume C++ 11, IQuery interface, seal the interface at this level
MetadataSet query( std::function< bool( const std::shared_ptr<Metadata>& spMetadata )> filter ) const;
MetadataSet queryByReference( std::function< bool( const std::shared_ptr<Metadata>& spMetadata, const std::shared_ptr<Metadata>& spReference )> filter ) const;
MetadataSet queryByFrameIndex( size_t index ) const;
MetadataSet queryByTime( long long startTime, long long endTime ) const;
MetadataSet queryBySchema( const std::string& sSchemaName ) const;
MetadataSet queryByName( const std::string& sName ) const;
MetadataSet queryByNameAndValue( const std::string& sMetadataName, const umf::FieldValue& value ) const;
MetadataSet queryByNameAndFields( const std::string& sMetadataName, const std::vector< umf::FieldValue>& vFields ) const;
MetadataSet queryByReference( const std::string& sReferenceName ) const;
MetadataSet queryByReference( const std::string& sReferenceName, const umf::FieldValue& value ) const;
MetadataSet queryByReference( const std::string& sReferenceName, const std::vector< umf::FieldValue>& vFields ) const;
void sortById()
{
std::sort(m_oMetadataSet.begin(), m_oMetadataSet.end(),
[](const std::shared_ptr<Metadata> &a, const std::shared_ptr<Metadata>& b){ return a->getId() < b->getId(); });
}
/*
* \brief serialized stream in std::string in selected format
*/
std::string serialize(Format& format);
/*
* \brief deserialized stream from std::string in selected format
*/
void deserialize(const std::string& text, Format& format);
/*!
* \brief Compute MD5 digest of media part of the opened file
* \return MD5 checksum in std::string format
*/
std::string computeChecksum();
/*!
* \brief Compute MD5 digest of media part of a file
* This functuion was created for developers purpose and it's a subject to remove,
* so the function is not recommended for using.
* \return MD5 checksum in std::string format
*/
std::string computeChecksum(long long& XMPPacketSize, long long& XMPPacketOffset);
/*!
* \brief Get MD5 digest of media part of opened file
* \return MD5 digest of opened file.
*/
std::string getChecksum() const;
/*!
* \brief Set new MD5 digest to MetadataStream field
* \param checksum [in] MD5 digest in string format
*/
void setChecksum(const std::string& checksum);
/*!
* \brief Add new video segment
* \throw IncorrectParamException when input segment intersected with anyone of already created segments.
*/
void addVideoSegment(std::shared_ptr<VideoSegment> newSegment);
/*!
* \brief Alias for %addVideoSegment
*/
void add(std::shared_ptr<VideoSegment> newSegment)
{ addVideoSegment(newSegment); }
/*!
* \brief Get vector of video segments that were set for the video
*/
std::vector<std::shared_ptr<VideoSegment>>& getAllVideoSegments();
/*!
* \brief Convert a pair timestamp - duration to a pair frame index - number of frames
*/
void convertTimestampToFrameIndex(
long long timestamp, long long duration,
long long& frameIndex, long long& numOfFrames );
/*!
* \brief Convert a pair frame index - number of frames to a pair timestamp - duration
*/
void convertFrameIndexToTimestamp(
long long frameIndex, long long numOfFrames,
long long& timestamp, long long& duration );
/*!
* \brief Check if the encryption of the whole metadata is enabled or not
* \return encryption status
*/
bool getUseEncryption() const;
/*!
* \brief Enables or disables the encryption of the whole data at saving or
* \param useEncryption
*/
void setUseEncryption(bool useEncryption);
/*!
* \brief Gets the Encryptor instance to be used at saving or serialization
* \return the instance of Encryptor
*/
std::shared_ptr<Encryptor> getEncryptor() const;
/*!
* \brief Sets the instance of Encryptor to be used at saving or serialization
* \param encryptor
*/
void setEncryptor(std::shared_ptr<Encryptor> encryptor);
/*!
* \brief Add new statistics object (copy semantics).
* \param stat [in] statistics object to add
* \throw IncorrectParamException if such statistics object already exist
*/
void addStat(std::shared_ptr<Stat> stat);
/*!
* \brief Alias for %addStat
*/
void add(std::shared_ptr<Stat> stat)
{ addStat(stat); }
/*!
* \brief Get statistics object by its name
* \param name [in] statistics object name
* \return Statistics object (reference to)
* \throw NotFoundException if such statistics object not exist
*/
std::shared_ptr<Stat> getStat(const std::string& name) const;
/*!
* \brief Get names of all statistics objects
* \return Statistics object names (vector of)
*/
std::vector< std::string > getAllStatNames() const;
/*!
* \brief Clear statistics and re-calculates it again using all the existing metadata items
*/
void recalcStat();
protected:
/*!
* \brief Notify statistics object(s) about statistics-related events
* \param action [in] action
* \param spMetadata [in] pointer to metadata object
*/
void notifyStat(std::shared_ptr< Metadata > spMetadata, Stat::Action::Type action = Stat::Action::Add);
void dataSourceCheck();
std::shared_ptr<Metadata> import( MetadataStream& srcStream, std::shared_ptr< Metadata >& spMetadata, std::map< IdType, IdType >& mapIds,
long long nTarFrameIndex, long long nSrcFrameIndex, long long nNumOfFrames = FRAME_COUNT_ALL );
void internalAdd(const std::shared_ptr< Metadata >& spMetadata);
void decrypt();
void encrypt();
private:
OpenMode m_eMode;
std::string m_sFilePath;
MetadataSet m_oMetadataSet;
std::map<IdType, std::vector<std::pair<IdType, std::string>>> m_pendingReferences;
std::map< std::string, std::shared_ptr< MetadataSchema > > m_mapSchemas;
std::map< std::string, std::shared_ptr< MetadataSchema > > removedSchemas;
std::vector<std::shared_ptr<VideoSegment>> videoSegments;
std::vector<IdType> removedIds;
std::vector<IdType> addedIds;
std::shared_ptr<IDataSource> dataSource;
umf::IdType nextId;
std::string m_sChecksumMedia;
bool m_useEncryption;
std::shared_ptr<Encryptor> m_encryptor;
std::string m_hintEncryption;
std::vector< std::shared_ptr<Stat> > m_stats;
};
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif /* __METADATA_STREAM_H__ */
| 32.741597 | 193 | 0.673917 | [
"object",
"vector"
] |
e39c0a6ed06a0854477477361d9245ffb5810a84 | 16,090 | cpp | C++ | provider/src/ocpn-import/Viewport.cpp | free-x/avnav-ocharts-provider | 7df95482d7bcef30f0cb0e1ae538cb9befc30deb | [
"MIT"
] | 1 | 2020-09-10T21:11:10.000Z | 2020-09-10T21:11:10.000Z | provider/src/ocpn-import/Viewport.cpp | free-x/avnav-ocharts-provider | 7df95482d7bcef30f0cb0e1ae538cb9befc30deb | [
"MIT"
] | 15 | 2020-09-10T17:58:35.000Z | 2022-03-08T18:03:08.000Z | provider/src/ocpn-import/Viewport.cpp | free-x/avnav-ocharts-provider | 7df95482d7bcef30f0cb0e1ae538cb9befc30deb | [
"MIT"
] | 2 | 2020-06-18T07:29:05.000Z | 2021-05-07T09:47:59.000Z | #include <math.h>
#include "ocpn_types.h"
#include "georef.h"
#include "dychart.h"
//from chartbase.h
// Projection type enum
typedef enum OcpnProjType
{
PROJECTION_UNKNOWN,
PROJECTION_MERCATOR,
PROJECTION_TRANSVERSE_MERCATOR,
PROJECTION_POLYCONIC
}_OcpnProjType;
static bool g_bCourseUp=false;
static bool g_bskew_comp=false;
//------------------------------------------------------------------------------
// ViewPort Implementation
//------------------------------------------------------------------------------
ViewPort::ViewPort()
{
bValid = false;
skew = 0.;
view_scale_ppm = 1;
rotation = 0.;
b_quilt = false;
pix_height = pix_width = 0;
}
wxPoint ViewPort::GetPixFromLL(double lat, double lon) const
{
double easting, northing;
double xlon = lon;
/* Make sure lon and lon0 are same phase */
if(xlon * clon < 0.)
{
if(xlon < 0.)
xlon += 360.;
else
xlon -= 360.;
}
if(fabs(xlon - clon) > 180.)
{
if(xlon > clon)
xlon -= 360.;
else
xlon += 360.;
}
if(PROJECTION_TRANSVERSE_MERCATOR == m_projection_type)
{
// We calculate northings as referenced to the equator
// And eastings as though the projection point is midscreen.
double tmeasting, tmnorthing;
double tmceasting, tmcnorthing;
toTM(clat, clon, 0., clon, &tmceasting, &tmcnorthing);
toTM(lat, xlon, 0., clon, &tmeasting, &tmnorthing);
// tmeasting -= tmceasting;
// tmnorthing -= tmcnorthing;
northing = tmnorthing - tmcnorthing;
easting = tmeasting - tmceasting;
}
else if(PROJECTION_POLYCONIC == m_projection_type)
{
// We calculate northings as referenced to the equator
// And eastings as though the projection point is midscreen.
double pceasting, pcnorthing;
toPOLY(clat, clon, 0., clon, &pceasting, &pcnorthing);
double peasting, pnorthing;
toPOLY(lat, xlon, 0., clon, &peasting, &pnorthing);
easting = peasting;
northing = pnorthing - pcnorthing;
}
else
toSM(lat, xlon, clat, clon, &easting, &northing);
if(!wxFinite(easting) || !wxFinite(northing))
return wxPoint(0,0);
double epix = easting * view_scale_ppm;
double npix = northing * view_scale_ppm;
double dxr = epix;
double dyr = npix;
// Apply VP Rotation
if(g_bCourseUp)
{
dxr = epix * cos ( rotation ) + npix * sin ( rotation );
dyr = npix * cos ( rotation ) - epix * sin ( rotation );
}
wxPoint r;
// We definitely need a round() function here
r.x = ( int ) wxRound ( ( pix_width / 2 ) + dxr );
r.y = ( int ) wxRound ( ( pix_height / 2 ) - dyr );
return r;
}
wxPoint2DDouble ViewPort::GetDoublePixFromLL(double lat, double lon)
{
double easting, northing;
double xlon = lon;
/* Make sure lon and lon0 are same phase */
if(xlon * clon < 0.)
{
if(xlon < 0.)
xlon += 360.;
else
xlon -= 360.;
}
if(fabs(xlon - clon) > 180.)
{
if(xlon > clon)
xlon -= 360.;
else
xlon += 360.;
}
if(PROJECTION_TRANSVERSE_MERCATOR == m_projection_type)
{
// We calculate northings as referenced to the equator
// And eastings as though the projection point is midscreen.
double tmeasting, tmnorthing;
double tmceasting, tmcnorthing;
toTM(clat, clon, 0., clon, &tmceasting, &tmcnorthing);
toTM(lat, xlon, 0., clon, &tmeasting, &tmnorthing);
// tmeasting -= tmceasting;
// tmnorthing -= tmcnorthing;
northing = tmnorthing - tmcnorthing;
easting = tmeasting - tmceasting;
}
else if(PROJECTION_POLYCONIC == m_projection_type)
{
// We calculate northings as referenced to the equator
// And eastings as though the projection point is midscreen.
double pceasting, pcnorthing;
toPOLY(clat, clon, 0., clon, &pceasting, &pcnorthing);
double peasting, pnorthing;
toPOLY(lat, xlon, 0., clon, &peasting, &pnorthing);
easting = peasting;
northing = pnorthing - pcnorthing;
}
else
toSM(lat, xlon, clat, clon, &easting, &northing);
if(!wxFinite(easting) || !wxFinite(northing))
return wxPoint(0,0);
double epix = easting * view_scale_ppm;
double npix = northing * view_scale_ppm;
double dxr = epix;
double dyr = npix;
// Apply VP Rotation
if(g_bCourseUp)
{
dxr = epix * cos ( rotation ) + npix * sin ( rotation );
dyr = npix * cos ( rotation ) - epix * sin ( rotation );
}
wxPoint2DDouble r;
// We definitely need a round() function here
r.m_x = ( ( pix_width / 2 ) + dxr );
r.m_y = ( ( pix_height / 2 ) - dyr );
return r;
}
void ViewPort::GetLLFromPix(const wxPoint &p, double *lat, double *lon)
{
int dx = p.x - (pix_width / 2 );
int dy = ( pix_height / 2 ) - p.y;
double xpr = dx;
double ypr = dy;
// Apply VP Rotation
if(g_bCourseUp)
{
xpr = ( dx * cos ( rotation ) ) - ( dy * sin ( rotation ) );
ypr = ( dy * cos ( rotation ) ) + ( dx * sin ( rotation ) );
}
double d_east = xpr / view_scale_ppm;
double d_north = ypr / view_scale_ppm;
double slat, slon;
if(PROJECTION_TRANSVERSE_MERCATOR == m_projection_type)
{
double tmceasting, tmcnorthing;
toTM(clat, clon, 0., clon, &tmceasting, &tmcnorthing);
fromTM ( d_east, d_north + tmcnorthing, 0., clon, &slat, &slon );
}
else if(PROJECTION_POLYCONIC == m_projection_type)
{
double polyeasting, polynorthing;
toPOLY(clat, clon, 0., clon, &polyeasting, &polynorthing);
fromPOLY ( d_east, d_north + polynorthing, 0., clon, &slat, &slon );
}
//TODO This could be fromSM_ECC to better match some Raster charts
// However, it seems that cm93 (and S57) prefer no eccentricity correction
// Think about it....
else
fromSM ( d_east, d_north, clat, clon, &slat, &slon );
*lat = slat;
if(slon < -180.)
slon += 360.;
else if(slon > 180.)
slon -= 360.;
*lon = slon;
}
wxRegion ViewPort::GetVPRegionIntersect( const wxRegion &Region, size_t n, float *llpoints, int chart_native_scale, wxPoint *ppoints )
{
// Calculate the intersection between a given wxRegion (Region) and a polygon specified by lat/lon points.
// If the viewpoint is highly overzoomed wrt to chart native scale, the polygon region may be huge.
// This can be very expensive, and lead to crashes on some platforms (gtk in particular)
// So, look for this case and handle appropriately with respect to the given Region
if(chart_scale < chart_native_scale / 10)
{
// Make a positive definite vp
ViewPort vp_positive = *this;
while(vp_positive.vpBBox.GetMinX() < 0)
{
vp_positive.clon += 360.;
wxPoint2DDouble t(360., 0.);
vp_positive.vpBBox.Translate(t);
}
// Scan the points one-by-one, so that we can get min/max to make a bbox
float *pfp = llpoints;
float lon_max = -10000.;
float lon_min = 10000.;
float lat_max = -10000.;
float lat_min = 10000.;
for(unsigned int ip=0 ; ip < n ; ip++)
{
lon_max = wxMax(lon_max, pfp[1]);
lon_min = wxMin(lon_min, pfp[1]);
lat_max = wxMax(lat_max, pfp[0]);
lat_min = wxMin(lat_min, pfp[0]);
pfp+=2;
}
wxBoundingBox chart_box(lon_min, lat_min, lon_max, lat_max);
// Case: vpBBox is completely outside the chart box, or vice versa
// Return an empty region
if(_OUT == chart_box.Intersect((wxBoundingBox&)vp_positive.vpBBox))
{
if(_OUT == chart_box.Intersect((wxBoundingBox&)vpBBox))
{
// try again with the chart translated 360
wxPoint2DDouble rtw(360., 0.);
wxBoundingBox trans_box = chart_box;
trans_box.Translate( rtw );
if(_OUT == trans_box.Intersect((wxBoundingBox&)vp_positive.vpBBox))
{
if(_OUT == trans_box.Intersect((wxBoundingBox&)vpBBox))
{
return wxRegion();
}
}
}
}
// Case: vpBBox is completely inside the chart box
if(_IN == chart_box.Intersect((wxBoundingBox&)vp_positive.vpBBox))
{
return Region;
}
// The ViewPort and the chart region overlap in some way....
// Create the intersection of the two bboxes
double cb_minlon = wxMax(chart_box.GetMinX(), vp_positive.vpBBox.GetMinX());
double cb_maxlon = wxMin(chart_box.GetMaxX(), vp_positive.vpBBox.GetMaxX());
double cb_minlat = wxMax(chart_box.GetMinY(), vp_positive.vpBBox.GetMinY());
double cb_maxlat = wxMin(chart_box.GetMaxY(), vp_positive.vpBBox.GetMaxY());
if(cb_maxlon < cb_minlon)
cb_maxlon += 360.;
wxPoint p1 = GetPixFromLL(cb_maxlat, cb_minlon); // upper left
wxPoint p2 = GetPixFromLL(cb_minlat, cb_maxlon); // lower right
wxRegion r(p1, p2);
r.Intersect(Region);
return r;
}
// More "normal" case
wxPoint *pp;
// Use the passed point buffer if available
if(ppoints == NULL)
pp = new wxPoint[n];
else
pp = ppoints;
float *pfp = llpoints;
for(unsigned int ip=0 ; ip < n ; ip++)
{
wxPoint p = GetPixFromLL(pfp[0], pfp[1]);
pp[ip] = p;
pfp+=2;
}
wxRegion r = wxRegion(n, pp);
if(NULL == ppoints)
delete[] pp;
r.Intersect(Region);
return r;
}
void ViewPort::SetBoxes(void)
{
// In the case where canvas rotation is applied, we need to define a larger "virtual" pixel window size to ensure that
// enough chart data is fatched and available to fill the rotated screen.
rv_rect = wxRect(0, 0, pix_width, pix_height);
// Specify the minimum required rectangle in unrotated screen space which will supply full screen data after specified rotation
if(( g_bskew_comp && (fabs(skew) > .001)) || (fabs(rotation) > .001))
{
/*
// Get four reference "corner" points in rotated space
// First, get screen geometry factors
double pw2 = pix_width / 2;
double ph2 = pix_height / 2;
double pix_l = sqrt ( ( pw2 * pw2 ) + ( ph2 * ph2 ) );
double phi = atan2 ( ph2, pw2 );
//Rotate the 4 corner points, and get the max rectangle enclosing it
double rotator = rotation;
rotator -= skew;
double a_east = pix_l * cos ( phi + rotator ) ;
double a_north = pix_l * sin ( phi + rotator ) ;
double b_east = pix_l * cos ( rotator - phi + PI ) ;
double b_north = pix_l * sin ( rotator - phi + PI ) ;
double c_east = pix_l * cos ( phi + rotator + PI ) ;
double c_north = pix_l * sin ( phi + rotator + PI ) ;
double d_east = pix_l * cos ( rotator - phi ) ;
double d_north = pix_l * sin ( rotator - phi ) ;
int xmin = (int)wxMin( wxMin(a_east, b_east), wxMin(c_east, d_east));
int xmax = (int)wxMax( wxMax(a_east, b_east), wxMax(c_east, d_east));
int ymin = (int)wxMin( wxMin(a_north, b_north), wxMin(c_north, d_north));
int ymax = (int)wxMax( wxMax(a_north, b_north), wxMax(c_north, d_north));
int dx = xmax - xmin;
int dy = ymax - ymin;
// It is important for MSW build that viewport pixel dimensions be multiples of 4.....
if(dy % 4)
dy+= 4 - (dy%4);
if(dx % 4)
dx+= 4 - (dx%4);
// Grow the source rectangle appropriately
if(fabs(rotator) > .001)
rv_rect.Inflate((dx - pix_width)/2, (dy - pix_height)/2);
*/
double rotator = rotation;
rotator -= skew;
int dy = wxRound(fabs(pix_height * cos(rotator)) + fabs(pix_width * sin(rotator)));
int dx = wxRound(fabs(pix_width * cos(rotator)) + fabs(pix_height * sin(rotator)));
// It is important for MSW build that viewport pixel dimensions be multiples of 4.....
if(dy % 4)
dy+= 4 - (dy%4);
if(dx % 4)
dx+= 4 - (dx%4);
// Grow the source rectangle appropriately
if(fabs(rotator) > .001)
rv_rect.Inflate((dx - pix_width)/2, (dy - pix_height)/2);
}
// Compute Viewport lat/lon reference points for co-ordinate hit testing
// This must be done in unrotated space with respect to full unrotated screen space calculated above
double rotation_save = rotation;
SetRotationAngle(0.);
double lat_ul, lat_ur, lat_lr, lat_ll;
double lon_ul, lon_ur, lon_lr, lon_ll;
GetLLFromPix(wxPoint(rv_rect.x , rv_rect.y), &lat_ul, &lon_ul);
GetLLFromPix(wxPoint(rv_rect.x + rv_rect.width, rv_rect.y), &lat_ur, &lon_ur);
GetLLFromPix(wxPoint(rv_rect.x + rv_rect.width, rv_rect.y + rv_rect.height), &lat_lr, &lon_lr);
GetLLFromPix(wxPoint(rv_rect.x , rv_rect.y + rv_rect.height), &lat_ll, &lon_ll);
if(clon < 0.)
{
if((lon_ul > 0.) && (lon_ur < 0.) ){ lon_ul -= 360.; lon_ll -= 360.;}
}
else
{
if((lon_ul > 0.) && (lon_ur < 0.) ){ lon_ur += 360.; lon_lr += 360.;}
}
if(lon_ur < lon_ul)
{
lon_ur += 360.;
lon_lr += 360.;
}
if(lon_ur > 360.)
{
lon_ur -= 360.;
lon_lr -= 360.;
lon_ul -= 360.;
lon_ll -= 360.;
}
double dlat_min = lat_ul;
dlat_min = fmin ( dlat_min, lat_ur );
dlat_min = fmin ( dlat_min, lat_lr );
dlat_min = fmin ( dlat_min, lat_ll );
double dlon_min = lon_ul;
dlon_min = fmin ( dlon_min, lon_ur );
dlon_min = fmin ( dlon_min, lon_lr );
dlon_min = fmin ( dlon_min, lon_ll );
double dlat_max = lat_ul;
dlat_max = fmax ( dlat_max, lat_ur );
dlat_max = fmax ( dlat_max, lat_lr );
dlat_max = fmax ( dlat_max, lat_ll );
double dlon_max = lon_ur;
dlon_max = fmax ( dlon_max, lon_ul );
dlon_max = fmax ( dlon_max, lon_lr );
dlon_max = fmax ( dlon_max, lon_ll );
// Set the viewport lat/lon bounding box appropriately
vpBBox.SetMin ( dlon_min, dlat_min );
vpBBox.SetMax ( dlon_max, dlat_max );
// Restore the rotation angle
SetRotationAngle(rotation_save);
}
| 31.673228 | 136 | 0.52747 | [
"geometry"
] |
e3a8cde8fab6fd1e21519287da12272f6d0ac227 | 14,979 | hpp | C++ | include/ProxyKernelServer.hpp | NotThatJonSmith/CASK-Proxy-Platform | 05c6326f2865f1337620adc132dc3acc6b5d3b56 | [
"MIT"
] | 1 | 2022-02-08T02:28:24.000Z | 2022-02-08T02:28:24.000Z | include/ProxyKernelServer.hpp | NotThatJonSmith/CASK-Proxy-Platform | 05c6326f2865f1337620adc132dc3acc6b5d3b56 | [
"MIT"
] | null | null | null | include/ProxyKernelServer.hpp | NotThatJonSmith/CASK-Proxy-Platform | 05c6326f2865f1337620adc132dc3acc6b5d3b56 | [
"MIT"
] | null | null | null | #pragma once
#include <IOTarget.hpp>
#include <EventQueue.hpp>
#include <vector>
#include <string>
#include <unordered_map>
#include <iostream>
#include <fstream>
namespace CASK {
class ProxyKernelServer : public CASK::IOTarget {
public:
ProxyKernelServer(IOTarget *systemBus, EventQueue *eq, __uint32_t shutdownEventNumber);
virtual __uint32_t Read32(__uint32_t startAddress, __uint32_t size, char* dst) override;
virtual __uint64_t Read64(__uint64_t startAddress, __uint64_t size, char* dst) override;
virtual __uint128_t Read128(__uint128_t startAddress, __uint128_t size, char* dst) override;
virtual __uint32_t Write32(__uint32_t startAddress, __uint32_t size, char* src) override;
virtual __uint64_t Write64(__uint64_t startAddress, __uint64_t size, char* src) override;
virtual __uint128_t Write128(__uint128_t startAddress, __uint128_t size, char* src) override;
virtual __uint32_t Fetch32(__uint32_t startAddress, __uint32_t size, char* src) override;
virtual __uint64_t Fetch64(__uint64_t startAddress, __uint64_t size, char* src) override;
virtual __uint128_t Fetch128(__uint128_t startAddress, __uint128_t size, char* src) override;
void SetFSRoot(std::string fsRoot);
void SetPipes(std::istream *stdin, std::ostream *stdout, std::ostream *stderr);
void SetCommandLine(std::string commandLine);
void AttachLog(std::ostream* log);
private:
IOTarget *bus;
EventQueue *events;
__uint8_t state[16];
std::string fileSystemRoot = ".";
std::string proxyKernelCommandLine = "";
__uint32_t shutdownEvent;
std::istream *sim_stdin = &std::cin;
std::ostream *sim_stdout = &std::cout;
std::ostream *sim_stderr = &std::cerr;
std::ostream *out = nullptr;
__uint64_t nextFD = 3;
std::vector<__uint64_t> fdFreePool;
std::unordered_map<__uint64_t, std::fstream*> openFiles;
typedef __uint64_t (ProxyKernelServer::*SysCallHandler)(__uint64_t, __uint64_t,
__uint64_t, __uint64_t, __uint64_t, __uint64_t, __uint64_t);
struct SystemCall {
SysCallHandler handler;
std::string name;
};
static std::unordered_map<int, SystemCall> syscallTable;
private:
void DispatchSystemCall(__uint64_t magic_mem);
__uint64_t registerFD(std::fstream* fs);
void releaseFD(__uint64_t fd);
std::fstream* resolveFD(__uint64_t fd);
std::ostream* ostreamFromFD(__uint64_t fd);
std::istream* istreamFromFD(__uint64_t fd);
static constexpr int
SYS_exit = 93, SYS_exit_group = 94, SYS_getpid = 172, SYS_kill = 129,
SYS_read = 63, SYS_write = 64, SYS_openat = 56, SYS_close = 57,
SYS_lseek = 62, SYS_brk = 214, SYS_linkat = 37, SYS_unlinkat = 35,
SYS_mkdirat = 34, SYS_renameat = 38, SYS_chdir = 49, SYS_getcwd = 17,
SYS_fstat = 80, SYS_fstatat = 79, SYS_faccessat = 48, SYS_pread = 67,
SYS_pwrite = 68, SYS_uname = 160, SYS_getuid = 174, SYS_geteuid = 175,
SYS_getgid = 176, SYS_getegid = 177, SYS_mmap = 222, SYS_munmap = 215,
SYS_mremap = 216, SYS_mprotect = 226, SYS_prlimit64 = 261,
SYS_getmainvars = 2011, SYS_rt_sigaction = 134, SYS_writev = 66,
SYS_gettimeofday = 169, SYS_times = 153, SYS_fcntl = 25,
SYS_ftruncate = 46, SYS_getdents = 61, SYS_dup = 23, SYS_dup3 = 24,
SYS_readlinkat = 78, SYS_rt_sigprocmask = 135, SYS_ioctl = 29,
SYS_getrlimit = 163, SYS_setrlimit = 164, SYS_getrusage = 165,
SYS_clock_gettime = 113, SYS_set_tid_address = 96,
SYS_set_robust_list = 99, SYS_madvise = 233, SYS_open = 1024,
SYS_link = 1025, SYS_unlink = 1026, SYS_mkdir = 1030, SYS_access = 1033,
SYS_stat = 1038, SYS_lstat = 1039, SYS_time = 1062,
ERR_eperm = 1, ERR_enoent = 2, ERR_esrch = 3, ERR_eintr = 4,
ERR_eio = 5, ERR_enxio = 6, ERR_e2big = 7, ERR_enoexec = 8,
ERR_ebadf = 9, ERR_echild = 10, ERR_eagain = 11, ERR_enomem = 12,
ERR_eacces = 13, ERR_efault = 14, ERR_enotblk = 15, ERR_ebusy = 16,
ERR_eexist = 17, ERR_exdev = 18, ERR_enodev = 19, ERR_enotdir = 20,
ERR_eisdir = 21, ERR_einval = 22, ERR_enfile = 23, ERR_emfile = 24,
ERR_enotty = 25, ERR_etxtbsy = 26, ERR_efbig = 27, ERR_enospc = 28,
ERR_espipe = 29, ERR_erofs = 30, ERR_emlink = 31, ERR_epipe = 32,
ERR_edom = 33, ERR_erange = 34, ERR_enomsg = 35, ERR_eidrm = 36,
ERR_echrng = 37, ERR_el2nsync = 38, ERR_el3hlt = 39, ERR_el3rst = 40,
ERR_elnrng = 41, ERR_eunatch = 42, ERR_enocsi = 43, ERR_el2hlt = 44,
ERR_edeadlk = 45, ERR_enolck = 46, ERR_ebade = 50, ERR_ebadr = 51,
ERR_exfull = 52, ERR_enoano = 53, ERR_ebadrqc = 54, ERR_ebadslt = 55,
ERR_edeadlock = 56, ERR_ebfont = 57, ERR_enostr = 60, ERR_enodata = 61,
ERR_etime = 62, ERR_enosr = 63, ERR_enonet = 64, ERR_enopkg = 65,
ERR_eremote = 66, ERR_enolink = 67, ERR_eadv = 68, ERR_esrmnt = 69,
ERR_ecomm = 70, ERR_eproto = 71, ERR_emultihop = 74, ERR_elbin = 75,
ERR_edotdot = 76, ERR_ebadmsg = 77, ERR_eftype = 79, ERR_enotuniq = 80,
ERR_ebadfd = 81, ERR_eremchg = 82, ERR_elibacc = 83, ERR_elibbad = 84,
ERR_elibscn = 85, ERR_elibmax = 86, ERR_elibexec = 87, ERR_enosys = 88,
ERR_enmfile = 89, ERR_enotempty = 90, ERR_enametoolong = 91,
ERR_eloop = 92, ERR_eopnotsupp = 95, ERR_epfnosupport = 96,
ERR_econnreset = 104, ERR_enobufs = 105, ERR_eafnosupport = 106,
ERR_eprototype = 107, ERR_enotsock = 108, ERR_enoprotoopt = 109,
ERR_eshutdown = 110, ERR_econnrefused = 111, ERR_eaddrinuse = 112,
ERR_econnaborted = 113, ERR_enetunreach = 114, ERR_enetdown = 115,
ERR_etimedout = 116, ERR_ehostdown = 117, ERR_ehostunreach = 118,
ERR_einprogress = 119, ERR_ealready = 120, ERR_edestaddrreq = 121,
ERR_emsgsize = 122, ERR_eprotonosupport = 123,
ERR_esocktnosupport = 124, ERR_eaddrnotavail = 125, ERR_enetreset = 126,
ERR_eisconn = 127, ERR_enotconn = 128, ERR_etoomanyrefs = 129,
ERR_eproclim = 130, ERR_eusers = 131, ERR_edquot = 132,
ERR_estale = 133, ERR_enotsup = 134, ERR_enomedium = 135,
ERR_enoshare = 136, ERR_ecaseclash = 137, ERR_eilseq = 138,
ERR_eoverflow = 139, ERR_ewouldblock = 11;
__uint64_t sys_exit(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_exit_group(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_getpid(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_kill(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_read(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_write(__uint64_t fd, __uint64_t addr, __uint64_t size, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_openat(__uint64_t dirfd, __uint64_t fn, __uint64_t fn_size, __uint64_t flags, __uint64_t mode, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_close(__uint64_t fd, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_lseek(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_brk(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_linkat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_unlinkat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_mkdirat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_renameat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_chdir(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_getcwd(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_fstat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_fstatat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_faccessat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_pread(__uint64_t fd, __uint64_t addr, __uint64_t size, __uint64_t offset, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_pwrite(__uint64_t fd, __uint64_t addr, __uint64_t size, __uint64_t offset, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_uname(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_getuid(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_geteuid(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_getgid(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_getegid(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_mmap(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_munmap(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_mremap(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_mprotect(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_prlimit64(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_getmainvars(__uint64_t addr, __uint64_t size, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_rt_sigaction(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_writev(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_gettimeofday(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_times(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_fcntl(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_ftruncate(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_getdents(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_dup(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_dup3(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_readlinkat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_rt_sigprocmask(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_ioctl(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_getrlimit(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_setrlimit(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_getrusage(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_clock_gettime(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_set_tid_address(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_set_robust_list(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_madvise(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_open(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_link(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_unlink(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_mkdir(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_access(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_stat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_lstat(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
__uint64_t sys_time(__uint64_t arg0, __uint64_t arg1, __uint64_t arg2, __uint64_t arg3, __uint64_t arg4, __uint64_t arg5, __uint64_t arg6);
};
} // namespace CASK
| 79.675532 | 154 | 0.756726 | [
"vector"
] |
e3ad71da83440f37d022121b4968d60f58d801f3 | 1,268 | cpp | C++ | Labs/lab08/vector_program/try_vector.cpp | pranavas11/CS162-Introduction-to-CS-II | c17c5c1f844de1be4a49646201d77717394dfdbc | [
"MIT"
] | null | null | null | Labs/lab08/vector_program/try_vector.cpp | pranavas11/CS162-Introduction-to-CS-II | c17c5c1f844de1be4a49646201d77717394dfdbc | [
"MIT"
] | null | null | null | Labs/lab08/vector_program/try_vector.cpp | pranavas11/CS162-Introduction-to-CS-II | c17c5c1f844de1be4a49646201d77717394dfdbc | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include "./vector.hpp"
//We do not want to include either statement. We wouldn't be able to compare our vector template to the Standard
//using std::vector;
//using namespace std;
using std::cout;
using std::endl;
int main() {
vector<int> v; // our vector class
std::vector<int> stdv; // standard vector
v.push_back(23); // compare operation of vector to std
stdv.push_back(23);
// invokes copy constructor
vector<int> vcpy = v;
std::vector<int> stdvcpy = stdv;
//invokes assignment operator overload
vector<int> vcpy2;
std::vector<int> stdvcpy2;
vcpy2 = vcpy;
stdvcpy2 = stdvcpy;
cout << "\n\n\nOur vector size: " << v.size() << endl;
cout << "STL vector size: " << stdv.size() << endl;
cout << "Copy of our vector size: " << vcpy.size() << endl;
cout << "Copy of STL vector size: " << stdvcpy.size() << endl;
cout << "Copy of our vector size with =: " << vcpy2.size() << endl;
cout << "Copy of STL vector size with =: " << stdvcpy2.size() << endl;
vcpy.push_back(15);
cout << "Pushed back 15 onto vector copy. Element: " << vcpy[1] << endl;
vcpy2.push_back(55);
cout << "Pushed back 55 onto second copy of vector -> vcpy(2).at(1) = " << vcpy2.at(1) << "\n\n\n";
return 0;
} | 29.488372 | 112 | 0.638801 | [
"vector"
] |
e3b0d0538e7d7c98bbbc5403a44a9960b3d6f5ab | 9,516 | cpp | C++ | src/other/ext/openscenegraph/src/osg/AttributeDispatchers.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/other/ext/openscenegraph/src/osg/AttributeDispatchers.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/other/ext/openscenegraph/src/osg/AttributeDispatchers.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/AttributeDispatchers>
#include <osg/State>
#include <osg/Drawable>
#include <osg/Notify>
#include <osg/io_utils>
namespace osg
{
#if defined(OSG_GLES1_AVAILABLE)
inline void GL_APIENTRY glColor4ubv(const GLubyte* c) { glColor4ub(c[0], c[1], c[2], c[3]); }
inline void GL_APIENTRY glColor3fv(const GLfloat* c) { glColor4f(c[0], c[1], c[2], 1.0f); }
inline void GL_APIENTRY glColor4fv(const GLfloat* c) { glColor4f(c[0], c[1], c[2], c[3]); }
inline void GL_APIENTRY glColor3dv(const GLdouble* c) { glColor4f(c[0], c[1], c[2], 1.0f); }
inline void GL_APIENTRY glColor4dv(const GLdouble* c) { glColor4f(c[0], c[1], c[2], c[3]); }
inline void GL_APIENTRY glNormal3bv(const GLbyte* n) { const float div = 1.0f/128.0f; glNormal3f(float(n[0])*div, float(n[1])*div, float(n[3])*div); }
inline void GL_APIENTRY glNormal3sv(const GLshort* n) { const float div = 1.0f/32768.0f; glNormal3f(float(n[0])*div, float(n[1])*div, float(n[3])*div); }
inline void GL_APIENTRY glNormal3fv(const GLfloat* n) { glNormal3f(n[0], n[1], n[3]); }
inline void GL_APIENTRY glNormal3dv(const GLdouble* n) { glNormal3f(n[0], n[1], n[3]); }
#endif
template<typename T>
class TemplateAttributeDispatch : public AttributeDispatch
{
public:
typedef void (GL_APIENTRY * F) (const T*);
TemplateAttributeDispatch(F functionPtr, unsigned int stride):
_functionPtr(functionPtr), _stride(stride), _array(0) {}
virtual void assign(const GLvoid* array)
{
_array = reinterpret_cast<const T*>(array);
}
virtual void operator () (unsigned int pos)
{
_functionPtr(&(_array[pos*_stride]));
}
F _functionPtr;
unsigned int _stride;
const T* _array;
};
template<typename I, typename T>
class TemplateTargetAttributeDispatch : public AttributeDispatch
{
public:
typedef void (GL_APIENTRY * F) (I, const T*);
TemplateTargetAttributeDispatch(I target, F functionPtr, unsigned int stride):
_functionPtr(functionPtr), _target(target), _stride(stride), _array(0) {}
virtual void assign(const GLvoid* array)
{
_array = reinterpret_cast<const T*>(array);
}
virtual void operator () (unsigned int pos)
{
_functionPtr(_target, &(_array[pos * _stride]));
}
F _functionPtr;
I _target;
unsigned int _stride;
const T* _array;
};
class AttributeDispatchMap
{
public:
AttributeDispatchMap() {}
template<typename T>
void assign(Array::Type type, void (GL_APIENTRY *functionPtr) (const T*), unsigned int stride)
{
if ((unsigned int)type >= _attributeDispatchList.size()) _attributeDispatchList.resize(type+1);
_attributeDispatchList[type] = functionPtr ? new TemplateAttributeDispatch<T>(functionPtr, stride) : 0;
}
template<typename I, typename T>
void targetAssign(I target, Array::Type type, void (GL_APIENTRY *functionPtr) (I, const T*), unsigned int stride)
{
if ((unsigned int)type >= _attributeDispatchList.size()) _attributeDispatchList.resize(type+1);
_attributeDispatchList[type] = functionPtr ? new TemplateTargetAttributeDispatch<I,T>(target, functionPtr, stride) : 0;
}
AttributeDispatch* dispatcher(const Array* array)
{
// OSG_NOTICE<<"dispatcher("<<array<<")"<<std::endl;
if (!array) return 0;
Array::Type type = array->getType();
AttributeDispatch* dispatcher = 0;
// OSG_NOTICE<<" array->getType()="<<type<<std::endl;
// OSG_NOTICE<<" _attributeDispatchList.size()="<<_attributeDispatchList.size()<<std::endl;
if ((unsigned int)type<_attributeDispatchList.size())
{
dispatcher = _attributeDispatchList[array->getType()].get();
}
if (dispatcher)
{
// OSG_NOTICE<<" returning dispatcher="<<dispatcher<<std::endl;
dispatcher->assign(array->getDataPointer());
return dispatcher;
}
else
{
// OSG_NOTICE<<" no dispatcher found"<<std::endl;
return 0;
}
}
typedef std::vector< ref_ptr<AttributeDispatch> > AttributeDispatchList;
AttributeDispatchList _attributeDispatchList;
};
AttributeDispatchers::AttributeDispatchers():
_initialized(false),
_state(0),
_normalDispatchers(0),
_colorDispatchers(0),
_secondaryColorDispatchers(0),
_fogCoordDispatchers(0),
_useVertexAttribAlias(false)
{
}
AttributeDispatchers::~AttributeDispatchers()
{
delete _normalDispatchers;
delete _colorDispatchers;
delete _secondaryColorDispatchers;
delete _fogCoordDispatchers;
for(AttributeDispatchMapList::iterator itr = _vertexAttribDispatchers.begin();
itr != _vertexAttribDispatchers.end();
++itr)
{
delete *itr;
}
}
void AttributeDispatchers::setState(osg::State* state)
{
_state = state;
}
void AttributeDispatchers::init()
{
if (_initialized) return;
_initialized = true;
_normalDispatchers = new AttributeDispatchMap();
_colorDispatchers = new AttributeDispatchMap();
_secondaryColorDispatchers = new AttributeDispatchMap();
_fogCoordDispatchers = new AttributeDispatchMap();
#ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE
GLExtensions* extensions = _state->get<GLExtensions>();
_normalDispatchers->assign<GLbyte>(Array::Vec3bArrayType, glNormal3bv, 3);
_normalDispatchers->assign<GLshort>(Array::Vec3sArrayType, glNormal3sv, 3);
_normalDispatchers->assign<GLfloat>(Array::Vec3ArrayType, glNormal3fv, 3);
_normalDispatchers->assign<GLdouble>(Array::Vec3dArrayType, glNormal3dv, 3);
_colorDispatchers->assign<GLubyte>(Array::Vec4ubArrayType, glColor4ubv, 4);
_colorDispatchers->assign<GLfloat>(Array::Vec3ArrayType, glColor3fv, 3);
_colorDispatchers->assign<GLfloat>(Array::Vec4ArrayType, glColor4fv, 4);
_colorDispatchers->assign<GLdouble>(Array::Vec3dArrayType, glColor3dv, 3);
_colorDispatchers->assign<GLdouble>(Array::Vec4dArrayType, glColor4dv, 4);
_secondaryColorDispatchers->assign<GLfloat>(Array::Vec3ArrayType, extensions->glSecondaryColor3fv, 3);
_fogCoordDispatchers->assign<GLfloat>(Array::FloatArrayType, extensions->glFogCoordfv, 1);
#endif
// pre allocate.
_activeDispatchList.resize(5);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// With inidices
//
AttributeDispatch* AttributeDispatchers::normalDispatcher(Array* array)
{
return _useVertexAttribAlias ?
vertexAttribDispatcher(_state->getNormalAlias()._location, array) :
_normalDispatchers->dispatcher(array);
}
AttributeDispatch* AttributeDispatchers::colorDispatcher(Array* array)
{
return _useVertexAttribAlias ?
vertexAttribDispatcher(_state->getColorAlias()._location, array) :
_colorDispatchers->dispatcher(array);
}
AttributeDispatch* AttributeDispatchers::secondaryColorDispatcher(Array* array)
{
return _useVertexAttribAlias ?
vertexAttribDispatcher(_state->getSecondaryColorAlias()._location, array) :
_secondaryColorDispatchers->dispatcher(array);
}
AttributeDispatch* AttributeDispatchers::fogCoordDispatcher(Array* array)
{
return _useVertexAttribAlias ?
vertexAttribDispatcher(_state->getFogCoordAlias()._location, array) :
_fogCoordDispatchers->dispatcher(array);
}
AttributeDispatch* AttributeDispatchers::vertexAttribDispatcher(unsigned int unit, Array* array)
{
if (unit>=_vertexAttribDispatchers.size()) assignVertexAttribDispatchers(unit);
return _vertexAttribDispatchers[unit]->dispatcher(array);
}
void AttributeDispatchers::assignVertexAttribDispatchers(unsigned int unit)
{
GLExtensions* extensions = _state->get<GLExtensions>();
for(unsigned int i=_vertexAttribDispatchers.size(); i<=unit; ++i)
{
_vertexAttribDispatchers.push_back(new AttributeDispatchMap());
AttributeDispatchMap& vertexAttribDispatcher = *_vertexAttribDispatchers[i];
vertexAttribDispatcher.targetAssign<GLuint, GLfloat>(i, Array::FloatArrayType, extensions->glVertexAttrib1fv, 1);
vertexAttribDispatcher.targetAssign<GLuint, GLfloat>(i, Array::Vec2ArrayType, extensions->glVertexAttrib2fv, 2);
vertexAttribDispatcher.targetAssign<GLuint, GLfloat>(i, Array::Vec3ArrayType, extensions->glVertexAttrib3fv, 3);
vertexAttribDispatcher.targetAssign<GLuint, GLfloat>(i, Array::Vec4ArrayType, extensions->glVertexAttrib4fv, 4);
}
}
void AttributeDispatchers::reset()
{
if (!_initialized) init();
_useVertexAttribAlias = false;
_activeDispatchList.clear();
}
}
| 34.603636 | 153 | 0.683586 | [
"vector"
] |
e3b459ffd46898591b2595d1535c02c42c15a5eb | 6,759 | hpp | C++ | physics/dynamic_frame_body.hpp | tnuvoletta/Principia | 25cf2fb70c512cf86a842ed525f6ab10e57f937c | [
"MIT"
] | 2 | 2015-02-23T19:32:16.000Z | 2015-04-07T03:55:53.000Z | physics/dynamic_frame_body.hpp | tnuvoletta/Principia | 25cf2fb70c512cf86a842ed525f6ab10e57f937c | [
"MIT"
] | null | null | null | physics/dynamic_frame_body.hpp | tnuvoletta/Principia | 25cf2fb70c512cf86a842ed525f6ab10e57f937c | [
"MIT"
] | null | null | null |
#pragma once
#include "physics/barycentric_rotating_dynamic_frame.hpp"
#include "physics/body_centred_body_direction_dynamic_frame.hpp"
#include "physics/body_centred_non_rotating_dynamic_frame.hpp"
#include "physics/body_surface_dynamic_frame.hpp"
#include "physics/dynamic_frame.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/si.hpp"
namespace principia {
namespace physics {
namespace internal_dynamic_frame {
using geometry::AngularVelocity;
using geometry::Bivector;
using geometry::Displacement;
using geometry::InnerProduct;
using geometry::Normalize;
using geometry::R3x3Matrix;
using geometry::Velocity;
using geometry::Wedge;
using quantities::Pow;
using quantities::Sqrt;
using quantities::Variation;
using quantities::si::Radian;
template<typename InertialFrame, typename ThisFrame>
RigidMotion<InertialFrame, ThisFrame>
DynamicFrame<InertialFrame, ThisFrame>::ToThisFrameAtTime(
Instant const& t) const {
return FromThisFrameAtTime(t).Inverse();
}
template<typename InertialFrame, typename ThisFrame>
RigidMotion<ThisFrame, InertialFrame>
DynamicFrame<InertialFrame, ThisFrame>::FromThisFrameAtTime(
Instant const& t) const {
return ToThisFrameAtTime(t).Inverse();
}
template<typename InertialFrame, typename ThisFrame>
Vector<Acceleration, ThisFrame>
DynamicFrame<InertialFrame, ThisFrame>::GeometricAcceleration(
Instant const& t,
DegreesOfFreedom<ThisFrame> const& degrees_of_freedom) const {
AcceleratedRigidMotion<InertialFrame, ThisFrame> const motion =
MotionOfThisFrame(t);
RigidMotion<InertialFrame, ThisFrame> const& to_this_frame =
motion.rigid_motion();
RigidMotion<ThisFrame, InertialFrame> const from_this_frame =
to_this_frame.Inverse();
// Beware, we want the angular velocity of ThisFrame as seen in the
// InertialFrame, but pushed to ThisFrame. Otherwise the sign is wrong.
AngularVelocity<ThisFrame> const Ω = to_this_frame.orthogonal_map()(
to_this_frame.angular_velocity_of_to_frame());
Variation<AngularVelocity<ThisFrame>> const dΩ_over_dt =
to_this_frame.orthogonal_map()(motion.angular_acceleration_of_to_frame());
Displacement<ThisFrame> const r =
degrees_of_freedom.position() - ThisFrame::origin;
Vector<Acceleration, ThisFrame> const gravitational_acceleration_at_point =
to_this_frame.orthogonal_map()(
GravitationalAcceleration(t,
from_this_frame.rigid_transformation()(
degrees_of_freedom.position())));
Vector<Acceleration, ThisFrame> const linear_acceleration =
-to_this_frame.orthogonal_map()(motion.acceleration_of_to_frame_origin());
Vector<Acceleration, ThisFrame> const coriolis_acceleration_at_point =
-2 * Ω * degrees_of_freedom.velocity() / Radian;
Vector<Acceleration, ThisFrame> const centrifugal_acceleration_at_point =
-Ω * (Ω * r) / Pow<2>(Radian);
Vector<Acceleration, ThisFrame> const euler_acceleration_at_point =
-dΩ_over_dt * r / Radian;
Vector<Acceleration, ThisFrame> const fictitious_acceleration =
linear_acceleration +
coriolis_acceleration_at_point +
centrifugal_acceleration_at_point +
euler_acceleration_at_point;
return gravitational_acceleration_at_point + fictitious_acceleration;
}
template<typename InertialFrame, typename ThisFrame>
Rotation<Frenet<ThisFrame>, ThisFrame>
DynamicFrame<InertialFrame, ThisFrame>::FrenetFrame(
Instant const& t,
DegreesOfFreedom<ThisFrame> const& degrees_of_freedom) const {
Velocity<ThisFrame> const& velocity = degrees_of_freedom.velocity();
Vector<Acceleration, ThisFrame> const acceleration =
GeometricAcceleration(t, degrees_of_freedom);
Vector<Acceleration, ThisFrame> const normal_acceleration =
acceleration.OrthogonalizationAgainst(velocity);
Vector<double, ThisFrame> tangent = Normalize(velocity);
Vector<double, ThisFrame> normal = Normalize(normal_acceleration);
Bivector<double, ThisFrame> binormal = Wedge(tangent, normal);
// Maps |tangent| to {1, 0, 0}, |normal| to {0, 1, 0}, and |binormal| to
// {0, 0, 1}.
return Rotation<Frenet<ThisFrame>, ThisFrame>(tangent, normal, binormal);
}
template<typename InertialFrame, typename ThisFrame>
not_null<std::unique_ptr<DynamicFrame<InertialFrame, ThisFrame>>>
DynamicFrame<InertialFrame, ThisFrame>::ReadFromMessage(
serialization::DynamicFrame const& message,
not_null<Ephemeris<InertialFrame> const*> const ephemeris) {
std::unique_ptr<DynamicFrame> result;
int extensions_found = 0;
// NOTE(egg): the |static_cast|ing below is needed on MSVC, because the silly
// compiler doesn't see the |operator std::unique_ptr<DynamicFrame>() &&|.
if (message.HasExtension(
serialization::BarycentricRotatingDynamicFrame::extension)) {
++extensions_found;
result = static_cast<not_null<std::unique_ptr<DynamicFrame>>>(
BarycentricRotatingDynamicFrame<InertialFrame, ThisFrame>::
ReadFromMessage(ephemeris,
message.GetExtension(
serialization::BarycentricRotatingDynamicFrame::
extension)));
}
if (message.HasExtension(
serialization::BodyCentredBodyDirectionDynamicFrame::extension)) {
++extensions_found;
result = static_cast<not_null<std::unique_ptr<DynamicFrame>>>(
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
ReadFromMessage(
ephemeris,
message.GetExtension(
serialization::BodyCentredBodyDirectionDynamicFrame::
extension)));
}
if (message.HasExtension(
serialization::BodyCentredNonRotatingDynamicFrame::extension)) {
++extensions_found;
result = static_cast<not_null<std::unique_ptr<DynamicFrame>>>(
BodyCentredNonRotatingDynamicFrame<InertialFrame, ThisFrame>::
ReadFromMessage(
ephemeris,
message.GetExtension(
serialization::BodyCentredNonRotatingDynamicFrame::
extension)));
}
if (message.HasExtension(
serialization::BodySurfaceDynamicFrame::extension)) {
++extensions_found;
result = static_cast<not_null<std::unique_ptr<DynamicFrame>>>(
BodySurfaceDynamicFrame<InertialFrame, ThisFrame>::
ReadFromMessage(
ephemeris,
message.GetExtension(
serialization::BodySurfaceDynamicFrame::extension)));
}
CHECK_EQ(extensions_found, 1) << message.DebugString();
return std::move(result);
}
} // namespace internal_dynamic_frame
} // namespace physics
} // namespace principia
| 41.722222 | 80 | 0.729398 | [
"geometry",
"vector"
] |
e3c52613b06e761a4654d18e8da10fdfe376499d | 7,333 | hpp | C++ | lib/mockturtle/include/mockturtle/views/mffc_view.hpp | Ace-Ma/LSOracle | 6e940906303ef6c2c6b96352f44206567fdd50d3 | [
"MIT"
] | null | null | null | lib/mockturtle/include/mockturtle/views/mffc_view.hpp | Ace-Ma/LSOracle | 6e940906303ef6c2c6b96352f44206567fdd50d3 | [
"MIT"
] | null | null | null | lib/mockturtle/include/mockturtle/views/mffc_view.hpp | Ace-Ma/LSOracle | 6e940906303ef6c2c6b96352f44206567fdd50d3 | [
"MIT"
] | null | null | null | /* mockturtle: C++ logic network library
* Copyright (C) 2018 EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
\file cut_view.hpp
\brief Implements an isolated view on a single cut in a network
\author Mathias Soeken
*/
#pragma once
#include <algorithm>
#include <cstdint>
#include <unordered_map>
#include <vector>
#include "../networks/detail/foreach.hpp"
#include "../traits.hpp"
#include "immutable_view.hpp"
namespace mockturtle
{
/*! \brief Implements an isolated view on the MFFC of a node.
*
* The network is constructed from a given root node which is traversed towards
* the primary inputs. Nodes are collected as long they only fanout into nodes
* which are already among the visited nodes. Therefore the final view only
* has outgoing edges to nodes not in the view from the given root node or from
* the newly generated primary inputs.
*
* The view reimplements the methods `size`, `num_pis`, `num_pos`, `foreach_pi`,
* `foreach_po`, `foreach_node`, `foreach_gate`, `is_pi`, `node_to_index`, and
* `index_to_node`.
*
* **Required network functions:**
* - `get_node`
* - `clear_values`
* - `set_value`
* - `decr_value`
* - `value`
* - `fanout_size`
* - `foreach_node`
* - `foreach_fanin`
* - `is_constant`
* - `node_to_index`
*/
template<typename Ntk>
class mffc_view : public immutable_view<Ntk>
{
public:
using storage = typename Ntk::storage;
using node = typename Ntk::node;
using signal = typename Ntk::signal;
public:
explicit mffc_view( Ntk const& ntk, const node& root )
: immutable_view<Ntk>( ntk ), _root( root )
{
static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" );
static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" );
static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the clear_values method" );
static_assert( has_set_value_v<Ntk>, "Ntk does not implement the set_value method" );
static_assert( has_decr_value_v<Ntk>, "Ntk does not implement the decr_value method" );
static_assert( has_value_v<Ntk>, "Ntk does not implement the value method" );
static_assert( has_fanout_size_v<Ntk>, "Ntk does not implement the fanout_size method" );
static_assert( has_foreach_node_v<Ntk>, "Ntk does not implement the foreach_node method" );
static_assert( has_foreach_fanin_v<Ntk>, "Ntk does not implement the foreach_fanin method" );
static_assert( has_is_constant_v<Ntk>, "Ntk does not implement the is_constant method" );
static_assert( has_is_pi_v<Ntk>, "Ntk does not implement the is_pi method" );
static_assert( has_node_to_index_v<Ntk>, "Ntk does not implement the node_to_index method" );
this->clear_values();
Ntk::foreach_node( [&]( auto const& n ) {
if ( this->is_constant( n ) )
{
_constants.push_back( n );
_node_to_index.emplace( n, _node_to_index.size() );
}
this->set_value( n, Ntk::fanout_size( n ) );
} );
update();
}
inline auto size() const { return _num_constants + _num_leaves + _inner.size(); }
inline auto num_pis() const { return _num_leaves; }
inline auto num_pos() const { return 1u; }
inline auto num_gates() const { return _inner.size(); }
inline bool is_pi( node const& pi ) const
{
return std::find( _leaves.begin(), _leaves.end(), pi ) != _leaves.end();
}
template<typename Fn>
void foreach_pi( Fn&& fn ) const
{
detail::foreach_element( _leaves.begin(), _leaves.end(), fn );
}
template<typename Fn>
void foreach_po( Fn&& fn ) const
{
std::vector<signal> signals( 1, this->make_signal( _root ) );
detail::foreach_element( signals.begin(), signals.end(), fn );
}
template<typename Fn>
void foreach_gate( Fn&& fn ) const
{
detail::foreach_element( _inner.begin(), _inner.end(), fn );
}
template<typename Fn>
void foreach_node( Fn&& fn ) const
{
detail::foreach_element( _constants.begin(), _constants.end(), fn );
detail::foreach_element( _leaves.begin(), _leaves.end(), fn, _num_constants );
detail::foreach_element( _inner.begin(), _inner.end(), fn, _num_constants + _num_leaves );
}
inline auto index_to_node( uint32_t index ) const
{
if ( index < _num_constants )
{
return _constants[index];
}
if ( index < _num_constants + _num_leaves )
{
return _leaves[index - _num_constants];
}
return _inner[index - _num_constants - _num_leaves];
}
inline auto node_to_index( node const& n ) const { return _node_to_index.at( n ); }
void update()
{
collect( _root );
compute_sets();
}
private:
void collect( node const& n )
{
if ( Ntk::is_constant( n ) || Ntk::is_pi( n ) )
{
return;
}
this->foreach_fanin( n, [&]( auto const& f ) {
_nodes.push_back( this->get_node( f ) );
if ( this->decr_value( this->get_node( f ) ) == 0 )
{
collect( this->get_node( f ) );
}
} );
}
void compute_sets()
{
_leaves.clear();
_inner.clear();
auto orig = _nodes;
std::sort( orig.begin(), orig.end(),
[&]( auto const& n1, auto const& n2 ) { return static_cast<Ntk*>( this )->node_to_index( n1 ) < static_cast<Ntk*>( this )->node_to_index( n2 ); } );
for ( auto const& n : orig )
{
if ( Ntk::is_constant( n ) )
{
continue;
}
if ( this->value( n ) > 0 || Ntk::is_pi( n ) ) /* PI candidate */
{
if ( _leaves.empty() || _leaves.back() != n )
{
_leaves.push_back( n );
}
}
else
{
if ( _inner.empty() || _inner.back() != n )
{
_inner.push_back( n );
}
}
}
_num_constants = _constants.size();
_num_leaves = _leaves.size();
for ( auto const& n : _leaves )
{
_node_to_index.emplace( n, _node_to_index.size() );
}
for ( auto const& n : _inner )
{
_node_to_index.emplace( n, _node_to_index.size() );
}
_inner.push_back( _root );
_node_to_index.emplace( _root, _node_to_index.size() );
}
public:
std::vector<node> _nodes, _constants, _leaves, _inner;
unsigned _num_constants{0}, _num_leaves{0};
std::unordered_map<node, uint32_t> _node_to_index;
node _root;
};
} /* namespace mockturtle */
| 30.554167 | 163 | 0.65853 | [
"vector"
] |
e3c634461067f2e22a1e6322d29447772fc4718c | 899 | cpp | C++ | CodeForces/Complete/200-299/295A-GregAndArray.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/200-299/295A-GregAndArray.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/200-299/295A-GregAndArray.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <cstdio>
#include <vector>
int main(){
long long n, m, k; scanf("%lld %lld %lld\n", &n, &m, &k);
std::vector<long long> array(n, 0), add(n + 1, 0);
for(long long p = 0; p < n; p++){scanf("%lld", &array[p]);}
std::vector<long long> left(m, 0), right(m, 0), value(m, 0);
for(long long p = 0; p < m; p++){scanf("%lld %lld %lld", &left[p], &right[p], &value[p]);}
std::vector<long long> q(m + 1, 0);
for(long long p = 0; p < k; p++){
long long x, y; scanf("%lld %lld", &x, &y);
++q[x - 1]; --q[y];
}
long long sum = 0;
for(long long p = 0; p < m; p++){
sum += q[p];
add[left[p] - 1] += sum * value[p];
add[right[p]] -= sum * value[p];
}
long long totalAdd = 0;
for(long long p = 0; p < n; p++){
totalAdd += add[p];
printf("%lld ", totalAdd + array[p]);
}
return 0;
}
| 25.685714 | 94 | 0.461624 | [
"vector"
] |
e3c6ce027190bbde32bf6b6ed862b5de24c6aee8 | 1,064 | cpp | C++ | src/homework/04_vectors/main.cpp | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean | 9e2f45a1d9682f5c9391a594e1284c6beffd9f58 | [
"MIT"
] | null | null | null | src/homework/04_vectors/main.cpp | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean | 9e2f45a1d9682f5c9391a594e1284c6beffd9f58 | [
"MIT"
] | null | null | null | src/homework/04_vectors/main.cpp | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-ChelliBean | 9e2f45a1d9682f5c9391a594e1284c6beffd9f58 | [
"MIT"
] | null | null | null | #include "vectors.h"
#include<iostream>
#include<vector>
using std::cout; using std::cin;
/*
use a vector of int with values 8, 4, 20, 88, 66, 99
Prompt user for 1 for Get Max from vector and 2 for Get primes.
Prompt user for a number and return max value or list of primes
and display them to screen.
Program continues until user decides to exit.
*/
int main()
{
std::vector<int>numbers{ 8, 4, 20, 88, 66, 99 };
int starter = 0;
int num;
char keepGoing = 'y';
do
{
cout << "Enter 1 for get max or enter 2 for get primes " << "\n";
cin >> starter;
if (starter == 1)
{
get_max_from_vector(numbers);
cout << get_max_from_vector(numbers) << "\n";
cout << "y to continue: ";
cin >> keepGoing;
}
else if (starter == 2)
{
cout << "Enter a number greater than 0: ";
cin >> num;
std::vector<int>prime = vector_of_primes(num);
for (auto n : prime)
{
cout << n << ", " << "\n";
}
cout << "y to continue: ";
cin >> keepGoing;
}
} while (starter == 0 || keepGoing == 'y');
return 0;
} | 20.461538 | 67 | 0.595865 | [
"vector"
] |
e3d934406c45021d5c9fac41c2f09a29eb300179 | 150 | cpp | C++ | 04/7_stl/01_pointer_aliasing_vector/main.cpp | HuSharp/parallel101 | 882a35c254538a64d3594d112caa6d1bb5315903 | [
"CC0-1.0"
] | 1,276 | 2021-12-11T05:21:48.000Z | 2022-03-31T15:30:45.000Z | 04/7_stl/01_pointer_aliasing_vector/main.cpp | HuSharp/parallel101 | 882a35c254538a64d3594d112caa6d1bb5315903 | [
"CC0-1.0"
] | 7 | 2021-12-30T15:41:34.000Z | 2022-03-02T07:13:51.000Z | 04/7_stl/01_pointer_aliasing_vector/main.cpp | HuSharp/parallel101 | 882a35c254538a64d3594d112caa6d1bb5315903 | [
"CC0-1.0"
] | 196 | 2021-12-12T08:15:36.000Z | 2022-03-31T07:15:23.000Z | #include <vector>
void func(std::vector<int> &a,
std::vector<int> &b,
std::vector<int> &c) {
c[0] = a[0];
c[0] = b[0];
}
| 16.666667 | 32 | 0.453333 | [
"vector"
] |
e3ea5d3c7f29c7d20c5a4c8773f5a59f2fa51e07 | 6,403 | cpp | C++ | examples/abcinvaders/openglwindow.cpp | pi-etro/abc-invaders | 72e45b9ad71b03560207ff15c94be713cfd1a682 | [
"MIT"
] | null | null | null | examples/abcinvaders/openglwindow.cpp | pi-etro/abc-invaders | 72e45b9ad71b03560207ff15c94be713cfd1a682 | [
"MIT"
] | null | null | null | examples/abcinvaders/openglwindow.cpp | pi-etro/abc-invaders | 72e45b9ad71b03560207ff15c94be713cfd1a682 | [
"MIT"
] | 1 | 2021-10-31T01:28:14.000Z | 2021-10-31T01:28:14.000Z | #include "openglwindow.hpp"
#include <imgui.h>
#include "abcg.hpp"
void OpenGLWindow::handleEvent(SDL_Event &event) {
// keyboard events
if (event.type == SDL_KEYDOWN) {
if (event.key.keysym.sym == SDLK_SPACE)
m_gameData.m_input.set(static_cast<size_t>(Input::Fire));
if (event.key.keysym.sym == SDLK_LEFT || event.key.keysym.sym == SDLK_a)
m_gameData.m_input.set(static_cast<size_t>(Input::Left));
if (event.key.keysym.sym == SDLK_RIGHT || event.key.keysym.sym == SDLK_d)
m_gameData.m_input.set(static_cast<size_t>(Input::Right));
}
if (event.type == SDL_KEYUP) {
if (event.key.keysym.sym == SDLK_SPACE)
m_gameData.m_input.reset(static_cast<size_t>(Input::Fire));
if (event.key.keysym.sym == SDLK_LEFT || event.key.keysym.sym == SDLK_a)
m_gameData.m_input.reset(static_cast<size_t>(Input::Left));
if (event.key.keysym.sym == SDLK_RIGHT || event.key.keysym.sym == SDLK_d)
m_gameData.m_input.reset(static_cast<size_t>(Input::Right));
}
// mouse events
if (event.type == SDL_MOUSEBUTTONDOWN) {
if (event.button.button == SDL_BUTTON_LEFT)
m_gameData.m_input.set(static_cast<size_t>(Input::Fire));
}
if (event.type == SDL_MOUSEBUTTONUP) {
if (event.button.button == SDL_BUTTON_LEFT)
m_gameData.m_input.reset(static_cast<size_t>(Input::Fire));
}
}
void OpenGLWindow::initializeGL() {
// load new font
ImGuiIO &io{ImGui::GetIO()};
const auto filename{getAssetsPath() + "Retro-Gaming.ttf"};
m_font = io.Fonts->AddFontFromFileTTF(filename.c_str(), 60.0f);
if (m_font == nullptr) {
throw abcg::Exception{abcg::Exception::Runtime("Cannot load font file")};
}
// create program to render the objects
m_objectsProgram = createProgramFromFile(getAssetsPath() + "objects.vert",
getAssetsPath() + "objects.frag");
abcg::glClearColor(0, 0, 0, 1);
#if !defined(__EMSCRIPTEN__)
abcg::glEnable(GL_PROGRAM_POINT_SIZE);
#endif
restart();
}
void OpenGLWindow::restart() {
m_gameData.m_state = State::Playing;
m_cannon.initializeGL(m_objectsProgram);
m_bullets.initializeGL(m_objectsProgram);
m_aliens.initializeGL(m_objectsProgram);
m_rays.initializeGL(m_objectsProgram);
}
void OpenGLWindow::update() {
const float deltaTime{static_cast<float>(getDeltaTime())};
// wait 5 seconds before restarting
if (m_gameData.m_state != State::Playing &&
m_restartWaitTimer.elapsed() > 5) {
restart();
return;
}
m_cannon.update(m_gameData, deltaTime);
m_bullets.update(m_cannon, m_gameData, deltaTime);
m_aliens.update(deltaTime);
m_rays.update(m_aliens, deltaTime);
if (m_gameData.m_state == State::Playing) {
checkCollisions();
checkWinCondition();
}
}
void OpenGLWindow::paintGL() {
update();
abcg::glClear(GL_COLOR_BUFFER_BIT);
abcg::glViewport(0, 0, m_viewportWidth, m_viewportHeight);
m_cannon.paintGL(m_gameData);
m_bullets.paintGL();
m_aliens.paintGL();
m_rays.paintGL();
}
void OpenGLWindow::paintUI() {
abcg::OpenGLWindow::paintUI();
{
const auto size{ImVec2(350, 85)};
const auto position{ImVec2((m_viewportWidth - size.x) / 2.0f,
(m_viewportHeight - size.y) / 2.0f)};
ImGui::SetNextWindowPos(position);
ImGui::SetNextWindowSize(size);
ImGuiWindowFlags flags{ImGuiWindowFlags_NoBackground |
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoInputs};
ImGui::Begin(" ", nullptr, flags);
ImGui::PushFont(m_font);
if (m_gameData.m_state == State::GameOver) {
ImGui::Text("GAME OVER");
} else if (m_gameData.m_state == State::Win) {
ImGui::Text(" You Win!");
}
ImGui::PopFont();
ImGui::End();
}
}
void OpenGLWindow::resizeGL(int width, int height) {
m_viewportWidth = width;
m_viewportHeight = height;
abcg::glClear(GL_COLOR_BUFFER_BIT);
}
void OpenGLWindow::terminateGL() {
abcg::glDeleteProgram(m_objectsProgram);
m_cannon.terminateGL();
m_bullets.terminateGL();
m_aliens.terminateGL();
m_rays.terminateGL();
}
void OpenGLWindow::checkCollisions() {
// check collision between cannon and aliens
for (const auto &alien : m_aliens.m_aliens) {
const auto alienTranslation{alien.m_translation};
const auto distance{
glm::distance(m_cannon.m_translation, alienTranslation)};
if (distance < 0.1125f / 2 + 0.0825f / 2 || alien.m_translation.y < -1.0f) {
m_gameData.m_state = State::GameOver;
m_restartWaitTimer.restart();
}
}
// check collision between cannon and rays
for (auto &ray : m_rays.m_rays) {
auto rayTranslation{ray.m_translation};
auto distance{glm::distance(m_cannon.m_translation, rayTranslation)};
if (distance < 0.0225f / 2 + 0.1125f / 2 || ray.m_translation.y < -1.1f) {
ray.m_dead = true;
m_gameData.m_state = State::GameOver;
m_restartWaitTimer.restart();
}
}
// check collision between bullets and aliens
for (auto &bullet : m_bullets.m_bullets) {
if (bullet.m_dead) continue;
for (auto &alien : m_aliens.m_aliens) {
for (const auto i : {-2, 0, 2}) {
for (const auto j : {-2, 0, 2}) {
const auto alienTranslation{alien.m_translation + glm::vec2(i, j)};
const auto distance{
glm::distance(bullet.m_translation, alienTranslation)};
if (distance < 0.0075f / 2 + 0.0825f / 2) {
alien.m_hit = true;
bullet.m_dead = true;
}
}
}
}
// kill aliens marked as hit
m_aliens.m_aliens.remove_if([](const Aliens::Alien &a) { return a.m_hit; });
}
// check collision between bullets and rays
for (auto &bullet : m_bullets.m_bullets) {
if (bullet.m_dead) continue;
for (auto &ray : m_rays.m_rays) {
for (const auto i : {-2, 0, 2}) {
for (const auto j : {-2, 0, 2}) {
const auto rayTranslation{ray.m_translation + glm::vec2(i, j)};
const auto distance{
glm::distance(bullet.m_translation, rayTranslation)};
if (distance < 0.0075f / 2 + 0.0225f / 2) {
ray.m_dead = true;
bullet.m_dead = true;
}
}
}
}
}
}
void OpenGLWindow::checkWinCondition() {
if (m_aliens.m_aliens.empty()) {
m_gameData.m_state = State::Win;
m_restartWaitTimer.restart();
}
}
| 29.37156 | 80 | 0.648602 | [
"render"
] |
e3f05642749bb3b7b59d3546db9451090677a8ae | 2,799 | hpp | C++ | third-party/Empirical/include/emp/matching/selectors_static/RankedSelector.hpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/include/emp/matching/selectors_static/RankedSelector.hpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/include/emp/matching/selectors_static/RankedSelector.hpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | /**
* @note This file is part of Empirical, https://github.com/devosoft/Empirical
* @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md
* @date 2020
*
* @file RankedSelector.hpp
* @brief Selector that picks the N best matches within a threshold.
*
*/
#ifndef EMP_RANKED_SELECTOR_HPP
#define EMP_RANKED_SELECTOR_HPP
#include <algorithm>
#include <numeric>
#include <ratio>
#include "../../base/vector.hpp"
#include "../../datastructs/SmallVector.hpp"
namespace emp {
namespace statics {
/// Returns top N matches within the threshold ThreshRatio.
template<
typename ThreshRatio = std::ratio<-1,1>, // neg numerator means +infy
size_t N = 1
>
struct RankedSelector {
using res_t = emp::SmallVector<size_t, 1>;
inline static constexpr float thresh = (
ThreshRatio::num < 0
? std::numeric_limits<float>::infinity()
: static_cast<float>(ThreshRatio::num)
/ static_cast<float>(ThreshRatio::den)
);
static res_t select_partition( const emp::vector< float >& scores ) {
res_t res( scores.size() );
std::iota( std::begin(res), std::end(res), 0 );
const auto partition = std::partition(
std::begin( res ),
std::end( res ),
[&scores](const size_t idx){ return scores[idx] <= thresh; }
);
res.resize( std::distance( std::begin(res), partition ) );
return res;
}
static res_t select_traverse( const emp::vector< float >& scores ) {
res_t res;
for (size_t idx{}; idx < scores.size(); ++idx) {
if ( scores[idx] > thresh ) continue;
res.push_back( idx );
if ( res.size() <= N ) continue;
const auto worst_it = std::max_element(
std::begin( res ),
std::end( res ),
[&scores](const size_t a, const size_t b){
return scores[a] < scores[b];
}
);
// swap 'n' pop
*worst_it = res.back();
res.pop_back();
}
return res;
}
static res_t select_pick( const emp::vector< float>& scores ) {
res_t res;
if ( scores.empty() ) return res;
const auto best_it = std::min_element(
std::begin( scores ),
std::end( scores )
);
// if constexpr threshold is finite, then if best was better than thresh
if constexpr ( ThreshRatio::num >= 0 ) if (*best_it > thresh) return res;
res.push_back( std::distance( std::begin( scores ), best_it ) );
return res;
}
static res_t select( const emp::vector< float >& scores ) {
if constexpr (N == std::numeric_limits<size_t>::max() ) {
return select_partition( scores );
} else if constexpr (N == 1) return select_pick( scores );
else return select_traverse( scores );
}
};
} // namespace statics
} // namespace emp
#endif // #ifndef EMP_RANKED_SELECTOR_HPP
| 23.521008 | 96 | 0.628439 | [
"vector"
] |
e3f3961634f7b358fb83c814f02e1119ee0baa95 | 755 | cpp | C++ | 713.subarray-product-less-than-k.166266173.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 713.subarray-product-less-than-k.166266173.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 713.subarray-product-less-than-k.166266173.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int count=0;
/*
for(int i=0;i<nums.size();i++)
{
long long int prod=1;
for(int j=i;j<nums.size();j++)
{
prod*=nums[j];
if(prod<k)count++;
}
}
return count;
*/
int start = 0;
int end=0;
long long int prod=1;
while(end<nums.size())
{
prod*=nums[end];
while(prod>=k&&start<=end)
prod/=nums[start++];
count+=end-start+1;
end++;
}
return count;
}
};
| 20.972222 | 63 | 0.366887 | [
"vector"
] |
e3f789d1bff7407db30189c6c03b1df40d2ec7ad | 226 | cpp | C++ | src/AcetylCompound.cpp | jweinst1/acetyl | 2d092b882b966fb645cf7cc89b4f8465294a7810 | [
"MIT"
] | null | null | null | src/AcetylCompound.cpp | jweinst1/acetyl | 2d092b882b966fb645cf7cc89b4f8465294a7810 | [
"MIT"
] | null | null | null | src/AcetylCompound.cpp | jweinst1/acetyl | 2d092b882b966fb645cf7cc89b4f8465294a7810 | [
"MIT"
] | null | null | null | #include "AcetylCompound.h"
bool AcetylCompound::hasId(const char* id) const
{
for(std::vector<AcetylElement>::const_iterator it = begin(); it != end(); it++)
{
if(it->isId(id)) {
return true;
}
}
return false;
}
| 16.142857 | 80 | 0.641593 | [
"vector"
] |
e3fe6df51f825191b061730e8a8854c0c131a42c | 1,615 | cpp | C++ | src/vedo/common/CDSphere2Sphere.cpp | IAries/VEDO | 8268005d381268cafcf7024ff38fef91c6318ef4 | [
"BSD-3-Clause"
] | null | null | null | src/vedo/common/CDSphere2Sphere.cpp | IAries/VEDO | 8268005d381268cafcf7024ff38fef91c6318ef4 | [
"BSD-3-Clause"
] | null | null | null | src/vedo/common/CDSphere2Sphere.cpp | IAries/VEDO | 8268005d381268cafcf7024ff38fef91c6318ef4 | [
"BSD-3-Clause"
] | null | null | null | #include <vedo/common/CDSphere2Sphere.h>
#include <vedo/common/DOSphere.h>
#include <aries/utility/Constants.h>
namespace vedo
{
CDSphere_Sphere::CDSphere_Sphere(): ContactDetector()
{
cInfo.uShapeTypeSlave = DOShapeType::Sphere;
cInfo.uShapeTypeMaster = DOShapeType::Sphere;
}
void CDSphere_Sphere::CalDistance(const DiscreteObject* pdoSlave, const DiscreteObject* pdoMaster)
{
// Impact std::vector form slave to master
Vector3df vIm = pdoMaster->GetDOStatus()->GetPosition() - pdoSlave->GetDOStatus()->GetPosition();
if(this->pBC)
{
this->pBC->DifferenceBoundaryConditions(&vIm);
}
cInfo.vCenterToCenter = vIm;
_float_t dRa = pdoSlave->GetDOModel()->GetShapeAttributes().sphere.radius;
_float_t dRb = pdoMaster->GetDOModel()->GetShapeAttributes().sphere.radius;
cInfo.dImpactDepth = dRa + dRb - vIm.length();
if(cInfo.dImpactDepth > 0.0)
{
_float_t dS = dRa - cInfo.dImpactDepth * dRb / (dRa + dRb);
cInfo.dOverlapArea = (dRa * dRa - dS * dS) * aries::math::_PI;
}
else
{
cInfo.dOverlapArea = 0.0;
}
cInfo.vImpactDirection = vIm.direction();
}
void CDSphere_Sphere::Detect(const DiscreteObject* pdoSlave, const DiscreteObject* pdoMaster)
{
CDSphere_Sphere::CalDistance(pdoSlave, pdoMaster);
cInfo.vImpactPoint
= pdoSlave->GetDOStatus()->GetPosition()
+ (pdoSlave->GetDOModel()->GetShapeAttributes().sphere.radius - 0.5 * cInfo.dImpactDepth) * cInfo.vImpactDirection;
if (cInfo.dImpactDepth > 0)
{
cInfo.bUnBalance = (cInfo.bActive == false);
cInfo.bActive = true;
}
else
{
cInfo.bActive = false;
cInfo.bUnBalance = false;
}
}
} // namespace vedo
| 25.634921 | 117 | 0.722601 | [
"vector"
] |
e3ffa60f9753476cd91fe8c734a1f1f0fb2ea0e8 | 3,925 | c++ | C++ | src/Ogita.d/main.c++ | naruto2/CodeFEM | eb689aa7573d4ac9fc83d057f99c79a5d8f3bd90 | [
"MIT"
] | 1 | 2020-09-27T07:28:04.000Z | 2020-09-27T07:28:04.000Z | src/Ogita.d/main.c++ | naruto2/CodeFEM | eb689aa7573d4ac9fc83d057f99c79a5d8f3bd90 | [
"MIT"
] | null | null | null | src/Ogita.d/main.c++ | naruto2/CodeFEM | eb689aa7573d4ac9fc83d057f99c79a5d8f3bd90 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <vector>
#include <future>
#include <thread>
#include <unistd.h>
#include "est/sparse.hpp"
#include "est/op.hpp"
#include "est/xmesh.hpp"
#include "est/matrix.hpp"
#include "est/solver.hpp"
using namespace std;
vector<xyc> ncpolynomial1(vector<xyc> Z, vector<nde> &N );
void estiva_forgammap1(long *x);
int estiva_forgammap1_loop(long *x, const char *name, vector<xyc> &Z);
void printmatrix(sparse::matrix<double> &A, const char *name);
void printvector(vector<double> &b, const char *name);
void plotncpolynomial1(vector<xyc> Mid, vector<double> x);
void setanimefilename(const char *fname);
void squaremesh(int n, vector<xyc> &Z);
void start_baton(void);
int end_baton(void);
#define batonth() for(start_baton();end_baton();)
void mkcont(int argc, char**argv);
void contop(int &argc0, char** &argv0);
int kbhit(void);
vector<double> S_(vector<xyc> &Z, vector<nde> &N);
sparse::matrix<double> M__(vector<xyc> &Mid, vector<nde> &N, vector<double> &S);
sparse::matrix<double> K__(vector<xyc> &Mid, vector<xyc> &Z, vector<nde> &N, vector<double> &S);
sparse::matrix<double> Hx__(vector<xyc> &Mid, vector<xyc> &Z, vector<nde> &N);
sparse::matrix<double> Hy__(vector<xyc> &Mid, vector<xyc> &Z, vector<nde> &N);
void A__(sparse::matrix<double> &A, vector<xyc> &Mid, vector<nde> &N, sparse::matrix<double> &M, double tau, sparse::matrix<double> &K, sparse::matrix<double> &Hx, sparse::matrix<double> &Hy);
void Rhs(vector<double> &b, vector<xyc> &Mid, vector<nde> &N,sparse::matrix<double> &M,double t,vector<double> &Fx,vector<double> &Fy,
vector<double> &Ux, vector<double> &Uy, vector<double> &x);
void boundary_condition(vector<nde> &N, vector<xyc> &Mid, sparse::matrix<double> &A, vector<double> &b);
int main(int argc, char ** argv)
{
initop(argc,argv);
vector<xyc> Z;
vector<nde> N;
{
unsigned long n = 16;
if ( defop("-n") ) n = atoi(getop("-n").c_str());
squaremesh(n,Z);
}
delaunay(Z, N);
sortmesh(Z,N);
vector<xyc> Mid = ncpolynomial1(Z,N);
vector<double> S = S_(Z,N);
unsigned long m = Mid.size()-1;
unsigned long n = S.size()-1;
unsigned long NUM = 2*m+n;
sparse::matrix<double> M = M__(Mid, N, S);
sparse::matrix<double> K = K__(Mid, Z, N, S);
sparse::matrix<double> Hx= Hx__(Mid, Z, N);
sparse::matrix<double> Hy= Hy__(Mid, Z, N);
double t = 0.001;
if ( defop("-t") ) t = atof(getop("-t").c_str());
vector<double> Fx(m+1), Fy(m+1), Ux(m+1), Uy(m+1), x(NUM+1), b(NUM+1);
sparse::matrix<double> A;
unsigned long i, k;
for ( k = 1; k<=60; k++ ) {
A__(A, Mid, N, M,t,K,Hx,Hy);
Rhs(b, Mid, N, M, t, Fx, Fy, Ux, Uy, x);
boundary_condition(N,Mid,A,b);
printf("\nk = %ld \n",k);
//x = solve(A,b);
#define nonzeroloop(A) for(i=0; i<A.size(); i++) for ( auto it : A[i] ) if( A[i][(j=it.first)] != 0.0 )
{ int i, j; double t;
/*
NUM=3;
A.clear();
A.resize(NUM+1);
A[1][1] = 1.0; A[1][2] = 1.0; A[1][3] = 0;
A[2][1] = 0.0; A[2][2] = 1.0; A[2][3] = 1;
A[3][1] = 0.0; A[3][2] = 0.0; A[3][3] = 1;
b[1] = 2; b[2] = 1;
*/
sparse::matrix<double> B;
B.clear();
B.resize(2*NUM+1);
for(i=1;i<=NUM;i++)for(j=1;j<=NUM;j++)if((t=A[i][j]+A[j][i])!=0.0) {
B[i][j] = t;
B[i+NUM][j+NUM] = -t;
}
for(i=1;i<=NUM;i++)for(j=1;j<=NUM;j++)if((t=A[i][j]-A[j][i])!=0.0) {
B[i][j+NUM] = t;
B[i+NUM][j] = -t;
}
B[0][0] = 1;
vector<double> xx(2*NUM+1), bb(2*NUM+1);
for(i=1;i<=NUM;i++){ bb[i] = 2.0*b[i]; bb[i+NUM] = -2.0*b[i];}
//printmatrix(B,"B");
xx = solve(B,bb);
exit(0);
}
for(i=1;i<m;i++){ Ux[i] = x[i]; Uy[i] = x[i+m];}
if (defop("-o")) setanimefilename(getop("-o").c_str());
plotncpolynomial1(Mid, x);
}
return 0;
}
| 29.074074 | 192 | 0.575541 | [
"vector"
] |
5404ec3e9617420c2f3e55528ec815657892fbab | 827 | cc | C++ | tsdf_plusplus/src/mesh/color_map.cc | TheMangalex/tsdf-plusplus | aefb7fa40b53475ce424d5082b3045587bbb5de3 | [
"MIT"
] | 91 | 2021-05-18T03:15:18.000Z | 2022-03-28T01:53:02.000Z | tsdf_plusplus/src/mesh/color_map.cc | ali-robot/tsdf-plusplus | 602f2aeec267a82ac3c5d88ef3eabba2ea2f3c04 | [
"MIT"
] | 4 | 2021-05-18T06:10:20.000Z | 2022-01-25T11:38:33.000Z | tsdf_plusplus/src/mesh/color_map.cc | cmrobotics/tsdf-plusplus | 9cb15273b2bd5e7b13f67ef563856d2f92cd34dd | [
"MIT"
] | 16 | 2021-05-18T02:17:48.000Z | 2022-03-07T02:57:01.000Z | // Copyright (c) 2020- Margarita Grinvald, Autonomous Systems Lab, ETH Zurich
// Licensed under the MIT License (see LICENSE for details)
#include "tsdf_plusplus/mesh/color_map.h"
#include <voxblox/core/color.h>
void ColorMap::getColor(const ObjectID& object_id, voxblox::Color* color) {
CHECK_NOTNULL(color);
CHECK_NE(object_id, EmptyID);
std::map<ObjectID, voxblox::Color>::iterator color_map_it;
{
std::shared_lock<std::shared_timed_mutex> readerLock(color_map_mutex_);
color_map_it = color_map_.find(object_id);
}
if (color_map_it != color_map_.end()) {
*color = color_map_it->second;
} else {
*color = voxblox::randomColor();
std::lock_guard<std::shared_timed_mutex> writerLock(color_map_mutex_);
color_map_.insert(std::pair<ObjectID, voxblox::Color>(object_id, *color));
}
}
| 30.62963 | 78 | 0.726723 | [
"mesh"
] |
541076e6a0b42596ee15052cc50f4397c320af23 | 837 | cpp | C++ | codes/ch3-filter-example.cpp | polossk/Zero-Kara-FCPP | 4cc3110b6c01dbfb07edc3e2b7f81e8d4f31bb67 | [
"MIT"
] | 77 | 2018-09-15T11:33:39.000Z | 2022-02-20T09:10:36.000Z | codes/ch3-filter-example.cpp | polossk/Zero-Kara-FCPP | 4cc3110b6c01dbfb07edc3e2b7f81e8d4f31bb67 | [
"MIT"
] | null | null | null | codes/ch3-filter-example.cpp | polossk/Zero-Kara-FCPP | 4cc3110b6c01dbfb07edc3e2b7f81e8d4f31bb67 | [
"MIT"
] | 7 | 2018-11-09T07:05:50.000Z | 2021-02-03T12:24:59.000Z | #include <iostream>
#include <algorithm>
#include <vector>
using std::cout;
using std::endl;
int main()
{
auto print_value = [](auto v){ for (auto e : v) cout << " " << int(e); cout << endl; };
#define DISPLAY_VALUE(v) do { cout << #v ":"; print_value(v); } while (0);
std::vector<int> a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<int> b;
std::copy_if(a.begin(), a.end(), std::back_inserter(b),
[](int _){ return _ % 2; });
DISPLAY_VALUE(a); // => a: 1 2 3 4 5 6 7 8 9 10
DISPLAY_VALUE(b); // => b: 1 3 5 7 9
a.erase(std::remove_if(a.begin(), a.end(), [](int _){ return _ % 2; }),
a.end());
DISPLAY_VALUE(a); // => a: 2 4 6 8 10
#undef DISPLAY_VALUE
return 0;
}
// filename: ch3-filter-example.cpp
// compile this> g++ ch3-filter-example.cpp -o ch3-filter-example.exe
| 31 | 91 | 0.555556 | [
"vector"
] |
5410f639de2ab5624bed9aa242921f180cddcd2f | 9,099 | cpp | C++ | week 5/project.cpp | mtereshkin/coursera-white-belt-cpp | 54c57315bdc8733ebfdbd83b72d767f1c6e9a2d7 | [
"MIT"
] | null | null | null | week 5/project.cpp | mtereshkin/coursera-white-belt-cpp | 54c57315bdc8733ebfdbd83b72d767f1c6e9a2d7 | [
"MIT"
] | null | null | null | week 5/project.cpp | mtereshkin/coursera-white-belt-cpp | 54c57315bdc8733ebfdbd83b72d767f1c6e9a2d7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include<algorithm>
#include <stdexcept>
#include <iostream>
#include <exception>
#include <string>
#include <iomanip>
#include <iterator>
using namespace std;
class Date {
public:
Date(int year_input, int month_input, int day_input) {
if (month_input < 1 || month_input > 12) {
throw invalid_argument("Month value is invalid: " + to_string(month_input));
}
else if (day_input < 1 || day_input > 31) {
throw invalid_argument("Day value is invalid: " + to_string(day_input));
}
year = year_input;
month = month_input;
day = day_input;
}
int GetYear() const {
return year;
}
int GetMonth() const {
return month;
}
int GetDay() const {
return day;
}
private:
int year;
int month;
int day;
};
bool operator<(const Date& lhs, const Date& rhs) {
if (lhs.GetYear() < rhs.GetYear()) {
return true;
}
else if (lhs.GetYear() > rhs.GetYear()) {
return false;
}
else {
if (lhs.GetMonth() < rhs.GetMonth()) {
return true;
} else if (lhs.GetMonth() > rhs.GetMonth()) {
return false;
}
else {
return lhs.GetDay() < rhs.GetDay();
}
}
}
class Database {
public:
void AddEvent(const Date& date, const string& event) {
if (count(begin(dates_events[date]), end(dates_events[date]), event) == 0) {
dates_events[date].push_back(event);
}
}
bool DeleteEvent(const Date& date, const string& event) {
if (count(begin(dates_events[date]), end(dates_events[date]), event) == 0) {
return false;
}
else {
dates_events[date].erase(find(begin(dates_events[date]), end(dates_events[date]), event));
return true;
}
}
int DeleteDate(const Date& date) {
int N = dates_events[date].size();
dates_events.erase(date);
return N;
}
vector<string> Find(const Date& date) {
bool ind = false;
for (auto &item:dates_events) {
if (item.first.GetYear() == date.GetYear() && item.first.GetMonth() == date.GetMonth() && item.first.GetDay() == date.GetDay()) {
ind = true;
}
}
if (ind) {
sort(begin(dates_events.at(date)), end(dates_events.at(date)));
return dates_events.at(date);
}
else {
throw out_of_range("");
}
}
void Print() {
for (auto& item: dates_events) {
sort(begin(item.second), end(item.second));
for (auto& event:item.second) {
cout << setw(4) << setfill('0') << item.first.GetYear() << '-' << setw(2) <<
setfill('0')<<item.first.GetMonth()<< '-' << setw(2) <<setfill('0')<<item.first.GetDay()<<
' '<< event<<endl;
}
}
}
private:
map<Date, vector<string>> dates_events;
};
int main() {
Database db;
string command;
while (getline(cin, command)) {
stringstream ss;
if (command.substr(0, 3) == "Add") {
ss << command.substr(4, command.size() - 4);
string event;
int year;
int month;
int day;
bool flag = true;
ss>>year;
if (ss.bad() || ss.peek() != '-') {
flag = false;
cout << "Wrong date format: " << command.substr(4, find(begin(command) + 4, end(command), ' ') - begin(command) - 4) << endl;
}
else {
ss.ignore(1);
ss >> month;
if (ss.bad() || ss.peek() != '-') {
flag = false;
cout << "Wrong date format: " << command.substr(4, find(begin(command) + 4, end(command), ' ') - begin(command) - 4) << endl;
} else {
ss.ignore(1);
ss >> day;
if (ss.bad() || ss.peek() != ' ') {
flag = false;
cout << "Wrong date format: " << command.substr(4, find(begin(command) + 4, end(command), ' ') - begin(command) - 4) << endl;
}
else {
ss>> event;
}
}
}
if (flag) {
try {
Date date = Date(year, month, day);
db.AddEvent(date, event);
}
catch (invalid_argument& inv_arg) {
cout << inv_arg.what()<<endl;
}
}
}
else if (command.substr(0, 4) == "Find") {
ss << command.substr(5, command.size() - 5);
string event;
int year;
int month;
int day;
bool flag = true;
ss>>year;
if (ss.bad() || ss.peek() != '-') {
flag = false;
cout << "Wrong date format: " << command.substr(5, find(begin(command) + 5, end(command), ' ') - begin(command) - 5) << endl;
}
else {
ss.ignore(1);
ss >> month;
if (ss.bad() || ss.peek() != '-') {
flag = false;
cout << "Wrong date format: " << command.substr(5, find(begin(command) + 5, end(command), ' ') - begin(command) - 5) << endl;
} else {
ss.ignore(1);
ss >> day;
if (ss.bad()) {
flag = false;
cout << "Wrong date format: " << command.substr(5, find(begin(command) + 5, end(command), ' ') - begin(command) - 5) << endl;
}
else {
}
}
}
if (flag) {
try {
Date date = Date(year, month, day);
vector<string> events = db.Find(date);
for (auto &item: events) {
cout << item <<endl;
}
}
catch (invalid_argument& inv_arg) {
cout << inv_arg.what()<<endl;
}
catch (out_of_range& out) {
}
}
}
else if (command.substr(0, 5) == "Print") {
db.Print();
}
else if (command.substr(0, 3) == "Del") {
ss << command.substr(4, command.size() - 4);
string event;
int year;
int month;
int day;
bool flag = true;
ss>>year;
if (ss.bad() || ss.peek() != '-') {
flag = false;
cout << "Wrong date format: " << command.substr(4, find(begin(command) + 4, end(command), ' ') - begin(command) - 4) << endl;
}
else {
ss.ignore(1);
ss >> month;
if (ss.bad() || ss.peek() != '-') {
flag = false;
cout << "Wrong date format: " << command.substr(4, find(begin(command) + 4, end(command), ' ') - begin(command) - 4) << endl;
} else {
ss.ignore(1);
ss >> day;
if (ss.bad() || !ss.eof() && ss.peek() != ' ') {
flag = false;
cout << "Wrong date format: " << command.substr(4, find(begin(command) + 4, end(command), ' ') - begin(command) - 4) << endl;
}
}
}
if (flag) {
if (ss.eof()) {
try {
Date date = Date(year, month, day);
int n = db.DeleteDate(date);
cout << "Deleted " << n <<" events"<<endl;
}
catch (invalid_argument& inv_arg) {
cout << inv_arg.what()<<endl;
}
}
else {
ss >> event;
try {
Date date = Date(year, month, day);
bool indicator = db.DeleteEvent(date, event);
if (indicator) {
cout << "Deleted successfully" <<endl;
}
else {
cout <<"Event not found" <<endl;
}
}
catch (invalid_argument& inv_arg) {
cout << inv_arg.what()<<endl;
}
}
}
}
else if (!command.empty()) {
cout << "Unknown command:" << ' ' <<command.substr(0, find(begin(command), end(command), ' ') - begin(command))
<<endl;
}
}
return 0;
}
| 32.151943 | 149 | 0.411803 | [
"vector"
] |
5418c01f15ab1df5c5bb6987a85093893285bffd | 1,205 | cpp | C++ | src/main/cpp/binarysearch/edges_that_disconnect_the_graph.cpp | jo3-l/cp-practice | d1db0c8e9269c8720b31013068dff948b33f57fd | [
"MIT"
] | 5 | 2022-01-05T20:15:47.000Z | 2022-02-15T22:40:44.000Z | src/main/cpp/binarysearch/edges_that_disconnect_the_graph.cpp | jo3-l/ccc-java | 7a77f365e52496967e5265ecefb34f3b7db5fae8 | [
"MIT"
] | 3 | 2022-01-06T01:34:42.000Z | 2022-01-20T23:46:53.000Z | src/main/cpp/binarysearch/edges_that_disconnect_the_graph.cpp | jo3-l/ccc-java | 7a77f365e52496967e5265ecefb34f3b7db5fae8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
template <class Fun> class y_combinator_result {
Fun fun_;
public:
template <class T> explicit y_combinator_result(T &&fun) : fun_(std::forward<T>(fun)) {}
template <class... Args> decltype(auto) operator()(Args &&...args) { return fun_(std::ref(*this), std::forward<Args>(args)...); }
};
template <class Fun> decltype(auto) y_combinator(Fun &&fun) { return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun)); }
bool vis[250];
int seen_at[250];
int lo_link[250];
int solve(vector<vector<int>> &graph) {
memset(vis, false, sizeof(vis));
memset(seen_at, -1, sizeof(seen_at));
memset(lo_link, -1, sizeof(lo_link));
int ctr = 0, bridges = 0;
auto dfs = y_combinator([&](auto dfs, int node, int par = -1) -> void {
vis[node] = true;
seen_at[node] = lo_link[node] = ctr++;
for (int to : graph[node]) {
if (to == par) continue;
if (vis[to]) {
lo_link[node] = min(lo_link[node], seen_at[to]);
} else {
dfs(to, node);
lo_link[node] = min(lo_link[node], lo_link[to]);
if (lo_link[to] > seen_at[node]) bridges++;
}
}
});
for (int i = 0; i < graph.size(); i++) {
if (!vis[i]) dfs(i);
}
return bridges;
} | 28.690476 | 134 | 0.629876 | [
"vector"
] |
541ec14eb94f24da28b053ef79ce4ad2e101c1d4 | 1,518 | cpp | C++ | ZJ/zj a017.cpp | Xi-Plus/OJ-Code | 7ff6d691f34c9553d53dc9cddf90ad7dc7092349 | [
"MIT"
] | null | null | null | ZJ/zj a017.cpp | Xi-Plus/OJ-Code | 7ff6d691f34c9553d53dc9cddf90ad7dc7092349 | [
"MIT"
] | null | null | null | ZJ/zj a017.cpp | Xi-Plus/OJ-Code | 7ff6d691f34c9553d53dc9cddf90ad7dc7092349 | [
"MIT"
] | null | null | null | // By xiplus
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
vector<char> op;
vector<int> ans;
map<char, int> oporder;
int a, b;
bool ophigher(char op1, char op2) {
return oporder[op1] < oporder[op2];
}
void action(char c) {
b = ans.back(); ans.pop_back();
a = ans.back(); ans.pop_back();
switch(c) {
case '+': a+=b; break;
case '-': a-=b; break;
case '*': a*=b; break;
case '/': a/=b; break;
case '%': a%=b; break;
}
ans.push_back(a);
}
int main(){
// ios::sync_with_stdio(false);
// cin.tie(0);
char q,w;
oporder['('] = 2;
oporder[')'] = 2;
oporder['*'] = 5;
oporder['/'] = 5;
oporder['%'] = 5;
oporder['+'] = 6;
oporder['-'] = 6;
oporder['#'] = 100;
string s;
int a, b;
char c;
while(getline(cin, s)){
stringstream ss(s);
op.clear();
op.push_back('#');
ans.clear();
ans.push_back(0);
while(ss>>s){
c=s[0];
switch(c){
case '(':
op.push_back('(');
break;
case ')':
while(op.back()!='(') {
action(op.back());
op.pop_back();
}
op.pop_back();
break;
default:
if(oporder[c]!=0) {
if(ophigher(c, op.back())) {
op.push_back(c);
} else {
while(!ophigher(c, op.back()) && op.back() != '(') {
action(op.back());
op.pop_back();
}
op.push_back(c);
}
} else {
a=atoi(s.c_str());
ans.push_back(a);
}
break;
}
}
while(op.back() != '#') {
action(op.back());
op.pop_back();
}
cout<<ans.back()<<endl;
}
}
| 18.289157 | 59 | 0.498024 | [
"vector"
] |
f9ac30017eb8b1ca70fefb6d5a61967489908e7d | 8,567 | cpp | C++ | Speck/Speck/JointShowcaseState.cpp | Bojanovski/Speck | 41d64de63c54424e06b66f653e854cab8a1cc6f8 | [
"MIT"
] | 4 | 2019-01-27T01:17:27.000Z | 2021-09-16T05:29:33.000Z | Speck/Speck/JointShowcaseState.cpp | Bojanovski/Speck | 41d64de63c54424e06b66f653e854cab8a1cc6f8 | [
"MIT"
] | null | null | null | Speck/Speck/JointShowcaseState.cpp | Bojanovski/Speck | 41d64de63c54424e06b66f653e854cab8a1cc6f8 | [
"MIT"
] | null | null | null |
#include "JointShowcaseState.h"
#include <EngineCore.h>
#include <ProcessAndSystemData.h>
#include <AppCommands.h>
#include <WorldCommands.h>
#include <World.h>
#include <InputHandler.h>
#include <SetLookAtCameraController.h>
#include "SpeckPrimitivesGenerator.h"
#include "StaticPrimitivesGenerator.h"
using namespace std;
using namespace DirectX;
using namespace Speck;
JointShowcaseState::JointShowcaseState(EngineCore &mEC)
: AppState(),
mCC(mEC)
{
}
JointShowcaseState::~JointShowcaseState()
{
}
#pragma optimize("", off)
void JointShowcaseState::Initialize()
{
AppCommands::LimitFrameTimeCommand lftc;
lftc.minFrameTime = 1.0f / 60.0f;
GetApp().ExecuteCommand(lftc);
WorldCommands::GetWorldPropertiesCommand gwp;
WorldCommands::GetWorldPropertiesCommandResult gwpr;
GetWorld().ExecuteCommand(gwp, &gwpr);
float speckRadius = gwpr.speckRadius;
WorldCommands::SetSpecksSolverParametersCommand sspc;
sspc.substepsIterations = 4;
GetWorld().ExecuteCommand(sspc);
//
// PBR testing
//
AppCommands::LoadResourceCommand lrc_albedo;
lrc_albedo.name = "spaced-tiles1-albedo";
lrc_albedo.path = L"Data/Textures/spaced-tiles1/spaced-tiles1-albedo.dds";
lrc_albedo.resType = AppCommands::ResourceType::Texture;
GetApp().ExecuteCommand(lrc_albedo);
AppCommands::LoadResourceCommand lrc_normal;
lrc_normal.name = "spaced-tiles1-normal";
lrc_normal.path = L"Data/Textures/spaced-tiles1/spaced-tiles1-normal.dds";
lrc_normal.resType = AppCommands::ResourceType::Texture;
GetApp().ExecuteCommand(lrc_normal);
AppCommands::LoadResourceCommand lrc_height;
lrc_height.name = "spaced-tiles1-height";
lrc_height.path = L"Data/Textures/spaced-tiles1/spaced-tiles1-height.dds";
lrc_height.resType = AppCommands::ResourceType::Texture;
GetApp().ExecuteCommand(lrc_height);
AppCommands::LoadResourceCommand lrc_metalness;
lrc_metalness.name = "spaced-tiles1-metalness";
lrc_metalness.path = L"Data/Textures/spaced-tiles1/spaced-tiles1-metalness.dds";
lrc_metalness.resType = AppCommands::ResourceType::Texture;
GetApp().ExecuteCommand(lrc_metalness);
AppCommands::LoadResourceCommand lrc_rough;
lrc_rough.name = "spaced-tiles1-rough";
lrc_rough.path = L"Data/Textures/spaced-tiles1/spaced-tiles1-rough.dds";
lrc_rough.resType = AppCommands::ResourceType::Texture;
GetApp().ExecuteCommand(lrc_rough);
AppCommands::LoadResourceCommand lrc_ao;
lrc_ao.name = "spaced-tiles1-ao";
lrc_ao.path = L"Data/Textures/spaced-tiles1/spaced-tiles1-ao.dds";
lrc_ao.resType = AppCommands::ResourceType::Texture;
GetApp().ExecuteCommand(lrc_ao);
AppCommands::CreateMaterialCommand cmc_pbr;
cmc_pbr.materialName = "pbrMatTest";
//cmc_pbr.albedoTexName = lrc_albedo.name;
//cmc_pbr.normalTexName = lrc_normal.name;
//cmc_pbr.heightTexName = lrc_height.name;
//cmc_pbr.metalnessTexName = lrc_metalness.name;
//cmc_pbr.roughnessTexName = lrc_rough.name;
//cmc_pbr.aoTexName = lrc_ao.name;
cmc_pbr.DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
cmc_pbr.FresnelR0 = XMFLOAT3(0.02f, 0.02f, 0.02f);
cmc_pbr.Roughness = 1.0f;
GetApp().ExecuteCommand(cmc_pbr);
//
// Generate the world
//
StaticPrimitivesGenerator staticPrimGen(GetWorld());
staticPrimGen.GenerateBox({ 270.0f, 5.0f, 270.0f }, "pbrMatTest", { 0.0f, -4.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }); // ground
SpeckPrimitivesGenerator speckPrimGen(GetWorld());
speckPrimGen.GeneratreConstrainedRigidBodyPair(SpeckPrimitivesGenerator::ConstrainedRigidBodyPairType::StiffJoint, { -10.0f, 10.0f, 0.0f }, { 0.0f, 0.0f, XM_PIDIV2 });
speckPrimGen.GeneratreConstrainedRigidBodyPair(SpeckPrimitivesGenerator::ConstrainedRigidBodyPairType::HingeJoint, { -00.0f, 10.0f, 0.0f }, { 0.0f, 0.0f, XM_PIDIV2 });
//speckPrimGen.GeneratreConstrainedRigidBodyPair(SpeckPrimitivesGenerator::ConstrainedRigidBodyPairType::AsymetricHingeJoint, { 0.0f, 10.0f, 0.0f }, { 0.0f, 0.0f, XM_PIDIV2 });
speckPrimGen.GeneratreConstrainedRigidBodyPair(SpeckPrimitivesGenerator::ConstrainedRigidBodyPairType::BallAndSocket, { 10.0f, 10.0f, 0.0f }, { 0.0f, 0.0f, XM_PIDIV2 });
speckPrimGen.GeneratreConstrainedRigidBodyPair(SpeckPrimitivesGenerator::ConstrainedRigidBodyPairType::UniversalJoint, { 20.0f, 10.0f, 0.0f }, { 0.0f, 0.0f, XM_PIDIV2 });
//speckPrimGen.GenerateBox(1, 4, 4, "pbrMatTest", false, { -5.0f, 20.0f, 0.0f }, { 0.0f, 0.0f, 1.0f });
//speckPrimGen.GenerateBox(1, 1, 4, "pbrMatTest", false, { 0.0f, 20.0f, 0.0f }, { 0.0f, 0.0f, 1.0f });
//speckPrimGen.GenerateBox(4, 4, 1, "pbrMatTest", false, { 5.0f, 20.0f, 0.0f }, { 0.0f, 0.0f, 1.0f });
// add gravity
WorldCommands::AddExternalForceCommand efc;
efc.vector = XMFLOAT3(0.0f, -10.0f, 0.0f);
efc.type = ExternalForces::Types::Acceleration;
GetWorld().ExecuteCommand(efc);
// modify the time
WorldCommands::SetTimeMultiplierCommand stmc;
stmc.timeMultiplierConstant = 1.0f;
GetWorld().ExecuteCommand(stmc);
// position the camera
SetLookAtCameraController slacc(XMFLOAT3(0.0f, 28.0f, -30.0f), XMFLOAT3(0.0f, 10.0f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f));
AppCommands::UpdateCameraCommand ucc;
ucc.ccPt = &slacc;
GetApp().ExecuteCommand(ucc);
// set title
AppCommands::SetWindowTitleCommand cmd;
cmd.text = L"Press 1, 2 & 3 to change the angular velocity. Press F to release.";
GetApp().ExecuteCommand(cmd);
}
#pragma optimize("", on)
void JointShowcaseState::Update(float dt)
{
mCC.Update(dt);
AppCommands::UpdateCameraCommand ucc;
ucc.ccPt = &mCC;
ucc.deltaTime = dt;
GetApp().ExecuteCommand(ucc);
auto ih = GetApp().GetEngineCore().GetInputHandler();
float fPressedTime;
ih->IsPressed(0x46, &fPressedTime); // F key
static float anglularVelocity = 1.0f;
static float angle = 0.0f;
float pressed_1_Time;
ih->IsPressed(0x31, &pressed_1_Time); // 1 key
if (pressed_1_Time > 0.0f) anglularVelocity += dt * 2.0f;
float pressed_2_Time;
ih->IsPressed(0x32, &pressed_2_Time); // 2 key
if (pressed_2_Time > 0.0f) anglularVelocity = 0.0f;
float pressed_3_Time;
ih->IsPressed(0x33, &pressed_3_Time); // 3 key
if (pressed_3_Time > 0.0f) anglularVelocity -= dt * 2.0f;
angle += anglularVelocity * dt;
if (fPressedTime == 0.0f)
{
WorldCommands::UpdateSpeckRigidBodyCommand command;
command.movementMode = WorldCommands::RigidBodyMovementMode::CPU;
command.rigidBodyIndex = 0;
XMStoreFloat3(&command.transform.mT, XMVectorSet(-10.0f, 10.0f, 0.0f, 1.0f));
XMStoreFloat4(&command.transform.mR, XMQuaternionRotationRollPitchYaw(angle, 0, 0));
GetWorld().ExecuteCommand(command);
command.movementMode = WorldCommands::RigidBodyMovementMode::CPU;
command.rigidBodyIndex = 2;
XMStoreFloat3(&command.transform.mT, XMVectorSet(0.0f, 10.0f, 0.0f, 1.0f));
XMStoreFloat4(&command.transform.mR, XMQuaternionRotationRollPitchYaw(angle, 0, 0));
GetWorld().ExecuteCommand(command);
command.movementMode = WorldCommands::RigidBodyMovementMode::CPU;
command.rigidBodyIndex = 4;
XMStoreFloat3(&command.transform.mT, XMVectorSet(10.0f, 10.0f, 0.0f, 1.0f));
XMStoreFloat4(&command.transform.mR, XMQuaternionRotationRollPitchYaw(angle, 0, 0));
GetWorld().ExecuteCommand(command);
command.movementMode = WorldCommands::RigidBodyMovementMode::CPU;
command.rigidBodyIndex = 6;
XMStoreFloat3(&command.transform.mT, XMVectorSet(20.0f, 10.0f, 0.0f, 1.0f));
XMStoreFloat4(&command.transform.mR, XMQuaternionRotationRollPitchYaw(angle, 0, 0));
GetWorld().ExecuteCommand(command);
//command.movementMode = WorldCommands::RigidBodyMovementMode::CPU;
//command.rigidBodyIndex = 8;
//XMStoreFloat3(&command.transform.mT, XMVectorSet(20.0f, 10.0f, 0.0f, 1.0f));
//XMStoreFloat4(&command.transform.mR, XMQuaternionRotationRollPitchYaw(angle, 0, 0));
//GetWorld().ExecuteCommand(command);
}
else
{
WorldCommands::UpdateSpeckRigidBodyCommand command;
command.movementMode = WorldCommands::RigidBodyMovementMode::GPU;
command.rigidBodyIndex = 0;
GetWorld().ExecuteCommand(command);
command.movementMode = WorldCommands::RigidBodyMovementMode::GPU;
command.rigidBodyIndex = 2;
GetWorld().ExecuteCommand(command);
command.movementMode = WorldCommands::RigidBodyMovementMode::GPU;
command.rigidBodyIndex = 4;
GetWorld().ExecuteCommand(command);
command.movementMode = WorldCommands::RigidBodyMovementMode::GPU;
command.rigidBodyIndex = 6;
GetWorld().ExecuteCommand(command);
command.movementMode = WorldCommands::RigidBodyMovementMode::GPU;
command.rigidBodyIndex = 8;
GetWorld().ExecuteCommand(command);
}
}
void JointShowcaseState::Draw(float dt)
{
}
void JointShowcaseState::OnResize()
{
}
void JointShowcaseState::BuildOffScreenViews()
{
}
| 36.76824 | 177 | 0.757908 | [
"vector",
"transform"
] |
f9aca1d66f63bb390333ca59a18a020454f48c58 | 10,054 | cpp | C++ | MultiStationWorker.cpp | EricAlex/structrock | 754d8c481d22a48ea7eb4e055eb16c64c44055ab | [
"BSD-3-Clause"
] | 11 | 2016-05-10T07:07:35.000Z | 2022-03-23T02:57:14.000Z | MultiStationWorker.cpp | liuxinren456852/structrock | 1a5e660bdbb5f80fb2ab479b7398c072e2573fd1 | [
"BSD-3-Clause"
] | null | null | null | MultiStationWorker.cpp | liuxinren456852/structrock | 1a5e660bdbb5f80fb2ab479b7398c072e2573fd1 | [
"BSD-3-Clause"
] | 11 | 2016-03-25T01:24:59.000Z | 2020-06-04T23:40:06.000Z | /*
* Software License Agreement (BSD License)
*
* Xin Wang
*
* 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.
*
* Author : Xin Wang
* Email : ericrussell@zju.edu.cn
*
*/
#include <string>
#include <sstream>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/registration/icp.h>
#include <pcl/registration/icp_nl.h>
#include <pcl/registration/transforms.h>
#include "geo_normal_3d.h"
#include "geo_normal_3d_omp.h"
#include "globaldef.h"
#include "MultiStationWorker.h"
#include "dataLibrary.h"
bool MultiStationWorker::is_para_satisfying(QString &message)
{
this->setParaSize(6);
if(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters.size()>=this->getParaSize())
{
std::istringstream line_stream(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[0]);
char command_split_str = '|';
std::vector<std::string> tokens;
for(std::string each; std::getline(line_stream, each, command_split_str); tokens.push_back(each));
for(int i=0; i<tokens.size(); i++)
{
tokens[i].erase(std::remove(tokens[i].begin(), tokens[i].end(),'\n'), tokens[i].end());
tokens[i].erase(std::remove(tokens[i].begin(), tokens[i].end(),'\r'), tokens[i].end());
tokens[i].erase(std::remove(tokens[i].begin(), tokens[i].end(),'\t'), tokens[i].end());
if(tokens[i].empty())
tokens.erase(tokens.begin()+i);
}
if(tokens.size()>0)
{
for(int i=0; i<tokens.size(); i++)
{
this->multiStationFilePath.push_back(tokens[i]);
}
double pre_align_ds_leaf, pre_align_StdDev, max_correspondence_distance, euclidean_fitness_epsilon;
int pre_align_normals_k;
std::stringstream ss_pre_align_ds_leaf(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[1]);
ss_pre_align_ds_leaf >> pre_align_ds_leaf;
this->setPreAlignDSLeaf(pre_align_ds_leaf);
std::stringstream ss_pre_align_StdDev(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[2]);
ss_pre_align_StdDev >> pre_align_StdDev;
this->setPreAlignStdDev(pre_align_StdDev);
std::stringstream ss_pre_align_normals_k(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[3]);
ss_pre_align_normals_k >> pre_align_normals_k;
this->setPreAlignNormalsK(pre_align_normals_k);
std::stringstream ss_max_correspondence_distance(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[4]);
ss_max_correspondence_distance >> max_correspondence_distance;
this->setMaxCorrDistance(max_correspondence_distance);
std::stringstream ss_euclidean_fitness_epsilon(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[5]);
ss_euclidean_fitness_epsilon >> euclidean_fitness_epsilon;
this->setEFEpsilon(euclidean_fitness_epsilon);
this->setParaIndex(this->getParaSize());
return true;
}
else
{
message = QString("multistation: None Valid MultiStation Point Cloud File Path Provided.");
return false;
}
}
else
{
message = QString("multistation: MultiStation Point Cloud File Paths Not Provided and/or Not Enough Parameters Given.");
return false;
}
}
void MultiStationWorker::prepare()
{
this->setUnmute();
this->setWriteLog();
this->check_mute_nolog();
}
void MultiStationWorker::doWork()
{
bool is_success(false);
dataLibrary::Status = STATUS_MULTISTATION;
this->timer_start();
//begin of processing
bool is_reading_success(true);
for(int i=0; i<this->multiStationFilePath.size(); i++)
{
sensor_msgs::PointCloud2::Ptr cloud_blob(new sensor_msgs::PointCloud2);
if(!pcl::io::loadPCDFile (this->multiStationFilePath[i], *cloud_blob))
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr temp_cloudxyzrgb(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::fromROSMsg (*cloud_blob, *temp_cloudxyzrgb);
this->multiStationPointClouds.push_back(temp_cloudxyzrgb);
}
else
{
std::string error_msg = "Error opening pcd file: " + this->multiStationFilePath[i];
emit showErrors(QString::fromUtf8(error_msg.c_str()));
is_reading_success = false;
break;
}
}
if(is_reading_success)
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr dsed_rgb_cloud(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr ro_rgb_cloud(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::Normal>::Ptr target_normals (new pcl::PointCloud<pcl::Normal>);
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr target_pointnormal (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
if(!dataLibrary::cloudxyzrgb->empty())
{
dataLibrary::cloudxyzrgb->clear();
}
*dataLibrary::cloudxyzrgb = *this->multiStationPointClouds[0];
pcl::VoxelGrid<pcl::PointXYZRGB> vg;
vg.setInputCloud (this->multiStationPointClouds[0]);
vg.setLeafSize (this->getPreAlignDSLeaf(), this->getPreAlignDSLeaf(), this->getPreAlignDSLeaf());
vg.filter (*dsed_rgb_cloud);
pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor;
sor.setInputCloud(dsed_rgb_cloud);
sor.setMeanK(50);
sor.setStddevMulThresh(this->getPreAlignStdDev());
sor.setNegative(false);
sor.filter(*ro_rgb_cloud);
GeoNormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal> ne_target;
ne_target.setInputCloud(ro_rgb_cloud);
pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree_target (new pcl::search::KdTree<pcl::PointXYZRGB>());
ne_target.setSearchMethod(tree_target);
ne_target.setKSearch(this->getPreAlignNormalsK());
ne_target.compute(*target_normals);
pcl::concatenateFields(*ro_rgb_cloud, *target_normals, *target_pointnormal);
for(int i=1; i<this->multiStationPointClouds.size(); i++)
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr dsed_rgb_cloud_i(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr ro_rgb_cloud_i(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::Normal>::Ptr src_normals (new pcl::PointCloud<pcl::Normal>);
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr src_pointnormal (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr transformed_pointnormal (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr transformed_rgb_cloud_i(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::VoxelGrid<pcl::PointXYZRGB> vg_i;
vg_i.setInputCloud (this->multiStationPointClouds[i]);
vg_i.setLeafSize (this->getPreAlignDSLeaf(), this->getPreAlignDSLeaf(), this->getPreAlignDSLeaf());
vg_i.filter (*dsed_rgb_cloud_i);
pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor_i;
sor_i.setInputCloud(dsed_rgb_cloud_i);
sor_i.setMeanK(50);
sor_i.setStddevMulThresh(this->getPreAlignStdDev());
sor_i.setNegative(false);
sor_i.filter(*ro_rgb_cloud_i);
GeoNormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal> ne_i;
ne_i.setInputCloud(ro_rgb_cloud_i);
pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree_i (new pcl::search::KdTree<pcl::PointXYZRGB>());
ne_i.setSearchMethod(tree_i);
ne_i.setKSearch(this->getPreAlignNormalsK());
ne_i.compute(*src_normals);
pcl::concatenateFields(*ro_rgb_cloud_i, *src_normals, *src_pointnormal);
pcl::IterativeClosestPoint<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal> icp;
icp.setInputCloud(src_pointnormal);
icp.setInputTarget(target_pointnormal);
icp.setMaxCorrespondenceDistance(this->getMaxCorrDistance());
icp.setEuclideanFitnessEpsilon(this->getEFEpsilon());
icp.align (*transformed_pointnormal);
//pcl::copyPointCloud(*transformed_pointnormal, *transformed_rgb_cloud_i);
pcl::transformPointCloud (*this->multiStationPointClouds[i], *transformed_rgb_cloud_i, icp.getFinalTransformation());
*dataLibrary::cloudxyzrgb += *transformed_rgb_cloud_i;
}
if(!dataLibrary::cloudxyz->empty())
{
dataLibrary::cloudxyz->clear();
}
pcl::copyPointCloud(*dataLibrary::cloudxyzrgb, *dataLibrary::cloudxyz);
is_success = true;
}
//end of processing
this->timer_stop();
if(this->getWriteLogMode()&&is_success)
{
std::string log_text = "MultiStation costs: ";
std::ostringstream strs;
strs << this->getTimer_sec();
log_text += (strs.str() +" seconds.");
dataLibrary::write_text_to_log_file(log_text);
}
if(!this->getMuteMode()&&is_success)
{
emit show(CLOUDXYZRGB);
}
dataLibrary::Status = STATUS_READY;
emit showReadyStatus();
if(this->getWorkFlowMode()&&is_success)
{
this->Sleep(1000);
emit GoWorkFlow();
}
} | 41.374486 | 126 | 0.740501 | [
"vector"
] |
f9c1efe940e16b53b27807bf58fc53f7298d8e12 | 2,560 | cpp | C++ | production_apps/ESPRESO/src/output/resultstore/libvtk/vtkxml.cpp | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 2 | 2020-11-25T13:10:11.000Z | 2021-03-15T20:26:35.000Z | production_apps/ESPRESO/src/output/resultstore/libvtk/vtkxml.cpp | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | null | null | null | production_apps/ESPRESO/src/output/resultstore/libvtk/vtkxml.cpp | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 1 | 2018-09-30T19:04:38.000Z | 2018-09-30T19:04:38.000Z |
#include <fstream>
#include "vtkSmartPointer.h"
#include "vtkUnstructuredGrid.h"
#include "vtkXMLWriter.h"
#include "../../regiondata.h"
#include "../../../assembler/solution.h"
#include "../../../mesh/structures/elementtypes.h"
#include "../vtkxmlascii.h"
using namespace espreso;
VTKXML::VTKXML(const OutputConfiguration &output, const Mesh *mesh, MeshInfo::InfoMode mode)
: ResultStore(output, mesh, mode), _VTKGrid(NULL), _writer(NULL), _os(NULL)
{
}
VTKXML::~VTKXML()
{
}
std::string VTKXML::initWriter(const std::string &name, size_t points, size_t cells)
{
_VTKGrid = vtkUnstructuredGrid::New();
_writer->SetFileName((name + ".vtu").c_str());
_writer->SetInputData(_VTKGrid);
return name + ".vtu";
}
void VTKXML::addMesh(const RegionData ®ionData)
{
// TODO: avoid copying
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
points->SetDataTypeToDouble();
for (size_t i = 0; i < regionData.coordinates.size(); i += 3) {
points->InsertNextPoint(regionData.coordinates[i + 0], regionData.coordinates[i + 1], regionData.coordinates[i + 2]);
}
_VTKGrid->SetPoints(points);
_VTKGrid->Allocate(static_cast<vtkIdType>(regionData.elements.size()));
std::vector<vtkIdType> nodes(20);
for (size_t i = 0, p = 0; i < regionData.elementsTypes.size(); p = regionData.elementsNodes[i++]) {
nodes.clear();
nodes.insert(nodes.end(), regionData.elements.begin() + p, regionData.elements.begin() + regionData.elementsNodes[i]);
_VTKGrid->InsertNextCell(regionData.elementsTypes[i], regionData.elementsNodes[i] - p, nodes.data());
}
}
void VTKXML::addData(const RegionData ®ionData)
{
for (auto it = regionData.data.pointDataInteger.begin(); it != regionData.data.pointDataInteger.end(); ++it) {
storePointData(it->first, it->second.first, *it->second.second);
}
for (auto it = regionData.data.pointDataDouble.begin(); it != regionData.data.pointDataDouble.end(); ++it) {
storePointData(it->first, it->second.first, *it->second.second);
}
for (auto it = regionData.data.elementDataInteger.begin(); it != regionData.data.elementDataInteger.end(); ++it) {
storeCellData(it->first, it->second.first, *it->second.second);
}
for (auto it = regionData.data.elementDataDouble.begin(); it != regionData.data.elementDataDouble.end(); ++it) {
storeCellData(it->first, it->second.first, *it->second.second);
}
}
void VTKXML::finalizeWriter()
{
_writer->Write();
_VTKGrid->Delete();
for (size_t i = 0; i < _VTKDataArrays.size(); i++) {
delete[] _VTKDataArrays[i];
}
_VTKDataArrays.clear();
}
| 29.090909 | 120 | 0.707422 | [
"mesh",
"vector"
] |
f9c8ac258406c1f9437d74f49deba8aa0d9dee45 | 555 | cpp | C++ | source/vxEngine/ActionPlayAnimation.cpp | DennisWandschura/vxEngine | 1396a65f7328aaed50dd34634c65cac561271b9e | [
"MIT"
] | 1 | 2015-11-29T11:38:04.000Z | 2015-11-29T11:38:04.000Z | source/vxEngine/ActionPlayAnimation.cpp | DennisWandschura/vxEngine | 1396a65f7328aaed50dd34634c65cac561271b9e | [
"MIT"
] | null | null | null | source/vxEngine/ActionPlayAnimation.cpp | DennisWandschura/vxEngine | 1396a65f7328aaed50dd34634c65cac561271b9e | [
"MIT"
] | null | null | null | #include "ActionPlayAnimation.h"
#include <PxRigidDynamic.h>
ActionPlayAnimation::ActionPlayAnimation()
:m_animation(),
m_currentFrame(0),
m_frameCount(0)
{
}
ActionPlayAnimation::~ActionPlayAnimation()
{
}
void ActionPlayAnimation::run()
{
auto currentFrame = m_currentFrame;
auto &layer = m_animation->layers[0];
auto ¤tSample = layer.samples[currentFrame];
auto transform = currentSample.transform;
//m_rigidDynamic->
++m_currentFrame;
}
bool ActionPlayAnimation::isComplete() const
{
return (m_frameCount == m_currentFrame);
} | 16.818182 | 51 | 0.758559 | [
"transform"
] |
f9d1b3cf80d3beead02784ddf5863136a13bfa68 | 45,438 | cpp | C++ | src/adv_diff/AdvDiffHierarchyIntegrator.cpp | MSV-Project/IBAMR | 3cf614c31bb3c94e2620f165ba967cba719c45ea | [
"BSD-3-Clause"
] | 2 | 2017-12-06T06:16:36.000Z | 2021-03-13T12:28:08.000Z | src/adv_diff/AdvDiffHierarchyIntegrator.cpp | MSV-Project/IBAMR | 3cf614c31bb3c94e2620f165ba967cba719c45ea | [
"BSD-3-Clause"
] | null | null | null | src/adv_diff/AdvDiffHierarchyIntegrator.cpp | MSV-Project/IBAMR | 3cf614c31bb3c94e2620f165ba967cba719c45ea | [
"BSD-3-Clause"
] | null | null | null | // Filename: AdvDiffHierarchyIntegrator.cpp
// Created on 21 May 2012 by Boyce Griffith
//
// Copyright (c) 2002-2013, Boyce Griffith
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of New York University 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 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.
/////////////////////////////// INCLUDES /////////////////////////////////////
#include <stddef.h>
#include <algorithm>
#include <deque>
#include <iosfwd>
#include <iterator>
#include <limits>
#include <memory>
#include <ostream>
#include <utility>
#include "AdvDiffHierarchyIntegrator.h"
#include "BasePatchHierarchy.h"
#include "Box.h"
#include "CartesianGridGeometry.h"
#include "CartesianPatchGeometry.h"
#include "CellDataFactory.h"
#include "CellVariable.h"
#include "CoarsenAlgorithm.h"
#include "CoarsenOperator.h"
#include "FaceData.h"
#include "FaceVariable.h"
#include "GriddingAlgorithm.h"
#include "HierarchyDataOpsManager.h"
#include "HierarchyDataOpsReal.h"
#include "IBAMR_config.h"
#include "Index.h"
#include "IntVector.h"
#include "Patch.h"
#include "PatchHierarchy.h"
#include "PatchLevel.h"
#include "SAMRAIVectorReal.h"
#include "SAMRAI_config.h"
#include "SideDataFactory.h"
#include "SideVariable.h"
#include "Variable.h"
#include "VariableContext.h"
#include "VariableDatabase.h"
#include "VisItDataWriter.h"
#include "ibamr/ibamr_utilities.h"
#include "ibamr/namespaces.h" // IWYU pragma: keep
#include "ibtk/CCLaplaceOperator.h"
#include "ibtk/CCPoissonSolverManager.h"
#include "ibtk/CartGridFunction.h"
#include "ibtk/CartGridFunctionSet.h"
#include "ibtk/HierarchyMathOps.h"
#include "ibtk/LaplaceOperator.h"
#include "ibtk/PoissonSolver.h"
#include "tbox/MathUtilities.h"
#include "tbox/MemoryDatabase.h"
#include "tbox/PIO.h"
#include "tbox/RestartManager.h"
#include "tbox/Utilities.h"
namespace SAMRAI {
namespace solv {
template <int DIM> class RobinBcCoefStrategy;
} // namespace solv
} // namespace SAMRAI
// FORTRAN ROUTINES
#if (NDIM == 2)
#define ADVECT_STABLEDT_FC FC_FUNC_(advect_stabledt2d, ADVECT_STABLEDT2D)
#endif
#if (NDIM == 3)
#define ADVECT_STABLEDT_FC FC_FUNC_(advect_stabledt3d, ADVECT_STABLEDT3D)
#endif
extern "C"
{
void
ADVECT_STABLEDT_FC(
const double*,
#if (NDIM == 2)
const int& , const int& , const int& , const int& ,
const int& , const int& ,
const double* , const double* ,
#endif
#if (NDIM == 3)
const int& , const int& , const int& , const int& , const int& , const int& ,
const int& , const int& , const int& ,
const double* , const double* , const double* ,
#endif
double&
);
}
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
namespace
{
// Number of ghosts cells used for each variable quantity.
static const int CELLG = (USING_LARGE_GHOST_CELL_WIDTH ? 2 : 1);
static const int FACEG = (USING_LARGE_GHOST_CELL_WIDTH ? 2 : 1);
// Types of refining and coarsening to perform prior to setting coarse-fine
// boundary and physical boundary ghost cell values.
static const std::string DATA_REFINE_TYPE = "NONE";
static const bool USE_CF_INTERPOLATION = true;
static const std::string DATA_COARSEN_TYPE = "CUBIC_COARSEN";
// Type of extrapolation to use at physical boundaries.
static const std::string BDRY_EXTRAP_TYPE = "LINEAR";
// Whether to enforce consistent interpolated values at Type 2 coarse-fine
// interface ghost cells.
static const bool CONSISTENT_TYPE_2_BDRY = false;
// Version of AdvDiffHierarchyIntegrator restart file data.
static const int ADV_DIFF_HIERARCHY_INTEGRATOR_VERSION = 3;
}
/////////////////////////////// PUBLIC ///////////////////////////////////////
AdvDiffHierarchyIntegrator::~AdvDiffHierarchyIntegrator()
{
d_helmholtz_solvers.clear();
d_helmholtz_rhs_ops.clear();
return;
}// ~AdvDiffHierarchyIntegrator
void
AdvDiffHierarchyIntegrator::setDefaultDiffusionTimeSteppingType(
TimeSteppingType default_diffusion_time_stepping_type)
{
d_default_diffusion_time_stepping_type = default_diffusion_time_stepping_type;
return;
}// setDefaultDiffusionTimeSteppingType
TimeSteppingType
AdvDiffHierarchyIntegrator::getDefaultDiffusionTimeSteppingType() const
{
return d_default_diffusion_time_stepping_type;
}// getDefaultDiffusionTimeSteppingType
void
AdvDiffHierarchyIntegrator::setDefaultConvectiveDifferencingType(
ConvectiveDifferencingType default_convective_difference_form)
{
d_default_convective_difference_form = default_convective_difference_form;
return;
}// setDefaultConvectiveDifferencingType
ConvectiveDifferencingType
AdvDiffHierarchyIntegrator::getDefaultConvectiveDifferencingType() const
{
return d_default_convective_difference_form;
}// getDefaultConvectiveDifferencingType
void
AdvDiffHierarchyIntegrator::registerAdvectionVelocity(
Pointer<FaceVariable<NDIM,double> > u_var)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(u_var);
TBOX_ASSERT(std::find(d_u_var.begin(), d_u_var.end(), u_var) == d_u_var.end());
#endif
d_u_var.push_back(u_var);
// Set default values.
d_u_is_div_free[u_var] = true;
d_u_fcn[u_var] = NULL;
return;
}// registerAdvectionVelocity
void
AdvDiffHierarchyIntegrator::setAdvectionVelocityIsDivergenceFree(
Pointer<FaceVariable<NDIM,double> > u_var,
const bool is_div_free)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_u_var.begin(), d_u_var.end(), u_var) != d_u_var.end());
#endif
d_u_is_div_free[u_var] = is_div_free;
return;
}// setAdvectionVelocityIsDivergenceFree
bool
AdvDiffHierarchyIntegrator::getAdvectionVelocityIsDivergenceFree(
Pointer<FaceVariable<NDIM,double> > u_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_u_var.begin(), d_u_var.end(), u_var) != d_u_var.end());
#endif
return d_u_is_div_free.find(u_var)->second;
}// getAdvectionVelocityIsDivergenceFree
void
AdvDiffHierarchyIntegrator::setAdvectionVelocityFunction(
Pointer<FaceVariable<NDIM,double> > u_var,
Pointer<IBTK::CartGridFunction> u_fcn)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_u_var.begin(), d_u_var.end(), u_var) != d_u_var.end());
#endif
d_u_fcn[u_var] = u_fcn;
return;
}// setAdvectionVelocityFunction
Pointer<IBTK::CartGridFunction>
AdvDiffHierarchyIntegrator::getAdvectionVelocityFunction(
Pointer<FaceVariable<NDIM,double> > u_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_u_var.begin(), d_u_var.end(), u_var) != d_u_var.end());
#endif
return d_u_fcn.find(u_var)->second;
}// getAdvectionVelocityFunction
void
AdvDiffHierarchyIntegrator::registerSourceTerm(
Pointer<CellVariable<NDIM,double> > F_var)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(F_var);
TBOX_ASSERT(std::find(d_F_var.begin(), d_F_var.end(), F_var) == d_F_var.end());
#endif
d_F_var.push_back(F_var);
// Set default values.
d_F_fcn[F_var] = NULL;
return;
}// registerSourceTerm
void
AdvDiffHierarchyIntegrator::setSourceTermFunction(
Pointer<CellVariable<NDIM,double> > F_var,
Pointer<IBTK::CartGridFunction> F_fcn)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_F_var.begin(), d_F_var.end(), F_var) != d_F_var.end());
#endif
if (d_F_fcn[F_var])
{
const std::string& F_var_name = F_var->getName();
Pointer<CartGridFunctionSet> p_F_fcn = d_F_fcn[F_var];
if (!p_F_fcn)
{
pout << d_object_name << "::setSourceTermFunction(): WARNING:\n"
<< " source term function for source term variable " << F_var_name << " has already been set.\n"
<< " functions will be evaluated in the order in which they were registered with the solver\n"
<< " when evaluating the source term value.\n";
p_F_fcn = new CartGridFunctionSet(d_object_name+"::"+F_var_name+"::source_function_set");
p_F_fcn->addFunction(d_F_fcn[F_var]);
}
p_F_fcn->addFunction(F_fcn);
}
else
{
d_F_fcn[F_var] = F_fcn;
}
return;
}// setSourceTermFunction
Pointer<IBTK::CartGridFunction>
AdvDiffHierarchyIntegrator::getSourceTermFunction(
Pointer<CellVariable<NDIM,double> > F_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_F_var.begin(), d_F_var.end(), F_var) != d_F_var.end());
#endif
return d_F_fcn.find(F_var)->second;
}// getSourceTermFunction
void
AdvDiffHierarchyIntegrator::registerTransportedQuantity(
Pointer<CellVariable<NDIM,double> > Q_var)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(Q_var);
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) == d_Q_var.end());
#endif
d_Q_var.push_back(Q_var);
Pointer<CellDataFactory<NDIM,double> > Q_factory = Q_var->getPatchDataFactory();
const int Q_depth = Q_factory->getDefaultDepth();
Pointer<CellVariable<NDIM,double> > Q_rhs_var = new CellVariable<NDIM,double>(Q_var->getName()+"::Q_rhs",Q_depth);
// Set default values.
d_Q_u_map[Q_var] = NULL;
d_Q_F_map[Q_var] = NULL;
d_Q_rhs_var.push_back(Q_rhs_var);
d_Q_Q_rhs_map[Q_var] = Q_rhs_var;
d_Q_diffusion_time_stepping_type[Q_var] = d_default_diffusion_time_stepping_type;
d_Q_difference_form[Q_var] = d_default_convective_difference_form;
d_Q_diffusion_coef[Q_var] = 0.0;
d_Q_diffusion_coef_variable[Q_var] = NULL;
d_Q_is_diffusion_coef_variable[Q_var] = false;
d_Q_damping_coef[Q_var] = 0.0;
d_Q_init[Q_var] = NULL;
d_Q_bc_coef[Q_var] = std::vector<RobinBcCoefStrategy<NDIM>*>(Q_depth,static_cast<RobinBcCoefStrategy<NDIM>*>(NULL));
return;
}// registerTransportedQuantity
void
AdvDiffHierarchyIntegrator::setAdvectionVelocity(
Pointer<CellVariable<NDIM,double> > Q_var,
Pointer<FaceVariable<NDIM,double> > u_var)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
TBOX_ASSERT(std::find(d_u_var.begin(), d_u_var.end(), u_var) != d_u_var.end());
#endif
d_Q_u_map[Q_var] = u_var;
return;
}// setAdvectionVelocity
Pointer<FaceVariable<NDIM,double> >
AdvDiffHierarchyIntegrator::getAdvectionVelocity(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_u_map.find(Q_var)->second;
}// getAdvectionVelocity
void
AdvDiffHierarchyIntegrator::setSourceTerm(
Pointer<CellVariable<NDIM,double> > Q_var,
Pointer<CellVariable<NDIM,double> > F_var)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
TBOX_ASSERT(std::find(d_F_var.begin(), d_F_var.end(), F_var) != d_F_var.end());
#endif
d_Q_F_map[Q_var] = F_var;
return;
}// setSourceTerm
Pointer<CellVariable<NDIM,double> >
AdvDiffHierarchyIntegrator::getSourceTerm(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_F_map.find(Q_var)->second;
}// getSourceTerm
void
AdvDiffHierarchyIntegrator::setDiffusionTimeSteppingType(
Pointer<CellVariable<NDIM,double> > Q_var,
const TimeSteppingType diffusion_time_stepping_type)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
d_Q_diffusion_time_stepping_type[Q_var] = diffusion_time_stepping_type;
return;
}// setDiffusionTimeSteppingType
TimeSteppingType
AdvDiffHierarchyIntegrator::getDiffusionTimeSteppingType(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_diffusion_time_stepping_type.find(Q_var)->second;
}// getDiffusionTimeSteppingType
void
AdvDiffHierarchyIntegrator::setConvectiveDifferencingType(
Pointer<CellVariable<NDIM,double> > Q_var,
const ConvectiveDifferencingType difference_form)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
d_Q_difference_form[Q_var] = difference_form;
return;
}// setConvectiveDifferencingType
ConvectiveDifferencingType
AdvDiffHierarchyIntegrator::getConvectiveDifferencingType(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_difference_form.find(Q_var)->second;
}// getConvectiveDifferencingType
void
AdvDiffHierarchyIntegrator::setDiffusionCoefficient(
Pointer<CellVariable<NDIM,double> > Q_var,
const double kappa)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
d_Q_diffusion_coef[Q_var] = kappa;
// indicate that the diffusion coefficient associated to Q_var is constant.
d_Q_is_diffusion_coef_variable[Q_var] = false;
// if there is already a variable diffusion coefficient associated to Q_var
if (d_Q_diffusion_coef_variable[Q_var])
{
const std::string& Q_var_name = Q_var->getName();
Pointer<SideVariable<NDIM,double> > D_var = d_Q_diffusion_coef_variable[Q_var];
// print a warning.
pout << d_object_name << "::setDiffusionCoefficient(Pointer<CellVariable<NDIM,double> > Q_var, const double kappa): WARNING: \n"
<< " a variable diffusion coefficient for the variable " << Q_var_name << " has already been set.\n"
<< " this variable coefficient will be overriden by the constant diffusion coefficient "
<< "kappa = " << kappa << "\n";
// erase entries from maps with key D_var
d_diffusion_coef_fcn.erase(D_var);
d_diffusion_coef_rhs_map.erase(D_var);
// set a null entry in the map for variable diffusion coefficients.
d_Q_diffusion_coef_variable[Q_var] = NULL;
}
return;
}// setDiffusionCoefficient
double
AdvDiffHierarchyIntegrator::getDiffusionCoefficient(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_diffusion_coef.find(Q_var)->second;
}// getDiffusionCoefficient
void
AdvDiffHierarchyIntegrator::registerDiffusionCoefficientVariable(
Pointer<SideVariable<NDIM,double> > D_var)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(D_var);
TBOX_ASSERT(std::find(d_diffusion_coef_var.begin(), d_diffusion_coef_var.end(), D_var)
== d_diffusion_coef_var.end());
#endif
d_diffusion_coef_var.push_back(D_var);
Pointer<SideDataFactory<NDIM,double> > D_factory = D_var->getPatchDataFactory();
const int D_depth = D_factory->getDefaultDepth();
Pointer<SideVariable<NDIM,double> > D_rhs_var = new SideVariable<NDIM,double>(D_var->getName()+"::D_rhs",D_depth);
// Set default values.
d_diffusion_coef_fcn[D_var] = NULL;
d_diffusion_coef_rhs_map[D_var] = D_rhs_var;
// Also register D_rhs_var
d_diffusion_coef_rhs_var.push_back(D_rhs_var);
return;
}// registerDiffusionCoefficientVariable
void
AdvDiffHierarchyIntegrator::setDiffusionCoefficientFunction(
Pointer<SideVariable<NDIM,double> > D_var,
Pointer<IBTK::CartGridFunction> D_fcn)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_diffusion_coef_var.begin(), d_diffusion_coef_var.end(), D_var)
!= d_diffusion_coef_var.end());
#endif
if (d_diffusion_coef_fcn[D_var])
{
const std::string& D_var_name = D_var->getName();
Pointer<CartGridFunctionSet> p_D_fcn = d_diffusion_coef_fcn[D_var];
if (!p_D_fcn)
{
pout << d_object_name << "::setDiffusionCoefficientFunction(): WARNING:\n"
<< " diffusion coefficient function for diffusion coefficient variable "
<< D_var_name << " has already been set.\n"
<< " functions will be evaluated in the order in which they were registered with the solver\n"
<< " when evaluating the source term value.\n";
p_D_fcn = new CartGridFunctionSet(d_object_name+"::"+D_var_name+"::diffusion_coef_function_set");
p_D_fcn->addFunction(d_diffusion_coef_fcn[D_var]);
}
p_D_fcn->addFunction(D_fcn);
}
else
{
d_diffusion_coef_fcn[D_var] = D_fcn;
}
return;
}// setDiffusionCoefficientFunction
Pointer<IBTK::CartGridFunction>
AdvDiffHierarchyIntegrator::getDiffusionCoefficientFunction(
Pointer<SideVariable<NDIM,double> > D_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_diffusion_coef_var.begin(), d_diffusion_coef_var.end(), D_var)
!= d_diffusion_coef_var.end());
#endif
return d_diffusion_coef_fcn.find(D_var)->second;
}// getDiffusionCoefficientFunction
void
AdvDiffHierarchyIntegrator::setDiffusionCoefficientVariable(
Pointer<CellVariable<NDIM,double> > Q_var,
Pointer<SideVariable<NDIM,double> > D_var)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
TBOX_ASSERT(std::find(d_diffusion_coef_var.begin(), d_diffusion_coef_var.end(), D_var)
!= d_diffusion_coef_var.end());
#endif
d_Q_diffusion_coef_variable[Q_var] = D_var;
// indicate that the diffusion coefficient associated to Q_var is variable
d_Q_is_diffusion_coef_variable[Q_var] = true;
// set the corresponding constant diffusion coefficient to zero.
d_Q_diffusion_coef[Q_var] = 0.0;
return;
}// setDiffusionCoefficientVariable
Pointer<SideVariable<NDIM,double> >
AdvDiffHierarchyIntegrator::getDiffusionCoefficientVariable(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_diffusion_coef_variable.find(Q_var)->second;
}// getDiffusionCoefficientVariable
bool
AdvDiffHierarchyIntegrator::isDiffusionCoefficientVariable(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_is_diffusion_coef_variable.find(Q_var)->second;
}// isDiffusionCoefficientVariable
void
AdvDiffHierarchyIntegrator::setDampingCoefficient(
Pointer<CellVariable<NDIM,double> > Q_var,
const double lambda)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
d_Q_damping_coef[Q_var] = lambda;
return;
}// setDampingCoefficient
double
AdvDiffHierarchyIntegrator::getDampingCoefficient(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_damping_coef.find(Q_var)->second;
}// getDampingCoefficient
void
AdvDiffHierarchyIntegrator::setInitialConditions(
Pointer<CellVariable<NDIM,double> > Q_var,
Pointer<IBTK::CartGridFunction> Q_init)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
d_Q_init[Q_var] = Q_init;
return;
}// setInitialConditions
Pointer<IBTK::CartGridFunction>
AdvDiffHierarchyIntegrator::getInitialConditions(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_init.find(Q_var)->second;
}// getInitialConditions
void
AdvDiffHierarchyIntegrator::setPhysicalBcCoef(
Pointer<CellVariable<NDIM,double> > Q_var,
RobinBcCoefStrategy<NDIM>* Q_bc_coef)
{
setPhysicalBcCoefs(Q_var, std::vector<RobinBcCoefStrategy<NDIM>*>(1,Q_bc_coef));
return;
}// setPhysicalBcCoef
void
AdvDiffHierarchyIntegrator::setPhysicalBcCoefs(
Pointer<CellVariable<NDIM,double> > Q_var,
const std::vector<RobinBcCoefStrategy<NDIM>*>& Q_bc_coef)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
Pointer<CellDataFactory<NDIM,double> > Q_factory = Q_var->getPatchDataFactory();
const unsigned int Q_depth = Q_factory->getDefaultDepth();
TBOX_ASSERT(Q_depth == Q_bc_coef.size());
#endif
d_Q_bc_coef[Q_var] = Q_bc_coef;
return;
}// setPhysicalBcCoefs
std::vector<RobinBcCoefStrategy<NDIM>*>
AdvDiffHierarchyIntegrator::getPhysicalBcCoefs(
Pointer<CellVariable<NDIM,double> > Q_var) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
return d_Q_bc_coef.find(Q_var)->second;
}// getPhysicalBcCoefs
void
AdvDiffHierarchyIntegrator::setHelmholtzSolver(
Pointer<CellVariable<NDIM,double> > Q_var,
Pointer<PoissonSolver> helmholtz_solver)
{
d_helmholtz_solvers.resize(d_Q_var.size());
d_helmholtz_solvers_need_init.resize(d_Q_var.size());
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
const unsigned int l = distance(d_Q_var.begin(),std::find(d_Q_var.begin(),d_Q_var.end(),Q_var));
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(!d_helmholtz_solvers[l]);
#endif
d_helmholtz_solvers[l] = helmholtz_solver;
d_helmholtz_solvers_need_init[l] = true;
return;
}// setHelmholtzSolver
Pointer<PoissonSolver>
AdvDiffHierarchyIntegrator::getHelmholtzSolver(
Pointer<CellVariable<NDIM,double> > Q_var)
{
d_helmholtz_solvers.resize(d_Q_var.size());
d_helmholtz_solvers_need_init.resize(d_Q_var.size());
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
const unsigned int l = distance(d_Q_var.begin(),std::find(d_Q_var.begin(),d_Q_var.end(),Q_var));
if (!d_helmholtz_solvers[l])
{
const std::string& name = Q_var->getName();
d_helmholtz_solvers[l] = CCPoissonSolverManager::getManager()->allocateSolver(
d_helmholtz_solver_type , d_object_name+"::helmholtz_solver::" +name, d_helmholtz_solver_db , "adv_diff_" ,
d_helmholtz_precond_type, d_object_name+"::helmholtz_precond::"+name, d_helmholtz_precond_db, "adv_diff_pc_");
d_helmholtz_solvers_need_init[l] = true;
}
return d_helmholtz_solvers[l];
}// getHelmholtzSolver
void
AdvDiffHierarchyIntegrator::setHelmholtzRHSOperator(
Pointer<CellVariable<NDIM,double> > Q_var,
Pointer<LaplaceOperator> helmholtz_op)
{
d_helmholtz_rhs_ops.resize(d_Q_var.size());
d_helmholtz_rhs_ops_need_init.resize(d_Q_var.size());
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
const unsigned int l = distance(d_Q_var.begin(),std::find(d_Q_var.begin(),d_Q_var.end(),Q_var));
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(!d_helmholtz_rhs_ops[l]);
#endif
d_helmholtz_rhs_ops[l] = helmholtz_op;
d_helmholtz_rhs_ops_need_init[l] = true;
return;
}// setHelmholtzRHSOperator
Pointer<LaplaceOperator>
AdvDiffHierarchyIntegrator::getHelmholtzRHSOperator(
Pointer<CellVariable<NDIM,double> > Q_var)
{
d_helmholtz_rhs_ops.resize(d_Q_var.size());
d_helmholtz_rhs_ops_need_init.resize(d_Q_var.size());
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(std::find(d_Q_var.begin(), d_Q_var.end(), Q_var) != d_Q_var.end());
#endif
const unsigned int l = distance(d_Q_var.begin(),std::find(d_Q_var.begin(),d_Q_var.end(),Q_var));
if (!d_helmholtz_rhs_ops[l])
{
const std::string& name = Q_var->getName();
d_helmholtz_rhs_ops[l] = new CCLaplaceOperator(d_object_name+"::helmholtz_rhs_op::"+name, /*homogeneous_bc*/ false);
d_helmholtz_rhs_ops_need_init[l] = true;
}
return d_helmholtz_rhs_ops[l];
}// getHelmholtzRHSOperator
void
AdvDiffHierarchyIntegrator::initializeHierarchyIntegrator(
Pointer<PatchHierarchy<NDIM> > hierarchy,
Pointer<GriddingAlgorithm<NDIM> > gridding_alg)
{
if (d_integrator_is_initialized) return;
d_hierarchy = hierarchy;
d_gridding_alg = gridding_alg;
Pointer<CartesianGridGeometry<NDIM> > grid_geom = d_hierarchy->getGridGeometry();
// Setup hierarchy data operations objects.
HierarchyDataOpsManager<NDIM>* hier_ops_manager = HierarchyDataOpsManager<NDIM>::getManager();
Pointer<CellVariable<NDIM,double> > cc_var = new CellVariable<NDIM,double>("cc_var");
d_hier_cc_data_ops = hier_ops_manager->getOperationsDouble(cc_var, d_hierarchy, true);
Pointer<SideVariable<NDIM,double> > sc_var = new SideVariable<NDIM,double>("sc_var");
d_hier_sc_data_ops = hier_ops_manager->getOperationsDouble(sc_var, d_hierarchy, true);
// Setup coarsening communications algorithms, used in synchronizing refined
// regions of coarse data with the underlying fine data.
VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
for (std::vector<Pointer<CellVariable<NDIM,double> > >::const_iterator cit = d_Q_var.begin(); cit != d_Q_var.end(); ++cit)
{
Pointer<CellVariable<NDIM,double> > Q_var = *cit;
const int Q_current_idx = var_db->mapVariableAndContextToIndex(Q_var, getCurrentContext());
const int Q_new_idx = var_db->mapVariableAndContextToIndex(Q_var, getNewContext());
Pointer<CoarsenOperator<NDIM> > coarsen_operator = grid_geom->lookupCoarsenOperator(Q_var, "CONSERVATIVE_COARSEN");
getCoarsenAlgorithm(SYNCH_CURRENT_DATA_ALG)->registerCoarsen(Q_current_idx, Q_current_idx, coarsen_operator);
getCoarsenAlgorithm(SYNCH_NEW_DATA_ALG )->registerCoarsen(Q_new_idx , Q_new_idx , coarsen_operator);
}
// Operators and solvers are maintained for each variable registered with the
// integrator.
if (d_helmholtz_solver_type == CCPoissonSolverManager::UNDEFINED)
{
d_helmholtz_solver_type = CCPoissonSolverManager::DEFAULT_KRYLOV_SOLVER;
}
if (d_helmholtz_precond_type == CCPoissonSolverManager::UNDEFINED)
{
const int max_levels = gridding_alg->getMaxLevels();
if (max_levels == 1)
{
d_helmholtz_precond_type = CCPoissonSolverManager::DEFAULT_LEVEL_SOLVER;
}
else
{
d_helmholtz_precond_type = CCPoissonSolverManager::DEFAULT_FAC_PRECONDITIONER;
}
d_helmholtz_precond_db->putInteger("max_iterations", 1);
}
d_helmholtz_solvers.resize(d_Q_var.size());
d_helmholtz_solvers_need_init.resize(d_Q_var.size());
for (std::vector<Pointer<CellVariable<NDIM,double> > >::const_iterator cit = d_Q_var.begin(); cit != d_Q_var.end(); ++cit)
{
Pointer<CellVariable<NDIM,double> > Q_var = *cit;
const unsigned int l = distance(d_Q_var.begin(),std::find(d_Q_var.begin(),d_Q_var.end(),Q_var));
d_helmholtz_solvers[l] = getHelmholtzSolver(Q_var);
}
d_helmholtz_rhs_ops.resize(d_Q_var.size());
d_helmholtz_rhs_ops_need_init.resize(d_Q_var.size());
for (std::vector<Pointer<CellVariable<NDIM,double> > >::const_iterator cit = d_Q_var.begin(); cit != d_Q_var.end(); ++cit)
{
Pointer<CellVariable<NDIM,double> > Q_var = *cit;
const unsigned int l = distance(d_Q_var.begin(),std::find(d_Q_var.begin(),d_Q_var.end(),Q_var));
d_helmholtz_rhs_ops[l] = getHelmholtzRHSOperator(Q_var);
}
// Indicate that the integrator has been initialized.
d_integrator_is_initialized = true;
return;
}// initializeHierarchyIntegrator
/////////////////////////////// PROTECTED ////////////////////////////////////
AdvDiffHierarchyIntegrator::AdvDiffHierarchyIntegrator(
const std::string& object_name,
Pointer<Database> input_db,
bool register_for_restart)
: HierarchyIntegrator(object_name, input_db, register_for_restart),
d_integrator_is_initialized(false),
d_cfl_max(0.5),
d_default_diffusion_time_stepping_type(TRAPEZOIDAL_RULE),
d_default_convective_difference_form(CONSERVATIVE),
d_u_var(),
d_u_is_div_free(),
d_u_fcn(),
d_F_var(),
d_F_fcn(),
d_diffusion_coef_var(),
d_diffusion_coef_rhs_var(),
d_diffusion_coef_fcn(),
d_diffusion_coef_rhs_map(),
d_Q_var(),
d_Q_rhs_var(),
d_Q_u_map(),
d_Q_F_map(),
d_Q_Q_rhs_map(),
d_Q_difference_form(),
d_Q_diffusion_coef(),
d_Q_diffusion_coef_variable(),
d_Q_is_diffusion_coef_variable(),
d_Q_damping_coef(),
d_Q_init(),
d_Q_bc_coef(),
d_hier_cc_data_ops(NULL),
d_hier_sc_data_ops(NULL),
d_sol_vecs(),
d_rhs_vecs(),
d_helmholtz_solver_type(CCPoissonSolverManager::UNDEFINED),
d_helmholtz_precond_type(CCPoissonSolverManager::UNDEFINED),
d_helmholtz_solver_db(),
d_helmholtz_precond_db(),
d_helmholtz_solvers(),
d_helmholtz_rhs_ops(),
d_helmholtz_solvers_need_init(),
d_helmholtz_rhs_ops_need_init(),
d_coarsest_reset_ln(-1),
d_finest_reset_ln(-1)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(!object_name.empty());
TBOX_ASSERT(input_db);
#endif
// Initialize object with data read from the input and restart databases.
bool from_restart = RestartManager::getManager()->isFromRestart();
if (from_restart) getFromRestart();
if (input_db) getFromInput(input_db, from_restart);
return;
}// AdvDiffHierarchyIntegrator
double
AdvDiffHierarchyIntegrator::getMaximumTimeStepSizeSpecialized()
{
double dt = d_dt_max;
const bool initial_time = MathUtilities<double>::equalEps(d_integrator_time, d_start_time);
for (int ln = 0; ln <= d_hierarchy->getFinestLevelNumber(); ++ln)
{
Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);
for (PatchLevel<NDIM>::Iterator p(level); p; p++)
{
Pointer<Patch<NDIM> > patch = level->getPatch(p());
const Box<NDIM>& patch_box = patch->getBox();
const Index<NDIM>& ilower = patch_box.lower();
const Index<NDIM>& iupper = patch_box.upper();
const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry();
const double* const dx = patch_geom->getDx();
for (std::vector<Pointer<FaceVariable<NDIM,double> > >::const_iterator cit = d_u_var.begin(); cit != d_u_var.end(); ++cit)
{
Pointer<FaceVariable<NDIM,double> > u_var = *cit;
Pointer<FaceData<NDIM,double> > u_data = patch->getPatchData(u_var, getCurrentContext());
const IntVector<NDIM>& u_ghost_cells = u_data->getGhostCellWidth();
double stable_dt = std::numeric_limits<double>::max();
#if (NDIM == 2)
ADVECT_STABLEDT_FC(
dx,
ilower(0),iupper(0),ilower(1),iupper(1),
u_ghost_cells(0),u_ghost_cells(1),
u_data->getPointer(0),u_data->getPointer(1),
stable_dt);
#endif
#if (NDIM == 3)
ADVECT_STABLEDT_FC(
dx,
ilower(0),iupper(0),ilower(1),iupper(1),ilower(2),iupper(2),
u_ghost_cells(0),u_ghost_cells(1),u_ghost_cells(2),
u_data->getPointer(0),u_data->getPointer(1),u_data->getPointer(2),
stable_dt);
#endif
dt = std::min(dt,d_cfl_max*stable_dt);
}
}
}
if (!initial_time && d_dt_growth_factor >= 1.0)
{
dt = std::min(dt,d_dt_growth_factor*d_dt_previous[0]);
}
return dt;
}// getMaximumTimeStepSizeSpecialized
void
AdvDiffHierarchyIntegrator::resetHierarchyConfigurationSpecialized(
const Pointer<BasePatchHierarchy<NDIM> > base_hierarchy,
const int coarsest_level,
const int finest_level)
{
const Pointer<BasePatchHierarchy<NDIM> > hierarchy = base_hierarchy;
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(hierarchy);
TBOX_ASSERT((coarsest_level >= 0)
&& (coarsest_level <= finest_level)
&& (finest_level <= hierarchy->getFinestLevelNumber()));
for (int ln = 0; ln <= finest_level; ++ln)
{
TBOX_ASSERT(hierarchy->getPatchLevel(ln));
}
#endif
const int finest_hier_level = hierarchy->getFinestLevelNumber();
// Reset the Hierarchy data operations for the new hierarchy configuration.
d_hier_cc_data_ops->setPatchHierarchy(hierarchy);
d_hier_cc_data_ops->resetLevels(0, finest_hier_level);
d_hier_sc_data_ops->setPatchHierarchy(hierarchy);
d_hier_sc_data_ops->resetLevels(0, finest_hier_level);
// Reset the interpolation operators.
VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
d_hier_bdry_fill_ops.resize(d_Q_var.size());
unsigned int l = 0;
for (std::vector<Pointer<CellVariable<NDIM,double> > >::const_iterator cit = d_Q_var.begin(); cit != d_Q_var.end(); ++cit, ++l)
{
Pointer<CellVariable<NDIM,double> > Q_var = *cit;
const int Q_scratch_idx = var_db->mapVariableAndContextToIndex(Q_var, getScratchContext());
// Setup the interpolation transaction information.
typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent;
InterpolationTransactionComponent transaction_comp(Q_scratch_idx, DATA_REFINE_TYPE, USE_CF_INTERPOLATION, DATA_COARSEN_TYPE, BDRY_EXTRAP_TYPE, CONSISTENT_TYPE_2_BDRY, d_Q_bc_coef[Q_var]);
// Initialize the interpolation operators.
d_hier_bdry_fill_ops[l] = new HierarchyGhostCellInterpolation();
d_hier_bdry_fill_ops[l]->initializeOperatorState(transaction_comp, d_hierarchy);
}
// Reset the solution and rhs vectors.
d_sol_vecs.resize(d_Q_var.size());
d_rhs_vecs.resize(d_Q_var.size());
l = 0;
const int wgt_idx = d_hier_math_ops->getCellWeightPatchDescriptorIndex();
for (std::vector<Pointer<CellVariable<NDIM,double> > >::const_iterator cit = d_Q_var.begin(); cit != d_Q_var.end(); ++cit, ++l)
{
Pointer<CellVariable<NDIM,double> > Q_var = *cit;
const std::string& name = Q_var->getName();
const int Q_scratch_idx = var_db->mapVariableAndContextToIndex(Q_var, getScratchContext());
d_sol_vecs[l] = new SAMRAIVectorReal<NDIM,double>(d_object_name+"::sol_vec::"+name, d_hierarchy, 0, finest_hier_level);
d_sol_vecs[l]->addComponent(Q_var,Q_scratch_idx,wgt_idx,d_hier_cc_data_ops);
Pointer<CellVariable<NDIM,double> > Q_rhs_var = d_Q_Q_rhs_map[Q_var];
const int Q_rhs_scratch_idx = var_db->mapVariableAndContextToIndex(Q_rhs_var, getScratchContext());
d_rhs_vecs[l] = new SAMRAIVectorReal<NDIM,double>(d_object_name+"::rhs_vec::"+name, d_hierarchy, 0, finest_hier_level);
d_rhs_vecs[l]->addComponent(Q_rhs_var,Q_rhs_scratch_idx,wgt_idx,d_hier_cc_data_ops);
}
// Indicate that all linear solvers must be re-initialized.
std::fill(d_helmholtz_solvers_need_init.begin(), d_helmholtz_solvers_need_init.end(), true);
std::fill(d_helmholtz_rhs_ops_need_init.begin(), d_helmholtz_rhs_ops_need_init.end(), true);
d_coarsest_reset_ln = coarsest_level;
d_finest_reset_ln = finest_level;
return;
}// resetHierarchyConfigurationSpecialized
void
AdvDiffHierarchyIntegrator::putToDatabaseSpecialized(
Pointer<Database> db)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(db);
#endif
db->putInteger("ADV_DIFF_HIERARCHY_INTEGRATOR_VERSION", ADV_DIFF_HIERARCHY_INTEGRATOR_VERSION);
db->putDouble("d_cfl_max", d_cfl_max);
db->putString("d_default_diffusion_time_stepping_type", enum_to_string<TimeSteppingType>(d_default_diffusion_time_stepping_type));
db->putString("d_default_convective_difference_form", enum_to_string<ConvectiveDifferencingType>(d_default_convective_difference_form));
return;
}// putToDatabaseSpecialized
void
AdvDiffHierarchyIntegrator::registerVariables()
{
const IntVector<NDIM> cell_ghosts = CELLG;
const IntVector<NDIM> face_ghosts = FACEG;
for (std::vector<Pointer<FaceVariable<NDIM,double> > >::const_iterator cit = d_u_var.begin(); cit != d_u_var.end(); ++cit)
{
Pointer<FaceVariable<NDIM,double> > u_var = *cit;
int u_current_idx, u_new_idx, u_scratch_idx;
registerVariable(u_current_idx, u_new_idx, u_scratch_idx, u_var, face_ghosts, "CONSERVATIVE_COARSEN", "CONSERVATIVE_LINEAR_REFINE", d_u_fcn[u_var]);
}
for (std::vector<Pointer<CellVariable<NDIM,double> > >::const_iterator cit = d_Q_var.begin(); cit != d_Q_var.end(); ++cit)
{
Pointer<CellVariable<NDIM,double> > Q_var = *cit;
int Q_current_idx, Q_new_idx, Q_scratch_idx;
registerVariable(Q_current_idx, Q_new_idx, Q_scratch_idx, Q_var, cell_ghosts, "CONSERVATIVE_COARSEN", "CONSERVATIVE_LINEAR_REFINE", d_Q_init[Q_var]);
Pointer<CellDataFactory<NDIM,double> > Q_factory = Q_var->getPatchDataFactory();
const int Q_depth = Q_factory->getDefaultDepth();
if (d_visit_writer) d_visit_writer->registerPlotQuantity(Q_var->getName(), Q_depth == 1 ? "SCALAR" : "VECTOR", Q_current_idx);
}
for (std::vector<Pointer<CellVariable<NDIM,double> > >::const_iterator cit = d_F_var.begin(); cit != d_F_var.end(); ++cit)
{
Pointer<CellVariable<NDIM,double> > F_var = *cit;
int F_current_idx, F_new_idx, F_scratch_idx;
registerVariable(F_current_idx, F_new_idx, F_scratch_idx, F_var, cell_ghosts, "CONSERVATIVE_COARSEN", "CONSERVATIVE_LINEAR_REFINE", d_F_fcn[F_var]);
Pointer<CellDataFactory<NDIM,double> > F_factory = F_var->getPatchDataFactory();
const int F_depth = F_factory->getDefaultDepth();
if (d_visit_writer) d_visit_writer->registerPlotQuantity(F_var->getName(), F_depth == 1 ? "SCALAR" : "VECTOR", F_current_idx);
}
for (std::vector<Pointer<SideVariable<NDIM,double> > >::const_iterator cit = d_diffusion_coef_var.begin(); cit != d_diffusion_coef_var.end(); ++cit)
{
Pointer<SideVariable<NDIM,double> > D_var = *cit;
int D_current_idx, D_new_idx, D_scratch_idx;
registerVariable(D_current_idx, D_new_idx, D_scratch_idx, D_var, face_ghosts, "CONSERVATIVE_COARSEN", "CONSERVATIVE_LINEAR_REFINE", d_diffusion_coef_fcn[D_var]);
}
for (std::vector<Pointer<CellVariable<NDIM,double> > >::const_iterator cit = d_Q_rhs_var.begin(); cit != d_Q_rhs_var.end(); ++cit)
{
Pointer<CellVariable<NDIM,double> > Q_rhs_var = *cit;
int Q_rhs_scratch_idx;
registerVariable(Q_rhs_scratch_idx, Q_rhs_var, cell_ghosts, getScratchContext());
}
for (std::vector<Pointer<SideVariable<NDIM,double> > >::const_iterator cit = d_diffusion_coef_rhs_var.begin(); cit != d_diffusion_coef_rhs_var.end(); ++cit)
{
Pointer<SideVariable<NDIM,double> > D_rhs_var = *cit;
int D_rhs_scratch_idx;
registerVariable(D_rhs_scratch_idx, D_rhs_var, cell_ghosts, getScratchContext());
}
return;
}// registerVariables
/////////////////////////////// PRIVATE //////////////////////////////////////
void
AdvDiffHierarchyIntegrator::getFromInput(
Pointer<Database> db,
bool is_from_restart)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(db);
#endif
// Read in data members from input database.
if (!is_from_restart)
{
if (db->keyExists("diffusion_time_stepping_type")) d_default_diffusion_time_stepping_type = string_to_enum<TimeSteppingType>(db->getString("diffusion_time_stepping_type"));
else if (db->keyExists("diffusion_timestepping_type" )) d_default_diffusion_time_stepping_type = string_to_enum<TimeSteppingType>(db->getString("diffusion_timestepping_type") );
else if (db->keyExists("default_diffusion_time_stepping_type")) d_default_diffusion_time_stepping_type = string_to_enum<TimeSteppingType>(db->getString("default_diffusion_time_stepping_type"));
else if (db->keyExists("default_diffusion_timestepping_type" )) d_default_diffusion_time_stepping_type = string_to_enum<TimeSteppingType>(db->getString("default_diffusion_timestepping_type") );
if (db->keyExists("convective_difference_type")) d_default_convective_difference_form = string_to_enum<ConvectiveDifferencingType>(db->getString("convective_difference_type"));
else if (db->keyExists("convective_difference_form")) d_default_convective_difference_form = string_to_enum<ConvectiveDifferencingType>(db->getString("convective_difference_form"));
else if (db->keyExists("default_convective_difference_type")) d_default_convective_difference_form = string_to_enum<ConvectiveDifferencingType>(db->getString("default_convective_difference_type"));
else if (db->keyExists("default_convective_difference_form")) d_default_convective_difference_form = string_to_enum<ConvectiveDifferencingType>(db->getString("default_convective_difference_form"));
}
if (db->keyExists("cfl_max")) d_cfl_max = db->getDouble("cfl_max");
else if (db->keyExists("CFL_max")) d_cfl_max = db->getDouble("CFL_max");
else if (db->keyExists("cfl" )) d_cfl_max = db->getDouble("cfl" );
else if (db->keyExists("CFL" )) d_cfl_max = db->getDouble("CFL" );
if (db->keyExists("solver_type" )) d_helmholtz_solver_type = db->getString("solver_type" );
else if (db->keyExists("helmholtz_solver_type")) d_helmholtz_solver_type = db->getString("helmholtz_solver_type");
if (db->keyExists("solver_type") || db->keyExists("helmholtz_solver_type"))
{
if (db->keyExists("solver_db" )) d_helmholtz_solver_db = db->getDatabase("solver_db" );
else if (db->keyExists("helmholtz_solver_db")) d_helmholtz_solver_db = db->getDatabase("helmholtz_solver_db");
}
if (!d_helmholtz_solver_db) d_helmholtz_solver_db = new MemoryDatabase("helmholtz_solver_db");
if (db->keyExists("precond_type" )) d_helmholtz_precond_type = db->getString("precond_type" );
else if (db->keyExists("helmholtz_precond_type")) d_helmholtz_precond_type = db->getString("helmholtz_precond_type");
if (db->keyExists("precond_type") || db->keyExists("helmholtz_precond_type"))
{
if (db->keyExists("precond_db" )) d_helmholtz_precond_db = db->getDatabase("precond_db" );
else if (db->keyExists("helmholtz_precond_db")) d_helmholtz_precond_db = db->getDatabase("helmholtz_precond_db");
}
if (!d_helmholtz_precond_db) d_helmholtz_precond_db = new MemoryDatabase("helmholtz_precond_db");
return;
}// getFromInput
void
AdvDiffHierarchyIntegrator::getFromRestart()
{
Pointer<Database> restart_db = RestartManager::getManager()->getRootDatabase();
Pointer<Database> db;
if (restart_db->isDatabase(d_object_name))
{
db = restart_db->getDatabase(d_object_name);
}
else
{
TBOX_ERROR(d_object_name << ": Restart database corresponding to "
<< d_object_name << " not found in restart file." << std::endl);
}
int ver = db->getInteger("ADV_DIFF_HIERARCHY_INTEGRATOR_VERSION");
if (ver != ADV_DIFF_HIERARCHY_INTEGRATOR_VERSION)
{
TBOX_ERROR(d_object_name << ": Restart file version different than class version." << std::endl);
}
d_cfl_max = db->getDouble("d_cfl_max");
d_default_diffusion_time_stepping_type = string_to_enum<TimeSteppingType>(db->getString("d_default_diffusion_time_stepping_type"));
d_default_convective_difference_form = string_to_enum<ConvectiveDifferencingType>(db->getString("d_default_convective_difference_form"));
return;
}// getFromRestart
//////////////////////////////////////////////////////////////////////////////
}// namespace IBAMR
//////////////////////////////////////////////////////////////////////////////
| 40.788151 | 205 | 0.717791 | [
"object",
"vector"
] |
f9d3b7f02dd1ceca0c3b54f44e9bc641d39bb4fe | 4,287 | cpp | C++ | Source/Position/DirectionPredictor.cpp | favorart/robot-hand | 55ea2a74573972a6e5efcf525485e56918d81086 | [
"MIT"
] | 2 | 2016-01-16T09:28:40.000Z | 2016-04-14T05:21:20.000Z | Source/Position/DirectionPredictor.cpp | favorart/robot-hand | 55ea2a74573972a6e5efcf525485e56918d81086 | [
"MIT"
] | null | null | null | Source/Position/DirectionPredictor.cpp | favorart/robot-hand | 55ea2a74573972a6e5efcf525485e56918d81086 | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#include "Position.h"
namespace Positions
{
using namespace std;
using namespace HandMoves;
//------------------------------------------
DirectionPredictor::DirectionPredictor (IN Hand &hand)
{
hand.SET_DEFAULT;
hand_base = hand.position;
for ( auto j : hand.joints_ )
{
Hand::MusclesEnum muscle;
hand.set (Hand::JointsSet{ { j, 100. } });
muscle = muscleByJoint (j, true);
main_directions[muscle] = MainDirection (muscle, hand);
hand.set (Hand::JointsSet{ { j, 0. } });
muscle = muscleByJoint (j, false);
main_directions[muscle] = MainDirection (muscle, hand);
hand.SET_DEFAULT;
}
// for ( auto m : hand.muscles_ )
// { mainDirections[m] = MainDirection (m, hand); }
}
//------------------------------------------
void DirectionPredictor::predict (IN Hand::Control control, OUT Point &end)
{
for ( Hand::MusclesEnum m : muscles )
{
const MainDirection &md = main_directions[m & control.muscle];
if ( control.last < md.shifts.size () )
{
end.x += md.shifts[control.last].x;
end.y += md.shifts[control.last].y;
} // end if
} // end for
}
//------------------------------------------
bool DirectionPredictor::shifting_gt (Hand::MusclesEnum m, unsigned int &inx, const Point &aim)
{
bool changes = false;
Point prev, curr;
auto &shifts = main_directions[m].shifts;
curr.x = hand_base.x + shifts[inx].x;
curr.y = hand_base.y + shifts[inx].y;
do
{
prev = curr;
curr.x = hand_base.x + shifts[inx + 1].x;
curr.y = hand_base.y + shifts[inx + 1].y;
++inx;
} while ( (inx < (shifts.size () - 1U))
&& (boost_distance (aim, curr) < boost_distance (aim, prev))
&& (changes = true) );
return changes;
}
bool DirectionPredictor::shifting_ls (Hand::MusclesEnum m, unsigned int &inx, const Point &aim)
{
bool changes = false;
Point prev, curr;
auto &shifts = main_directions[m].shifts;
curr.x = hand_base.x + shifts[inx].x;
curr.y = hand_base.y + shifts[inx].y;
do
{
prev = curr;
curr.x = hand_base.x + shifts[inx - 1].x;
curr.y = hand_base.y + shifts[inx - 1].y;
--inx;
} while ( (inx > 0)
&& (boost_distance (aim, curr) > boost_distance (aim, prev))
&& (changes = true) );
return changes;
}
//------------------------------------------
void DirectionPredictor::measure (IN Hand &hand, IN const Point &aim,
OUT HandMoves::controling_t &controls)
{ /*
* У нас есть 4 линейки, их надо сопоставить так,
* чтобы приблизить aim.
*
* Система линейных уравнений
*/
std::vector<int> indices (hand.joints_.size ());
// std::fill (indices.begin (), indices.end (), 1U);
bool changes = true;
while ( changes )
{
for ( size_t ij = 0; ij < hand.joints_.size (); ++ij )
{
auto mo = muscleByJoint (hand.joints_[ij], true);
auto mc = muscleByJoint (hand.joints_[ij], false);
changes = false;
// wcout << hand.joints_[ij] << endl;
if ( indices[ij] >= 0 )
{
unsigned int inx = indices[ij];
changes = shifting_gt (mo, inx, aim);
if ( !changes )
changes = shifting_ls (mo, inx, aim);
indices[ij] = inx;
}
if ( indices[ij] <= 0 )
{
unsigned int inx = -indices[ij];
changes = shifting_gt (mo, inx, aim);
if ( !changes )
changes = shifting_ls (mo, inx, aim);
indices[ij] = -(int) inx;
} // end if
} // end for
} // end while
for ( size_t ij = hand.joints_.size (); ij > 0; --ij )
{
auto mo = muscleByJoint (hand.joints_[ij - 1U], true);
auto mc = muscleByJoint (hand.joints_[ij - 1U], false);
if ( indices[ij - 1U] > 0 )
controls.push_back (Hand::Control (mo, 0U, size_t (indices[ij - 1U]) /* - stopping ? */));
else if ( indices[ij - 1U] < 0 )
controls.push_back (Hand::Control (mc, 0U, size_t (-indices[ij - 1U]) /* - stopping ? */));
}
}
//------------------------------------------
};
| 28.203947 | 99 | 0.520411 | [
"vector"
] |
f9d4da2b65353d59caf6ed93b47833f1072bc621 | 15,720 | cpp | C++ | tools/developer/generatelts/generatelts.cpp | nouwaarom/mCRL2 | cd77f9ab46c9568aa655a49d4d49c08d1768e870 | [
"BSL-1.0"
] | null | null | null | tools/developer/generatelts/generatelts.cpp | nouwaarom/mCRL2 | cd77f9ab46c9568aa655a49d4d49c08d1768e870 | [
"BSL-1.0"
] | null | null | null | tools/developer/generatelts/generatelts.cpp | nouwaarom/mCRL2 | cd77f9ab46c9568aa655a49d4d49c08d1768e870 | [
"BSL-1.0"
] | null | null | null | // Author(s): Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://github.com/mCRL2org/mCRL2/blob/master/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
/// \file transform.cpp
#include <csignal>
#include <iostream>
#include <limits>
#include <memory>
#include <string>
#include "mcrl2/data/rewriter.h"
#include "mcrl2/data/rewriter_tool.h"
#include "mcrl2/lps/explorer.h"
#include "mcrl2/lps/io.h"
#include "mcrl2/lps/is_stochastic.h"
#include "mcrl2/lts/lts_builder.h"
#include "mcrl2/lts/lts_io.h"
#include "mcrl2/lts/stochastic_lts_builder.h"
#include "mcrl2/lts/state_space_generator.h"
#include "mcrl2/utilities/input_output_tool.h"
using namespace mcrl2;
using data::tools::rewriter_tool;
using utilities::tools::input_output_tool;
class generatelts_tool: public rewriter_tool<input_output_tool>
{
typedef rewriter_tool<input_output_tool> super;
lps::explorer_options options;
lts::lts_type output_format = lts::lts_none;
lps::abortable* current_explorer = nullptr;
public:
generatelts_tool()
: super("generatelts",
"Wieger Wesselink",
"generates an LTS from an LPS",
"Transforms the LPS in INFILE and writes a corresponding LTS in .aut format "
" to OUTFILE. If OUTFILE is not present, stdout is used. If INFILE is not "
" present, stdin is used."
)
{}
void add_options(utilities::interface_description& desc) override
{
super::add_options(desc);
desc.add_option("global-cache", "use a global cache");
desc.add_option("no-one-point-rule-rewrite", "do not apply the one point rule rewriter");
desc.add_option("no-replace-constants-by-variables", "do not move constant expressions to a substitution");
desc.add_option("no-resolve-summand-variable-name-clashes", "do not resolve summand variable name clashes");
desc.add_option("dfs-recursive", "use recursive depth first search for divergence detection");
// copied from lps2lts
desc.add_option("cached", "use enumeration caching techniques to speed up state space generation. ");
desc.add_option("max", utilities::make_mandatory_argument("NUM"), "explore at most NUM states", 'l');
desc.add_option("todo-max", utilities::make_mandatory_argument("NUM"),
"keep at most NUM states in todo lists; this option is only relevant for "
"highway search, where NUM is the maximum number of states per "
"level. ");
desc.add_option("nondeterminism", "detect nondeterministic states, i.e. states with outgoing transitions with the same label to different states. ", 'n');
desc.add_option("deadlock", "detect deadlocks (i.e. for every deadlock a message is printed). ", 'D');
desc.add_option("divergence",
"detect divergences (i.e. for every state with a divergence (=tau loop) a message is printed). "
"The algorithm to detect the divergences is linear for every state, "
"so state space exploration becomes quadratic with this option on, causing a state "
"space exploration to become slow when this option is enabled. ", 'F');
desc.add_option("action", utilities::make_mandatory_argument("NAMES"),
"report whether an action from NAMES occurs in the transitions system, "
"where NAMES is a comma-separated list. A message "
"is printed for every occurrence of one of these action names. "
"With the -t flag traces towards these actions are generated. "
"When using -tN only N traces are generated after which the generation of the state space stops. ", 'a');
desc.add_option("multiaction", utilities::make_mandatory_argument("NAMES"),
"detect and report multiactions in the transitions system "
"from NAMES, a comma-separated list. Works like -a, except that multi-actions "
"are matched exactly, including data parameters. ", 'm');
desc.add_option("error-trace",
"if an error occurs during exploration, save a trace to the state that could "
"not be explored. ");
desc.add_option("trace", utilities::make_optional_argument("NUM", std::to_string(std::numeric_limits<std::size_t>::max())),
"Write a shortest trace to each state that is reached with an action from NAMES "
"with the option --action, is a deadlock with the option --deadlock, is nondeterministic with the option --nondeterminism, or is a "
"divergence with the option --divergence to a file. "
"No more than NUM traces will be written. If NUM is not supplied the number of "
"traces is unbounded. "
"For each trace that is to be written a unique file with extension .trc (trace) "
"will be created containing a shortest trace from the initial state to the deadlock "
"state. The traces can be pretty printed and converted to other formats using tracepp. ", 't');
desc.add_option("confluence", utilities::make_optional_argument("NAME", "ctau"),
"apply prioritization of transitions with the action label NAME. "
"(when no NAME is supplied (i.e., '-c') priority is given to the action 'ctau'. To give priority to "
"to tau use the flag -ctau. Note that if the linear process is not tau-confluent, the generated "
"state space is necessarily branching bisimilar to the state space of the lps. The generation "
"algorithm that is used does not require the linear process to be tau convergent. ", 'c');
desc.add_option("out", utilities::make_mandatory_argument("FORMAT"), "save the output in the specified FORMAT. ", 'o');
desc.add_option("tau", utilities::make_mandatory_argument("ACTNAMES"),
"consider actions with a name in the comma separated list ACTNAMES to be internal. "
"This list is only used and allowed when searching for divergencies. ");
desc.add_option("strategy", utilities::make_enum_argument<lps::exploration_strategy>("NAME")
.add_value_short(lps::es_breadth, "b", true)
.add_value_short(lps::es_depth, "d")
.add_value_short(lps::es_highway, "h")
, "explore the state space using strategy NAME:"
, 's');
desc.add_option("suppress","in verbose mode, do not print progress messages indicating the number of visited states and transitions. "
"For large state spaces the number of progress messages can be quite "
"horrendous. This feature helps to suppress those. Other verbose messages, "
"such as the total number of states explored, just remain visible. ");
desc.add_option("no-store", "save the resulting LTS to disk while generating. Currently this only works "
"for .aut files.");
}
std::list<std::string> split_actions(const std::string& s)
{
std::size_t count = 0;
std::string a;
std::list<std::string> result;
for (char ch: s)
{
if (ch == ',' && count == 0)
{
result.push_back(a);
a.clear();
}
else
{
if (ch == '(')
{
++count;
}
else if (ch == ')')
{
--count;
}
a.push_back(ch);
}
}
if (!a.empty())
{
result.push_back(a);
}
return result;
}
void parse_options(const utilities::command_line_parser& parser) override
{
super::parse_options(parser);
options.no_store = parser.has_option("no-store");
options.cached = parser.has_option("cached");
options.global_cache = parser.has_option("global-cache");
options.confluence = parser.has_option("confluence");
options.one_point_rule_rewrite = !parser.has_option("no-one-point-rule-rewrite");
options.replace_constants_by_variables = !parser.has_option("no-replace-constants-by-variables");
options.resolve_summand_variable_name_clashes = !parser.has_option("no-resolve-summand-variable-name-clashes");
options.detect_deadlock = parser.has_option("deadlock");
options.detect_nondeterminism = parser.has_option("nondeterminism");
options.detect_divergence = parser.has_option("divergence");
options.save_error_trace = parser.has_option("error-trace");
options.suppress_progress_messages = parser.has_option("suppress");
options.dfs_recursive = parser.has_option("dfs-recursive");
options.search_strategy = parser.option_argument_as<lps::exploration_strategy>("strategy");
if (parser.has_option("max"))
{
options.max_states = parser.option_argument_as<std::size_t> ("max");
}
if (parser.has_option("todo-max"))
{
options.todo_max = parser.option_argument_as<std::size_t>("todo-max");
}
if (parser.has_option("out"))
{
output_format = lts::detail::parse_format(parser.option_argument("out"));
if (output_format == lts::lts_none)
{
parser.error("Format '" + parser.option_argument("out") + "' is not recognised.");
}
}
if (output_format == lts::lts_none && !output_filename().empty())
{
output_format = lts::detail::guess_format(output_filename());
if (output_format == lts::lts_none)
{
mCRL2log(log::warning) << "no output format set or detected; using default (lts)" << std::endl;
output_format = lts::lts_lts;
}
}
if (parser.has_option("action"))
{
options.detect_action = true;
for (const std::string& s: split_actions(parser.option_argument("action")))
{
options.trace_actions.insert(core::identifier_string(s));
}
}
if (parser.has_option("multiaction"))
{
std::list<std::string> actions = split_actions(parser.option_argument("multiaction"));
options.trace_multiaction_strings.insert(actions.begin(), actions.end());
}
if (parser.has_option("trace"))
{
options.generate_traces = true;
options.max_traces = parser.option_argument_as<std::size_t>("trace");
}
if (parser.has_option("tau"))
{
if (!parser.has_option("divergence"))
{
parser.error("Option --tau requires the option --divergence.");
}
std::list<std::string> actions = split_actions(parser.option_argument("tau"));
for (const std::string& s: actions)
{
options.actions_internal_for_divergencies.insert(core::identifier_string(s));
}
}
if (parser.has_option("confluence"))
{
options.priority_action = parser.option_argument("confluence");
}
if (2 < parser.arguments.size())
{
parser.error("Too many file arguments.");
}
if (options.no_store && (output_filename().empty() || output_format != lts::lts_aut))
{
options.no_store = false;
mCRL2log(log::warning) << "Ignoring the no-store option.";
}
if (options.search_strategy == lps::es_highway && !parser.has_option("todo-max"))
{
parser.error("Search strategy 'highway' requires that the option todo-max is set");
}
options.rewrite_strategy = rewrite_strategy();
}
std::unique_ptr<lts::lts_builder> create_lts_builder(const lps::specification& lpsspec)
{
switch (output_format)
{
case lts::lts_aut:
{
return options.no_store ? std::unique_ptr<lts::lts_builder>(new lts::lts_aut_disk_builder(output_filename()))
: std::unique_ptr<lts::lts_builder>(new lts::lts_aut_builder());
}
case lts::lts_dot: return std::unique_ptr<lts::lts_builder>(new lts::lts_dot_builder(lpsspec.data(), lpsspec.action_labels(), lpsspec.process().process_parameters()));
case lts::lts_fsm: return std::unique_ptr<lts::lts_builder>(new lts::lts_fsm_builder(lpsspec.data(), lpsspec.action_labels(), lpsspec.process().process_parameters()));
case lts::lts_lts: return std::unique_ptr<lts::lts_builder>(new lts::lts_lts_builder(lpsspec.data(), lpsspec.action_labels(), lpsspec.process().process_parameters()));
default: return std::unique_ptr<lts::lts_builder>(new lts::lts_none_builder());
}
}
std::unique_ptr<lts::stochastic_lts_builder> create_stochastic_lts_builder(const lps::stochastic_specification& lpsspec)
{
switch (output_format)
{
case lts::lts_aut: return std::unique_ptr<lts::stochastic_lts_builder>(new lts::stochastic_lts_aut_builder());
case lts::lts_lts: return std::unique_ptr<lts::stochastic_lts_builder>(new lts::stochastic_lts_lts_builder(lpsspec.data(), lpsspec.action_labels(), lpsspec.process().process_parameters()));
default: return std::unique_ptr<lts::stochastic_lts_builder>(new lts::stochastic_lts_none_builder());
}
}
template <bool Stochastic, bool Timed, typename Specification, typename LTSBuilder>
void generate_state_space(const Specification& lpsspec, LTSBuilder& builder)
{
lts::state_space_generator<Stochastic, Timed, Specification> generator(lpsspec, options);
current_explorer = &generator.explorer;
generator.explore(builder);
builder.save(output_filename());
}
bool run() override
{
mCRL2log(log::verbose) << options << std::endl;
options.trace_prefix = input_filename();
lps::stochastic_specification stochastic_lpsspec;
lps::load_lps(stochastic_lpsspec, input_filename());
bool is_timed = stochastic_lpsspec.process().has_time();
if (lps::is_stochastic(stochastic_lpsspec))
{
auto builder = create_stochastic_lts_builder(stochastic_lpsspec);
if (is_timed)
{
generate_state_space<true, true>(stochastic_lpsspec, *builder);
}
else
{
generate_state_space<true, false>(stochastic_lpsspec, *builder);
}
}
else
{
lps::specification lpsspec = lps::remove_stochastic_operators(stochastic_lpsspec);
auto builder = create_lts_builder(lpsspec);
if (is_timed)
{
generate_state_space<false, true>(lpsspec, *builder);
}
else
{
generate_state_space<false, false>(lpsspec, *builder);
}
}
return true;
}
void abort()
{
current_explorer->abort();
}
};
std::unique_ptr<generatelts_tool> tool_instance;
static void premature_termination_handler(int)
{
// Reset signal handlers.
signal(SIGABRT, nullptr);
signal(SIGINT, nullptr);
tool_instance->abort();
}
int main(int argc, char** argv)
{
tool_instance = std::make_unique<generatelts_tool>();
signal(SIGABRT, premature_termination_handler);
signal(SIGINT, premature_termination_handler); // At ^C invoke the termination handler.
return tool_instance->execute(argc, argv);
}
| 45.172414 | 197 | 0.635242 | [
"transform"
] |
f9dba936c76c047d8094211ebe444813e95ee4db | 18,771 | cpp | C++ | src/raygen/sceneloader.cpp | jingwood/raygen-renderer | c77f3efc4753690bb2a4dc1c58ed5c1ea8d6c814 | [
"MIT"
] | 3 | 2020-01-18T01:30:02.000Z | 2021-12-21T15:15:26.000Z | src/raygen/sceneloader.cpp | jingwood/raygen-renderer | c77f3efc4753690bb2a4dc1c58ed5c1ea8d6c814 | [
"MIT"
] | null | null | null | src/raygen/sceneloader.cpp | jingwood/raygen-renderer | c77f3efc4753690bb2a4dc1c58ed5c1ea8d6c814 | [
"MIT"
] | 1 | 2021-08-03T05:16:15.000Z | 2021-08-03T05:16:15.000Z | ///////////////////////////////////////////////////////////////////////////////
// Raygen Renderer
// A simple cross-platform ray tracing engine for 3D graphics rendering.
//
// MIT License
// (c) 2016-2020 Jingwood, unvell.com, all rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include "sceneloader.h"
#include "ucm/jsonreader.h"
#include "ucm/strutil.h"
#include "ucm/file.h"
#include "ugm/imgcodec.h"
#include "meshloader.h"
#include "fbxloader.h"
#include "polygons.h"
#define FORMAT_TAG_JSON 0x6e6f736a
#define FORMAT_TAG_MIFT 0x7466696d
namespace raygen {
SceneJsonLoader::SceneJsonLoader(SceneResourcePool* resPool) {
if (resPool != NULL) {
this->resPool = resPool;
}
}
SceneJsonLoader::~SceneJsonLoader() {
}
void SceneJsonLoader::setBasePath(const string& basePath) {
this->basePath = basePath;
if (this->basePath.length() > 0 && !this->basePath.endsWith(PATH_SPLITTER)) {
this->basePath.append(PATH_SPLITTER);
}
}
void SceneJsonLoader::transformPath(const string &input, string &output) {
output.clear();
if (!input.startsWith("sob://")
&& !input.startsWith("tob://")
&& !input.startsWith('/')
&& !input.startsWith("\\")) {
output.append(this->basePath);
output.append(PATH_SPLITTER);
}
output.append(input);
}
color4f SceneJsonLoader::readColorProperty(const JSObject* obj) {
return color4f((float)obj->getNumberProperty("r", 0.0f),
(float)obj->getNumberProperty("g", 0.0f),
(float)obj->getNumberProperty("b", 0.0f),
(float)obj->getNumberProperty("a", 0.0f));
}
color4f SceneJsonLoader::readColorArray(const std::vector<JSValue>& array) {
color4f c;
if (array.size() >= 3) {
if (array[0].type == JSType::JSType_Number) c.r = (float)array[0].number;
if (array[1].type == JSType::JSType_Number) c.g = (float)array[1].number;
if (array[2].type == JSType::JSType_Number) c.b = (float)array[2].number;
}
if (array.size() >= 4) {
if (array[3].type == JSType::JSType_Number) c.a = (float)array[3].number;
}
return c;
}
void SceneJsonLoader::readMaterialDefines(const JSObject& jsmats, Archive* bundle) {
for (const auto& p : jsmats.getProperties()) {
if (p.second.type == JSType::JSType_Object && p.second.object != NULL) {
Material* mat = new Material();
mat->name = p.first;
this->readMaterial(*mat, *p.second.object, this->resPool, bundle);
// this->resPool->materials[p.first] = mp;
this->loadingStack.back().materials[p.first] = mat;
// this->materialList
// materials[p.first] = m;
}
}
}
void SceneJsonLoader::readMaterial(Material& mat, const JSObject& jsmat, SceneResourcePool* pool, Archive* bundle) {
string* texPath = NULL;
if ((texPath = jsmat.getStringProperty("tex")) != NULL && texPath->length() > 0) {
string filepath;
this->transformPath(*texPath, filepath);
mat.texturePath = filepath;
if (pool != NULL) {
mat.texture = pool->getTexture(filepath, bundle);
}
#ifdef DEBUG
assert(mat.texture != NULL);
assert(mat.texture->getImage().width() > 0);
assert(mat.texture->getImage().width() < 65500);
#endif
}
string* normalmapPath = NULL;
if ((normalmapPath = jsmat.getStringProperty("normalmap")) != NULL && normalmapPath->length() > 0) {
mat.normalmapPath = *normalmapPath;
// TODO: load normalmap from file
}
SceneJsonLoader::tryReadVec2Property(jsmat, "texTiling", &mat.texTiling);
jsmat.tryGetNumberProperty("emission", &mat.emission);
jsmat.tryGetNumberProperty("glossy", &mat.glossy);
jsmat.tryGetNumberProperty("roughness", &mat.roughness);
jsmat.tryGetNumberProperty("transparency", &mat.transparency);
jsmat.tryGetNumberProperty("refraction", &mat.refraction);
jsmat.tryGetNumberProperty("refractionRatio", &mat.refractionRatio);
jsmat.tryGetNumberProperty("spotRange", &mat.spotRange);
jsmat.tryGetNumberProperty("normalMipmap", &mat.normalMipmap);
JSValue val;
if ((val = jsmat.getProperty("color")).type != JSType_Unknown) {
switch (val.type) {
default:
break;
case JSType::JSType_String:
if (val.str != NULL) {
color4 c;
tryParseColorString(*val.str, c);
mat.color = c;
}
break;
case JSType::JSType_Array:
if (val.array != NULL) {
mat.color = readColorArray(*val.array);
}
break;
}
}
}
bool SceneJsonLoader::tryParseColorString(const string& str, color4& color) {
int len = str.length();
if (len < 3) {
return false;
}
const char* buf = str.getBuffer();
if ((len == 4 && str[0] == '#')
|| (len == 5 && str[0] == '#')
|| (len == 7 && str[0] == '#')
|| (len == 9 && str[0] == '#')) {
buf++;
len--;
}
switch (len) {
case 3:
color = tocolor3f(hex2dec(buf, 3) * 2);
return true;
case 4:
color = tocolor4f(hex2dec(buf, 4) * 2);
return true;
case 6:
color = tocolor3f(hex2dec(buf, 6));
return true;
case 8:
color = tocolor4f(hex2dec(buf, 8));
return true;
}
return false;
}
bool SceneJsonLoader::tryReadVec3Property(const JSObject& obj, const char* name, vec3* v) {
const JSValue& val = obj.getProperty(name);
switch (val.type) {
default:
break;
case JSType::JSType_Array:
if (val.array->size() >= 3) {
v->x = (float)val.array->at(0).number;
v->y = (float)val.array->at(1).number;
v->z = (float)val.array->at(2).number;
return true;
}
break;
case JSType::JSType_Object:
v->x = (float)obj.getNumberProperty("x", 0);
v->y = (float)obj.getNumberProperty("y", 0);
v->z = (float)obj.getNumberProperty("z", 0);
return true;
}
return false;
}
bool SceneJsonLoader::tryReadVec2Property(const JSObject& obj, const char* name, vec2* v) {
const JSValue& val = obj.getProperty(name);
switch (val.type) {
default:
break;
case JSType::JSType_Array:
if (val.array->size() >= 2) {
v->x = (float)val.array->at(0).number;
v->y = (float)val.array->at(1).number;
return true;
}
break;
case JSType::JSType_Object:
v->x = (float)obj.getNumberProperty("x", 0);
v->y = (float)obj.getNumberProperty("y", 0);
return true;
}
return false;
}
void SceneJsonLoader::readMeshDefines(const JSObject* obj, std::vector<Mesh> meshes) {
// TODO
}
void SceneJsonLoader::readMesh(SceneObject& obj, const string& meshPath, Archive* bundle) {
// Mesh* mesh = this->loadMeshFile(obj, meshPath, bundle);
string filepath;
this->transformPath(meshPath, filepath);
Mesh* mesh = this->resPool->loadMeshFromFile(filepath, bundle);
if (mesh != NULL) {
obj.addMesh(*mesh);
}
}
//Mesh* SceneJsonLoader::loadMeshFile(SceneObject& obj, const string &path, Archive* bundle) {
// Mesh* mesh = new Mesh();
//
// string finalPath;
// finalPath.append(this->basePath);
// finalPath.append(path);
//
//#if _WIN32
// finalPath.replace('/', '\\');
//#endif // _WIN32
//
// if (finalPath.endsWith('.fbx', StringComparingFlags::SCF_CASE_INSENSITIVE)) {
//#if defined(FBX_SUPPORT)
// SceneFBXLoader loader;
// loader.loadAsChildren(&obj, finalPath);
//#endif /* FBX_SUPPORT */
// } else {
// MeshLoader::load(*mesh, finalPath);
// }
//
// return mesh;
//}
void SceneJsonLoader::readSceneObject(SceneObject& obj, const JSObject& jsobj, Archive* bundle) {
this->loadingStack.push_back(LoadingStack());
JSObject* matObj = jsobj.getObjectProperty("_materials");
if (matObj != NULL) {
this->readMaterialDefines(*matObj, bundle);
}
string* jsBundleURI = jsobj.getStringProperty("_bundle");
if (jsBundleURI != NULL && !jsBundleURI->isEmpty()) {
string bundleFilepath;
this->transformPath(*jsBundleURI, bundleFilepath);
Archive* archive = this->resPool->loadArchive(bundleFilepath, bundleFilepath);
string manifest;
archive->getTextChunkData(0x1, FORMAT_TAG_MIFT, &manifest);
JSONReader reader(manifest);
JSObject* bundleJSChildRoot = reader.readObject();
for (auto& p : bundleJSChildRoot->getProperties()) {
if (p.first == "_materials") {
if (p.second.type == JSType_Object && p.second.object != NULL) {
this->readMaterialDefines(*p.second.object, archive);
}
} else if(p.first != "_models"
&& p.second.type == JSType::JSType_Object && p.second.object != NULL) {
SceneObject* child = new SceneObject();
this->readSceneObject(*child, *p.second.object, archive);
child->setName(p.first);
obj.addObject(*child);
}
}
delete bundleJSChildRoot;
}
Camera* camera;
if ((camera = dynamic_cast<Camera*>(&obj)) != NULL) {
if (jsobj.hasProperty("fieldOfView", JSType::JSType_Number)) {
camera->fieldOfView = (float)jsobj.getNumberProperty("fieldOfView");
}
if (jsobj.hasProperty("depthOfField", JSType::JSType_Number)) {
camera->depthOfField = (float)jsobj.getNumberProperty("depthOfField");
}
if (jsobj.hasProperty("aperture", JSType::JSType_Number)) {
camera->aperture = (float)jsobj.getNumberProperty("aperture");
}
if (jsobj.hasProperty("focusOn", JSType::JSType_String)) {
const string* focusAtObjName = jsobj.getStringProperty("focusOn");
if (focusAtObjName != NULL && !focusAtObjName->isEmpty()) {
camera->focusOnObjectName = *focusAtObjName;
}
}
}
for (const auto& p : jsobj.getProperties()) {
const string& key = p.first;
const JSValue& val = p.second;
if (key == "_materials" || key == "_bundles") {
// ignore these properties since handled before loop
} else if (key == "location") {
SceneJsonLoader::tryReadVec3Property(jsobj, key, &obj.location);
}
else if (key == "angle") {
SceneJsonLoader::tryReadVec3Property(jsobj, key, &obj.angle);
}
else if (key == "scale") {
SceneJsonLoader::tryReadVec3Property(jsobj, key, &obj.scale);
}
else if (key == "mesh") {
// read mesh from file path
if (val.type == JSType_String && val.str != NULL) {
this->readMesh(obj, *val.str, bundle);
}
// read multiple mesh from path
else if (val.type == JSType::JSType_Array) {
for (const JSValue& meshItem : *val.array) {
if (meshItem.type == JSType::JSType_String
&& meshItem.str != NULL) {
this->readMesh(obj, *meshItem.str, bundle);
}
}
}
// read mesh define
else if (val.type == JSType::JSType_Object) {
string* meshType = val.object->getStringProperty("type");
if (*meshType == "plane") {
obj.addMesh(*new PlaneMesh());
} else if (*meshType == "cube") {
obj.addMesh(*new CubeMesh());
}
}
}
else if (key == "mat") {
if (this->materialReadingHandler != NULL) {
this->materialReadingHandler(obj, jsobj, this->meshLoadHandlerUserData);
} else {
if (val.type == JSType::JSType_String && val.str != NULL) {
const string& matName = *val.str;
Material* mat = this->findMaterialByName(matName);
if (mat != NULL) {
obj.material = *mat;
}
// obj->material.name = matName;
} else if (val.type == JSType::JSType_Object && val.object != NULL) {
SceneJsonLoader::readMaterial(obj.material, *val.object, this->resPool);
}
}
}
else if (key == "visible" && val.type == JSType::JSType_Boolean) {
obj.visible = val.boolean;
}
else if (key == "mainCamera") {
Camera* camera = new Camera();
this->readSceneObject(*camera, *val.object, bundle);
camera->setName(key);
obj.addObject(*camera);
}
else if (key == "_generateLightmap") {
obj._generateLightmap = true;
}
else if (key == "mainCamera") {
Camera* child = new Camera();
this->readSceneObject(*child, *val.object, bundle);
child->setName(key);
obj.addObject(*child);
}
else if (val.type == JSType::JSType_Object && val.object != NULL) {
SceneObject* child = NULL;
int type = (int)val.object->getNumberProperty("type");
switch (type) {
case 15: /* RefRange */
child = new ReflectionMapObject();
break;
case 801: /* Camera */
child = new Camera();
break;
default:
child = new SceneObject();
break;
}
this->readSceneObject(*child, *val.object, bundle);
child->setName(key);
obj.addObject(*child);
}
}
this->loadingStack.pop_back();
}
Camera* findMainCamera(SceneObject& obj) {
for (auto* child : obj.getObjects()) {
if (child == NULL) continue;
Camera* camera = NULL;
if (child->getName() == "mainCamera" && (camera = dynamic_cast<Camera*>(child)) != NULL) {
return camera;
}
camera = findMainCamera(*child);
if (camera != NULL) return camera;
}
return NULL;
}
void SceneJsonLoader::load(const string& jsonPath, Scene& scene) {
this->jsonFilePath = jsonPath;
if (resPool == NULL) {
resPool = &SceneResourcePool::instance;
}
if (this->basePath.isEmpty()) {
File file(jsonPath);
this->setBasePath(file.getPath());
}
// scene.resPool.basePath = this->basePath;
string json;
File::readTextFile(this->jsonFilePath, json);
if (json.isEmpty()) {
throw Exception("scene file is empty");
}
SceneObject* rootObj = this->loadObject(json);
if (rootObj != NULL) {
for (auto child : rootObj->getObjects()) {
child->setParent(NULL);
scene.addObject(*child);
}
Camera* mainCamera = findMainCamera(*rootObj);
if (mainCamera != NULL) {
scene.mainCamera = mainCamera;
}
rootObj->objects.clear();
delete rootObj;
rootObj = NULL;
}
}
SceneObject* SceneJsonLoader::loadObject(const string& json, Archive* bundle) {
// if (this->resPool == NULL) {
// this->resPool = new SceneResourcePool();
// }
JSONReader reader(json);
JSObject* jsobj = reader.readObject();
SceneObject* obj = this->loadObject(*jsobj, bundle);
delete jsobj;
jsobj = NULL;
return obj;
}
SceneObject* SceneJsonLoader::loadObject(const JSObject& jsobj, Archive* bundle) {
SceneObject* obj = new SceneObject();
this->readSceneObject(*obj, jsobj, bundle);
return obj;
// this->loadingStack.push_back(LoadingStack());
// std::vector<Mesh> meshes;
//
// for (const auto& p : jsobj.getProperties()) {
// if (p.first == "_materials") {
// // ignore since read before
// continue;
// }
// else if (p.first == "_meshes") {
// this->readMeshDefines(p.second.object, meshes);
// }
// else if (p.first == "mainCamera") {
// Camera* camera = new Camera();
// camera->setName(p.first);
// this->readSceneObject(camera, *p.second.object, bundle);
// return camera;
// }
// else if (p.second.type == JSType::JSType_Object && p.second.object != NULL) {
// SceneObject* child = new SceneObject();
// child->setName(p.first);
// this->readSceneObject(child, *p.second.object, bundle);
// return child;
// }
// }
// unknow why this here, we don't need it
//this->readSceneObject(obj, jsobj, bundle);
// this->loadingStack.pop_back();
// return NULL;
}
SceneObject* SceneJsonLoader::createObjectFromBundle(const string& path) {
if (resPool == NULL) {
resPool = &SceneResourcePool::instance;
}
Archive* archive = this->resPool->loadArchive(path);
if (archive == NULL) {
return NULL;
}
string manifest;
archive->getTextChunkData(1, FORMAT_TAG_MIFT, &manifest);
SceneObject* obj = this->loadObject(manifest, archive);
if (obj->objects.size() == 1) {
SceneObject* child = obj->objects[0];
obj->removeObject(*child);
delete obj;
obj = NULL;
return child;
}
return obj;
}
//////////////////// SceneJsonWriter ////////////////////
//void SceneJsonWriter::writeObject(const SceneObject& obj, bool insoba) {
//
// writer.format = JSONOutputFormat::defaultFormat;
//
// writer.beginObject();
//
//// // materials
//// const std::vector<ObjMaterial>& materials = this->objReader.getMaterials();
////
//// if (materials.size() > 0) {
//// // materials
//// writer.beginObjectWithKey("_materials");
////
//// for (const ObjMaterial& m : materials) {
//// this->writeMaterial(m, insoba);
//// }
////
//// writer.endObject();
//// }
//
// for (SceneObject* child : obj.objects) {
// writeObject(child, insoba);
// }
//
// writer.endObject();
//}
//
//void SceneJsonWriter::writeMaterial(const Material& m) {
// this->writer.beginObjectWithKey(m.name);
//
// // tex
// const string texFile = m.texturePath;
//
// if (!texFile.isEmpty()) {
// this->writeTexture(writer, "tex", texFile);
// }
//
// // normal-map
// const string normalFile = mat.getNormalmapFilename();
//
// if (!normalFile.isEmpty()) {
// writeTexture(writer, "normalmap", normalFile, insoba);
// }
//
// // color
// if (m.color != colors::black) {
// string colorValue;
// colorValue.appendFormat("[%f, %f, %f]", m.color.r, m.color.g, m.color.b);
// writer.writeCustomProperty("color", colorValue.getBuffer());
// }
//
// // transparency
// if (m.transparency > 0) {
// writer.writeProperty("transparency", m.transparency);
// }
//
// writer.endObject();
//}
//
//void SceneJsonWriter::writeTexture(const string& name, const string &texFile) {
//
// if (!this->embedResources) {
// char texPath[300];
// _strcpy(texPath, texFile.getBuffer());
// convertToUnixRelativePath(texPath, this->workpath);
//
// writer.writeProperty(name, texPath);
// }
// else {
//
// string texFullPath;
// if (texFile.startsWith(PATH_SPLITTER)) {
// texFullPath = texFile;
// } else {
// texFullPath.append(this->fromFile.getPath());
// if (!texFile.startsWith(PATH_SPLITTER)) texFullPath.append(PATH_SPLITTER);
// texFullPath.append(texFile);
// }
//
// ChunkEntry* entry = archiveInfo.archive.newChunk(0x20786574);
//
// if (!texFile.endsWith(".bmp", StringComparingFlags::SCF_CASE_INSENSITIVE)) {
// entry->isCompressed = false;
// }
//
// if (this->textureToJPEG) {
// Texture* tex = resPool.getTexture(texFullPath);
// Image img3b(PixelDataFormat::PDF_RGB, 8);
// Image::copy(tex->getImage(), img3b);
// saveImage(img3b, *entry->stream, ImageCodecFormat::ICF_JPEG);
// } else {
// FileStream fs = File::openRead(texFullPath);
// Stream::copy(fs, *entry->stream);
// }
//
// writer.writeProperty(name, "sob://%s/%08x", insoba ? "__this__" : this->outputJsonObjectName.getBuffer(), entry->uid);
// archiveInfo.archive.updateAndCloseChunk(entry);
// }
//}
//////////////////// RendererSceneLoader ////////////////////
void RendererSceneLoader::load(Renderer &renderer, Scene* scene, const string &path) {
// if (scene == NULL) {
// scene = new Scene();
// }
if (path.endsWith(".fbx", StringComparingFlags::SCF_CASE_INSENSITIVE)) {
#ifdef FBX_SUPPORT
SceneFBXLoader fbxLoader;
fbxLoader.load(*scene, path);
#endif /* FBX_SUPPORT */
} else {
// SceneResourcePool* pool = new SceneResourcePool(); // FIXME: release
SceneJsonLoader jsonLoader(&SceneResourcePool::instance);
jsonLoader.load(path, *scene);
renderer.setScene(scene);
// Camera* camera = new Camera();
// scene->addObject(camera);
// scene->setMainCamera(camera);
// resetMainCamera(scene);
}
}
}
| 25.998615 | 122 | 0.643919 | [
"mesh",
"object",
"vector",
"3d"
] |
f9eb4aa343653b6fc3ac323ef3e86e1641f81498 | 4,441 | cc | C++ | db/nvmdb.cc | DaviBrg/nvrec_ycsb | ebb786793c48dd1565ff4d891c3c5523f1ad2ccd | [
"Apache-2.0"
] | null | null | null | db/nvmdb.cc | DaviBrg/nvrec_ycsb | ebb786793c48dd1565ff4d891c3c5523f1ad2ccd | [
"Apache-2.0"
] | null | null | null | db/nvmdb.cc | DaviBrg/nvrec_ycsb | ebb786793c48dd1565ff4d891c3c5523f1ad2ccd | [
"Apache-2.0"
] | null | null | null | #include "db/nvmdb.h"
#include <algorithm>
#include "recovery/nvmblk_engine.h"
#include "recovery/nvmlog_engine.h"
#include "recovery/nvrec_engine.h"
using namespace ycsbc;
using Tables = std::map<std::string, NVMDB::Table>;
NVMDB::NVMDB(kNVMDBType type) {
switch (type) {
case kNVMBlk:
rec_engine_= NVMBlkEngine::BuildEngine();
break;
case kNVMLog:
rec_engine_= NVMLogEngine::BuildEngine();
break;
case kNVMRec:
rec_engine_= std::make_unique<NVRecEngine>();
break;
default:
throw std::runtime_error("Unknown NVM database");
break;
}
if (nullptr == rec_engine_) throw std::runtime_error("NVMDB intance error");
}
auto NVMDB::FindByTableKey(const std::string &table, const std::string &key) {
auto table_it = tables_.find(table);
if (std::end(tables_) == table_it) {
return std::make_tuple(false, Tables::iterator{}, Table::iterator{});
}
Table& my_table = table_it->second;
auto key_it = my_table.find(key);
if (std::end(my_table) == key_it) {
return std::make_tuple(false, Tables::iterator{}, Table::iterator{});
}
return std::make_tuple(true, table_it, key_it);
}
int NVMDB::Read(const std::string &table, const std::string &key,
const std::vector<std::string> *fields,
std::vector<DB::KVPair> &result) {
std::lock_guard lk{mutex_};
auto [found, table_it, key_it] = FindByTableKey(table, key);
if (!found) {
return kErrorNoData;
}
if (nullptr == fields) {
result = key_it->second;
}
else {
result = FilterByFields(key_it->second, *fields);
}
return kOK;
}
int NVMDB::Scan(const std::string &table, const std::string &key,
int record_count, const std::vector<std::string> *fields,
std::vector<std::vector<DB::KVPair> > &result) {
std::lock_guard lk{mutex_};
auto [found, table_it, key_it] = FindByTableKey(table, key);
if (!found) {
return kErrorNoData;
}
auto end_it = std::end(table_it->second);
for (int i = 0; i < record_count; i++) {
if (key_it == end_it) {
break;
}
result.emplace_back(((key_it++)->second));
}
}
int NVMDB::Update(const std::string &table, const std::string &key,
std::vector<DB::KVPair> &values) {
std::lock_guard lk{mutex_};
auto [found, table_it, key_it] = FindByTableKey(table, key);
if (!found) {
return kErrorNoData;
}
auto &stored_values = (*key_it).second;
for (const auto& value : values) {
auto find_it = std::find_if(std::begin(stored_values),
std::end(stored_values),
[&value](const auto& kvpair){
return kvpair.first == value.first;
});
if (std::end(stored_values) != find_it) {
find_it->second = value.second;
} else {
stored_values.emplace_back(value);
}
}
if (rec_engine_->PersistUpdate(std::stoul(key), values) == kSuccess) {
return kOK;
} else {
return kErrorConflict;
}
}
int NVMDB::Insert(const std::string &table, const std::string &key,
std::vector<DB::KVPair> &values) {
std::lock_guard lk{mutex_};
tables_[table][key] = values;
if (rec_engine_->PersistUpdate(std::stoul(key), values) == kSuccess) {
return kOK;
} else {
return kErrorConflict;
}
}
int NVMDB::Delete(const std::string &table, const std::string &key) {
std::lock_guard lk{mutex_};
auto [found, table_it, key_it] = FindByTableKey(table, key);
if (!found) {
return kErrorNoData;
}
table_it->second.erase(key_it);
if (rec_engine_->PersistDelete(std::stoul(key)) == kSuccess) {
return kOK;
} else {
return kErrorConflict;
}
}
std::vector<DB::KVPair> NVMDB::FilterByFields(
const std::vector<DB::KVPair> &values,
const std::vector<std::string> &fields) {
std::vector<DB::KVPair> result;
for (const auto& value : values) {
auto it = std::find_if(std::begin(fields), std::end(fields),
[&value](const auto& field){
return value.first == field;
});
if (std::end(fields) != it) {
result.emplace_back(value);
}
}
return result;
}
| 30.006757 | 80 | 0.583202 | [
"vector"
] |
f9eb4ffa56b3b4eedf4a6dd7ae995d10a4992da7 | 2,492 | cpp | C++ | Cartwheel/cartwheel-3d/Core/TwoLinkIK.cpp | MontyThibault/centre-of-mass-awareness | 58778f148e65749e1dfc443043e9fc054ca3ff4d | [
"MIT"
] | null | null | null | Cartwheel/cartwheel-3d/Core/TwoLinkIK.cpp | MontyThibault/centre-of-mass-awareness | 58778f148e65749e1dfc443043e9fc054ca3ff4d | [
"MIT"
] | null | null | null | Cartwheel/cartwheel-3d/Core/TwoLinkIK.cpp | MontyThibault/centre-of-mass-awareness | 58778f148e65749e1dfc443043e9fc054ca3ff4d | [
"MIT"
] | null | null | null | #include "TwoLinkIK.h"
TwoLinkIK::TwoLinkIK(void){
}
TwoLinkIK::~TwoLinkIK(void){
}
/**
All quantities that are passed in as parameters here need to be expressed in the same "global" coordinate frame, unless otherwise noted:
- p1: this is the location of the origin of the parent link
- p2: this is the target location of the end effector on the child link
- n: this is the default normal to the rotation plane (it will get modified as little as possible to account for the target location)
- vParent: vector from parent origin to child origin, expressed in parent coordinates
- nParent: this is the rotation axis, expressed in parent coordinates. The relative orientation between child and parent will be about this axis
- vChild: vector from child origin, to position of the end effector, expressed in child coordinates
Output:
- qP: relative orientation of parent, relative to "global" coordinate frame
- qC: relative orientation of child, relative to the parent coordinate frame
NOTE: for now, the vector vChild is pretty much ignored. Only its length is taken into account. The axis that the child is lined up around is the same as the direction
of the vector from the parent's origin to the child's origin (when there is zero relative orientation between the two, the axis has the same coordinates in both
child and parent frame).
*/
void TwoLinkIK::getIKOrientations(const Point3d& p1, const Point3d& p2, const Vector3d& n, const Vector3d& vParent, const Vector3d& nParent, const Vector3d& vChild, Quaternion* qP, Quaternion* qC){
//modify n so that it's perpendicular to the vector (p1, p2), and still as close as possible to n
Vector3d line = Vector3d(p1, p2);
Vector3d temp = n.crossProductWith(line);
Vector3d nG = line.crossProductWith(temp);
nG.toUnit();
//now compute the location of the child origin, in "global" coordinates
Vector3d solvedJointPosW = TwoLinkIK::solve(p1, p2, nG, vParent.length(), vChild.length());
Vector3d vParentG = Vector3d(p1, solvedJointPosW);
Vector3d vChildG = Vector3d(solvedJointPosW, p2);
//now we need to solve for the orientations of the parent and child
//if the parent has 0 relative orientation to the grandparent (default), then the grandparent's orientation is also the parent's
*qP = TwoLinkIK::getParentOrientation(vParentG, nG, vParent, nParent);
double childAngle = TwoLinkIK::getChildRotationAngle(vParentG, vChildG, nG);
*qC = Quaternion::getRotationQuaternion(childAngle, nParent);
}
| 51.916667 | 197 | 0.76565 | [
"vector"
] |
f9f306f7b803d240532c3b8948680ae8193d5a6e | 8,067 | cpp | C++ | test/distribution/decorrelated_gaussian_test.cpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 17 | 2015-07-03T06:53:05.000Z | 2021-05-15T20:55:12.000Z | test/distribution/decorrelated_gaussian_test.cpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 3 | 2015-02-20T12:48:17.000Z | 2019-12-18T08:45:13.000Z | test/distribution/decorrelated_gaussian_test.cpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 15 | 2015-02-20T11:34:14.000Z | 2021-05-15T20:55:13.000Z | /*
* This is part of the fl library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2015 Max Planck Society,
* Autonomous Motion Department,
* Institute for Intelligent Systems
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_test.cpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#include <gtest/gtest.h>
#include "../typecast.hpp"
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <fl/distribution/decorrelated_gaussian.hpp>
template <typename TestType>
class DecorrelatedGaussianTests
: public testing::Test
{
public:
typedef typename TestType::Parameter Configuration;
enum: signed int
{
Dim = Configuration::Dim,
Size = fl::TestSize<Dim, TestType>::Value
};
typedef Eigen::Matrix<fl::Real, Size, 1> Vector;
protected:
template <typename Gaussian, typename Covariance>
void test_gaussian_attributes(Gaussian& gaussian,
const Covariance& covariance,
const Covariance& precision,
const Covariance& square_root)
{
EXPECT_GT(gaussian.dimension(), 0);
EXPECT_TRUE(
fl::are_similar(gaussian.covariance().diagonal(),
covariance.diagonal()));
EXPECT_TRUE(
fl::are_similar(gaussian.precision().diagonal(),
precision.diagonal()));
EXPECT_TRUE(
fl::are_similar(gaussian.square_root().diagonal(),
square_root.diagonal()));
EXPECT_TRUE(gaussian.has_full_rank());
}
template <typename Gaussian>
void test_gaussian_covariance(Gaussian& gaussian)
{
typedef typename Gaussian::SecondMoment SecondMoment;
SecondMoment covariance;
SecondMoment square_root;
SecondMoment precision;
covariance.setIdentity(Dim);
precision.setIdentity(Dim);
square_root.setIdentity(Dim);
// first verify standard gaussian
{
SCOPED_TRACE("Unchanged");
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
// set covariance and verify representations
{
SCOPED_TRACE("Covariance setter");
covariance.diagonal().setRandom(Dim);
covariance.diagonal() = covariance.diagonal().cwiseProduct(
covariance.diagonal());
square_root.diagonal() = covariance.diagonal().cwiseSqrt();
precision.diagonal() = covariance.diagonal().cwiseInverse();
gaussian.covariance(covariance);
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
// set square root and verify representations
{
SCOPED_TRACE("SquareRoot setter");
covariance.diagonal().setRandom(Dim);
covariance.diagonal() = covariance.diagonal().cwiseProduct(
covariance.diagonal());
square_root.diagonal() = covariance.diagonal().cwiseSqrt();
precision.diagonal() = covariance.diagonal().cwiseInverse();
gaussian.square_root(square_root);
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
// set covariance and verify representations
{
SCOPED_TRACE("Precision setter");
covariance.diagonal().setRandom(Dim);
covariance.diagonal() = covariance.diagonal().cwiseProduct(
covariance.diagonal());
square_root.diagonal() = covariance.diagonal().cwiseSqrt();
precision.diagonal() = covariance.diagonal().cwiseInverse();
gaussian.precision(precision);
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
}
};
TYPED_TEST_CASE_P(DecorrelatedGaussianTests);
TYPED_TEST_P(DecorrelatedGaussianTests, dimension)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
auto gaussian = Gaussian(This::Dim);
EXPECT_EQ(gaussian.dimension(), This::Dim);
EXPECT_EQ(gaussian.standard_variate_dimension(), This::Dim);
EXPECT_EQ(gaussian.mean().size(), This::Dim);
EXPECT_EQ(gaussian.covariance().rows(), This::Dim);
EXPECT_EQ(gaussian.precision().rows(), This::Dim);
EXPECT_EQ(gaussian.square_root().rows(), This::Dim);
auto noise = Gaussian::StandardVariate::Random(
gaussian.standard_variate_dimension(), 1).eval();
EXPECT_EQ(gaussian.map_standard_normal(noise).size(), This::Dim);
}
TYPED_TEST_P(DecorrelatedGaussianTests, standard_covariance)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
auto gaussian = Gaussian(This::Dim);
This::test_gaussian_covariance(gaussian);
}
TYPED_TEST_P(DecorrelatedGaussianTests, dynamic_uninitialized_gaussian)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
auto gaussian = Gaussian();
if (This::Size != Eigen::Dynamic)
{
EXPECT_NO_THROW(gaussian.covariance());
EXPECT_NO_THROW(gaussian.precision());
EXPECT_NO_THROW(gaussian.square_root());
}
else
{
EXPECT_THROW(gaussian.covariance(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.precision(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.square_root(), fl::GaussianUninitializedException);
gaussian.dimension(1);
EXPECT_NO_THROW(gaussian.covariance());
EXPECT_NO_THROW(gaussian.precision());
EXPECT_NO_THROW(gaussian.square_root());
gaussian.dimension(0);
EXPECT_THROW(gaussian.covariance(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.precision(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.square_root(), fl::GaussianUninitializedException);
}
}
TYPED_TEST_P(DecorrelatedGaussianTests, gaussian_covariance_dimension_init)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
auto gaussian = Gaussian();
gaussian.dimension(This::Dim);
EXPECT_NO_THROW(This::test_gaussian_covariance(gaussian));
}
TYPED_TEST_P(DecorrelatedGaussianTests, gaussian_covariance_constructor_init)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
auto gaussian = Gaussian(This::Dim);
EXPECT_NO_THROW(This::test_gaussian_covariance(gaussian));
}
REGISTER_TYPED_TEST_CASE_P(DecorrelatedGaussianTests,
dimension,
standard_covariance,
dynamic_uninitialized_gaussian,
gaussian_covariance_dimension_init,
gaussian_covariance_constructor_init);
template <int Dimension>
struct TestConfiguration
{
enum: signed int { Dim = Dimension };
};
typedef ::testing::Types<
fl::StaticTest<TestConfiguration<2>>,
fl::StaticTest<TestConfiguration<3>>,
fl::StaticTest<TestConfiguration<10>>,
fl::StaticTest<TestConfiguration<10000>>,
fl::DynamicTest<TestConfiguration<2>>,
fl::DynamicTest<TestConfiguration<3>>,
fl::DynamicTest<TestConfiguration<10>>,
fl::DynamicTest<TestConfiguration<1000000>>
> TestTypes;
INSTANTIATE_TYPED_TEST_CASE_P(DecorrelatedGaussianTestCases,
DecorrelatedGaussianTests,
TestTypes);
| 31.635294 | 81 | 0.640263 | [
"vector"
] |
f9fb91ea2b16c7add2d8b4a0abeb4701737bed0e | 102,734 | cpp | C++ | cognitics/meshgen/ws/WebServices.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/meshgen/ws/WebServices.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/meshgen/ws/WebServices.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | #include "rapidjson/filereadstream.h"
#include "rapidjson/document.h"
#include "WebServices.h"
#include "ip/GDALRasterSampler.h"
#include <fstream>
#include <vector>
#include <iomanip>
#include <iterator>
#include <iostream>
#include <string>
#include "b64/base64.h"
#include <cctype>
#include "gdal_utils.h"
#include <string>
#include "curl/curl.h"
//#include <direct.h>
//#include <filesystem>
#include <ccl/FileInfo.h>
#include <elev/DataSourceManager.h>
#include <thread>
#include <atomic>
#include <scenegraphobj/scenegraphobj.h>
#include <scenegraph/FlattenVisitor.h>
#include <scenegraph/CoordinateTransformVisitor.h>
#include <scenegraph/TransformVisitor.h>
#include <ctl/ctl.h>
#include <mutex>
#include <ip/jpgwrapper.h>
#undef min
#undef max
#pragma warning(disable : 4996)
using namespace std;
namespace ws
{
std::mutex fbx_mutex;
struct GeoExtents
{
double north;
double east;
double south;
double west;
};
struct TileInfo
{
GeoExtents extents;
float centerX;
float centerY;
std::string elevationFileName;
std::string imageFileName;
int width;
int height;
std::string quadKey;
GsBuildings GSFeatures;
};
struct memBuffer
{
public:
memBuffer() : buffer((u_char*)malloc(1)), size(0) {}
u_char * buffer;
size_t size;
void clear()
{
size = 0;
}
};
size_t WriteMemory_Callback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct memBuffer *mem = (struct memBuffer *)userp;
mem->buffer = (u_char*)realloc(mem->buffer, mem->size + realsize + 1);
if (mem->buffer == NULL)
{
// out of memory!
std::cout << "WebServices: not enough memory (realloc returned NULL) " << std::endl;
return 0;
}
memcpy(&(mem->buffer[mem->size]), contents, realsize);
mem->size += realsize;
mem->buffer[mem->size] = 0;
return realsize;
}
bool GetCurlResponse(CURL* curl)
{
bool succeeded = true;
CURLcode result = curl_easy_perform(curl);
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
if (result != CURLE_OK)
{
std::cout << "WebServices: curl easy getinfo failed: " << curl_easy_strerror(result) << std::endl;
succeeded = false;
}
if (http_code != 200)
{
std::cout << "WebServices: Error: Returned http code=" << http_code << std::endl;
succeeded = false;
}
return succeeded;
}
void WriteLODfile(std::vector<TileInfo>& infos, std::string outputFilename, int nLODs)
{
std::ofstream lodFile;
lodFile.open(outputFilename, std::ofstream::out);
lodFile << nLODs << std::endl;
cts::FlatEarthProjection flatEarth;
for (auto& info : infos)
{
flatEarth.setOrigin(info.extents.south, info.extents.west);
lodFile << "beginBuildingList\n";
for (int i = 0; i < info.GSFeatures.Count(); ++i)
{
float lat = info.GSFeatures.GetBuilding(i).lat;
float lon = info.GSFeatures.GetBuilding(i).lon;
float elev = info.GSFeatures.GetBuilding(i).elev;
double y = flatEarth.convertGeoToLocalY(lat);
double x = flatEarth.convertGeoToLocalX(lon);
double z = info.GSFeatures.GetBuilding(i).elev;
double ao1 = info.GSFeatures.GetBuilding(i).AO1;
double scalex = info.GSFeatures.GetBuilding(i).scaleX;
double scaley = info.GSFeatures.GetBuilding(i).scaleY;
double scalez = info.GSFeatures.GetBuilding(i).scaleZ;
std::string modelpath = info.GSFeatures.GetBuilding(i).modelpath;
lodFile << x << " " << y << " " << z << " " << ao1 << " " << modelpath << " " << scalex << " " << scaley << " " << scalez << "\n";
}
lodFile << "endBuildingList\n";
lodFile << info.quadKey << " " << info.centerX << " " << info.centerY << std::endl;
}
}
void ComputeCenterPosition(std::vector<TileInfo>& infos, double originLat, double originLon)
{
cts::FlatEarthProjection flatEarth;
flatEarth.setOrigin(originLat, originLon);
for (auto& info : infos)
{
double centerLat = (info.extents.north - info.extents.south) / 2 + info.extents.south;
double centerLon = (info.extents.east - info.extents.west) / 2 + info.extents.west;
info.centerX = flatEarth.convertGeoToLocalX(centerLon);
info.centerY = flatEarth.convertGeoToLocalY(centerLat);
}
}
void GenerateFileNames(std::vector<TileInfo>& infos, const std::string& outputTmpPath)
{
for (auto& info : infos)
{
double centerLat = (info.extents.north - info.extents.south) / 2 + info.extents.south;
double centerLon = (info.extents.east - info.extents.west) / 2 + info.extents.west;
auto name = GetName(centerLon, centerLat, 0, 0, "obj", ".tif");
info.elevationFileName = outputTmpPath + "/" + name;
info.imageFileName = outputTmpPath + "/img/" + name;
}
}
void GenerateFileNames(std::vector<TileInfo>& infos, const std::string& outputTmpPath, int height, int width, std::string format)
{
for (auto& info : infos)
{
double centerLat = (info.extents.north - info.extents.south) / 2 + info.extents.south;
double centerLon = (info.extents.east - info.extents.west) / 2 + info.extents.west;
auto name = GetName(centerLon, centerLat, height, width, format, ".tif");
info.elevationFileName = outputTmpPath + "/" + name;
info.imageFileName = outputTmpPath + "/img/" + name;
}
}
void GenerateLODBounds(std::vector<TileInfo>& infos, const TileInfo& info, int depth)
{
if (info.extents.north <= info.extents.south || info.extents.east <= info.extents.west)
{
return;
}
infos.push_back(info);
if (depth == 0)
{
return;
}
double centerLat = (info.extents.north - info.extents.south) / 2 + info.extents.south;
double centerLon = (info.extents.east - info.extents.west) / 2 + info.extents.west;
TileInfo topLeft;
topLeft.extents.north = info.extents.north;
topLeft.extents.west = info.extents.west;
topLeft.extents.east = centerLon;
topLeft.extents.south = centerLat;
topLeft.quadKey = info.quadKey + std::to_string(0);
TileInfo topRight;
topRight.extents.north = info.extents.north;
topRight.extents.west = centerLon;
topRight.extents.east = info.extents.east;
topRight.extents.south = centerLat;
topRight.quadKey = info.quadKey + std::to_string(1);
TileInfo bottomLeft;
bottomLeft.extents.north = centerLat;
bottomLeft.extents.west = info.extents.west;
bottomLeft.extents.east = centerLon;
bottomLeft.extents.south = info.extents.south;
bottomLeft.quadKey = info.quadKey + std::to_string(2);
TileInfo bottomRight;
bottomRight.extents.north = centerLat;
bottomRight.extents.west = centerLon;
bottomRight.extents.east = info.extents.east;
bottomRight.extents.south = info.extents.south;
bottomRight.quadKey = info.quadKey + std::to_string(3);
GenerateLODBounds(infos, topLeft, depth - 1);
GenerateLODBounds(infos, topRight, depth - 1);
GenerateLODBounds(infos, bottomLeft, depth - 1);
GenerateLODBounds(infos, bottomRight, depth - 1);
}
void GetData(const std::string& geoServerURL, int beginIndex, int endIndex, std::vector<TileInfo>* infos)
{
if (infos == NULL)
{
return;
}
for (int i = beginIndex; i < endIndex; i++)
{
if (i >= infos->size())
{
break;
}
auto& info = (*infos)[i];
GetElevation(geoServerURL, info.extents.north, info.extents.south, info.extents.east, info.extents.west, info.width, info.height, info.elevationFileName);
GetImagery(geoServerURL, info.extents.north, info.extents.south, info.extents.east, info.extents.west, info.width, info.height, info.imageFileName);
}
}
void GenerateFixedGridParallel(cognitics::TerrainGenerator* terrainGenerator, int beginIndex, int endIndex, const std::string& outputFormat, const std::string& outputPath, elev::Elevation_DSM& edsm, std::vector<TileInfo>* infos)
{
for (int i = beginIndex; i < endIndex; i++)
{
auto& info = (*infos)[i];
terrainGenerator->generateFixedGrid(info.imageFileName, outputPath, info.quadKey, outputFormat, edsm, info.extents.north, info.extents.south, info.extents.east, info.extents.west);
}
}
void generateFixedGridWeb2(double north, double south, double west, double east, std::string format, const std::string& geoServerURL, const std::string& outputTmpPath, const std::string& outputPath, const std::string& outputFormat, cognitics::TerrainGenerator* terrainGenerator, int lodDepth, int textureHeight, int textureWidth)
{
double deltaX = east - west;
double deltaY = north - south;
double delta = min(deltaX, deltaY) / 2;
double centerLat = (north - south) / 2 + south;
double centerLon = (east - west) / 2 + west;
east = centerLon + delta;
west = centerLon - delta;
north = centerLat + delta;
south = centerLat - delta;
centerLat = (north - south) / 2 + south;
centerLon = (east - west) / 2 + west;
std::vector<TileInfo> infos;
TileInfo info;
info.extents.east = east;
info.extents.north = north;
info.extents.south = south;
info.extents.west = west;
info.quadKey = std::to_string(0);
GenerateLODBounds(infos, info, lodDepth);
GenerateFileNames(infos, outputTmpPath, textureHeight, textureWidth, format);
ComputeCenterPosition(infos, centerLat, centerLon);
int nthreads = std::thread::hardware_concurrency();
std::vector<std::thread> threads(nthreads);
int span = infos.size() / nthreads;
int index = 0;
for (int t = 0; t < nthreads; t++)
{
int begin = index;
int end = index + span;
if (t == nthreads - 1)
{
end = infos.size() - 1;
}
threads[t] = std::thread(GetData, geoServerURL, begin, end, &infos);
index = end + 1;
}
std::for_each(threads.begin(), threads.end(), [](std::thread& x) {x.join(); });
cout << "DONE" << endl;
elev::DataSourceManager dsm(1000000);
for (auto& info : infos)
{
//GetElevationSquare(geoServerURL, info.extents.north, info.extents.south, info.extents.east, info.extents.west, info.width, info.height, info.elevationFileName);
//GetImagery(geoServerURL, info.extents.north, info.extents.south, info.extents.east, info.extents.west, info.width, info.height, info.imageFileName);
//dsm.AddFile_Raster_GDAL(info.elevationFileName);
}
elev::Elevation_DSM edsm(&dsm, elev::elevation_strategy::ELEVATION_BILINEAR);
for (auto& info : infos)
{
terrainGenerator->generateFixedGrid(info.imageFileName, outputPath, info.quadKey, outputFormat, edsm, info.extents.north, info.extents.south, info.extents.east, info.extents.west);
}
//sfa::Point p(0, 0);
//for(double lat = south; lat < north; lat += 0.001)
// for (double lon = west; lon < east; lon += 0.001)
// {
// p.setX(lon);
// p.setY(lat);
// edsm.Get(&p);
// if (p.Z() < 0 || p.Z() > 0)
// {
// int itWorks = 4;
// }
// }
#ifdef CAE_MESH
terrainGenerator->createFeatures(edsm);
#endif
WriteLODfile(infos, outputPath + "/lodFile.txt", lodDepth);
terrainGenerator->setBounds(north, south, east, west);
terrainGenerator->CreateMasterFile();
}
void GetFeatureData(const std::string& geoServerURL, std::string tmpPath, double north, double south, double east, double west)
{
std::string dataPath = ccl::joinPaths(tmpPath, "data");
ccl::makeDirectory(dataPath);
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
string sUrl = geoServerURL;
sUrl += "/wfs";
curl_easy_setopt(curl, CURLOPT_URL, sUrl.c_str());
//curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/geoserver/wfs");
struct curl_slist *hs = NULL;
hs = curl_slist_append(hs, "Content-Type: text/xml;charset=utf-8");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hs);
//curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "<wfs:GetFeature xmlns:wfs=\"http://www.opengis.net/wfs\" service=\"WFS\" version=\"1.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd\"><wfs:Query typeName=\"CDB_Vectors:GT_TreePoints\"><ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\"><ogc:BBOX><ogc:PropertyName>geom</ogc:PropertyName><gml:Box xmlns:gml=\"http://www.opengis.net/gml\" srsName=\"EPSG:4326\"><gml:coordinates decimal=\".\" cs=\",\" ts=\" \">45.0546875,12.75 45.0625,12.7578125</gml:coordinates></gml:Box></ogc:BBOX></ogc:Filter></wfs:Query></wfs:GetFeature>");
//curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "<wfs:GetFeature xmlns:wfs=\"http://www.opengis.net/wfs\" service=\"WFS\" version=\"1.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd\"><wfs:Query typeName=\"CDB_Vectors:GS_ManMadePoints_Footprints\"><ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\"><ogc:BBOX><ogc:PropertyName>geom</ogc:PropertyName><gml:Box xmlns:gml=\"http://www.opengis.net/gml\" srsName=\"EPSG:4326\"><gml:coordinates decimal=\".\" cs=\",\" ts=\" \">45.0546875,12.75 45.0625,12.7578125</gml:coordinates></gml:Box></ogc:BBOX></ogc:Filter></wfs:Query></wfs:GetFeature>");
//{//shouldn't need footprints, just export models
//
// std::stringstream footprintsXml;
// footprintsXml <<
// //footprints!
// //"<wfs:GetFeature xmlns:wfs=\"http://www.opengis.net/wfs\" service=\"WFS\" version=\"1.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd\"><wfs:Query typeName=\"CDB_Vectors:GS_ManMadePoints_Footprints\"><ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\"><ogc:BBOX><ogc:PropertyName>geom</ogc:PropertyName><gml:Box xmlns:gml=\"http://www.opengis.net/gml\" srsName=\"EPSG:4326\"><gml:coordinates decimal=\".\" cs=\",\" ts=\" \">45.046875,12.7578125 45.0546875,12.765625</gml:coordinates></gml:Box></ogc:BBOX></ogc:Filter></wfs:Query></wfs:GetFeature>";
// "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
// "<wfs:GetFeature xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" service=\"WFS\" version=\"1.0.0\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd\">"
// "<wfs:Query typeName=\"CDB_Vectors:GS_ManMadePoints_Footprints\">"
// "<ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\">"
// "<ogc:BBOX>"
// "<ogc:PropertyName>geom</ogc:PropertyName>"
// "<gml:Box xmlns:gml=\"http://www.opengis.net/gml\" srsName=\"EPSG:4326\">"
// "<gml:coordinates decimal=\".\" cs=\",\" ts=\" \">"
// << west << "," << south << " " << east << "," << north << //45.046875,12.7578125 45.0546875,12.765625
// "</gml:coordinates>"
// "</gml:Box>"
// "</ogc:BBOX>"
// "</ogc:Filter>"
// "</wfs:Query>"
// "</wfs:GetFeature>";
//
// std::string footprintsStr = footprintsXml.str();
// curl_easy_setopt(curl, CURLOPT_POSTFIELDS, footprintsStr.c_str());
//
// memBuffer wfsResponseBuffer;
// curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemory_Callback);
// curl_easy_setopt(curl, CURLOPT_WRITEDATA, &wfsResponseBuffer);
//
// if (!GetCurlResponse(curl))
// {
// std::cout << "WebServices: Error: Failed getting footprints" << std::endl;
// }
// else
// {
// std::ofstream file(ccl::joinPaths(dataPath, "building_footprints.xml"));
// file.write((char*)wfsResponseBuffer.buffer, wfsResponseBuffer.size);
// file.close();
// }
//}
{
std::stringstream treeXml;
treeXml <<
//trees!
//"<wfs:GetFeature xmlns:wfs=\"http://www.opengis.net/wfs\" service=\"WFS\" version=\"1.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd\"><wfs:Query typeName=\"CDB_Vectors:GT_TreePoints\"><ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\"><ogc:BBOX><ogc:PropertyName>geom</ogc:PropertyName><gml:Box xmlns:gml=\"http://www.opengis.net/gml\" srsName=\"EPSG:4326\"><gml:coordinates decimal=\".\" cs=\",\" ts=\" \">45.015625,12.796875 45.0234375,12.8046875</gml:coordinates></gml:Box></ogc:BBOX></ogc:Filter></wfs:Query></wfs:GetFeature>";
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<wfs:GetFeature xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" service=\"WFS\" version=\"1.0.0\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd\">"
"<wfs:Query typeName=\"CDB_Vectors:GT_TreePoints\">"
"<ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\">"
"<ogc:BBOX>"
"<ogc:PropertyName>geom</ogc:PropertyName>"
"<gml:Box xmlns:gml=\"http://www.opengis.net/gml\" srsName=\"EPSG:4326\">"
"<gml:coordinates decimal=\".\" cs=\",\" ts=\" \">"
<< west << "," << south << " " << east << "," << north << //45.015625,12.796875 45.0234375,12.8046875
"</gml:coordinates>"
"</gml:Box>"
"</ogc:BBOX>"
"</ogc:Filter>"
"</wfs:Query>"
"</wfs:GetFeature>";
std::string treeStr = treeXml.str();
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, treeStr.c_str());
memBuffer wfsResponseBuffer;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemory_Callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &wfsResponseBuffer);
if (!GetCurlResponse(curl))
{
std::cout << "WebServices: Error: Failed getting trees" << std::endl;
}
else
{
std::ofstream file(ccl::joinPaths(dataPath, "tree_points.xml"));
file.write((char*)wfsResponseBuffer.buffer, wfsResponseBuffer.size);
file.close();
}
}
{
std::stringstream modelsXml;
modelsXml <<
//buildings / premade models
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><wps:Execute version=\"1.0.0\" service=\"WPS\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.opengis.net/wps/1.0.0\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:wcs=\"http://www.opengis.net/wcs/1.1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd\">"
"<ows:Identifier>gs:CdbExportModels</ows:Identifier>"
"<wps:DataInputs>"
"<wps:Input>"
"<ows:Identifier>envelope</ows:Identifier>"
"<wps:Data>"
"<wps:BoundingBoxData dimensions=\"2\">"
"<ows:LowerCorner>" << west << " " << south << "</ows:LowerCorner>"
"<ows:UpperCorner>" << east << " " << north << "</ows:UpperCorner>"
"</wps:BoundingBoxData>"
"</wps:Data>"
"</wps:Input>"
"<wps:Input>"
"<ows:Identifier>gsLOD</ows:Identifier>"
"<wps:Data>"
"<wps:LiteralData>1000</wps:LiteralData>"
"</wps:Data>"
"</wps:Input>"
"<wps:Input>"
"<ows:Identifier>gtLOD</ows:Identifier>"
"<wps:Data>"
"<wps:LiteralData>1000</wps:LiteralData>"
"</wps:Data>"
"</wps:Input>"
"<wps:Input>"
"<ows:Identifier>Texture Width</ows:Identifier>"
"<wps:Data>"
"<wps:LiteralData>128</wps:LiteralData>"
"</wps:Data>"
"</wps:Input>"
"<wps:Input>"
"<ows:Identifier>Texture Height</ows:Identifier>"
"<wps:Data>"
"<wps:LiteralData>128</wps:LiteralData>"
"</wps:Data>"
"</wps:Input>"
"<wps:Input>"
"<ows:Identifier>Geo-Typical</ows:Identifier>"
"<wps:Data>"
"<wps:LiteralData>true</wps:LiteralData>"
"</wps:Data>"
"</wps:Input>"
"<wps:Input>"
"<ows:Identifier>Geo-Specific</ows:Identifier>"
"<wps:Data>"
"<wps:LiteralData>true</wps:LiteralData>"
"</wps:Data>"
"</wps:Input>"
"<wps:Input>"
"<ows:Identifier>ModelNamesOnly</ows:Identifier>"
"<wps:Data>"
"<wps:LiteralData>false</wps:LiteralData>"
"</wps:Data>"
"</wps:Input>"
"</wps:DataInputs>"
"<wps:ResponseForm>"
"<wps:RawDataOutput mimeType=\"application/json\">"
"<ows:Identifier>scene</ows:Identifier>"
"</wps:RawDataOutput>"
"</wps:ResponseForm>"
"</wps:Execute>";
std::string modelsStr = modelsXml.str();
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, modelsStr.c_str());
memBuffer wpsResponseBuffer;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemory_Callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &wpsResponseBuffer);
if (!GetCurlResponse(curl))
{
std::cout << "WebServices: Error: Failed getting models" << std::endl;
}
else
{
std::ofstream file(ccl::joinPaths(dataPath, "building_models.xml"));
file.write((char*)wpsResponseBuffer.buffer, wpsResponseBuffer.size);
file.close();
}
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
}
std::string GetName(double originLon, double originLat, double textureHeight, double textureWidth, std::string formatIn, std::string filetype)
{
std::string lat = "N";
std::string lon = "E";
std::string format = formatIn;
double latValue = originLat;
double lonValue = originLon;
if (latValue < 0)
lat = "S";
if (lonValue < 0)
lon = "W";
std::string chars = ".";
for (char c : chars)
{
format.erase(std::remove(format.begin(), format.end(), c), format.end());
}
for (std::string::size_type i = 0; i < format.length(); i++)
{
std::toupper(format[i]);
}
std::transform(format.begin(), format.end(), format.begin(), ::toupper);
std::string name;
name = lat + std::to_string(fabs(latValue)) + "_" + lon + std::to_string(fabs(lonValue)) + "_" + format + filetype;
return name;
}
void CreateElevationTiff(const std::string& sFile, float* data, int textureWidth, int textureHeight)
{
const char* tiffFileFormat = "GTiff";
GDALDriver* tiffDriver = GetGDALDriverManager()->GetDriverByName(tiffFileFormat);
GDALDatasetH hDataset = GDALCreate(tiffDriver, sFile.c_str(), textureWidth, textureHeight, 1, GDT_Float32, NULL);
GDALRasterBandH hBand = GDALGetRasterBand(hDataset, 1);
float fMax = 0;
for (int z = 0; z < textureHeight*textureWidth; z++)
{
if (data[z] > fMax)
{
fMax = data[z];
}
}
float* buf = new float[textureWidth*textureHeight];
for (int n = 0; n < textureWidth*textureHeight; ++n)
{
buf[n] = (data[n] / fMax);
}
GDALRasterIO(hBand, GF_Write, 0, 0, textureWidth, textureHeight, buf, textureWidth, textureHeight, GDT_Float32, 0, 0);
GDALClose(hDataset);
}
void CreateElevationDeltaTiff(const std::string& sFile, float* data, int textureWidth, int textureHeight, float delta)
{
const char* tiffFileFormat = "GTiff";
GDALDriver* tiffDriver = GetGDALDriverManager()->GetDriverByName(tiffFileFormat);
GDALDatasetH hDataset = GDALCreate(tiffDriver, sFile.c_str(), textureWidth, textureHeight, 1, GDT_Float32, NULL);
GDALRasterBandH hBand = GDALGetRasterBand(hDataset, 1);
float* buf = new float[textureWidth*textureHeight];
for (int n = 0; n < textureWidth*textureHeight; ++n)
{
buf[n] = 0;
}
for (int r = 0; r < textureHeight; ++r)
{
for (int c = 0; c < textureWidth - 1; ++c)
{
if (std::abs(data[r*textureWidth + c + 1] - data[r*textureWidth + c]) > delta)
{
buf[r*textureWidth + c] = 1;
}
}
}
for (int r = 0; r < textureHeight - 1; ++r)
{
for (int c = 0; c < textureWidth; ++c)
{
if (std::abs(data[r*textureWidth + c] - data[(r + 1)*textureWidth + c]) > delta)
{
buf[r*textureWidth + c] = 1;
}
}
}
GDALRasterIO(hBand, GF_Write, 0, 0, textureWidth, textureHeight, buf, textureWidth, textureHeight, GDT_Float32, 0, 0);
GDALClose(hDataset);
}
void GetElevation(const std::string& geoServerURL, double north, double south, double east, double west, int& textureWidth, int& textureHeight, const std::string& outputPath)
{
GDALDataset* elevationDataset;
char** papszDrivers = NULL;
papszDrivers = CSLAddString(papszDrivers, "WCS");
char** papszOptions = NULL;
papszOptions = CSLAddString(papszOptions, "GridCRSOptional");
std::stringstream parameters;
parameters << std::fixed << std::setprecision(15)
<< "SERVICE=WCS&FORMAT=GeoTIFF&BOUNDINGBOX="
<< south
<< "," << west
<< "," << north
<< "," << east
<< ",urn:ogc:def:crs:EPSG::4326&WIDTH="
<< std::to_string(textureWidth)
<< "&HEIGHT="
<< std::to_string(textureHeight);
std::string xml = "";
xml += "<WCS_GDAL>";
xml += " <ServiceURL>" + geoServerURL + "/wcs?SERVICE=WCS</ServiceURL>";
xml += " <Version>1.1.1</Version>";
xml += " <CoverageName>CDB Elevation_Terrain_Primary</CoverageName>";
xml += " <Parameters>" + parameters.str() + "</Parameters>";
xml += " <GridCRSOptional>TRUE</GridCRSOptional>";
xml += " <CoverageDescription>";
xml += " <Identifier>Base:CDB Elevation_Terrain_Primary</Identifier>";
xml += " <Domain>";
xml += " <SpatialDomain>";
xml += " <BoundingBox crs=\"urn:ogc:def:crs:OGC:1.3 : CRS84\" dimensions=\"2\">";
xml += " <LowerCorner>-180.0 -90.0</LowerCorner>";
xml += " <UpperCorner>180.0 90.0</UpperCorner>";
xml += " </BoundingBox>";
xml += " <BoundingBox crs=\"urn:ogc:def:crs:EPSG::4326\" dimensions=\"2\">";
xml += " <LowerCorner>-90.0 -180.0</LowerCorner>";
xml += " <UpperCorner>90.0 180.0</UpperCorner>";
xml += " </BoundingBox>";
xml += " <BoundingBox crs=\":imageCRS\" dimensions=\"2\">";
xml += " <LowerCorner>0 0</LowerCorner>";
xml += " <UpperCorner>356356356 3563456</UpperCorner>";
xml += " </BoundingBox>";
xml += " <GridCRS>";
xml += " <GridBaseCRS>urn:ogc:def:crs:EPSG::4326</GridBaseCRS>";
xml += " <GridType>urn:ogc:def:method:WCS:1.1:2dGridIn2dCrs</GridType>";
xml += " <GridOrigin>-179.82421875 89.91259765625</GridOrigin>";
xml += " <GridOffsets>0.3515625 0.0 0.0 -0.1748046875</GridOffsets>";
xml += " <GridCS>urn:ogc:def:cs:OGC:0.0:Grid2dSquareCS</GridCS>";
xml += " </GridCRS>";
xml += " </SpatialDomain>";
xml += " </Domain>";
xml += " <SupportedCRS>urn:ogc:def:crs:EPSG::4326</SupportedCRS>";
xml += " <SupportedCRS>EPSG:4326</SupportedCRS>";
xml += " <SupportedFormat>image/tiff</SupportedFormat>";
xml += " </CoverageDescription>";
xml += " <FieldName>contents</FieldName>";
xml += " <BandType>Float32</BandType>";
xml += " <PreferredFormat>image/tiff</PreferredFormat>";
xml += "</WCS_GDAL>";
elevationDataset = (GDALDataset*)GDALOpenEx(xml.c_str(), GDAL_OF_READONLY, papszDrivers, papszOptions, NULL);
auto band = elevationDataset->GetRasterBand(1);
textureWidth = 2452;
textureHeight = 2456;
float *data = new float[textureWidth * textureHeight + 1];
band->RasterIO(GF_Read, 0, 0, textureWidth, textureHeight, data, textureWidth, textureHeight, GDALDataType::GDT_Float32, 0, 0);
std::string err = CPLGetLastErrorMsg();
auto result = err.find("Got ");
result += 4;
err.erase(0, result);
result = err.find('x');
std::string firstnum = err.substr(0, result);
err.erase(0, result + 1);
result = err.find(' ');
std::string secondnum = err.substr(0, result);
textureWidth = std::stoi(firstnum);
textureHeight = std::stoi(secondnum);
band->RasterIO(GF_Read, 0, 0, textureWidth, textureHeight, data, textureWidth, textureHeight, GDALDataType::GDT_Float32, 0, 0);
for (int z = 0; z < textureHeight*textureWidth; z++)
{
if (std::isnan(data[z]))
{
data[z] = 0.0f;
}
}
//CreateElevationTiff("testTiff.tif", data, textureWidth, textureHeight);
//CreateElevationDeltaTiff("testTiff_delta1.tif", data, textureWidth, textureHeight, 1);
//CreateElevationDeltaTiff("testTiff_delta10.tif", data, textureWidth, textureHeight, 10);
float* rotate90 = new float[textureWidth * textureHeight];
for (int i = 0; i < textureWidth; ++i)
{
for (int j = 0; j < textureHeight; ++j)
{
rotate90[i * textureHeight + j] = data[j * textureWidth + i];
}
}
auto tmp = textureWidth;
textureWidth = textureHeight;
textureHeight = tmp;
float* flipped = new float[textureWidth * textureHeight];
float* lastRowSrc = rotate90 + (textureWidth * (textureHeight - 1));
float* firstRowDst = flipped;
for (int i = 0; i < textureHeight; i++)
{
float* forward = firstRowDst;
float* backward = lastRowSrc + textureWidth - 1;
for (int j = 0; j < textureWidth; j++)
{
*forward++ = *backward--;
}
firstRowDst += textureWidth;
lastRowSrc -= textureWidth;
}
GDALDriver* poDriver;
poDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
GDALDataset *poDstDS;
papszOptions[0] = NULL;
papszOptions[1] = NULL;
//std::string elevationName = SetName(originLon, originLat, textureHeight, textureWidth, outputPath, format, ".tif");
std::string path = outputPath;
poDstDS = poDriver->Create(path.c_str(), textureWidth, textureHeight, 1, GDT_Float32, papszOptions);
double adfGeoTransform[6];
adfGeoTransform[0] = west;
adfGeoTransform[1] = (east - west) / textureWidth;
adfGeoTransform[2] = 0;
adfGeoTransform[3] = north;
adfGeoTransform[4] = 0;
adfGeoTransform[5] = ((north - south) / textureHeight) * -1;
OGRSpatialReference oSRS;
char *pszSRS_WKT = NULL;
GDALRasterBand *poBand;
poDstDS->SetGeoTransform(adfGeoTransform);
oSRS.SetWellKnownGeogCS("WGS84");
oSRS.exportToWkt(&pszSRS_WKT);
poDstDS->SetProjection(pszSRS_WKT);
CPLFree(pszSRS_WKT);
poBand = poDstDS->GetRasterBand(1);
poBand->RasterIO(GF_Write, 0, 0, textureWidth, textureHeight,
flipped, textureWidth, textureHeight, GDT_Float32, 4, 0);
GDALClose(elevationDataset);
delete poDstDS;
delete[] data;
delete[] rotate90;
delete[] flipped;
}
void GetElevation(const std::string& geoServerURL, double north, double south, double east, double west, int& textureWidth, int& textureHeight, float*& buffer, double* adfGeoTransform)
{
GDALDataset* elevationDataset;
char** papszDrivers = NULL;
papszDrivers = CSLAddString(papszDrivers, "WCS");
char** papszOptions = NULL;
papszOptions = CSLAddString(papszOptions, "GridCRSOptional");
std::stringstream parameters;
parameters << std::fixed << std::setprecision(15)
<< "SERVICE=WCS&FORMAT=GeoTIFF&BOUNDINGBOX="
<< south
<< "," << west
<< "," << north
<< "," << east
<< ",urn:ogc:def:crs:EPSG::4326&WIDTH="
<< std::to_string(textureWidth)
<< "&HEIGHT="
<< std::to_string(textureHeight);
std::string xml = "";
xml += "<WCS_GDAL>";
xml += " <ServiceURL>" + geoServerURL + "/wcs?SERVICE=WCS</ServiceURL>";
xml += " <Version>1.1.1</Version>";
xml += " <CoverageName>CDB Elevation_Terrain_Primary</CoverageName>";
xml += " <Parameters>" + parameters.str() + "</Parameters>";
xml += " <GridCRSOptional>TRUE</GridCRSOptional>";
xml += " <CoverageDescription>";
xml += " <Identifier>Base:CDB Elevation_Terrain_Primary</Identifier>";
xml += " <Domain>";
xml += " <SpatialDomain>";
xml += " <BoundingBox crs=\"urn:ogc:def:crs:OGC:1.3 : CRS84\" dimensions=\"2\">";
xml += " <LowerCorner>-180.0 -90.0</LowerCorner>";
xml += " <UpperCorner>180.0 90.0</UpperCorner>";
xml += " </BoundingBox>";
xml += " <BoundingBox crs=\"urn:ogc:def:crs:EPSG::4326\" dimensions=\"2\">";
xml += " <LowerCorner>-90.0 -180.0</LowerCorner>";
xml += " <UpperCorner>90.0 180.0</UpperCorner>";
xml += " </BoundingBox>";
xml += " <BoundingBox crs=\":imageCRS\" dimensions=\"2\">";
xml += " <LowerCorner>0 0</LowerCorner>";
xml += " <UpperCorner>356356356 3563456</UpperCorner>";
xml += " </BoundingBox>";
xml += " <GridCRS>";
xml += " <GridBaseCRS>urn:ogc:def:crs:EPSG::4326</GridBaseCRS>";
xml += " <GridType>urn:ogc:def:method:WCS:1.1:2dGridIn2dCrs</GridType>";
xml += " <GridOrigin>-179.82421875 89.91259765625</GridOrigin>";
xml += " <GridOffsets>0.3515625 0.0 0.0 -0.1748046875</GridOffsets>";
xml += " <GridCS>urn:ogc:def:cs:OGC:0.0:Grid2dSquareCS</GridCS>";
xml += " </GridCRS>";
xml += " </SpatialDomain>";
xml += " </Domain>";
xml += " <SupportedCRS>urn:ogc:def:crs:EPSG::4326</SupportedCRS>";
xml += " <SupportedCRS>EPSG:4326</SupportedCRS>";
xml += " <SupportedFormat>image/tiff</SupportedFormat>";
xml += " </CoverageDescription>";
xml += " <FieldName>contents</FieldName>";
xml += " <BandType>Float32</BandType>";
xml += " <PreferredFormat>image/tiff</PreferredFormat>";
xml += "</WCS_GDAL>";
elevationDataset = (GDALDataset*)GDALOpenEx(xml.c_str(), GDAL_OF_READONLY, papszDrivers, papszOptions, NULL);
auto band = elevationDataset->GetRasterBand(1);
textureWidth = 2452;
textureHeight = 2456;
float *data = new float[textureWidth * textureHeight + 1];
band->RasterIO(GF_Read, 0, 0, textureWidth, textureHeight, data, textureWidth, textureHeight, GDALDataType::GDT_Float32, 0, 0);
std::string err = CPLGetLastErrorMsg();
auto result = err.find("Got ");
result += 4;
err.erase(0, result);
result = err.find('x');
std::string firstnum = err.substr(0, result);
err.erase(0, result + 1);
result = err.find(' ');
std::string secondnum = err.substr(0, result);
textureWidth = std::stoi(firstnum);
textureHeight = std::stoi(secondnum);
band->RasterIO(GF_Read, 0, 0, textureWidth, textureHeight, data, textureWidth, textureHeight, GDALDataType::GDT_Float32, 0, 0);
for (int z = 0; z < textureHeight*textureWidth; z++)
{
if (std::isnan(data[z]))
{
data[z] = 0.0f;
}
}
//CreateElevationTiff("testTiff.tif", data, textureWidth, textureHeight);
//CreateElevationDeltaTiff("testTiff_delta1.tif", data, textureWidth, textureHeight, 1);
//CreateElevationDeltaTiff("testTiff_delta10.tif", data, textureWidth, textureHeight, 10);
float* rotate90 = new float[textureWidth * textureHeight];
for (int i = 0; i < textureWidth; ++i)
{
for (int j = 0; j < textureHeight; ++j)
{
rotate90[i * textureHeight + j] = data[j * textureWidth + i];
}
}
auto tmp = textureWidth;
textureWidth = textureHeight;
textureHeight = tmp;
float* flipped = new float[textureWidth * textureHeight];
float* lastRowSrc = rotate90 + (textureWidth * (textureHeight - 1));
float* firstRowDst = flipped;
for (int i = 0; i < textureHeight; i++)
{
float* forward = firstRowDst;
float* backward = lastRowSrc + textureWidth - 1;
for (int j = 0; j < textureWidth; j++)
{
*forward++ = *backward--;
}
firstRowDst += textureWidth;
lastRowSrc -= textureWidth;
}
adfGeoTransform[0] = west;
adfGeoTransform[1] = (east - west) / textureWidth;
adfGeoTransform[2] = 0;
adfGeoTransform[3] = north;
adfGeoTransform[4] = 0;
adfGeoTransform[5] = ((north - south) / textureHeight) * -1;
buffer = flipped;
GDALClose(elevationDataset);
delete[] data;
delete[] rotate90;
}
void GetElevationSquare(const std::string& geoServerURL, double north, double south, double east, double west, int& textureWidth, int& textureHeight, const std::string& outputPath)
{
GDALDataset* elevationDataset;
char** papszDrivers = NULL;
papszDrivers = CSLAddString(papszDrivers, "WCS");
char** papszOptions = NULL;
papszOptions = CSLAddString(papszOptions, "GridCRSOptional");
std::stringstream parameters;
parameters << std::fixed << std::setprecision(15)
<< "SERVICE=WCS&FORMAT=GeoTIFF&BOUNDINGBOX="
<< south
<< "," << west
<< "," << north
<< "," << east
<< ",urn:ogc:def:crs:EPSG::4326&WIDTH="
<< std::to_string(textureWidth)
<< "&HEIGHT="
<< std::to_string(textureHeight);
std::string xml = "";
xml += "<WCS_GDAL>";
xml += " <ServiceURL>" + geoServerURL + "/wcs?SERVICE=WCS</ServiceURL>";
xml += " <Version>1.1.1</Version>";
xml += " <CoverageName>CDB Elevation_Terrain_Primary</CoverageName>";
xml += " <Parameters>" + parameters.str() + "</Parameters>";
xml += " <GridCRSOptional>TRUE</GridCRSOptional>";
xml += " <CoverageDescription>";
xml += " <Identifier>Base:CDB Elevation_Terrain_Primary</Identifier>";
xml += " <Domain>";
xml += " <SpatialDomain>";
xml += " <BoundingBox crs=\"urn:ogc:def:crs:OGC:1.3 : CRS84\" dimensions=\"2\">";
xml += " <LowerCorner>-180.0 -90.0</LowerCorner>";
xml += " <UpperCorner>180.0 90.0</UpperCorner>";
xml += " </BoundingBox>";
xml += " <BoundingBox crs=\"urn:ogc:def:crs:EPSG::4326\" dimensions=\"2\">";
xml += " <LowerCorner>-90.0 -180.0</LowerCorner>";
xml += " <UpperCorner>90.0 180.0</UpperCorner>";
xml += " </BoundingBox>";
xml += " <BoundingBox crs=\":imageCRS\" dimensions=\"2\">";
xml += " <LowerCorner>0 0</LowerCorner>";
xml += " <UpperCorner>1024 1024</UpperCorner>";
xml += " </BoundingBox>";
xml += " <GridCRS>";
xml += " <GridBaseCRS>urn:ogc:def:crs:EPSG::4326</GridBaseCRS>";
xml += " <GridType>urn:ogc:def:method:WCS:1.1:2dGridIn2dCrs</GridType>";
xml += " <GridOrigin>-179.82421875 89.91259765625</GridOrigin>";
xml += " <GridOffsets>0.3515625 0.0 0.0 -0.1748046875</GridOffsets>";
xml += " <GridCS>urn:ogc:def:cs:OGC:0.0:Grid2dSquareCS</GridCS>";
xml += " </GridCRS>";
xml += " </SpatialDomain>";
xml += " </Domain>";
xml += " <SupportedCRS>urn:ogc:def:crs:EPSG::4326</SupportedCRS>";
xml += " <SupportedCRS>EPSG:4326</SupportedCRS>";
xml += " <SupportedFormat>image/tiff</SupportedFormat>";
xml += " </CoverageDescription>";
xml += " <FieldName>contents</FieldName>";
xml += " <BandType>Float32</BandType>";
xml += " <PreferredFormat>image/tiff</PreferredFormat>";
xml += "</WCS_GDAL>";
elevationDataset = (GDALDataset*)GDALOpenEx(xml.c_str(), GDAL_OF_READONLY, papszDrivers, papszOptions, NULL);
auto band = elevationDataset->GetRasterBand(1);
textureWidth = 1024;
textureHeight = 1024;
float *data = new float[textureWidth * textureHeight + 1];
band->RasterIO(GF_Read, 0, 0, textureWidth, textureHeight, data, textureWidth, textureHeight, GDALDataType::GDT_Float32, 0, 0);
for (int z = 0; z < textureHeight*textureWidth; z++)
{
if (std::isnan(data[z]))
{
data[z] = 0.0f;
}
}
float* rotate90 = new float[textureWidth * textureHeight];
for (int i = 0; i < textureWidth; ++i)
{
for (int j = 0; j < textureHeight; ++j)
{
rotate90[i * textureHeight + j] = data[j * textureWidth + i];
}
}
auto tmp = textureWidth;
textureWidth = textureHeight;
textureHeight = tmp;
float* flipped = new float[textureWidth * textureHeight];
float* lastRowSrc = rotate90 + (textureWidth * (textureHeight - 1));
float* firstRowDst = flipped;
for (int i = 0; i < textureHeight; i++)
{
float* forward = firstRowDst;
float* backward = lastRowSrc + textureWidth - 1;
for (int j = 0; j < textureWidth; j++)
{
*forward++ = *backward--;
}
firstRowDst += textureWidth;
lastRowSrc -= textureWidth;
}
GDALDriver* poDriver;
poDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
GDALDataset *poDstDS;
papszOptions[0] = NULL;
papszOptions[1] = NULL;
//std::string elevationName = SetName(originLon, originLat, textureHeight, textureWidth, outputPath, format, ".tif");
std::string path = outputPath;
poDstDS = poDriver->Create(path.c_str(), textureWidth, textureHeight, 1, GDT_Float32, papszOptions);
double adfGeoTransform[6];
adfGeoTransform[0] = west;
adfGeoTransform[1] = (east - west) / textureWidth;
adfGeoTransform[2] = 0;
adfGeoTransform[3] = north;
adfGeoTransform[4] = 0;
adfGeoTransform[5] = ((north - south) / textureHeight) * -1;
OGRSpatialReference oSRS;
char *pszSRS_WKT = NULL;
GDALRasterBand *poBand;
poDstDS->SetGeoTransform(adfGeoTransform);
oSRS.SetWellKnownGeogCS("WGS84");
oSRS.exportToWkt(&pszSRS_WKT);
poDstDS->SetProjection(pszSRS_WKT);
CPLFree(pszSRS_WKT);
poBand = poDstDS->GetRasterBand(1);
poBand->RasterIO(GF_Write, 0, 0, textureWidth, textureHeight,
flipped, textureWidth, textureHeight, GDT_Float32, 4, 0);
GDALClose(elevationDataset);
delete poDstDS;
delete[] data;
delete[] rotate90;
delete[] flipped;
}
void GetImagery(const std::string& geoServerURL, double north, double south, double east, double west, int textureWidth, int textureHeight, const std::string &outputPath)
{
bool gdalError = false;
/// TIFF ///
std::ostringstream xmlTiff;
xmlTiff.precision(10);
xmlTiff << std::fixed
<< "<GDAL_WMS>"
<< "<Service name=\"WMS\">"
<< "<ServerUrl>" + geoServerURL + "/wms?</ServerUrl>"
<< "<Layers>Base%3ACDB%20Imagery_YearRound</Layers>"
<< "<ImageFormat>image/geotiff</ImageFormat>"
<< "</Service>"
<< "<DataWindow>"
<< "<UpperLeftX>"
<< west
<< "</UpperLeftX>"
<< "<UpperLeftY>"
<< north
<< "</UpperLeftY>"
<< "<LowerRightX>"
<< east
<< "</LowerRightX>"
<< "<LowerRightY>"
<< south
<< "</LowerRightY>"
<< "<SizeX>"
<< textureWidth
<< "</SizeX>"
<< "<SizeY>"
<< textureHeight
<< "</SizeY>"
<< "</DataWindow>"
<< "</GDAL_WMS>";
GDALDataset *datasetTiff = (GDALDataset*)GDALOpen(xmlTiff.str().c_str(), GA_ReadOnly);
if (datasetTiff == NULL)
{
std::cout << "Not getting imagery from xmlTiff" << std::endl;
gdalError = true;
}
const char* tiffFileFormat = "GTiff";
GDALDriver* tiffDriver = GetGDALDriverManager()->GetDriverByName(tiffFileFormat);
if (tiffDriver == NULL)
{
std::cout << "GTiff driver failed" << std::endl;
gdalError = true;
}
//std::string tiffName = SetName(originLon, originLat, textureHeight, textureWidth, outputPath, format, ".tif");
std::string tiffOutputFile = outputPath;// +"img/" + tiffName;
GDALDataset* ImageDatasetTiff = tiffDriver->CreateCopy(tiffOutputFile.c_str(), datasetTiff, FALSE, NULL, NULL, NULL);
if (ImageDatasetTiff == NULL)
{
std::cout << "GTiff dataset failed" << std::endl;
gdalError = true;
}
// cleanup GDAL
GDALClose((GDALDatasetH)datasetTiff);
GDALClose((GDALDatasetH)ImageDatasetTiff);
}
void GetImageryJPG(const std::string& geoServerURL, double north, double south, double east, double west, int textureWidth, int textureHeight, const std::string &outputPath)
{
bool gdalError = false;
/// TIFF ///
std::ostringstream xmlTiff;
xmlTiff.precision(10);
xmlTiff << std::fixed
<< "<GDAL_WMS>"
<< "<Service name=\"WMS\">"
<< "<ServerUrl>" + geoServerURL + "/wms?</ServerUrl>"
<< "<Layers>Base%3ACDB%20Imagery_YearRound</Layers>"
<< "<ImageFormat>image/geotiff</ImageFormat>"
<< "</Service>"
<< "<DataWindow>"
<< "<UpperLeftX>"
<< west
<< "</UpperLeftX>"
<< "<UpperLeftY>"
<< north
<< "</UpperLeftY>"
<< "<LowerRightX>"
<< east
<< "</LowerRightX>"
<< "<LowerRightY>"
<< south
<< "</LowerRightY>"
<< "<SizeX>"
<< textureWidth
<< "</SizeX>"
<< "<SizeY>"
<< textureHeight
<< "</SizeY>"
<< "</DataWindow>"
<< "</GDAL_WMS>";
GDALDataset *datasetTiff = (GDALDataset*)GDALOpen(xmlTiff.str().c_str(), GA_ReadOnly);
if (datasetTiff == NULL)
{
std::cout << "Not getting imagery from xmlTiff" << std::endl;
gdalError = true;
}
int len = textureHeight * textureWidth * 3;
u_char *buf = new u_char[len];
for (int i = 0; i < 3; i++)
{
auto band = datasetTiff->GetRasterBand(i + 1);
band->RasterIO(GF_Read, 0, 0, textureWidth, textureHeight, buf + i, textureWidth, textureHeight, GDALDataType::GDT_Byte, 3, 3 * textureWidth);
}
ip::ImageInfo info;
info.width = textureWidth;
info.height = textureHeight;
info.depth = 3;
info.interleaved = true;
info.dataType = ip::ImageInfo::UBYTE;
ip::WriteJPG24(outputPath, info, buf);
GDALClose((GDALDatasetH)datasetTiff);
delete[] buf;
return;
}
void GetElevationParallel(std::vector<TileInfo>* infos, const std::string& geoServerIpAddress)
{
static atomic_int counter;
while (true)
{
int index = counter++;
if (index >= infos->size())
{
return;
}
auto& info = infos->at(index);
ws::GetElevation(geoServerIpAddress, info.extents.north, info.extents.south, info.extents.east, info.extents.west, info.width, info.height, info.elevationFileName);
}
}
inline double GetElev(elev::Elevation_DSM& edsm, double lat, double lon)
{
sfa::Point p;
p.setY(lat);
p.setX(lon);
edsm.Get(&p);
return p.Z();
}
inline float GetElev(const float* buffer, const double* geotransform, int width, double lat, double lon)
{
int px = (lon - geotransform[0]) / geotransform[1] - 0.5f;
int py = (lat - geotransform[3]) / geotransform[5] - 0.5f;
return buffer[width * py + px];
}
int LatLongToZoneNumber(double latitude, double longitude)
{
if ((56.0 <= latitude && latitude <= 64.0) && (3.0 <= longitude && longitude <= 12.0))
{
return 32;
}
if ((72.0 <= latitude && latitude <= 84.0) && (longitude >= 0.0))
{
if (longitude <= 9.0)
{
return 31;
}
else if (longitude <= 21.0)
{
return 33;
}
else if (longitude <= 33.0)
{
return 35;
}
else if (longitude <= 42.0)
{
return 37;
}
}
return (((int)(longitude + 180)) / 6) + 1;
}
double ZoneNumberToCentralLongitude(int zoneNumber)
{
return (zoneNumber - 1) * 6 - 180 + 3;
}
char LatitudeToZoneLetter(double Lat)
{
char LetterDesignator;
if ((84 >= Lat) && (Lat >= 72)) LetterDesignator = 'X';
else if ((72 > Lat) && (Lat >= 64)) LetterDesignator = 'W';
else if ((64 > Lat) && (Lat >= 56)) LetterDesignator = 'V';
else if ((56 > Lat) && (Lat >= 48)) LetterDesignator = 'U';
else if ((48 > Lat) && (Lat >= 40)) LetterDesignator = 'T';
else if ((40 > Lat) && (Lat >= 32)) LetterDesignator = 'S';
else if ((32 > Lat) && (Lat >= 24)) LetterDesignator = 'R';
else if ((24 > Lat) && (Lat >= 16)) LetterDesignator = 'Q';
else if ((16 > Lat) && (Lat >= 8)) LetterDesignator = 'P';
else if ((8 > Lat) && (Lat >= 0)) LetterDesignator = 'N';
else if ((0 > Lat) && (Lat >= -8)) LetterDesignator = 'M';
else if ((-8 > Lat) && (Lat >= -16)) LetterDesignator = 'L';
else if ((-16 > Lat) && (Lat >= -24)) LetterDesignator = 'K';
else if ((-24 > Lat) && (Lat >= -32)) LetterDesignator = 'J';
else if ((-32 > Lat) && (Lat >= -40)) LetterDesignator = 'H';
else if ((-40 > Lat) && (Lat >= -48)) LetterDesignator = 'G';
else if ((-48 > Lat) && (Lat >= -56)) LetterDesignator = 'F';
else if ((-56 > Lat) && (Lat >= -64)) LetterDesignator = 'E';
else if ((-64 > Lat) && (Lat >= -72)) LetterDesignator = 'D';
else if ((-72 > Lat) && (Lat >= -80)) LetterDesignator = 'C';
else LetterDesignator = 'Z'; //Latitude is outside the UTM limits
return LetterDesignator;
}
std::string FromLatLon(double latitude, double longitude, double& easting, double& northing)
{
double E, E2, E3, E_P2;
double SQRT_E, _E, _E3, _E4;
double M1, M2, M3, M4;
double P2, P3, P4;
double R;
double K0 = 0.9996;
E = 0.00669438;
E2 = E * E;
E3 = E2 * E;
E_P2 = E / (1.0 - E);
SQRT_E = sqrt(1.0 - E);
_E = (1.0 - SQRT_E) / (1.0 + SQRT_E);
_E3 = _E * _E * _E;
_E4 = _E3 * _E;
M1 = (1.0 - E / 4.0 - 3.0 * E2 / 64.0 - 5.0 * E3 / 256.0);
M2 = (3.0 * E / 8.0 + 3.0 * E2 / 32.0 + 45.0 * E3 / 1024.0);
M3 = (15.0 * E2 / 256.0 + 45.0 * E3 / 1024.0);
M4 = (35.0 * E3 / 3072.0);
P2 = (3.0 * _E / 2.0 - 27.0 * _E3 / 32.0);
P3 = (21.0 * _E3 / 16.0 - 55.0 * _E4 / 32.0);
P4 = (151.0 * _E3 / 96.0);
R = 6378137.0;
double lat_rad = DEG_TO_RAD * latitude;
double lat_sin = sin(lat_rad);
double lat_cos = cos(lat_rad);
double lat_tan = lat_sin / lat_cos;
double lat_tan2 = lat_tan * lat_tan;
double lat_tan4 = lat_tan2 * lat_tan2;
double lon_rad = DEG_TO_RAD * longitude;
int zone_number = LatLongToZoneNumber(latitude, longitude);
double central_lon = ZoneNumberToCentralLongitude(zone_number);
double central_lon_rad = DEG_TO_RAD * central_lon;
char zone_letter = LatitudeToZoneLetter(latitude);
double n = R / sqrt(1 - E * pow(lat_sin, 2));
double c = E_P2 * pow(lat_cos, 2);
double a = lat_cos * (lon_rad - central_lon_rad);
double a2 = a * a;
double a3 = a2 * a;
double a4 = a3 * a;
double a5 = a4 * a;
double a6 = a5 * a;
double m = R * (M1 * lat_rad -
M2 * sin(2 * lat_rad) +
M3 * sin(4 * lat_rad) -
M4 * sin(6 * lat_rad));
easting = K0 * n * (a +
a3 / 6 * (1 - lat_tan2 + c) +
a5 / 120 * (5 - 18 * lat_tan2 + lat_tan4 + 72 * c - 58 * E_P2)) + 500000;
northing = K0 * (m + n * lat_tan * (a2 / 2 +
a4 / 24 * (5 - lat_tan2 + 9 * c + 4 * pow(c, 2)) +
a6 / 720 * (61 - 58 * lat_tan2 + lat_tan4 + 600 * c - 330 * E_P2)));
if (latitude < 0)
{
northing += 10000000;
}
char hemisphere;
if (latitude >= 0)
{
hemisphere = 'N';
}
else
{
hemisphere = 'S';
}
return to_string(zone_number) + hemisphere;
}
std::string GetWellKnownTextUTM(double originLat, double originLon)
{
double easting, northing;
auto utm_zone = FromLatLon(originLat, originLon, easting, northing);
bool zone_north = utm_zone[utm_zone.size() - 1] == 'N';
int zone_id = atoi(utm_zone.substr(0, utm_zone.size() - 1).c_str());
if (zone_id <= 0)
throw std::runtime_error("invalid zone");
OGRSpatialReference utm_sr;
std::string name = "WGS 84 / UTM zone " + utm_zone;
utm_sr.SetProjCS(name.c_str());
utm_sr.SetWellKnownGeogCS("WGS84");
utm_sr.SetUTM(zone_id, zone_north);
char *wktp;
utm_sr.exportToWkt(&wktp);
return wktp;
}
void transformSceneFromFlatEarthToUTM(scenegraph::Scene* scene, double originLat, double originLon)
{
double easting, northing;
auto utm_zone = FromLatLon(originLat, originLon, easting, northing);
bool zone_north = utm_zone[utm_zone.size() - 1] == 'N';
int zone_id = atoi(utm_zone.substr(0, utm_zone.size() - 1).c_str());
if (zone_id <= 0)
throw std::runtime_error("invalid zone");
cts::CS_CoordinateSystemFactory coordinateSystemFactory;
cts::CT_MathTransformFactory mathTransformFactory;
cts::CS_CoordinateSystem* wgs84 = coordinateSystemFactory.createFromWKT("WGS84");
cts::WGS84FromFlatEarthMathTransform* fromFlatEarth = new cts::WGS84FromFlatEarthMathTransform(originLat, originLon);
OGRSpatialReference utm_sr;
utm_sr.SetWellKnownGeogCS("WGS84");
utm_sr.SetUTM(zone_id, zone_north);
char *wktp;
utm_sr.exportToWkt(&wktp);
std::string wkt(wktp);
cts::CS_CoordinateSystem *utm = coordinateSystemFactory.createFromWKT(wkt);
// transform from flat earth to geographic
scenegraph::CoordinateTransformVisitor transformVisitor1(fromFlatEarth);
transformVisitor1.transform(scene);
// transform from geographic to UTM
cts::CT_MathTransform *mt = mathTransformFactory.createFromOGR(wgs84, utm);
scenegraph::CoordinateTransformVisitor transformVisitor2(mt);
transformVisitor2.transform(scene);
// shift scene back:
sfa::Matrix transform;
transform.PushTranslate(sfa::Point(-easting, -northing));
scenegraph::TransformVisitor transformVisitor3(transform);
auto translatedScene = transformVisitor3.transform(scene);
delete mt;
delete fromFlatEarth;
delete utm;
}
void GDAL_Parallel(double north, double south, double west, double east, const std::string& geoServerIPAddress, const std::string& outputPath, const std::string& outputTmpPath, const std::string& outputFormat, scenegraph::Scene* masterScene, std::mutex* masterSceneMutex)
{
const int MAX_TILE_SIZE_METERS = 256;
const int IMAGE_WIDTH = 1024;
cts::FlatEarthProjection flatEarth;
flatEarth.setOrigin(south, west);
GsBuildings buildings;
std::string dataPath = ccl::joinPaths(outputTmpPath, "data");
buildings.ProcessBuildingData(ccl::joinPaths(dataPath, "building_models.xml"));
double width = flatEarth.convertGeoToLocalX(east);
double height = flatEarth.convertGeoToLocalY(north);
int rows = ceil(height / MAX_TILE_SIZE_METERS);
int cols = ceil(width / MAX_TILE_SIZE_METERS);
int newWidth = MAX_TILE_SIZE_METERS * cols;
int newHeight = MAX_TILE_SIZE_METERS * rows;
east = flatEarth.convertLocalToGeoLon(newWidth);
north = flatEarth.convertLocalToGeoLat(newHeight);
double zeroX = 0, zeroY = 0, oneX = 1, oneY = 1;
double zeroLon, zeroLat, oneLon, oneLat;
zeroLon = flatEarth.convertLocalToGeoLon(zeroX);
zeroLat = flatEarth.convertLocalToGeoLat(zeroY);
oneLon = flatEarth.convertLocalToGeoLon(oneX);
oneLat = flatEarth.convertLocalToGeoLat(oneY);
double deltaLatPerMeter = oneLat - zeroLat;
double deltaLonPerMeter = oneLon - zeroLon;
static atomic_int counter;
while (true)
{
int index = counter++;
if (index >= rows * cols)
{
return;
}
std::string status = "exporting tile " + to_string(index + 1) + " of " + to_string(rows*cols) + "\n";
cout << status;
int row = index / cols;
int col = index % cols;
int localSouth = row * MAX_TILE_SIZE_METERS;
int localNorth = localSouth + MAX_TILE_SIZE_METERS;
int localWest = col * MAX_TILE_SIZE_METERS;
int localEast = localWest + MAX_TILE_SIZE_METERS;
auto geoSouth = flatEarth.convertLocalToGeoLat(localSouth);
auto geoNorth = flatEarth.convertLocalToGeoLat(localNorth);
auto geoEast = flatEarth.convertLocalToGeoLon(localEast);
auto geoWest = flatEarth.convertLocalToGeoLon(localWest);
int nXsize;
int nYsize;
double geotransform[6];
float* buffer;
ws::GetElevation(geoServerIPAddress, geoNorth + deltaLatPerMeter, geoSouth - deltaLatPerMeter, geoEast + deltaLonPerMeter, geoWest - deltaLonPerMeter, nXsize, nYsize, buffer, geotransform);
ctl::PointList gamingArea;
ctl::Point southwest(localWest, localSouth, GetElev(buffer, geotransform, nXsize, geoSouth, geoWest));
ctl::Point southeast(localEast, localSouth, GetElev(buffer, geotransform, nXsize, geoSouth, geoEast));
ctl::Point northeast(localEast, localNorth, GetElev(buffer, geotransform, nXsize, geoNorth, geoEast));
ctl::Point northwest(localWest, localNorth, GetElev(buffer, geotransform, nXsize, geoNorth, geoWest));
std::string imageName = "tile_" + to_string(row) + "x" + to_string(col) + ".jpg";
ws::GetImageryJPG(geoServerIPAddress, geoNorth, geoSouth, geoEast, geoWest, IMAGE_WIDTH, IMAGE_WIDTH, outputPath + imageName);
//scenegraph::CreateMetaForObj(outputPath + imageName);
gamingArea.push_back(southwest);
gamingArea.push_back(southeast);
gamingArea.push_back(northeast);
gamingArea.push_back(northwest);
sfa::LineString boundaryLineString;
// left boundary
double lon = geoWest;
double lat = geoNorth;
double localPostX = localWest;
double localPostY = localNorth;
for (int i = 0; i <= MAX_TILE_SIZE_METERS; i++, localPostY -= 1, lat -= deltaLatPerMeter)
{
boundaryLineString.addPoint(sfa::Point(localPostX, localPostY, GetElev(buffer, geotransform, nXsize, lat, lon)));
}
// right boundary
lon = geoEast;
lat = geoNorth;
localPostX = localEast;
localPostY = localNorth;
for (int i = 0; i <= MAX_TILE_SIZE_METERS; i++, localPostY -= 1, lat -= deltaLatPerMeter)
{
boundaryLineString.addPoint(sfa::Point(localPostX, localPostY, GetElev(buffer, geotransform, nXsize, lat, lon)));
}
// bottom boundary
lat = geoSouth;
lon = geoWest;
localPostY = localSouth;
localPostX = localWest;
for (int i = 0; i <= MAX_TILE_SIZE_METERS; i++, localPostX += 1, lon += deltaLonPerMeter)
{
boundaryLineString.addPoint(sfa::Point(localPostX, localPostY, GetElev(buffer, geotransform, nXsize, lat, lon)));
}
// top boundary
lat = geoNorth;
lon = geoWest;
localPostY = localNorth;
localPostX = localWest;
for (int i = 0; i <= MAX_TILE_SIZE_METERS; i++, localPostX += 1, lon += deltaLonPerMeter)
{
boundaryLineString.addPoint(sfa::Point(localPostX, localPostY, GetElev(buffer, geotransform, nXsize, lat, lon)));
}
boundaryLineString.removeColinearPoints(0, 0.5);
ctl::PointList boundaryPoints;
for (int i = 0, c = boundaryLineString.getNumPoints(); i < c; ++i)
{
sfa::Point *p = boundaryLineString.getPointN(i);
boundaryPoints.push_back(ctl::Point(p->X(), p->Y(), p->Z()));
}
ctl::PointList workingPoints;
localPostY = localSouth;
lat = geoSouth;
for (int i = 0; i <= MAX_TILE_SIZE_METERS; i++, localPostY += 1, lat += deltaLatPerMeter)
{
localPostX = localWest;
lon = geoWest;
for (int j = 0; j <= MAX_TILE_SIZE_METERS; j++, localPostX += 1, lon += deltaLonPerMeter)
{
workingPoints.push_back(ctl::Point(localPostX, localPostY, GetElev(buffer, geotransform, nXsize, lat, lon)));
}
}
int delaunayResizeIncrement = (MAX_TILE_SIZE_METERS * MAX_TILE_SIZE_METERS) / 8;
ctl::DelaunayTriangulation *dt = new ctl::DelaunayTriangulation(gamingArea, delaunayResizeIncrement);
std::random_shuffle(workingPoints.begin(), workingPoints.end());
std::random_shuffle(boundaryPoints.begin(), boundaryPoints.end());
{
//Alternate inserting boundary and working points to avoid worst case performance of DelaunayTriangulation
size_t i = 0;
size_t j = 0;
while (i < boundaryPoints.size() || j < workingPoints.size())
{
if (i < boundaryPoints.size())
dt->InsertConstrainedPoint(boundaryPoints[i++]);
if (j < workingPoints.size())
dt->InsertWorkingPoint(workingPoints[j++]);
}
}
dt->Simplify(1, float(0.1));
ctl::TIN *tin = new ctl::TIN(dt);
scenegraph::Scene *scene = new scenegraph::Scene;
scene->faces.reserve(tin->triangles.size() / 3);
for (size_t i = 0, c = tin->triangles.size() / 3; i < c; ++i)
{
scenegraph::Face face;
scenegraph::MappedTexture mt;
mt.SetTextureName(imageName);
for (int z = 0; z < 3; z++)
{
auto index = tin->triangles[i * 3 + z];
auto& p = tin->verts[index];
auto& n = tin->normals[index];
float u = (p.x - localWest) / MAX_TILE_SIZE_METERS;
float v = (p.y - localSouth) / MAX_TILE_SIZE_METERS;
mt.uvs.push_back(sfa::Point(u, v));
face.verts.push_back(sfa::Point(p.x, p.y, p.z));
face.vertexNormals.push_back(sfa::Point(n.x, n.y, n.z));
}
face.textures.push_back(mt);
scene->faces.push_back(face);
}
for (int z = 0; z < buildings.Count(); z++)
{
FeatureInfo& building = buildings.GetBuilding(z);
if (!(building.lat < geoSouth || building.lat > geoNorth || building.lon < geoWest || building.lon > geoEast))
{
auto buildingScene = new scenegraph::Scene;
building.elev = GetElev(buffer, geotransform, nXsize, building.lat, building.lon);
ParseJSON(building.modelpath, outputPath, *buildingScene);
sfa::Matrix m;
auto radians = (building.AO1 * M_PI) / 180;
m.PushRotate(sfa::Point(0, 0, 1), -radians);
m.PushScale(sfa::Point(1, 1, 1));
auto localX = flatEarth.convertGeoToLocalX(building.lon);
auto localY = flatEarth.convertGeoToLocalY(building.lat);
m.PushTranslate(sfa::Point(localX, localY, building.elev));
buildingScene->matrix = m;
scene->addChild(buildingScene);
}
}
scenegraph::FlattenVisitor flatten;
auto flattenedScene = flatten.flatten(scene);
transformSceneFromFlatEarthToUTM(flattenedScene, south, west);
masterSceneMutex->lock();
masterScene->addChild(flattenedScene);
masterSceneMutex->unlock();
//scenegraph::buildObjFromScene(outputDir + "/" + tileName + outputFormat, 0, 0, 0, 0, flattenedScene);
//fbx_mutex.lock();
//scenegraph::buildFbxWithFeatures(outputPath + tileName + ".fbx", scene, buildings, &terrainGenerator, geoNorth, geoSouth, geoEast, geoWest, imageName, true);
//fbx_mutex.unlock();
delete scene;
//delete flattenedScene;
delete[] buffer;
delete tin;
delete dt;
}
}
void generateFixedGridSofprep(double north, double south, double west, double east, const std::string& geoServerIPAddress, const std::string& outputTmpPath, const std::string& outputPath, const std::string& outputFormat)
{
int nthreads = std::thread::hardware_concurrency();
std::vector<std::thread> threads(nthreads);
scenegraph::Scene masterScene;
std::mutex m;
for (int t = 0; t < nthreads; t++)
{
threads[t] = std::thread(GDAL_Parallel, north, south, west, east, geoServerIPAddress, outputPath, outputTmpPath, outputFormat, &masterScene, &m);
}
std::for_each(threads.begin(), threads.end(), [](std::thread& x) {x.join(); });
scenegraph::FlattenVisitor flatten;
auto flattenedScene = flatten.flatten(&masterScene);
scenegraph::buildObjFromScene(outputPath + "/" + "simplified_3d_mesh" + outputFormat, 0, 0, 0, 0, flattenedScene);
double easting, northing;
FromLatLon(south, west, easting, northing);
std::ofstream offsetFile;
offsetFile.open(outputPath + "offset.xyz", std::ofstream::out);
offsetFile << std::setprecision(10);
offsetFile << easting << " " << northing << " 0";
offsetFile.close();
std::ofstream wktFile;
wktFile.open(outputPath + "wkt.prj", std::ofstream::out);
auto wkt = GetWellKnownTextUTM(south, west);
wktFile << wkt;
wktFile.close();
}
void generateCesiumLods(double north, double south, double west, double east,
const std::string& geoServerURL, const std::string& outputTmpPath, const std::string& outputPath,
cognitics::TerrainGenerator& terrainGenerator, int lodDepth)
{
std::string outputFormat = ".b3dm";
double deltaX = east - west;
double deltaY = north - south;
double delta = min(deltaX, deltaY) / 2;
double centerLat = (north - south) / 2 + south;
double centerLon = (east - west) / 2 + west;
east = centerLon + delta;
west = centerLon - delta;
north = centerLat + delta;
south = centerLat - delta;
centerLat = (north - south) / 2 + south;
centerLon = (east - west) / 2 + west;
std::vector<TileInfo> infos;
TileInfo info;
info.extents.east = east;
info.extents.north = north;
info.extents.south = south;
info.extents.west = west;
info.quadKey = std::to_string(0);
GenerateLODBounds(infos, info, lodDepth);
GenerateFileNames(infos, outputTmpPath);
ComputeCenterPosition(infos, centerLat, centerLon);
int nthreads = std::thread::hardware_concurrency();
std::vector<std::thread> threads(nthreads);
int span = infos.size() / nthreads;
int index = 0;
for (int t = 0; t < nthreads; t++)
{
int begin = index;
int end = index + span;
if (t == nthreads - 1)
{
end = infos.size() - 1;
}
threads[t] = std::thread(GetData, geoServerURL, begin, end, &infos);
index = end + 1;
}
std::for_each(threads.begin(), threads.end(), [](std::thread& x) {x.join(); });
cout << "Finished getting LOD data." << endl;
elev::DataSourceManager dsm(1000000);
for (auto& info : infos)
{
dsm.AddFile_Raster_GDAL(info.elevationFileName);
}
elev::Elevation_DSM edsm(&dsm, elev::elevation_strategy::ELEVATION_BILINEAR);
for (auto& info : infos)
{
terrainGenerator.generateFixedGrid(info.imageFileName, outputPath,
info.quadKey, outputFormat, edsm,
info.extents.north, info.extents.south,
info.extents.east, info.extents.west);
}
#ifdef CAE_MESH
terrainGenerator.createFeatures(edsm);
#endif
//WriteLODfile(infos, outputPath + "/lodFile.txt", lodDepth);
terrainGenerator.setBounds(north, south, east, west);
terrainGenerator.CreateMasterFile();
ccl::FileInfo fi(outputPath);
bool removeTextures = true;
if (removeTextures)
{
if(ccl::directoryExists(fi.getDirName()))
{
std::cout << "generate Cesium Lods: Removing image files from " << outputPath << std::endl;
auto files = ccl::FileInfo::getAllFiles(fi.getDirName(),"*.*");
for(auto&& file : files)
{
if(ccl::FileInfo::fileExists(fi.getFileName()))
{
auto ext = fi.getSuffix();
if (ext == "jpg"
|| ext == "jpeg"
|| ext == "png")
{
ccl::deleteFile(fi.getFileName());
}
}
}
}
}
auto tmpDir = ccl::joinPaths(outputPath,"/tmp");
if(ccl::directoryExists(tmpDir))
{
auto files = ccl::FileInfo::getAllFiles(fi.getDirName(),"*.*");
for(auto&& file : files)
{
std::cout << "generate Cesium Lods: Removing tmp directory " << tmpDir << std::endl;
ccl::deleteFile(file.getFileName());
}
}
}
void ParseJSON(const std::string & filename, const std::string & outputPath, scenegraph::Scene & scene)
{
ccl::FileInfo fi(filename);
FILE *fp = fopen(filename.c_str(), "r");
char* source;
if (fp != nullptr)
{
if (fseek(fp, 0L, SEEK_END) == 0)
{
long bufSize = ftell(fp);
if (bufSize == -1)
{
;
}
source = new char[bufSize + 1];
if (fseek(fp, 0L, SEEK_SET) != 0)
{
;
}
size_t newLength = fread(source, sizeof(char), bufSize, fp);
if (ferror(fp) != 0)
{
std::cout << "error" << std::endl;
}
else
{
source[newLength++] = '\0';
}
rapidjson::Document document;
document.Parse(source);
// Vertices
auto vertices = document["vertices"].GetArray();
std::vector<sfa::Point> verts;
for (rapidjson::Value::ConstValueIterator itr = vertices.Begin(); itr != vertices.End(); ++itr)
{
double x = itr->GetDouble();
++itr;
double y = itr->GetDouble();
++itr;
double z = itr->GetDouble();
sfa::Point point(x, y, z);
verts.push_back(point);
}
// Normals
auto normals = document["normals"].GetArray();
std::vector<sfa::Point> normal;
for (rapidjson::Value::ConstValueIterator itr = normals.Begin(); itr != normals.End(); ++itr)
{
double x = itr->GetDouble();
++itr;
double y = itr->GetDouble();
++itr;
double z = itr->GetDouble();
sfa::Point point(x, y, z);
normal.push_back(point);
}
// UVS
auto uvs = document["uvs"].GetArray();
auto uv = uvs[0].GetArray(); // update
std::vector<sfa::Point> uvsPoint;
for (rapidjson::Value::ConstValueIterator itr = uv.Begin(); itr != uv.End(); ++itr)
{
double x = itr->GetDouble();
++itr;
double y = itr->GetDouble();
//if (IsGltfTypeOutput())
//{
// //gltf uses upper left origin for uvs
// //https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#images
// y = 1.0 - y;
//}
sfa::Point point(x, y);
uvsPoint.push_back(point);
}
// Materials
auto materials = document["materials"].GetArray();
std::vector<scenegraph::Material> materialList;
for (rapidjson::Value::ConstValueIterator itr = materials.Begin(); itr != materials.End(); ++itr)
{
scenegraph::Material mat;
auto ambient = (*itr)["colorAmbient"].GetArray(); // Ka
mat.ambient.r = ambient[0].GetFloat();
mat.ambient.g = ambient[1].GetFloat();
mat.ambient.b = ambient[2].GetFloat();
auto diffuse = (*itr)["colorDiffuse"].GetArray(); // Kd
mat.diffuse.r = diffuse[0].GetFloat();
mat.diffuse.g = diffuse[1].GetFloat();
mat.diffuse.b = diffuse[2].GetFloat();
auto specular = (*itr)["colorSpecular"].GetArray(); // Ks
mat.specular.r = specular[0].GetFloat();
mat.specular.g = specular[1].GetFloat();
mat.specular.b = specular[2].GetFloat();
mat.illumination = (*itr)["illumination"].GetInt(); // illum
std::string mapDiffuse = (*itr)["mapDiffuse"].GetString(); // material name
//std::experimental::filesystem::path path = mapDiffuse;
//path.replace_extension(""); //why was extension being removed?
auto filenameOfModel = mapDiffuse;
mat.mapDiffuse = filenameOfModel;
auto srcPath = ccl::joinPaths(fi.getDirName(), mapDiffuse);
if (!ccl::fileExists(srcPath))
{
return;
}
auto destPath = ccl::joinPaths(outputPath, mapDiffuse);
if (!ccl::fileExists(destPath))
{
if (!ccl::copyFile(srcPath, destPath))
{
std::cout << "copy failed" << std::endl;
}
}
mat.transparency = (*itr)["transparency"].GetDouble();
mat.transparent = (*itr)["transparent"].GetBool();
materialList.push_back(mat);
}
// Faces
auto faces = document["faces"].GetArray();
std::vector<scenegraph::Face> face;
int separator;
int vertex_index1;
int vertex_index2;
int vertex_index3;
int material_index;
int vertex_uv1;
int vertex_uv2;
int vertex_uv3;
int vertex_normal1;
int vertex_normal2;
int vertex_normal3;
for (rapidjson::Value::ConstValueIterator itr = faces.Begin(); itr != faces.End(); ++itr)
{
separator = itr->GetInt();
++itr;
vertex_index1 = itr->GetInt();
++itr;
vertex_index2 = itr->GetInt();
++itr;
vertex_index3 = itr->GetInt();
++itr;
material_index = itr->GetInt();
++itr;
vertex_uv1 = itr->GetInt();
++itr;
vertex_uv2 = itr->GetInt();
++itr;
vertex_uv3 = itr->GetInt();
++itr;
vertex_normal1 = itr->GetInt();
++itr;
vertex_normal2 = itr->GetInt();
++itr;
vertex_normal3 = itr->GetInt();
scenegraph::Face f;
scenegraph::MappedTexture mt;
mt.SetTextureName(materialList.at(material_index).mapDiffuse);
mt.uvs.push_back(uvsPoint[vertex_uv1]);
mt.uvs.push_back(uvsPoint[vertex_uv2]);
mt.uvs.push_back(uvsPoint[vertex_uv3]);
f.textures.push_back(mt);
f.addVert(verts[vertex_index1]);
f.addVert(verts[vertex_index2]);
f.addVert(verts[vertex_index3]);
f.setNormalN(0, normal[vertex_normal1]);
f.setNormalN(1, normal[vertex_normal2]);
f.setNormalN(2, normal[vertex_normal3]);
face.push_back(f);
}
scene.faces = face;
scene.faceMaterials = materialList;
int beg = filename.find_last_of("/");
int end = filename.find_first_of(".");
std::string name = filename.substr(beg + 1, end - beg - 1);
//scenegraph::buildOpenFlightFromScene(outputPath+"/"+name+".flt", &scene, 1640);
}
fclose(fp);
}
//free(fp);
}
void generateFixedGridWeb(double north, double south, double west, double east, std::string format, const std::string& geoServerURL, const std::string& outputTmpPath, const std::string& outputPath, const std::string& featurePath, const std::string& outputFormat, int textureWidth, int textureHeight, cognitics::TerrainGenerator& terrainGenerator)
{
std::string tileName = "webTest";
std::string tileInfoName = ccl::joinPaths(outputPath, "tileInfo.txt");
std::ofstream tileInfo(tileInfoName);
tileInfo << tileName << "\n";
const int MAX_TILE_SIZE_METERS = 500;
cts::FlatEarthProjection flatEarth;
flatEarth.setOrigin(south, west);
double width = flatEarth.convertGeoToLocalX(east);
double height = flatEarth.convertGeoToLocalY(north);
int rows = ceil(height / MAX_TILE_SIZE_METERS);
int cols = ceil(width / MAX_TILE_SIZE_METERS);
int newWidth = MAX_TILE_SIZE_METERS * cols;
int newHeight = MAX_TILE_SIZE_METERS * rows;
east = flatEarth.convertLocalToGeoLon(newWidth);
north = flatEarth.convertLocalToGeoLat(newHeight);
tileInfo << rows << " " << cols << "\n";
std::vector<std::string> elevationFileNames;
std::vector<int> heights;
std::vector<int> widths;
int imageHeight = 0;
int imageWidth = 0;
std::string filename;
OGRSpatialReference oSRS;
oSRS.SetWellKnownGeogCS("WGS84");
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
double bottomLeftX, bottomLeftY, topRightX, topRightY;
bottomLeftX = MAX_TILE_SIZE_METERS * col;
bottomLeftY = MAX_TILE_SIZE_METERS * row;
topRightX = bottomLeftX + MAX_TILE_SIZE_METERS;
topRightY = bottomLeftY + MAX_TILE_SIZE_METERS;
double tileNorth, tileWest, tileEast, tileSouth;
tileSouth = flatEarth.convertLocalToGeoLat(bottomLeftY);
tileNorth = flatEarth.convertLocalToGeoLat(topRightY);
tileEast = flatEarth.convertLocalToGeoLon(topRightX);
tileWest = flatEarth.convertLocalToGeoLon(bottomLeftX);
filename = ws::GetName(tileEast, tileNorth, textureHeight, textureWidth, outputFormat, ".tif");
auto elevationFilename = outputTmpPath + "/" + filename;
ws::GetElevation(geoServerURL, tileNorth, tileSouth, tileEast, tileWest, textureWidth, textureHeight, elevationFilename);
widths.push_back(textureWidth);
heights.push_back(textureHeight);
if (col == 0 && row == 0)
{
imageHeight = textureHeight * rows;
imageWidth = textureWidth * cols;
}
elevationFileNames.push_back(elevationFilename);
}
}
// request a giant wms request...
ws::GetImagery(geoServerURL, north, south, east, west, imageWidth, imageHeight, outputTmpPath + "/img/" + filename);
terrainGenerator.addImageryPath(outputTmpPath + "/img");
int counter = 0;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
int height = heights[counter];
int width = widths[counter];
std::string& elevFile = elevationFileNames[counter];
counter++;
std::stringstream ss;
ss << tileName << "_" << row << "_" << col << format;
filename = ccl::joinPaths(outputPath, ss.str());
terrainGenerator.generateFixedGrid(elevFile, filename, featurePath, 0, height * .5, width * .5, 0);
}
}
}
void ConvertGDALElevationToScene(double* adfGeoTransform, int rasterWidth, int rasterHeight, GDALRasterBand* poBand, scenegraph::Scene* masterScene, std::mutex* masterSceneMutex, std::mutex* gdalMutex)
{
double west = adfGeoTransform[0];
double north = adfGeoTransform[3];
double east = west + adfGeoTransform[1] * rasterWidth;
double south = north + adfGeoTransform[5] * rasterHeight;
cts::FlatEarthProjection flatEarth;
flatEarth.setOrigin(south, west);
double deltaMeterPerPixelY = flatEarth.convertGeoToLocalY(south - adfGeoTransform[5]);
double deltaMeterPerPixelX = flatEarth.convertGeoToLocalX(west + adfGeoTransform[1]);
const int TILE_SIZE = 256;
int subdivideHeight = ceil((float)rasterHeight / TILE_SIZE);
int subdivideWidth = ceil((float)rasterWidth / TILE_SIZE);
int totalWidth = flatEarth.convertGeoToLocalX(east) + deltaMeterPerPixelX;
int totalHeight = flatEarth.convertGeoToLocalY(north) + deltaMeterPerPixelY;
static atomic_int counter;
while (true)
{
int index = counter++;
if (index >= subdivideHeight * subdivideHeight)
{
return;
}
int i = index / subdivideWidth;
int j = index % subdivideWidth;
int offsetX = j * TILE_SIZE;
int offsetY = i * TILE_SIZE;
int tileWidth = std::min(TILE_SIZE + 1, rasterWidth - offsetX);
int tileHeight = std::min(TILE_SIZE + 1, rasterHeight - offsetY);
float* buffer = new float[tileWidth * tileHeight];
gdalMutex->lock();
poBand->RasterIO(GF_Read, offsetX, offsetY, tileWidth, tileHeight, buffer, tileWidth, tileHeight, GDT_Float32, 0, 0);
gdalMutex->unlock();
int northWestIndex = 0;
int northEastIndex = tileWidth - 1;
int southWestIndex = tileWidth * (tileHeight - 1);
int southEastIndex = southWestIndex + tileWidth - 1;
auto tileWest = west + offsetX * adfGeoTransform[1];
auto tileEast = tileWest + tileWidth * adfGeoTransform[1];
auto tileNorth = north + offsetY * adfGeoTransform[5];
auto tileSouth = tileNorth + tileHeight * adfGeoTransform[5];
double localWest = flatEarth.convertGeoToLocalX(tileWest + adfGeoTransform[1] / 2);
double localEast = flatEarth.convertGeoToLocalX(tileEast);
double localNorth = flatEarth.convertGeoToLocalY(tileNorth + adfGeoTransform[5] / 2);
double localSouth = flatEarth.convertGeoToLocalY(tileSouth);
ctl::PointList gamingArea;
ctl::Point southwest(localWest, localSouth, buffer[southWestIndex]);
ctl::Point southeast(localEast, localSouth, buffer[southEastIndex]);
ctl::Point northeast(localEast, localNorth, buffer[northEastIndex]);
ctl::Point northwest(localWest, localNorth, buffer[northWestIndex]);
gamingArea.push_back(southwest);
gamingArea.push_back(southeast);
gamingArea.push_back(northeast);
gamingArea.push_back(northwest);
sfa::LineString boundaryLineString;
// left boundary
double x = localWest;
double y = localNorth;
for (int i = 0; i < tileHeight; i++, y -= deltaMeterPerPixelY)
{
boundaryLineString.addPoint(sfa::Point(x, y, buffer[northWestIndex + i * tileWidth]));
}
// right boundary
x = localEast;
y = localNorth;
for (int i = 0; i < tileHeight; i++, y -= deltaMeterPerPixelY)
{
boundaryLineString.addPoint(sfa::Point(x, y, buffer[northEastIndex + i * tileWidth]));
}
// bottom boundary
x = localWest;
y = localSouth;
for (int i = 0; i < tileWidth; i++, x += deltaMeterPerPixelX)
{
boundaryLineString.addPoint(sfa::Point(x, y, buffer[southWestIndex + i]));
}
// top boundary
x = localWest;
y = localNorth;
for (int i = 0; i < tileWidth; i++, x += deltaMeterPerPixelX)
{
boundaryLineString.addPoint(sfa::Point(x, y, buffer[northWestIndex + i]));
}
ctl::PointList boundaryPoints;
for (int i = 0, c = boundaryLineString.getNumPoints(); i < c; ++i)
{
sfa::Point *p = boundaryLineString.getPointN(i);
boundaryPoints.push_back(ctl::Point(p->X(), p->Y(), p->Z()));
}
ctl::PointList workingPoints;
y = localNorth;
auto ptr = buffer;
for (int i = 0; i < tileHeight; i++, y -= deltaMeterPerPixelY)
{
x = localWest;
for (int j = 0; j < tileWidth; j++, x += deltaMeterPerPixelX)
{
workingPoints.push_back(ctl::Point(x, y, *ptr++));
}
}
int delaunayResizeIncrement = (tileWidth * tileHeight) / 8;
ctl::DelaunayTriangulation *dt = new ctl::DelaunayTriangulation(gamingArea, delaunayResizeIncrement);
std::random_shuffle(workingPoints.begin(), workingPoints.end());
std::random_shuffle(boundaryPoints.begin(), boundaryPoints.end());
{
//Alternate inserting boundary and working points to avoid worst case performance of DelaunayTriangulation
size_t i = 0;
size_t j = 0;
while (i < boundaryPoints.size() || j < workingPoints.size())
{
if (i < boundaryPoints.size())
dt->InsertConstrainedPoint(boundaryPoints[i++]);
if (j < workingPoints.size())
dt->InsertWorkingPoint(workingPoints[j++]);
}
}
dt->Simplify(1, float(0.01));
ctl::TIN *tin = new ctl::TIN(dt);
scenegraph::Scene *scene = new scenegraph::Scene;
std::string imageName = "texture.jpg";
scene->faces.reserve(tin->triangles.size() / 3);
for (size_t i = 0, c = tin->triangles.size() / 3; i < c; ++i)
{
scenegraph::Face face;
scenegraph::MappedTexture mt;
mt.SetTextureName(imageName);
for (int z = 0; z < 3; z++)
{
auto index = tin->triangles[i * 3 + z];
auto& p = tin->verts[index];
auto& n = tin->normals[index];
float u = p.x / totalWidth;
float v = p.y / totalHeight;
mt.uvs.push_back(sfa::Point(u, v));
face.verts.push_back(sfa::Point(p.x, p.y, p.z));
face.vertexNormals.push_back(sfa::Point(n.x, n.y, n.z));
}
face.textures.push_back(mt);
scene->faces.push_back(face);
}
transformSceneFromFlatEarthToUTM(scene, south, west);
masterSceneMutex->lock();
masterScene->addChild(scene);
masterSceneMutex->unlock();
delete[] buffer;
delete tin;
}
}
void GenerateSingleOBJ(const std::string& elevationFile, const std::string& geoserverIPAddress, const std::string& outputPath, const std::string& outputTmpPath)
{
GDALAllRegister();
auto poDataset = (GDALDataset*)GDALOpen(elevationFile.c_str(), GA_ReadOnly);
double adfGeoTransform[6];
poDataset->GetGeoTransform(adfGeoTransform);
auto poBand = poDataset->GetRasterBand(1);
int nthreads = std::thread::hardware_concurrency();
std::vector<std::thread> threads(nthreads);
std::mutex masterSceneMutex;
std::mutex gdalMutex;
scenegraph::Scene masterScene;
auto rasterHeight = poDataset->GetRasterYSize();
auto rasterWidth = poDataset->GetRasterXSize();
for (int t = 0; t < nthreads; t++)
{
threads[t] = std::thread(ConvertGDALElevationToScene, adfGeoTransform, rasterWidth, rasterHeight, poBand, &masterScene, &masterSceneMutex, &gdalMutex);
}
std::for_each(threads.begin(), threads.end(), [](std::thread& x) {x.join(); });
std::string multipleTexturesPath = outputPath + "Multiple_Textures/";
if (!ccl::directoryExists(multipleTexturesPath))
{
ccl::makeDirectory(multipleTexturesPath);
}
std::string singleTexturePath = outputPath + "Single_Texture/";
if (!ccl::directoryExists(singleTexturePath))
{
ccl::makeDirectory(singleTexturePath);
}
double west = adfGeoTransform[0];
double north = adfGeoTransform[3];
double south = north + adfGeoTransform[5] * rasterHeight;
double east = west + adfGeoTransform[1] * rasterWidth;
cts::FlatEarthProjection flatEarth;
flatEarth.setOrigin(south, west);
GsBuildings buildings;
std::string dataPath = ccl::joinPaths(outputTmpPath, "data");
buildings.ProcessBuildingData(ccl::joinPaths(dataPath, "building_models.xml"));
for (int i = 0; i < buildings.Count(); i++)
{
FeatureInfo& building = buildings.GetBuilding(i);
int offsetX = (building.lon - west) / adfGeoTransform[1];
int offsetY = (building.lat - north) / adfGeoTransform[5];
float elevVal;
poBand->RasterIO(GF_Read, offsetX, offsetY, 1, 1, &elevVal, 1, 1, GDALDataType::GDT_Float32, 0, 0);
building.elev = elevVal;
auto buildingScene = new scenegraph::Scene;
ParseJSON(building.modelpath, multipleTexturesPath, *buildingScene);
sfa::Matrix m;
auto radians = (building.AO1 * M_PI) / 180;
m.PushRotate(sfa::Point(0, 0, 1), -radians);
m.PushScale(sfa::Point(building.scaleX, building.scaleY, building.scaleZ));
auto localX = flatEarth.convertGeoToLocalX(building.lon);
auto localY = flatEarth.convertGeoToLocalY(building.lat);
m.PushTranslate(sfa::Point(localX, localY, building.elev));
buildingScene->matrix = m;
masterScene.addChild(buildingScene);
}
GDALClose(poDataset);
scenegraph::FlattenVisitor flatten;
auto flattenedScene = flatten.flatten(&masterScene);
ws::GetImageryJPG(geoserverIPAddress, north, south, east, west, 8192, 8192, multipleTexturesPath + "texture.jpg");
ccl::copyFile(multipleTexturesPath + "texture.jpg", singleTexturePath + "texture.jpg");
double easting, northing;
FromLatLon(south, west, easting, northing);
std::ofstream offsetFile;
offsetFile.open(multipleTexturesPath + "offset.xyz", std::ofstream::out);
offsetFile << std::setprecision(10);
offsetFile << easting << " " << northing << " 0";
offsetFile.close();
ccl::copyFile(multipleTexturesPath + "offset.xyz", singleTexturePath + "offset.xyz");
std::ofstream wktFile;
wktFile.open(multipleTexturesPath + "wkt.prj", std::ofstream::out);
auto wkt = GetWellKnownTextUTM(south, west);
wktFile << wkt;
wktFile.close();
ccl::copyFile(multipleTexturesPath + "wkt.prj", singleTexturePath + "wkt.prj");
scenegraph::buildObjFromScene(multipleTexturesPath + "/" + "simplified_3d_mesh.obj", 0, 0, 0, 0, flattenedScene);
auto totalWidth = flatEarth.convertGeoToLocalX(east);
auto totalHeight = flatEarth.convertGeoToLocalY(north);
for (size_t i = 0; i < flattenedScene->faces.size(); ++i)
{
auto& face = flattenedScene->faces[i];
scenegraph::MappedTexture mt;
for (int index = 0; index < face.verts.size(); index++)
{
auto& p = face.verts[index];
float u = p.X() / totalWidth;
float v = p.Y() / totalHeight;
mt.SetTextureName("texture.jpg");
mt.uvs.push_back(sfa::Point(u, v));
}
face.setMappedTextureN(0, mt);
}
scenegraph::buildObjFromScene(singleTexturePath + "/" + "simplified_3d_mesh.obj", 0, 0, 0, 0, flattenedScene);
delete flattenedScene;
}
} | 42.08685 | 721 | 0.538283 | [
"vector",
"transform"
] |
e60186c84ee6a604e9697f6ec3dfefcf88c1419e | 31,552 | cpp | C++ | src/liblightmetrica/renderer/renderer_vcm.cpp | jammm/lightmetrica-v2 | 6864942ec48d37f2c35dc30a38a26d7cc4bb527e | [
"MIT"
] | 150 | 2015-12-28T10:26:02.000Z | 2021-03-17T14:36:16.000Z | src/liblightmetrica/renderer/renderer_vcm.cpp | jammm/lightmetrica-v2 | 6864942ec48d37f2c35dc30a38a26d7cc4bb527e | [
"MIT"
] | null | null | null | src/liblightmetrica/renderer/renderer_vcm.cpp | jammm/lightmetrica-v2 | 6864942ec48d37f2c35dc30a38a26d7cc4bb527e | [
"MIT"
] | 17 | 2016-02-08T10:57:55.000Z | 2020-09-04T03:57:33.000Z | /*
Lightmetrica - A modern, research-oriented renderer
Copyright (c) 2015 Hisanari Otsu
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 <pch.h>
#include <lightmetrica/renderer.h>
#include <lightmetrica/property.h>
#include <lightmetrica/random.h>
#include <lightmetrica/scene3.h>
#include <lightmetrica/film.h>
#include <lightmetrica/renderutils.h>
#include <lightmetrica/primitive.h>
#include <lightmetrica/scene3.h>
#include <lightmetrica/random.h>
#include <lightmetrica/sensor.h>
#include <lightmetrica/detail/parallel.h>
#include <lightmetrica/detail/photonmap.h>
#include <lightmetrica/detail/subpathsampler.h>
#define LM_VCM_DEBUG 0
LM_NAMESPACE_BEGIN
struct VCMPathVertex
{
int type;
SurfaceGeometry geom;
const Primitive* primitive = nullptr;
};
struct VCMSubpath
{
std::vector<VCMPathVertex> vertices;
auto SampleSubpath(const Scene3* scene, Random* rng, TransportDirection transDir, int maxNumVertices) -> void
{
vertices.clear();
SubpathSampler::TraceSubpath(scene, rng, maxNumVertices, transDir, [&](int numVertices, const Vec2& /*rasterPos*/, const SubpathSampler::PathVertex& pv, const SubpathSampler::PathVertex& v, SPD& throughput) -> bool
{
VCMPathVertex v_;
v_.type = v.type;
v_.geom = v.geom;
v_.primitive = v.primitive;
vertices.emplace_back(v_);
return true;
});
}
};
struct VCMPath
{
std::vector<VCMPathVertex> vertices;
auto ConnectSubpaths(const Scene3* scene, const VCMSubpath& subpathL, const VCMSubpath& subpathE, int s, int t) -> bool
{
assert(s >= 0);
assert(t >= 0);
vertices.clear();
if (s == 0 && t > 0)
{
vertices.insert(vertices.end(), subpathE.vertices.rend() - t, subpathE.vertices.rend());
if ((vertices.front().primitive->Type() & SurfaceInteractionType::L) == 0) { return false; }
vertices.front().type = SurfaceInteractionType::L;
}
else if (s > 0 && t == 0)
{
vertices.insert(vertices.end(), subpathL.vertices.begin(), subpathL.vertices.begin() + s);
if ((vertices.back().primitive->Type() & SurfaceInteractionType::E) == 0) { return false; }
vertices.back().type = SurfaceInteractionType::E;
}
else
{
const auto& vL = subpathL.vertices[s - 1];
const auto& vE = subpathE.vertices[t - 1];
if (vL.geom.infinite || vE.geom.infinite) { return false; }
if (!scene->Visible(vL.geom.p, vE.geom.p)) { return false; }
vertices.insert(vertices.end(), subpathL.vertices.begin(), subpathL.vertices.begin() + s);
vertices.insert(vertices.end(), subpathE.vertices.rend() - t, subpathE.vertices.rend());
}
return true;
}
auto MergeSubpaths(const VCMSubpath& subpathL, const VCMSubpath& subpathE, int s, int t) -> bool
{
assert(s >= 1);
assert(t >= 1);
vertices.clear();
const auto& vL = subpathL.vertices[s - 1];
const auto& vE = subpathE.vertices[t - 1];
if (vL.primitive->IsDeltaPosition(vL.type) || vE.primitive->IsDeltaPosition(vE.type)) { return false; }
if (vL.geom.infinite || vE.geom.infinite) { return false; }
vertices.insert(vertices.end(), subpathL.vertices.begin(), subpathL.vertices.begin() + s);
vertices.insert(vertices.end(), subpathE.vertices.rend() - t, subpathE.vertices.rend());
return true;
}
auto EvaluateF(int s, bool merge) const -> SPD
{
const int n = (int)(vertices.size());
const int t = n - s;
assert(n >= 2);
// --------------------------------------------------------------------------------
SPD fL;
if (s == 0) { fL = SPD(1_f); }
else
{
{
const auto* vL = &vertices[0];
fL = vL->primitive->EvaluatePosition(vL->geom, false);
}
for (int i = 0; i < (merge ? s : s - 1); i++)
{
const auto* v = &vertices[i];
const auto* vPrev = i >= 1 ? &vertices[i - 1] : nullptr;
const auto* vNext = &vertices[i + 1];
const auto wi = vPrev ? Math::Normalize(vPrev->geom.p - v->geom.p) : Vec3();
const auto wo = Math::Normalize(vNext->geom.p - v->geom.p);
fL *= v->primitive->EvaluateDirection(v->geom, v->type, wi, wo, TransportDirection::LE, false);
fL *= RenderUtils::GeometryTerm(v->geom, vNext->geom);
}
}
if (fL.Black()) { return SPD(); }
// --------------------------------------------------------------------------------
SPD fE;
if (t == 0) { fE = SPD(1_f); }
else
{
{
const auto* vE = &vertices[n - 1];
fE = vE->primitive->EvaluatePosition(vE->geom, false);
}
for (int i = n - 1; i > s; i--)
{
const auto* v = &vertices[i];
const auto* vPrev = &vertices[i - 1];
const auto* vNext = i < n - 1 ? &vertices[i + 1] : nullptr;
const auto wi = vNext ? Math::Normalize(vNext->geom.p - v->geom.p) : Vec3();
const auto wo = Math::Normalize(vPrev->geom.p - v->geom.p);
fE *= v->primitive->EvaluateDirection(v->geom, v->type, wi, wo, TransportDirection::EL, false);
fE *= RenderUtils::GeometryTerm(v->geom, vPrev->geom);
}
}
if (fE.Black()) { return SPD(); }
// --------------------------------------------------------------------------------
SPD cst;
if (!merge)
{
if (s == 0 && t > 0)
{
const auto& v = vertices[0];
const auto& vNext = vertices[1];
cst = v.primitive->EvaluatePosition(v.geom, true) * v.primitive->EvaluateDirection(v.geom, v.type, Vec3(), Math::Normalize(vNext.geom.p - v.geom.p), TransportDirection::EL, false);
}
else if (s > 0 && t == 0)
{
const auto& v = vertices[n - 1];
const auto& vPrev = vertices[n - 2];
cst = v.primitive->EvaluatePosition(v.geom, true) * v.primitive->EvaluateDirection(v.geom, v.type, Vec3(), Math::Normalize(vPrev.geom.p - v.geom.p), TransportDirection::LE, false);
}
else if (s > 0 && t > 0)
{
const auto* vL = &vertices[s - 1];
const auto* vE = &vertices[s];
const auto* vLPrev = s - 2 >= 0 ? &vertices[s - 2] : nullptr;
const auto* vENext = s + 1 < n ? &vertices[s + 1] : nullptr;
const auto fsL = vL->primitive->EvaluateDirection(vL->geom, vL->type, vLPrev ? Math::Normalize(vLPrev->geom.p - vL->geom.p) : Vec3(), Math::Normalize(vE->geom.p - vL->geom.p), TransportDirection::LE, true);
const auto fsE = vE->primitive->EvaluateDirection(vE->geom, vE->type, vENext ? Math::Normalize(vENext->geom.p - vE->geom.p) : Vec3(), Math::Normalize(vL->geom.p - vE->geom.p), TransportDirection::EL, true);
const Float G = RenderUtils::GeometryTerm(vL->geom, vE->geom);
cst = fsL * G * fsE;
}
}
else
{
assert(s >= 1);
assert(t >= 1);
const auto& v = vertices[s];
const auto& vPrev = vertices[s - 1];
const auto& vNext = vertices[s + 1];
const auto fs = v.primitive->EvaluateDirection(v.geom, v.type, Math::Normalize(vNext.geom.p - v.geom.p), Math::Normalize(vPrev.geom.p - v.geom.p), TransportDirection::EL, true);
cst = fs;
}
// --------------------------------------------------------------------------------
return fL * cst * fE;
}
auto EvaluatePathPDF(const Scene3* scene, int s, bool merge, Float radius) const -> PDFVal
{
const int n = (int)(vertices.size());
const int t = n - s;
assert(n >= 2);
if (!merge)
{
// Check if the path is samplable by vertex connection
if (s == 0 && t > 0)
{
const auto& v = vertices[0];
if (v.primitive->IsDeltaPosition(v.type)) { return PDFVal(PDFMeasure::ProdArea, 0_f); }
}
else if (s > 0 && t == 0)
{
const auto& v = vertices[n - 1];
if (v.primitive->IsDeltaPosition(v.type)) { return PDFVal(PDFMeasure::ProdArea, 0_f); }
}
else if (s > 0 && t > 0)
{
const auto& vL = vertices[s - 1];
const auto& vE = vertices[s];
if (vL.primitive->IsDeltaDirection(vL.type) || vE.primitive->IsDeltaDirection(vE.type)) { return PDFVal(PDFMeasure::ProdArea, 0_f); }
}
}
else
{
// Check if the path is samplable by vertex merging
if (s == 0 || t == 0) { return PDFVal(PDFMeasure::ProdArea, 0_f); }
const auto& vE = vertices[s];
if (vE.primitive->IsDeltaPosition(vE.type) || vE.primitive->IsDeltaDirection(vE.type)) { return PDFVal(PDFMeasure::ProdArea, 0_f); }
}
// Otherwise the path can be generated with the given strategy (s,t,merge) so p_{s,t,merge} can be safely evaluated.
PDFVal pdf(PDFMeasure::ProdArea, 1_f);
if (s > 0)
{
pdf *= vertices[0].primitive->EvaluatePositionGivenDirectionPDF(vertices[0].geom, Math::Normalize(vertices[1].geom.p - vertices[0].geom.p), false) * scene->EvaluateEmitterPDF(vertices[0].primitive).v;
for (int i = 0; i < (merge ? s : s - 1); i++)
{
const auto* vi = &vertices[i];
const auto* vip = i - 1 >= 0 ? &vertices[i - 1] : nullptr;
const auto* vin = &vertices[i + 1];
pdf *= vi->primitive->EvaluateDirectionPDF(vi->geom, vi->type, vip ? Math::Normalize(vip->geom.p - vi->geom.p) : Vec3(), Math::Normalize(vin->geom.p - vi->geom.p), false).ConvertToArea(vi->geom, vin->geom);
}
}
if (t > 0)
{
pdf *= vertices[n - 1].primitive->EvaluatePositionGivenDirectionPDF(vertices[n - 1].geom, Math::Normalize(vertices[n - 2].geom.p - vertices[n - 1].geom.p), false) * scene->EvaluateEmitterPDF(vertices[n - 1].primitive).v;
for (int i = n - 1; i >= s + 1; i--)
{
const auto* vi = &vertices[i];
const auto* vip = &vertices[i - 1];
const auto* vin = i + 1 < n ? &vertices[i + 1] : nullptr;
pdf *= vi->primitive->EvaluateDirectionPDF(vi->geom, vi->type, vin ? Math::Normalize(vin->geom.p - vi->geom.p) : Vec3(), Math::Normalize(vip->geom.p - vi->geom.p), false).ConvertToArea(vi->geom, vip->geom);
}
}
if (merge)
{
pdf.v *= (Math::Pi() * radius * radius);
}
return pdf;
}
auto EvaluateMISWeight_VCM(const Scene3* scene, int s_, bool merge, Float radius, long long numPhotonTraceSamples) const -> Float
{
const int n = static_cast<int>(vertices.size());
const auto ps = EvaluatePathPDF(scene, s_, merge, radius);
assert(ps > 0_f);
Float invw = 0_f;
for (int s = 0; s <= n; s++)
{
for (int type = 0; type < 2; type++)
{
const auto pi = EvaluatePathPDF(scene, s, type > 0, radius);
if (pi > 0_f)
{
const auto r = pi.v / ps.v;
invw += r*r*(type > 0 ? (Float)(numPhotonTraceSamples) : 1_f);
}
}
}
return 1_f / invw;
}
auto EvaluateMISWeight_BDPT(const Scene3* scene, int s_) const -> Float
{
const int n = static_cast<int>(vertices.size());
const auto ps = EvaluatePathPDF(scene, s_, false, 0_f);
assert(ps > 0_f);
Float invw = 0_f;
for (int s = 0; s <= n; s++)
{
const auto pi = EvaluatePathPDF(scene, s, false, 0_f);
if (pi > 0_f)
{
const auto r = pi.v / ps.v;
invw += r*r;
}
}
return 1_f / invw;
}
auto EvaluateMISWeight_BDPM(const Scene3* scene, int s_, Float radius, long long numPhotonTraceSamples) const -> Float
{
const int n = static_cast<int>(vertices.size());
const auto ps = EvaluatePathPDF(scene, s_, true, radius);
assert(ps > 0_f);
Float invw = 0_f;
for (int s = 0; s <= n; s++)
{
const auto pi = EvaluatePathPDF(scene, s, true, radius);
if (pi > 0_f)
{
const auto r = pi.v / ps.v;
invw += r*r*(Float)(numPhotonTraceSamples);
}
}
return 1_f / invw;
}
auto RasterPosition() const -> Vec2
{
const auto& v = vertices[vertices.size() - 1];
const auto& vPrev = vertices[vertices.size() - 2];
Vec2 rasterPos;
v.primitive->sensor->RasterPosition(Math::Normalize(vPrev.geom.p - v.geom.p), v.geom, rasterPos);
return rasterPos;
}
};
// --------------------------------------------------------------------------------
struct VCMKdTree
{
struct Node
{
bool isleaf;
Bound bound;
union
{
struct
{
int begin;
int end;
} leaf;
struct
{
int child1;
int child2;
} internal;
};
};
struct Index
{
int subpathIndex;
int vertexIndex;
};
std::vector<std::unique_ptr<Node>> nodes_;
std::vector<int> indices_;
std::vector<Index> vertices_;
const std::vector<VCMSubpath>& subpathLs_;
VCMKdTree(const std::vector<VCMSubpath>& subpathLs)
: subpathLs_(subpathLs)
{}
auto Build() -> void
{
// Arrange in a vector
for (int i = 0; i < (int)subpathLs_.size(); i++)
{
const auto& subpathL = subpathLs_[i];
for (int j = 1; j < (int)subpathL.vertices.size(); j++)
{
const auto& v = subpathL.vertices[j];
if (!v.geom.infinite && !v.primitive->IsDeltaPosition(v.type) && !v.primitive->IsDeltaDirection(v.type))
{
vertices_.push_back({ i, j });
}
}
}
// Build function
const std::function<int(int, int)> Build_ = [&](int begin, int end) -> int
{
int idx = (int)(nodes_.size());
nodes_.emplace_back(new Node);
auto* node = nodes_[idx].get();
// Current bound
node->bound = Bound();
for (int i = begin; i < end; i++)
{
const auto& v = vertices_[indices_[i]];
node->bound = Math::Union(node->bound, subpathLs_[v.subpathIndex].vertices[v.vertexIndex].geom.p);
}
// Create leaf node
const int LeafNumNodes = 10;
if (end - begin < LeafNumNodes)
{
node->isleaf = true;
node->leaf.begin = begin;
node->leaf.end = end;
return idx;
}
// Select longest axis as split axis
const int axis = node->bound.LongestAxis();
// Select split position
const Float split = node->bound.Centroid()[axis];
// Partition into two sets according to split position
const auto it = std::partition(indices_.begin() + begin, indices_.begin() + end, [&](int i) -> bool
{
const auto& v = vertices_[i];
return subpathLs_[v.subpathIndex].vertices[v.vertexIndex].geom.p[axis] < split;
});
// Create intermediate node
const int mid = (int)(std::distance(indices_.begin(), it));
node->isleaf = false;
node->internal.child1 = Build_(begin, mid);
node->internal.child2 = Build_(mid, end);
return idx;
};
nodes_.clear();
indices_.assign(vertices_.size(), 0);
std::iota(indices_.begin(), indices_.end(), 0);
Build_(0, (int)(vertices_.size()));
}
auto RangeQuery(const Vec3& p, Float radius, const std::function<void(int subpathIndex, int vertexIndex)>& queryFunc) const -> void
{
const Float radius2 = radius * radius;
const std::function<void(int)> Collect = [&](int idx) -> void
{
const auto* node = nodes_.at(idx).get();
if (node->isleaf)
{
for (int i = node->leaf.begin; i < node->leaf.end; i++)
{
const auto& v = vertices_[indices_[i]];
if (Math::Length2(subpathLs_[v.subpathIndex].vertices[v.vertexIndex].geom.p - p) < radius2)
{
queryFunc(v.subpathIndex, v.vertexIndex);
}
}
return;
}
const int axis = node->bound.LongestAxis();
const Float split = node->bound.Centroid()[axis];
const auto dist2 = (p[axis] - split) * (p[axis] - split);
if (p[axis] < split)
{
Collect(node->internal.child1);
if (dist2 < radius2)
{
Collect(node->internal.child2);
}
}
else
{
Collect(node->internal.child2);
if (dist2 < radius2)
{
Collect(node->internal.child1);
}
}
};
Collect(0);
}
};
// --------------------------------------------------------------------------------
enum class Mode
{
VCM,
BDPT,
BDPM,
};
/*!
\brief Vertex connection and merging renderer (reference version).
Implements vertex connection and merging [Georgiev et al. 2012].
This implementation purposely adopts a naive way
to check the correctness of the implementation and
to be utilized as a baseline for the further modifications.
For the optimized implementation, see `renderer::vcmopt` (TODO),
which is based on the way described in the technical report [Georgiev 2012]
or SmallVCM renderer [Davidovic & Georgiev 2012].
References:
- [Georgiev et al. 2012] Light transport simulation with vertex connection and merging
- [Hachisuka et al. 2012] A path space extension for robust light transport simulation
- [Georgiev 2012] Implementing vertex connection and merging
- [Davidovic & Georgiev 2012] SmallVCM renderer
*/
class Renderer_VCM final : public Renderer
{
public:
LM_IMPL_CLASS(Renderer_VCM, Renderer);
private:
int maxNumVertices_;
int minNumVertices_;
long long numIterationPass_;
long long numPhotonTraceSamples_;
long long numEyeTraceSamples_;
Float initialRadius_;
Float alpha_;
Mode mode_;
#if LM_VCM_DEBUG
std::string debugOutputPath_;
#endif
public:
LM_IMPL_F(Initialize) = [this](const PropertyNode* p) -> bool
{
maxNumVertices_ = p->ChildAs<int>("max_num_vertices", 10);
minNumVertices_ = p->ChildAs<int>("min_num_vertices", 0);
numIterationPass_ = p->ChildAs<long long>("num_iteration_pass", 100L);
numPhotonTraceSamples_ = p->ChildAs<long long>("num_photon_trace_samples", 10000L);
numEyeTraceSamples_ = p->ChildAs<long long>("num_eye_trace_samples", 10000L);
initialRadius_ = p->ChildAs<Float>("initial_radius", 0.1_f);
alpha_ = p->ChildAs<Float>("alpha", 0.7_f);
#if LM_VCM_DEBUG
debugOutputPath_ = p->ChildAs<std::string>("debug_output_path", "vcm_%05d");
#endif
{
const auto modestr = p->ChildAs<std::string>("mode", "vcm");
if (modestr == "vcm") { mode_ = Mode::VCM; }
else if (modestr == "bdpt") { mode_ = Mode::BDPT; }
else if (modestr == "bdpm") { mode_ = Mode::BDPM; }
LM_LOG_INFO("Selected mode: '" + modestr + "'");
}
return true;
};
LM_IMPL_F(Render) = [this](const Scene* scene_, Random* initRng, const std::string& outputPath) -> void
{
const auto* scene = static_cast<const Scene3*>(scene_);
auto* film = static_cast<const Sensor*>(scene->GetSensor()->emitter)->GetFilm();
// --------------------------------------------------------------------------------
Float mergeRadius = 0_f;
for (long long pass = 0; pass < numIterationPass_; pass++)
{
LM_LOG_INFO("Pass " + std::to_string(pass));
LM_LOG_INDENTER();
// --------------------------------------------------------------------------------
#pragma region Update merge radius
mergeRadius = pass == 0 ? initialRadius_ : std::sqrt((alpha_ + pass) / (1_f + pass)) * mergeRadius;
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample light subpaths
std::vector<VCMSubpath> subpathLs;
if (mode_ == Mode::VCM || mode_ == Mode::BDPM)
{
LM_LOG_INFO("Sampling light subpaths");
LM_LOG_INDENTER();
struct Context
{
Random rng;
std::vector<VCMSubpath> subpathLs;
};
std::vector<Context> contexts(Parallel::GetNumThreads());
for (auto& ctx : contexts) { ctx.rng.SetSeed(initRng->NextUInt()); }
Parallel::For(numPhotonTraceSamples_, [&](long long index, int threadid, bool init)
{
auto& ctx = contexts[threadid];
ctx.subpathLs.emplace_back();
ctx.subpathLs.back().SampleSubpath(scene, &ctx.rng, TransportDirection::LE, maxNumVertices_);
});
for (auto& ctx : contexts)
{
subpathLs.insert(subpathLs.end(), ctx.subpathLs.begin(), ctx.subpathLs.end());
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Construct range query structure for vertices in light subpaths
VCMKdTree pm(subpathLs);
if (mode_ == Mode::VCM || mode_ == Mode::BDPM)
{
LM_LOG_INFO("Constructing range query structure");
LM_LOG_INDENTER();
pm.Build();
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Estimate contribution
{
LM_LOG_INFO("Estimating contribution");
LM_LOG_INDENTER();
struct Context
{
Random rng;
Film::UniquePtr film{nullptr, nullptr};
};
std::vector<Context> contexts(Parallel::GetNumThreads());
for (auto& ctx : contexts)
{
ctx.rng.SetSeed(initRng->NextUInt());
ctx.film = ComponentFactory::Clone<Film>(film);
ctx.film->Clear();
}
Parallel::For(numEyeTraceSamples_, [&](long long index, int threadid, bool init)
{
auto& ctx = contexts[threadid];
// --------------------------------------------------------------------------------
#pragma region Sample subpaths
static thread_local VCMSubpath subpathE;
static thread_local VCMSubpath subpathL;
subpathE.SampleSubpath(scene, &ctx.rng, TransportDirection::EL, maxNumVertices_);
subpathL.SampleSubpath(scene, &ctx.rng, TransportDirection::LE, maxNumVertices_);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Combine subpaths
const int nE = (int)(subpathE.vertices.size());
for (int t = 1; t <= nE; t++)
{
#pragma region Vertex connection
if (mode_ == Mode::VCM || mode_ == Mode::BDPT)
{
const int nL = (int)(subpathL.vertices.size());
const int minS = Math::Max(0, Math::Max(2 - t, minNumVertices_ - t));
const int maxS = Math::Min(nL, maxNumVertices_ - t);
for (int s = minS; s <= maxS; s++)
{
// Connect vertices and create a full path
static thread_local VCMPath fullpath;
if (!fullpath.ConnectSubpaths(scene, subpathL, subpathE, s, t)) { continue; }
// Evaluate contribution
const auto f = fullpath.EvaluateF(s, false);
if (f.Black()) { continue; }
// Evaluate connection PDF
const auto p = fullpath.EvaluatePathPDF(scene, s, false, 0_f);
if (p.v == 0)
{
// Due to precision issue, this can happen.
return;
}
// Evaluate MIS weight
const auto w = mode_ == Mode::VCM
? fullpath.EvaluateMISWeight_VCM(scene, s, false, mergeRadius, numPhotonTraceSamples_)
: fullpath.EvaluateMISWeight_BDPT(scene, s);
// Accumulate contribution
const auto C = f * w / p;
ctx.film->Splat(fullpath.RasterPosition(), C * (Float)(film->Width() * film->Height()) / (Float)numEyeTraceSamples_);
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Vertex merging
if (mode_ == Mode::VCM || mode_ == Mode::BDPM)
{
const auto& vE = subpathE.vertices[t - 1];
if (vE.primitive->IsDeltaPosition(vE.type))
{
continue;
}
pm.RangeQuery(vE.geom.p, mergeRadius, [&](int si, int vi) -> void
{
const int s = vi + 1;
const int n = s + t - 1;
if (n < minNumVertices_ || maxNumVertices_ < n) { return; }
// Merge vertices and create a full path
static thread_local VCMPath fullpath;
if (!fullpath.MergeSubpaths(subpathLs[si], subpathE, s - 1, t)) { return; }
// Evaluate contribution
const auto f = fullpath.EvaluateF(s - 1, true);
if (f.Black()) { return; }
// Evaluate path PDF
const auto p = fullpath.EvaluatePathPDF(scene, s - 1, true, mergeRadius);
if (p.v == 0)
{
// Due to precision issue, this can happen.
return;
}
// Evaluate MIS weight
const auto w = mode_ == Mode::VCM
? fullpath.EvaluateMISWeight_VCM(scene, s - 1, true, mergeRadius, numPhotonTraceSamples_)
: fullpath.EvaluateMISWeight_BDPM(scene, s - 1, mergeRadius, numPhotonTraceSamples_);
// Accumulate contribution
const auto C = f * w / p;
ctx.film->Splat(fullpath.RasterPosition(), C * (Float)(film->Width() * film->Height()) / (Float)numEyeTraceSamples_);
});
}
#pragma endregion
}
#pragma endregion
});
film->Rescale((Float)(pass) / (1_f + pass));
for (auto& ctx : contexts)
{
ctx.film->Rescale(1_f / (1_f + pass));
film->Accumulate(ctx.film.get());
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#if LM_VCM_DEBUG
{
boost::format f(debugOutputPath_);
f.exceptions(boost::io::all_error_bits ^ (boost::io::too_many_args_bit | boost::io::too_few_args_bit));
film->Save(boost::str(f % pass));
}
#endif
}
// --------------------------------------------------------------------------------
#pragma region Save image
{
LM_LOG_INFO("Saving image");
LM_LOG_INDENTER();
film->Save(outputPath);
}
#pragma endregion
};
};
LM_COMPONENT_REGISTER_IMPL(Renderer_VCM, "renderer::vcm");
LM_NAMESPACE_END
| 39.44 | 232 | 0.483773 | [
"render",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.