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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5b6b96f28ae9a92fb7ae760cd46c9d48f2712278 | 18,648 | cpp | C++ | code_reading/oceanbase-master/src/rootserver/ob_inner_table_monitor.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/rootserver/ob_inner_table_monitor.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/rootserver/ob_inner_table_monitor.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX SERVER
#include "ob_inner_table_monitor.h"
#include "lib/oblog/ob_log_module.h"
#include "lib/string/ob_sql_string.h"
#include "lib/stat/ob_diagnose_info.h"
#include "lib/mysqlclient/ob_mysql_proxy.h"
#include "common/ob_role_mgr.h"
#include "share/config/ob_server_config.h"
#include "share/ob_common_rpc_proxy.h"
#include "share/inner_table/ob_inner_table_schema.h"
#include "rootserver/ob_root_service.h"
namespace oceanbase {
using namespace common;
using namespace share;
namespace rootserver {
#define PURGE_SQL1 \
"/* purge_sql1 */ " \
" DELETE FROM %s PARTITION(p%d) WHERE (%s, schema_version) IN ( " \
" SELECT %s, t1.schema_version FROM %s PARTITION(p%d) t1 " \
" JOIN (SELECT %s, max(schema_version) as max_v FROM %s PARTITION(p%d)" \
" WHERE tenant_id=%ld and schema_version < %ld GROUP BY %s " \
" ) t2 " \
" USING(%s) WHERE t1.schema_version < t2.max_v LIMIT 1000" \
" ) LIMIT 1000"
#define PURGE_SQL2 \
"/* purge_sql2 */ " \
" DELETE FROM %s PARTITION(p%d) WHERE (%s, schema_version) IN ( " \
" SELECT %s, t1.schema_version FROM %s PARTITION(p%d) t1 " \
" JOIN (SELECT %s, max(schema_version) as max_v FROM %s PARTITION(p%d)" \
" WHERE tenant_id=%ld and schema_version < %ld and is_deleted = 1 GROUP BY %s " \
" ) t2 " \
" USING(%s) LIMIT 1000) LIMIT 1000"
//__all_column_history:
#define PREFIX_PRIMARY_KEY_FOR_COLUMN_HISTORY "`tenant_id`, `table_id`, `column_id`"
// __all_table_history:
#define PREFIX_PRIMARY_KEY_FOR_TABLE_HISTORY "`tenant_id`, `table_id`"
// __all_tablegroup_history:
#define PREFIX_PRIMARY_KEY_FOR_TABLEGROUP_HISTORY "`tenant_id`, `tablegroup_id`"
// __all_outline_history:
#define PREFIX_PRIMARY_KEY_FOR_OUTLINE_HISTORY "`tenant_id`, `outline_id`"
// __all_database_history:
#define PREFIX_PRIMARY_KEY_FOR_DATABASE_HISTORY "`tenant_id`, `database_id`"
// __all_tenant_history
#define PREFIX_PRIMARY_KEY_FOR_TENANT_HISTORY "`tenant_id`"
// __all_user_history:
#define PREFIX_PRIMARY_KEY_FOR_USER_HISTORY "`tenant_id`, `user_id`"
// __all_database_privilege_history:
#define PREFIX_PRIMARY_KEY_FOR_DATABASE_PRIVILEGE_HISTORY "`tenant_id`, `user_id`, `database_name`"
// __all_table_privilege_history:
#define PREFIX_PRIMARY_KEY_FOR_TABLE_PRIVILEGE_HISTORY "`tenant_id`, `user_id`, `database_name`, `table_name`"
// __all_ddl_operation:
#define PREFIX_PRIMARY_KEY_FOR_DDL_OPERATION "`tenant_id`"
ObInnerTableMonitor::ObInnerTableMonitor() : inited_(false), rs_proxy_(NULL), sql_proxy_(NULL), root_service_(NULL)
{}
int ObInnerTableMonitor::init(ObMySQLProxy& mysql_proxy, obrpc::ObCommonRpcProxy& rs_proxy, ObRootService& root_service)
{
int ret = OB_SUCCESS;
if (inited_) {
ret = OB_INIT_TWICE;
LOG_WARN("init twice");
} else {
sql_proxy_ = &mysql_proxy;
rs_proxy_ = &rs_proxy;
root_service_ = &root_service;
inited_ = true;
}
return ret;
}
int ObInnerTableMonitor::check_inner_stat() const
{
int ret = OB_SUCCESS;
if (OB_ISNULL(sql_proxy_)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("sql_proxy_ is null", K(ret));
} else if (OB_ISNULL(rs_proxy_)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("common_proxy_ is null", K(ret));
} else if (OB_ISNULL(root_service_)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("root_service is null", K(ret));
}
return ret;
}
int ObInnerTableMonitor::get_all_tenants_from_stats(ObIArray<uint64_t>& tenant_ids)
{
int ret = OB_SUCCESS;
SMART_VAR(ObMySQLProxy::MySQLResult, res)
{
sqlclient::ObMySQLResult* result = NULL;
ObSqlString sql;
if (OB_FAIL(check_inner_stat())) {
LOG_WARN("check inner stat failed", K(ret));
} else if (OB_FAIL(sql.append_fmt("SELECT distinct tenant_id FROM %s", OB_ALL_TENANT_HISTORY_TNAME))) {
LOG_WARN("assign sql string failed", K(ret));
} else if (OB_FAIL(sql_proxy_->read(res, sql.ptr()))) {
LOG_WARN("execute sql failed", K(sql), K(ret));
} else if (NULL == (result = res.get_result())) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("get result failed", K(ret));
}
while (OB_SUCC(ret)) {
if (OB_FAIL(result->next())) {
if (OB_ITER_END == ret) {
ret = OB_SUCCESS;
break;
} else {
LOG_WARN("get next result failed", K(ret));
}
} else {
int64_t tenant_id = 0;
if (OB_FAIL(result->get_int("tenant_id", tenant_id))) {
LOG_WARN("get tenant id failed", K(ret));
} else if (OB_FAIL(tenant_ids.push_back(tenant_id))) {
LOG_WARN("push back tenant id failed", K(ret));
}
}
}
}
return ret;
}
// 1. select global last_merged_version from __all_zone
// 2. use last_merged_version -1 as purge_frozen_verion
// 3. select frozen_timestamp from __all_frozen_map for purge_frozen_verion
int ObInnerTableMonitor::get_last_forzen_time(int64_t& last_frozen_time)
{
int ret = OB_SUCCESS;
SMART_VAR(ObMySQLProxy::MySQLResult, res)
{
sqlclient::ObMySQLResult* result = NULL;
ObSqlString sql;
int64_t last_merged_version = 0;
int64_t frozen_timestamp = 0;
if (OB_FAIL(check_inner_stat())) {
LOG_WARN("check inner stat failed", K(ret));
} else if (OB_FAIL(
sql.append_fmt("SELECT * FROM %s WHERE name = 'last_merged_version' LIMIT 1", OB_ALL_ZONE_TNAME))) {
LOG_WARN("assign sql string failed", K(ret));
} else if (OB_FAIL(sql_proxy_->read(res, sql.ptr()))) {
LOG_WARN("execute sql failed", K(sql), K(ret));
} else if (NULL == (result = res.get_result())) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("get result failed", K(ret));
} else if (OB_FAIL(result->next())) {
LOG_WARN("get next result failed", K(ret));
} else if (OB_FAIL(result->get_int("value", last_merged_version))) {
LOG_WARN("get last_merged_version failed", K(ret));
}
// for frozen_map, initial is empty, then don't purge any record.
// if only one record in frozen_map, also don't purge any record.
if (OB_SUCC(ret) && last_merged_version > 0) {
last_merged_version--;
sql.reset();
if (OB_FAIL(sql.append_fmt("SELECT frozen_timestamp FROM %s WHERE frozen_version = %ld",
OB_ALL_FROZEN_MAP_TNAME,
last_merged_version))) {
LOG_WARN("assign sql string failed", K(ret));
} else if (OB_FAIL(sql_proxy_->read(res, sql.ptr()))) {
LOG_WARN("execute sql failed", K(sql), K(ret));
} else if (NULL == (result = res.get_result())) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("get result failed", K(ret));
} else if (OB_FAIL(result->next())) {
if (OB_ITER_END == ret) {
// do nothing, reset ret to success
ret = OB_SUCCESS;
} else {
LOG_WARN("get next result failed", K(ret));
}
} else if (OB_FAIL(result->get_int("frozen_timestamp", frozen_timestamp))) {
LOG_WARN("get frozen_timestamp failed", K(ret));
}
}
if (OB_SUCC(ret)) {
last_frozen_time = frozen_timestamp;
}
}
return ret;
}
int ObInnerTableMonitor::purge_inner_table_history()
{
bool ret = OB_SUCCESS;
ObSEArray<uint64_t, 16> tenant_ids;
if (OB_FAIL(get_all_tenants_from_stats(tenant_ids))) {
LOG_WARN("get_all_tenants_from_stats failed", K(ret));
} else if (OB_FAIL(purge_recyclebin_objects(tenant_ids))) {
LOG_WARN("purge recyclebin objects failed", K(ret));
}
return ret;
}
int ObInnerTableMonitor::purge_inner_table_history(
const uint64_t tenant_id, const int64_t last_frozen_time, int64_t& purged_rows)
{
int ret = OB_SUCCESS;
int last_ret = OB_SUCCESS;
int64_t current_time = ObTimeUtility::current_time();
const int64_t delta_sec = 3600; // one hour
const int64_t schema_history_expire_time = GCONF.schema_history_expire_time;
int64_t min_schema_version = current_time - schema_history_expire_time;
// can not delete history since last froze_time - delta
min_schema_version = min(min_schema_version, last_frozen_time - delta_sec);
purged_rows = 0;
if (OB_FAIL(purge_table_column_history(tenant_id, min_schema_version, purged_rows))) {
last_ret = ret;
LOG_WARN("purage_table_column_history failed", K(ret));
}
if (OB_FAIL(purge_history(OB_ALL_TABLEGROUP_HISTORY_TNAME,
N_PARTITION_FOR_TABLEGROUP_HISTORY,
tenant_id,
min_schema_version,
PREFIX_PRIMARY_KEY_FOR_TABLEGROUP_HISTORY,
purged_rows))) {
last_ret = ret;
LOG_WARN("purge_tablegroup_history failed", K(ret));
}
if (OB_FAIL(purge_history(OB_ALL_OUTLINE_HISTORY_TNAME,
N_PARTITION_FOR_OUTLINE_HISTORY,
tenant_id,
min_schema_version,
PREFIX_PRIMARY_KEY_FOR_OUTLINE_HISTORY,
purged_rows))) {
last_ret = ret;
LOG_WARN("purge_tablegroup_history failed", K(ret));
}
if (OB_FAIL(purge_history(OB_ALL_DATABASE_HISTORY_TNAME,
N_PARTITION_FOR_DATABASE_HISTORY,
tenant_id,
min_schema_version,
PREFIX_PRIMARY_KEY_FOR_DATABASE_HISTORY,
purged_rows))) {
last_ret = ret;
LOG_WARN("purge_database_history failed", K(ret));
}
if (OB_FAIL(purge_history(OB_ALL_USER_HISTORY_TNAME,
N_PARTITION_FOR_USER_HISTORY,
tenant_id,
min_schema_version,
PREFIX_PRIMARY_KEY_FOR_USER_HISTORY,
purged_rows))) {
last_ret = ret;
LOG_WARN("purge_user_history failed", K(ret));
}
if (OB_FAIL(purge_history(OB_ALL_TENANT_HISTORY_TNAME,
N_PARTITION_FOR_TENANT_HISTORY,
tenant_id,
min_schema_version,
PREFIX_PRIMARY_KEY_FOR_TENANT_HISTORY,
purged_rows))) {
last_ret = ret;
LOG_WARN("purge_tenant_history failed", K(ret));
}
if (OB_FAIL(purge_history(OB_ALL_DATABASE_PRIVILEGE_HISTORY_TNAME,
N_PARTITION_FOR_DATABASE_PRIVILEGE_HISTORY,
tenant_id,
min_schema_version,
PREFIX_PRIMARY_KEY_FOR_DATABASE_PRIVILEGE_HISTORY,
purged_rows))) {
last_ret = ret;
LOG_WARN("purge_database_privilege_history failed", K(ret));
}
if (OB_FAIL(purge_history(OB_ALL_TABLE_PRIVILEGE_HISTORY_TNAME,
N_PARTITION_FOR_TABLE_PRIVILEGE_HISTORY,
tenant_id,
min_schema_version,
PREFIX_PRIMARY_KEY_FOR_TABLE_PRIVILEGE_HISTORY,
purged_rows))) {
last_ret = ret;
LOG_WARN("purge_table_privilege_history failed", K(ret));
}
if (OB_FAIL(purge_history(OB_ALL_DDL_OPERATION_TNAME,
N_PARTITION_FOR_DDL_OPERATION,
tenant_id,
min_schema_version,
PREFIX_PRIMARY_KEY_FOR_DDL_OPERATION,
purged_rows))) {
last_ret = ret;
LOG_WARN("pureg_ddl_operation failed", K(ret));
}
return last_ret;
}
int ObInnerTableMonitor::delete_history_for_partitions(const char* tname, const int np, const uint64_t tid,
const int64_t schema_version, const char* prefix_pk, int64_t& purged_rows, ObMySQLTransaction& trans)
{
int ret = OB_SUCCESS;
ObSqlString sql;
int64_t affected_rows = 0;
for (int i = 0; OB_SUCC(ret) && i < np; i++) {
if (OB_FAIL(sql.assign_fmt(PURGE_SQL1,
tname,
i,
prefix_pk,
prefix_pk,
tname,
i,
prefix_pk,
tname,
i,
tid,
schema_version,
prefix_pk,
prefix_pk))) {
LOG_WARN("assign_fmt failed", K(sql));
} else if (OB_FAIL(trans.write(sql.ptr(), affected_rows))) {
LOG_WARN("execute sql fail", K(sql), K(ret));
}
purged_rows += affected_rows;
if (OB_SUCCESS == ret &&
!ObCharset::case_insensitive_equal(
ObString(strlen(OB_ALL_DDL_OPERATION_TNAME), OB_ALL_DDL_OPERATION_TNAME), ObString(strlen(tname), tname))) {
if (OB_FAIL(sql.assign_fmt(PURGE_SQL2,
tname,
i,
prefix_pk,
prefix_pk,
tname,
i,
prefix_pk,
tname,
i,
tid,
schema_version,
prefix_pk,
prefix_pk))) {
LOG_WARN("assign_fmt failed", K(sql));
} else if (OB_FAIL(trans.write(sql.ptr(), affected_rows))) {
LOG_WARN("execute sql fail", K(sql), K(ret));
}
purged_rows += affected_rows;
}
}
return ret;
}
int ObInnerTableMonitor::purge_history(const char* tname, const int np, const uint64_t tid,
const int64_t schema_version, const char* prefix_pk, int64_t& purged_rows)
{
int ret = OB_SUCCESS;
int tmp_ret = OB_SUCCESS;
bool commit = false;
ObMySQLTransaction trans;
if (OB_FAIL(check_inner_stat())) {
LOG_WARN("check inner stat failed", K(ret));
} else if (OB_FAIL(trans.start(sql_proxy_))) {
SERVER_LOG(WARN, "start transaction failed", K(ret));
} else if (OB_FAIL(delete_history_for_partitions(tname, np, tid, schema_version, prefix_pk, purged_rows, trans))) {
LOG_WARN("delete_history_for_partitions fail", K(ret));
}
if (trans.is_started()) {
commit = (OB_SUCC(ret));
if (OB_SUCCESS != (tmp_ret = trans.end(commit))) {
SERVER_LOG(WARN, "end transaction failed", K(ret), K(tmp_ret), K(commit));
if (OB_SUCC(ret)) {
ret = tmp_ret;
}
}
}
return ret;
}
// purge table schema history and related schemas(such as column schema) history in one trans.
int ObInnerTableMonitor::purge_table_column_history(
const uint64_t tid, const int64_t schema_version, int64_t& purged_rows)
{
int ret = OB_SUCCESS;
int tmp_ret = OB_SUCCESS;
bool commit = false;
ObMySQLTransaction trans;
if (OB_ISNULL(sql_proxy_)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("sql_proxy is null", K(ret));
} else if (OB_FAIL(trans.start(sql_proxy_))) {
LOG_WARN("start transaction failed", K(ret));
} else if (OB_FAIL(delete_history_for_partitions(OB_ALL_COLUMN_HISTORY_TNAME,
N_PARTITION_FOR_COLUMN_HISTORY,
tid,
schema_version,
PREFIX_PRIMARY_KEY_FOR_COLUMN_HISTORY,
purged_rows,
trans))) {
LOG_WARN("purge_column_history failed", K(ret));
} else if (OB_FAIL(delete_history_for_partitions(OB_ALL_TABLE_HISTORY_TNAME,
N_PARTITION_FOR_TABLE_HISTORY,
tid,
schema_version,
PREFIX_PRIMARY_KEY_FOR_TABLE_HISTORY,
purged_rows,
trans))) {
LOG_WARN("purge_table_history failed", K(ret));
}
if (trans.is_started()) {
commit = (OB_SUCC(ret));
if (OB_SUCCESS != (tmp_ret = trans.end(commit))) {
LOG_WARN("end transaction failed", K(ret), K(tmp_ret), K(commit));
if (OB_SUCC(ret)) {
ret = tmp_ret;
}
}
}
return ret;
}
int ObInnerTableMonitor::check_cancel() const
{
int ret = OB_SUCCESS;
if (OB_FAIL(check_inner_stat())) {
LOG_WARN("check inner stat failed", K(ret));
} else if (!root_service_->in_service()) {
ret = OB_RS_SHUTDOWN;
LOG_WARN("root service is shutdown", K(ret));
}
return ret;
}
int ObInnerTableMonitor::purge_recyclebin_objects(ObIArray<uint64_t>& tenant_ids)
{
int ret = OB_SUCCESS;
const int64_t current_time = ObTimeUtility::current_time();
obrpc::Int64 expire_time = current_time - GCONF.schema_history_expire_time;
if (OB_FAIL(check_inner_stat())) {
LOG_WARN("check inner stat failed", K(ret));
} else {
const int64_t SLEEP_INTERVAL = 100 * 1000; // 100ms
const int64_t SLEEP_TIMES = 100;
const int64_t PURGE_EACH_TIME = 10;
obrpc::Int64 affected_rows = 0;
bool is_tenant_finish = false;
obrpc::ObPurgeRecycleBinArg arg;
// ignore ret
for (int i = 0; i < tenant_ids.count() && OB_SUCCESS == check_cancel(); ++i) {
is_tenant_finish = false;
affected_rows = 0;
arg.tenant_id_ = tenant_ids.at(i);
arg.purge_num_ = PURGE_EACH_TIME;
arg.expire_time_ = expire_time;
LOG_INFO("start purge recycle objects of tenant", K(arg));
int retry_cnt = 0;
while (!is_tenant_finish && OB_SUCCESS == check_cancel()) {
// In case of holding DDL thread in long time, Each tenant only purge 10 recycle objects in one round.
int64_t start_time = ObTimeUtility::current_time();
if (OB_FAIL(rs_proxy_->purge_expire_recycle_objects(arg, affected_rows))) {
LOG_WARN("purge reyclebin objects failed",
K(ret),
K(current_time),
K(expire_time),
K(affected_rows),
K(arg),
K(retry_cnt));
if (retry_cnt < 3) {
is_tenant_finish = false;
++retry_cnt;
} else {
LOG_WARN("retry purge recyclebin object of tenant failed, ignore it", K(retry_cnt), K(ret), K(arg));
is_tenant_finish = true;
}
} else {
retry_cnt = 0;
is_tenant_finish = PURGE_EACH_TIME == affected_rows ? false : true;
}
int64_t cost_time = ObTimeUtility::current_time() - start_time;
LOG_INFO("purge recycle objects",
K(ret),
K(cost_time),
K(expire_time),
K(current_time),
K(affected_rows),
K(is_tenant_finish));
// sleep 10s so that will not block the rs DDL thread
int i = 0;
while (OB_SUCCESS == check_cancel() && i < SLEEP_TIMES) {
usleep(SLEEP_INTERVAL);
++i;
}
}
}
}
return ret;
}
} // namespace rootserver
} // namespace oceanbase
| 35.587786 | 120 | 0.637709 | [
"object"
] |
ac892da2d0a68013b9e024f24abe90e7862c93b1 | 2,823 | cpp | C++ | OpenGL-sandbox/Sources/sceneobject.cpp | OpenGL-adepts/OpenGL-sandbox | 78ed291e03fd0d73667f46aec74af01bf7e58326 | [
"MIT"
] | 1 | 2021-11-27T08:12:09.000Z | 2021-11-27T08:12:09.000Z | OpenGL-sandbox/Sources/sceneobject.cpp | OpenGL-adepts/OpenGL-sandbox | 78ed291e03fd0d73667f46aec74af01bf7e58326 | [
"MIT"
] | null | null | null | OpenGL-sandbox/Sources/sceneobject.cpp | OpenGL-adepts/OpenGL-sandbox | 78ed291e03fd0d73667f46aec74af01bf7e58326 | [
"MIT"
] | 1 | 2019-01-04T03:35:17.000Z | 2019-01-04T03:35:17.000Z | #include "SceneObject.hpp"
#include <imgui.h>
#include <filesystem>
void SceneObject::config()
{
if(ImGui::TreeNode("Position"))
{
ImGui::SliderFloat("X", &m_position.x, -20.f, 20.f);
ImGui::SliderFloat("Y", &m_position.y, -20.f, 20.f);
ImGui::SliderFloat("Z", &m_position.z, -20.f, 20.f);
ImGui::TreePop();
}
if(ImGui::TreeNode("Rotation"))
{
ImGui::SliderAngle("X", &m_rotation.x);
ImGui::SliderAngle("Y", &m_rotation.y);
ImGui::SliderAngle("Z", &m_rotation.z);
ImGui::TreePop();
}
if(ImGui::TreeNode("Scale"))
{
ImGui::SliderFloat("X", &m_scale.x, 0.01f, 20.f);
ImGui::SliderFloat("Y", &m_scale.y, 0.01f, 20.f);
ImGui::SliderFloat("Z", &m_scale.z, 0.01f, 20.f);
float objScale = m_scale.x;
if(ImGui::SliderFloat("uniform", &objScale, 0.01f, 20.f))
m_scale = glm::vec3(objScale);
ImGui::TreePop();
}
doConfig();
}
nlohmann::json SceneObject::toJSON(const std::string& _savePath) const
{
nlohmann::json tmp;
tmp["name"] = m_displayName;
tmp["enabled"] = m_bEnabled;
tmp["position"] = {m_position.x, m_position.y, m_position.z};
tmp["rotation"] = {m_rotation.x, m_rotation.y, m_rotation.z};
tmp["scale"] = {m_scale.x, m_scale.y, m_scale.z};
saveToJSON(tmp, _savePath);
return tmp;
}
void SceneObject::fromJSON(const nlohmann::json& _json)
{
try { setDisplayName(_json.at("name").get<std::string>()); } catch(...) {}
try { setEnabled(_json.at("enabled")); } catch (...) {}
setPosition (JSON::loadVector3(_json, "position"));
setRotation (JSON::loadVector3(_json, "rotation"));
setScale (JSON::loadVector3(_json, "scale", glm::vec3(1.f)));
}
void SceneObject::setRotation(glm::vec3 _angles)
{
m_rotation = _angles;
}
void SceneObject::setPosition(glm::vec3 _pos)
{
m_position = _pos;
}
void SceneObject::setScale(glm::vec3 _scale)
{
m_scale = _scale;
}
void SceneObject::setDisplayName(std::string _name)
{
m_displayName = std::move(_name);
}
void SceneObject::setEnabled(bool _enabled)
{
m_bEnabled = _enabled;
}
const std::string& SceneObject::getDisplayName() const
{
return m_displayName;
}
glm::mat4 SceneObject::getModelMatrix() const
{
glm::mat4 model = doGetModelMatrix();
glm::mat4 rot = glm::rotate(glm::mat4(1.f), m_rotation.x, glm::vec3(1.f, 0.f, 0.f));
rot = glm::rotate(rot, m_rotation.y, glm::vec3(0.f, 1.f, 0.f));
rot = glm::rotate(rot, m_rotation.z, glm::vec3(0.f, 0.f, 1.f));
return glm::translate(glm::mat4(1.f), m_position) * glm::scale(rot, m_scale) * model;
}
glm::vec3 SceneObject::getPosition() const
{
return m_position;
}
glm::vec3 SceneObject::getRotation() const
{
return m_rotation;
}
glm::vec3 SceneObject::getScale() const
{
return m_scale;
}
bool SceneObject::isEnabled() const
{
return m_bEnabled;
}
glm::mat4 SceneObject::doGetModelMatrix() const
{
return glm::mat4(1.f);
}
| 19.880282 | 86 | 0.670563 | [
"model"
] |
ac8f1caad2130bb085b40bc6e6be542218c467c6 | 3,608 | cc | C++ | orttraining/orttraining/core/optimizer/insert_output_rewriter.cc | KsenijaS/onnxruntime | 5086e55a35f83e3137bdb34b6d7210c97a512e6a | [
"MIT"
] | 2 | 2021-07-24T01:13:36.000Z | 2021-11-17T11:03:52.000Z | orttraining/orttraining/core/optimizer/insert_output_rewriter.cc | KsenijaS/onnxruntime | 5086e55a35f83e3137bdb34b6d7210c97a512e6a | [
"MIT"
] | 4 | 2020-12-04T21:00:38.000Z | 2022-01-22T12:49:30.000Z | orttraining/orttraining/core/optimizer/insert_output_rewriter.cc | KsenijaS/onnxruntime | 5086e55a35f83e3137bdb34b6d7210c97a512e6a | [
"MIT"
] | 1 | 2020-06-08T19:08:12.000Z | 2020-06-08T19:08:12.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/graph_utils.h"
#include "orttraining/core/optimizer/insert_output_rewriter.h"
using namespace ONNX_NAMESPACE;
namespace onnxruntime {
Status InsertMaxPoolOutput::Apply(Graph& graph, Node& node, RewriteRuleEffect& rule_effect, const logging::Logger& /*logger*/) const {
auto& outputs = node.MutableOutputDefs();
const NodeArg* Y = outputs[0];
TypeProto t;
t.mutable_tensor_type()->set_elem_type(TensorProto_DataType_INT64);
if (Y->Shape() != nullptr) {
t.mutable_tensor_type()->mutable_shape()->CopyFrom(*Y->Shape());
}
NodeArg& node_arg = graph.GetOrCreateNodeArg(Y->Name() + "_mask", &t);
outputs.push_back(&node_arg);
rule_effect = RewriteRuleEffect::kUpdatedCurrentNode;
return Status::OK();
}
bool InsertMaxPoolOutput::SatisfyCondition(const Graph& /*graph*/, const Node& node, const logging::Logger& /*logger*/) const {
if (graph_utils::IsSupportedOptypeVersionAndDomain(node, "MaxPool", {8, 10, 11, 12}) &&
node.OutputDefs().size() == 1) {
return true;
}
return false;
}
Status InsertSoftmaxCrossEntropyLossOutput::Apply(Graph& graph, Node& node, RewriteRuleEffect& rule_effect, const logging::Logger& /*logger*/) const {
auto& outputs = node.MutableOutputDefs();
const NodeArg* X = node.InputDefs()[0];
TypeProto t;
t.mutable_tensor_type()->set_elem_type(X->TypeAsProto()->tensor_type().elem_type());
if (X->Shape() != nullptr) {
t.mutable_tensor_type()->mutable_shape()->CopyFrom(*X->Shape()); // log probability should have the same shape as logits.
}
NodeArg& node_arg = graph.GetOrCreateNodeArg(X->Name() + "_log_prob", &t);
outputs.push_back(&node_arg);
rule_effect = RewriteRuleEffect::kUpdatedCurrentNode;
return Status::OK();
}
bool InsertSoftmaxCrossEntropyLossOutput::SatisfyCondition(const Graph& /*graph*/, const Node& node, const logging::Logger& /*logger*/) const {
if (graph_utils::IsSupportedOptypeVersionAndDomain(node, "SoftmaxCrossEntropyLoss", {12}) &&
node.OutputDefs().size() == 1) {
return true;
}
return false;
}
Status AdjustBatchNormOutputs::Apply(Graph& graph, Node& node, RewriteRuleEffect& rule_effect, const logging::Logger& /*logger*/) const {
auto& outputs = node.MutableOutputDefs();
const auto& inputs = node.InputDefs();
const NodeArg* scale_input_def = inputs[1];
auto scale_input_def_type_proto = scale_input_def->TypeAsProto();
NodeArg& running_mean_def = graph.GetOrCreateNodeArg(graph.GenerateNodeArgName("running_mean_def"), scale_input_def_type_proto);
NodeArg& running_var_def = graph.GetOrCreateNodeArg(graph.GenerateNodeArgName("running_var_def"), scale_input_def_type_proto);
NodeArg& saved_mean_def = graph.GetOrCreateNodeArg(graph.GenerateNodeArgName("saved_mean_def"), scale_input_def_type_proto);
NodeArg& saved_var_def = graph.GetOrCreateNodeArg(graph.GenerateNodeArgName("saved_var_def"), scale_input_def_type_proto);
outputs.push_back(&running_mean_def);
outputs.push_back(&running_var_def);
outputs.push_back(&saved_mean_def);
outputs.push_back(&saved_var_def);
// check Batch Normalization node has 5 output node args for training mode
ORT_ENFORCE(node.OutputDefs().size() == 5);
rule_effect = RewriteRuleEffect::kUpdatedCurrentNode;
return Status::OK();
}
bool AdjustBatchNormOutputs::SatisfyCondition(const Graph& /*graph*/, const Node& node, const logging::Logger& /*logger*/) const {
if (node.OutputDefs().size() == 1) {
return true;
}
return false;
}
} // namespace onnxruntime
| 38.382979 | 150 | 0.742794 | [
"shape"
] |
ac99a528a56b68244aad46fbdd38430303800623 | 7,941 | cpp | C++ | threshsign/test/TestThresholdSerialization.cpp | big-data-lab-umbc/concord-bft | 7061695406885604471a8a7bd5944e8d16d7280f | [
"Apache-2.0"
] | 1 | 2021-03-03T10:06:22.000Z | 2021-03-03T10:06:22.000Z | threshsign/test/TestThresholdSerialization.cpp | yuliasherman/concord-bft | 81c5278828c4d05f4822087659decd4a926e85c9 | [
"Apache-2.0"
] | null | null | null | threshsign/test/TestThresholdSerialization.cpp | yuliasherman/concord-bft | 81c5278828c4d05f4822087659decd4a926e85c9 | [
"Apache-2.0"
] | 1 | 2020-12-06T21:02:03.000Z | 2020-12-06T21:02:03.000Z | // Concord
//
// Copyright (c) 2019 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License").
// You may not use this product except in compliance with the Apache 2.0 License.
//
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these sub-components is subject to the
// terms and conditions of the sub-component's license, as noted in the
// LICENSE file.
#include "threshsign/Configuration.h"
#include "threshsign/bls/relic/Library.h"
#include "threshsign/bls/relic/BlsPublicParameters.h"
#include "TestThresholdBls.h"
#include "app/RelicMain.h"
#include <map>
#include <set>
#include <vector>
#include <string>
#include <cassert>
#include <memory>
#include <stdexcept>
#include <inttypes.h>
#include "Logger.hpp"
#include "Utils.h"
#include "Timer.h"
#include "XAssert.h"
#include "Logger.hpp"
using namespace std;
using namespace BLS::Relic;
using namespace concord::serialize;
const char secretKeyValue[] =
"308204BA020100300D06092A864886F70D0101010500048204A4308204A00201000282010100C55B8F7979BF24B335017082BF33EE2960E3A"
"068DCDB45CA3017214BFB3F32649400A2484E2108C7CD07AA7616290667AF7C7A1922C82B51CA01867EED9B60A57F5B6EE33783EC258B2347"
"488B0FA3F99B05CFFBB45F80960669594B58C993D07B94D9A89ED8266D9931EAE70BB5E9063DEA9EFAF744393DCD92F2F5054624AA048C7EE"
"50BEF374FCDCE1C8CEBCA1EF12AF492402A6F56DC9338834162F3773B119145BF4B72672E0CF2C7009EBC3D593DFE3715D942CA8749771B48"
"4F72A2BC8C89F86DB52ECC40763B6298879DE686C9A2A78604A503609BA34B779C4F55E3BEB0C26B1F84D8FC4EB3C79693B25A77A158EF882"
"92D4C01F99EFE3CC912D09B020111028201001D05EF73BF149474B4F8AEA9D0D2EE5161126A69C6203EF8162184E586D4967833E1F9BF56C8"
"9F68AD35D54D99D8DB4B7BB06C4EFD95E840BBD30C3FD7A5E890CEF6DB99E284576EEED07B6C8CEBB63B4B80DAD2311D1A706A5AC95DE768F"
"017213B896B9EE38D2E3C2CFCE5BDF51ABD27391761245CDB3DCB686F05EA2FF654FA91F89DA699F14ACFA7F0D8030F74DBFEC28D55C902A2"
"7E9C03AB1CA2770EFC5BE541560D86FA376B1A688D92124496BB3E7A3B78A86EBF1B694683CDB32BC49431990A18B570C104E47AC6B0DE561"
"6851F4309CFE7D0E20B17C154A3D85F33C7791451FFF73BFC4CDC8C16387D184F42AD2A31FCF545C3F9A498FAAC6E94E902818100F40CF915"
"2ED4854E1BBF67C5EA185C52EBEA0C11875563AEE95037C2E61C8D988DDF71588A0B45C23979C5FBFD2C45F9416775E0A644CAD46792296FD"
"C68A98148F7BD3164D9A5E0D6A0C2DF0141D82D610D56CB7C53F3C674771ED9ED77C0B5BF3C936498218176DC9933F1215BC831E0D4128561"
"1F512F68327E4FBD9E5C5902818100CF05519FD69D7C6B61324F0A201574C647792B80E5D4D56A51CF5988927A1D54DF9AE4EA656AE259619"
"23A0EC046F1C569BAB53A64EB0E9F5AB2ABF1C9146935BA40F75E0EB68E0BE4BC29A5A0742B59DF5A55AB028F1CCC42243D2AEE4B74344CA3"
"3E72879EF2D1CDD874A7F237202AC7EB57AEDCBD539DEFDA094476EAE613028180396C76D7CEC897D624A581D43714CA6DDD2802D6F2AAAE0"
"B09B885974533E514D6167505C620C51EA41CA70E1D73D43AA5FA39DA81799922EB3173296109914B98B2C31AAE515434E734E28ED31E8D37"
"DA99BA11C2E693B6398570ABBF6778A33C0E40CC6007E23A15C9B1DE6233B6A25304B91053166D7490FCD26D1D8EAC5102818079C6E4B8602"
"0674E392CA6F6E5B244B0DEBFBF3CC36E232F7B6AE95F6538C5F5B0B57798F05CFD9DFD28D6DB8029BB6511046A9AD1F3AE3F9EC37433DFB1"
"A74CC7E9FAEC08A79ED9D1D8187F8B8FA107B08F7DAFE3633E1DCC8DC9A0C8689EB55A41E87F9B12347B6A06DB359D89D6AFC0E4CA2A9FF6E"
"5E46EF8BA2845F396650281802A89B2BD4A665A0F07DCAFA6D9DB7669B1D1276FC3365173A53F0E0D5F9CB9C3E08E68503C62EA73EB8E0DA4"
"2CCF6B136BF4A85B0AC424730B4F3CAD8C31D34DD75EF2A39B6BCFE3985CCECC470CF479CF0E9B9D6C7CE1C6C70D853728925326A22352DF7"
"3B502D4D3CBC2A770DE276E1C5953DF7A9614C970C94D194CAE9188";
const char publicKeyValue[] =
"0312651421b08cc9140e34471ed2b3a1c12e60e9bd55a4a1f78842bc06d80d6ac31598ee4cb26df7c81d30208ff2d065249a490634ed4e61a"
"5f19de1e203334339";
const char verificationKeyValue1[] =
"031ef8af0a33cd7b42a0b853847d9f275e8bab88dbe753b668309883a3e962ed72156ecabe1b83dcafbcef438bb334366f4e3e83f6b2564f3"
"e02f1f4a670ec36fa";
const char verificationKeyValue2[] =
"03102c402140a917648f5be446e65fcf0eee2a9cc3d2f8a9489b98997b152cc1010381ff14e508ef7d0f01346805e8ad1f396dfa218ea525f"
"695debc4bf2d43f8d";
const char verificationKeyValue3[] =
"03172b38140843bfd7fe63b55d13045effcf597bc9e003102e4e160c74a9e3fd6f11e38cd307a23afd1da250f72f4e422d9863a8c3db71381"
"432a5cf4171e50609";
const char verificationKeyValue4[] =
"02143bb5256bc80e9e1f048ef4c42f0c5e27f16e345b58482e0a4adf77b235d41d1e2c4b0636edf13b853f21b0ec738b70d47837389832498"
"ecbea82c878ecb5ba";
const int numOfSigners = 3;
bool testBlsThresholdSigner(const BlsPublicParameters ¶ms) {
ShareID id = 0x208419;
BNT secretKey(secretKeyValue);
SerializablePtr origSigner(new BlsThresholdSigner(params, id, secretKey));
std::stringstream strstr;
origSigner->serialize(strstr);
Serializable *resultSigner = nullptr;
BlsThresholdSigner::deserialize(strstr, resultSigner);
auto *inSigner = dynamic_cast<BlsThresholdSigner *>(origSigner.get());
auto *outSigner = dynamic_cast<BlsThresholdSigner *>(resultSigner);
auto returnVal = (resultSigner && (*inSigner == *outSigner));
delete resultSigner;
return returnVal;
}
vector<BlsPublicKey> prepareVerificationKeysVector() {
vector<BlsPublicKey> verificationKeys;
const G2T verificationKey1(verificationKeyValue1);
const G2T verificationKey2(verificationKeyValue2);
const G2T verificationKey3(verificationKeyValue3);
const G2T verificationKey4(verificationKeyValue4);
verificationKeys.emplace_back(BlsPublicKey(verificationKey1));
verificationKeys.emplace_back(BlsPublicKey(verificationKey2));
verificationKeys.emplace_back(BlsPublicKey(verificationKey3));
verificationKeys.emplace_back(BlsPublicKey(verificationKey4));
return verificationKeys;
}
void printRawBuf(const UniquePtrToChar &buf, int64_t bufSize) {
for (int i = 0; i < bufSize; ++i) {
char c = buf.get()[i];
if (c >= 48 && c <= 57)
printf("%d\n", c);
else
printf("%c\n", c);
}
}
bool testBlsThresholdVerifier(const BlsPublicParameters ¶ms, const vector<BlsPublicKey> &verificationKeys) {
G2T publicKey(publicKeyValue);
SerializablePtr origVerifier(
new BlsThresholdVerifier(params, publicKey, numOfSigners, numOfSigners, verificationKeys));
std::stringstream strstr;
origVerifier->serialize(strstr);
Serializable *resultVerifier(nullptr);
BlsThresholdVerifier::deserialize(strstr, resultVerifier);
auto *inVerifier = dynamic_cast<BlsThresholdVerifier *>(origVerifier.get());
auto *outVerifier = dynamic_cast<BlsThresholdVerifier *>(resultVerifier);
auto returnVal = (resultVerifier && (*inVerifier == *outVerifier));
delete resultVerifier;
return returnVal;
}
bool testBlsMultisigVerifier(const BlsPublicParameters ¶ms, const vector<BlsPublicKey> &verificationKeys) {
SerializablePtr origVerifier(new BlsMultisigVerifier(params, numOfSigners, numOfSigners, verificationKeys));
std::stringstream strstr;
origVerifier->serialize(strstr);
Serializable *resultVerifier(nullptr);
BlsMultisigVerifier::deserialize(strstr, resultVerifier);
auto *inVerifier = dynamic_cast<BlsMultisigVerifier *>(origVerifier.get());
auto *outVerifier = dynamic_cast<BlsMultisigVerifier *>(resultVerifier);
auto returnVal = (resultVerifier && (*inVerifier == *outVerifier));
delete resultVerifier;
return returnVal;
}
int RelicAppMain(const Library &lib, const vector<string> &args) {
(void)args;
(void)lib;
// uncomment if needed
// log4cplus::Logger::getInstance( LOG4CPLUS_TEXT("serializable")).setLogLevel(log4cplus::TRACE_LOG_LEVEL);
BlsPublicParameters params(PublicParametersFactory::getWhatever());
assertTrue(testBlsThresholdSigner(params));
vector<BlsPublicKey> verificationKeys = prepareVerificationKeysVector();
assertTrue(testBlsThresholdVerifier(params, verificationKeys));
assertTrue(testBlsMultisigVerifier(params, verificationKeys));
return 0;
}
| 47.837349 | 119 | 0.83793 | [
"vector"
] |
aca103b32c9a755309836e0d08be716d15ede3c0 | 64,105 | cpp | C++ | libs/base/src/math/geometry.cpp | yhexie/mrpt | 0bece2883aa51ad3dc88cb8bb84df571034ed261 | [
"OLDAP-2.3"
] | null | null | null | libs/base/src/math/geometry.cpp | yhexie/mrpt | 0bece2883aa51ad3dc88cb8bb84df571034ed261 | [
"OLDAP-2.3"
] | null | null | null | libs/base/src/math/geometry.cpp | yhexie/mrpt | 0bece2883aa51ad3dc88cb8bb84df571034ed261 | [
"OLDAP-2.3"
] | 1 | 2021-08-16T11:50:47.000Z | 2021-08-16T11:50:47.000Z | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "base-precomp.h" // Precompiled headers
#include <mrpt/math/geometry.h>
#include <mrpt/math/CPolygon.h>
#include <mrpt/math/CSparseMatrixTemplate.h>
#include <mrpt/math/CMatrixTemplateNumeric.h>
#include <mrpt/math/data_utils.h>
#include <mrpt/math/ops_containers.h>
#include <mrpt/poses/CPoint2D.h>
#include <mrpt/poses/CPose2D.h>
#include <mrpt/math/lightweight_geom_data.h>
using namespace mrpt;
using namespace mrpt::utils;
using namespace std;
using namespace mrpt::poses;
using namespace mrpt::math;
double mrpt::math::geometryEpsilon=1e-5;
/*---------------------------------------------------------------
Returns the closest point to a segment
---------------------------------------------------------------*/
void math::closestFromPointToSegment(
const double & Px,
const double & Py,
const double & x1,
const double & y1,
const double & x2,
const double & y2,
double &out_x,
double &out_y)
{
if (x1==x2 && y1==y2)
{
out_x = x1;
out_y = y1;
}
else
{
double Dx = x2 - x1;
double Dy = y2 - y1;
double Ratio = ((Px - x1) * Dx + (Py - y1) * Dy) / (Dx * Dx + Dy * Dy);
if (Ratio<0)
{
out_x = x1;
out_y = y1;
}
else
{
if (Ratio > 1)
{
out_x = x2;
out_y = y2;
}
else
{
out_x = x1 + (Ratio * Dx);
out_y = y1 + (Ratio * Dy);
}
}
}
}
/*---------------------------------------------------------------
Returns the closest point to a line
---------------------------------------------------------------*/
void math::closestFromPointToLine(
const double & Px,
const double & Py,
const double & x1,
const double & y1,
const double & x2,
const double & y2,
double &out_x,
double &out_y)
{
if (x1==x2 && y1==y2)
{
out_x = x1;
out_y = y1;
}
else
{
double Dx = x2 - x1;
double Dy = y2 - y1;
double Ratio = ((Px - x1) * Dx + (Py - y1) * Dy) / (Dx * Dx + Dy * Dy);
out_x = x1 + (Ratio * Dx);
out_y = y1 + (Ratio * Dy);
}
}
/*---------------------------------------------------------------
Returns the sq. distance to closest point to a line
---------------------------------------------------------------*/
double math::closestSquareDistanceFromPointToLine(
const double & Px,
const double & Py,
const double & x1,
const double & y1,
const double & x2,
const double & y2 )
{
if (x1==x2 && y1==y2)
{
return square( Px-x1 ) + square( Py-y1 );
}
else
{
double Dx = x2 - x1;
double Dy = y2 - y1;
double Ratio = ((Px - x1) * Dx + (Py - y1) * Dy) / (Dx * Dx + Dy * Dy);
return square( x1 + (Ratio * Dx) - Px ) + square( y1 + (Ratio * Dy) - Py );
}
}
/*---------------------------------------------------------------
Intersect
---------------------------------------------------------------*/
bool math::SegmentsIntersection(
const double x1,const double y1,
const double x2,const double y2,
const double x3,const double y3,
const double x4,const double y4,
double &ix,double &iy)
{
double UpperX,UpperY,LowerX,LowerY,Ax,Bx,Cx,Ay,By,Cy,d,f,e,Ratio;
Ax = x2 - x1;
Bx = x3 - x4;
if (Ax < 0)
{
LowerX = x2;
UpperX = x1;
}
else
{
UpperX = x2;
LowerX = x1;
}
if (Bx > 0)
{
if (UpperX < x4 || x3 < LowerX) return false;
}
else if (UpperX < x3 || x4 < LowerX) return false;
Ay = y2 - y1;
By = y3 - y4;
if (Ay < 0)
{
LowerY = y2;
UpperY = y1;
}
else
{
UpperY = y2;
LowerY = y1;
}
if (By > 0)
{
if (UpperY < y4 || y3 < LowerY) return false;
}
else if (UpperY < y3 || y4 < LowerY) return false;
Cx = x1 - x3;
Cy = y1 - y3;
d = (By * Cx) - (Bx * Cy);
f = (Ay * Bx) - (Ax * By);
if (f > 0)
{
if (d < 0 || d > f) return false;
}
else if (d > 0 || d < f) return false;
e = (Ax * Cy) - (Ay * Cx);
if (f > 0)
{
if (e < 0 || e > f) return false;
}
else if (e > 0 || e < f) return false;
Ratio = (Ax * -By) - (Ay * -Bx);
if (Ratio!=0)
{
Ratio = ((Cy * -Bx) - (Cx * -By)) / Ratio;
ix = x1 + (Ratio * Ax);
iy = y1 + (Ratio * Ay);
}
else
{
if ( (Ax * -Cy)==(-Cx * Ay) )
{
ix = x3;
iy = y3;
}
else
{
ix = x4;
iy = y4;
}
}
return true;
}
/*---------------------------------------------------------------
Intersect
---------------------------------------------------------------*/
bool math::SegmentsIntersection(
const double x1,const double y1,
const double x2,const double y2,
const double x3,const double y3,
const double x4,const double y4,
float &ix,float &iy)
{
double x,y;
bool b = SegmentsIntersection(x1,y1,x2,y2,x3,y3,x4,y4,x,y);
ix = static_cast<float>(x);
iy = static_cast<float>(y);
return b;
}
/*---------------------------------------------------------------
Intersect
---------------------------------------------------------------*/
bool math::pointIntoPolygon2D(const double & px, const double & py, unsigned int polyEdges, const double *poly_xs, const double *poly_ys )
{
unsigned int i,j;
bool res = false;
if (polyEdges<3) return res;
j = polyEdges - 1;
for (i=0;i<polyEdges;i++)
{
if ((poly_ys[i] <= py && py < poly_ys[j]) || // an upward crossing
(poly_ys[j] <= py && py < poly_ys[i]) ) // a downward crossing
{
// compute the edge-ray intersect @ the x-coordinate
if (px - poly_xs[i]<((poly_xs[j] - poly_xs[i]) * (py - poly_ys[i]) / (poly_ys[j] - poly_ys[i]) ))
res =! res;
}
j = i;
}
return res;
}
/*---------------------------------------------------------------
Intersect
---------------------------------------------------------------*/
double math::distancePointToPolygon2D(const double & px, const double & py, unsigned int polyEdges, const double *poly_xs, const double *poly_ys )
{
unsigned int i,j;
double minDist = 1e20f;
// Is the point INTO?
if (pointIntoPolygon2D(px,py,polyEdges,poly_xs,poly_ys))
return 0;
// Compute the closest distance from the point to any segment:
j = polyEdges - 1;
for (i=0;i<polyEdges;i++)
{
// segment: [j]-[i]
// ----------------------
double closestX,closestY;
double d = minimumDistanceFromPointToSegment(px,py, poly_xs[j],poly_ys[j], poly_xs[i],poly_ys[i],closestX,closestY);
minDist = min(d,minDist);
// For next iter:
j = i;
}
return minDist;
}
/*---------------------------------------------------------------
minDistBetweenLines
--------------------------------------------------------------- */
bool math::minDistBetweenLines(
const double & p1_x, const double & p1_y, const double & p1_z,
const double & p2_x, const double & p2_y, const double & p2_z,
const double & p3_x, const double & p3_y, const double & p3_z,
const double & p4_x, const double & p4_y, const double & p4_z,
double &x, double &y, double &z,
double &dist)
{
const double EPS = 1e-30f;
double p13_x,p13_y,p13_z;
double p43_x,p43_y,p43_z;
double p21_x,p21_y,p21_z;
double d1343,d4321,d1321,d4343,d2121;
double numer,denom;
p13_x = p1_x - p3_x;
p13_y = p1_y - p3_y;
p13_z = p1_z - p3_z;
p43_x = p4_x - p3_x;
p43_y = p4_y - p3_y;
p43_z = p4_z - p3_z;
if (fabs(p43_x) < EPS && fabs(p43_y) < EPS && fabs(p43_z) < EPS) return false;
p21_x = p2_x - p1_x;
p21_y = p2_y - p1_y;
p21_z = p2_z - p1_z;
if (fabs(p21_x) < EPS && fabs(p21_y) < EPS && fabs(p21_z) < EPS) return false;
d1343 = p13_x * p43_x + p13_y * p43_y + p13_z * p43_z;
d4321 = p43_x * p21_x + p43_y * p21_y + p43_z * p21_z;
d1321 = p13_x * p21_x + p13_y * p21_y + p13_z * p21_z;
d4343 = p43_x * p43_x + p43_y * p43_y + p43_z * p43_z;
d2121 = p21_x * p21_x + p21_y * p21_y + p21_z * p21_z;
denom = d2121 * d4343 - d4321 * d4321;
if (fabs(denom) < EPS) return false;
numer = d1343 * d4321 - d1321 * d4343;
double mua = numer / denom;
double mub = (d1343 + d4321 * mua) / d4343;
double pa_x, pa_y, pa_z;
double pb_x, pb_y, pb_z;
pa_x = p1_x + mua * p21_x;
pa_y = p1_y + mua * p21_y;
pa_z = p1_z + mua * p21_z;
pb_x = p3_x + mub * p43_x;
pb_y = p3_y + mub * p43_y;
pb_z = p3_z + mub * p43_z;
dist = (double) sqrt( square( pa_x - pb_x ) + square( pa_y - pb_y ) + square( pa_z - pb_z ) );
// the mid point:
x = 0.5*(pa_x + pb_x);
y = 0.5*(pa_y + pb_y);
z = 0.5*(pa_z + pb_z);
return true;
}
/*---------------------------------------------------------------
Rectangles Intersect
---------------------------------------------------------------*/
bool math::RectanglesIntersection(
const double & R1_x_min, const double & R1_x_max,
const double & R1_y_min, const double & R1_y_max,
const double & R2_x_min, const double & R2_x_max,
const double & R2_y_min, const double & R2_y_max,
const double & R2_pose_x,
const double & R2_pose_y,
const double & R2_pose_phi )
{
// Compute the rotated R2:
// ----------------------------------------
CVectorDouble xs(4),ys(4);
double ccos = cos(R2_pose_phi);
double ssin = sin(R2_pose_phi);
xs[0] = R2_pose_x + ccos * R2_x_min - ssin * R2_y_min;
ys[0] = R2_pose_y + ssin * R2_x_min + ccos * R2_y_min;
xs[1] = R2_pose_x + ccos * R2_x_max - ssin * R2_y_min;
ys[1] = R2_pose_y + ssin * R2_x_max + ccos * R2_y_min;
xs[2] = R2_pose_x + ccos * R2_x_max - ssin * R2_y_max;
ys[2] = R2_pose_y + ssin * R2_x_max + ccos * R2_y_max;
xs[3] = R2_pose_x + ccos * R2_x_min - ssin * R2_y_max;
ys[3] = R2_pose_y + ssin * R2_x_min + ccos * R2_y_max;
// Test for one vertice being inside the other rectangle:
// -------------------------------------------------------
if ( R1_x_min<=xs[0] && xs[0]<=R1_x_max && R1_y_min<=ys[0] && ys[0]<=R1_y_max) return true;
if ( R1_x_min<=xs[1] && xs[1]<=R1_x_max && R1_y_min<=ys[1] && ys[1]<=R1_y_max) return true;
if ( R1_x_min<=xs[2] && xs[2]<=R1_x_max && R1_y_min<=ys[2] && ys[2]<=R1_y_max) return true;
if ( R1_x_min<=xs[3] && xs[3]<=R1_x_max && R1_y_min<=ys[3] && ys[3]<=R1_y_max) return true;
CPolygon poly;
poly.AddVertex( xs[0],ys[0] );
poly.AddVertex( xs[1],ys[1] );
poly.AddVertex( xs[2],ys[2] );
poly.AddVertex( xs[3],ys[3] );
if (poly.PointIntoPolygon( R1_x_min, R1_y_min )) return true;
if (poly.PointIntoPolygon( R1_x_max, R1_y_min )) return true;
if (poly.PointIntoPolygon( R1_x_max, R1_y_max )) return true;
if (poly.PointIntoPolygon( R1_x_min, R1_y_max )) return true;
// Test for intersections:
// ----------------------------------------
double ix,iy;
for (int idx=0;idx<4;idx++)
{
if ( math::SegmentsIntersection( R1_x_min,R1_y_min, R1_x_max,R1_y_min, xs[idx],ys[idx], xs[(idx+1)%4],ys[(idx+1)%4], ix,iy) ) return true;
if ( math::SegmentsIntersection( R1_x_max,R1_y_min, R1_x_max,R1_y_max, xs[idx],ys[idx], xs[(idx+1)%4],ys[(idx+1)%4], ix,iy) ) return true;
if ( math::SegmentsIntersection( R1_x_max,R1_y_max, R1_x_min,R1_y_max, xs[idx],ys[idx], xs[(idx+1)%4],ys[(idx+1)%4], ix,iy) ) return true;
if ( math::SegmentsIntersection( R1_x_min,R1_y_max, R1_x_min,R1_y_min, xs[idx],ys[idx], xs[(idx+1)%4],ys[(idx+1)%4], ix,iy) ) return true;
}
// No intersections:
return false;
}
//Auxiliary functions needed to avoid code repetition and unnecesary recalculations
template<class T2D,class U2D,class T3D,class U3D> bool intersectInCommonPlane(const T3D &o1,const U3D &o2,const mrpt::math::TPlane &p,mrpt::math::TObject3D &obj) {
T3D proj1;
U3D proj2;
//Project into 3D plane, ignoring Z coordinate.
CPose3D pose;
TPlane(p).getAsPose3D(pose);
CPose3D poseNeg=CPose3D(0,0,0,0,0,0)-pose;
project3D(o1,poseNeg,proj1);
project3D(o2,poseNeg,proj2);
T2D proj1_2D;
U2D proj2_2D;
proj1.generate2DObject(proj1_2D);
proj2.generate2DObject(proj2_2D);
//Compute easier intersection in 2D space
TObject2D obj2D;
if (intersect(proj1_2D,proj2_2D,obj2D)) {
TObject3D tmp;
obj2D.generate3DObject(tmp);
//Undo projection
project3D(tmp,pose,obj);
return true;
} else return false;
}
bool intersectInCommonLine(const mrpt::math::TSegment3D &s1,const mrpt::math::TSegment3D &s2,const mrpt::math::TLine3D &lin,mrpt::math::TObject3D &obj) {
//Move in a free coordinate, searching for minima and maxima.
size_t i1=0;
while (abs(lin.director[i1])<geometryEpsilon) i1++;
TSegment3D s11=(s1[0][i1]>s1[1][i1])?TSegment3D(s1[1],s1[0]):s1;
TSegment3D s21=(s2[0][i1]>s2[1][i1])?TSegment3D(s2[1],s2[0]):s2;
TPoint3D pMin=((s11[0][i1]<s21[0][i1])?s21:s11)[0];
TPoint3D pMax=((s11[1][i1]<s21[1][i1])?s11:s21)[1];
if (abs(pMax[i1]-pMin[i1])<geometryEpsilon) { //Intersection is a point
obj=pMax;
return true;
} else if (pMax[i1]<pMin[i1]) return false; //No intersection
else {
obj=TSegment3D(pMin,pMax); //Intersection is a segment
return true;
}
}
bool intersectInCommonLine(const TSegment2D &s1,const TSegment2D &s2,const TLine2D &lin,TObject2D &obj) {
//Move in a free coordinate, searching for minima and maxima
size_t i1=(abs(lin.coefs[0])>=geometryEpsilon)?1:0;
TSegment2D s11=(s1[0][i1]>s1[1][i1])?TSegment2D(s1[1],s1[0]):s1;
TSegment2D s21=(s2[0][i1]>s2[1][i1])?TSegment2D(s2[1],s2[0]):s2;
TPoint2D pMin=((s11[0][i1]<s21[0][i1])?s21:s11)[0];
TPoint2D pMax=((s11[1][i1]<s21[1][i1])?s11:s21)[1];
if (abs(pMax[i1]-pMin[i1])<geometryEpsilon) { //Intersection is a point
obj=pMax;
return true;
} else if (pMax[i1]<pMin[i1]) return false; //No intersection
else {
obj=TSegment2D(pMin,pMax); //Intersection is a segment
return true;
}
}
inline void unsafeProjectPoint(const TPoint3D &point,const CPose3D &pose,TPoint2D &newPoint) {
double dummy;
pose.composePoint(point.x,point.y,point.z,newPoint.x,newPoint.y,dummy);
}
void unsafeProjectPolygon(const TPolygon3D &poly,const CPose3D &pose,TPolygon2D &newPoly) {
size_t N=poly.size();
newPoly.resize(N);
for (size_t i=0;i<N;i++) unsafeProjectPoint(poly[i],pose,newPoly[i]);
}
bool intersect(const TPolygonWithPlane &p1,const TLine3D &l2,double &d,double bestKnown) {
//LINE MUST BE UNITARY
TObject3D obj;
TPoint3D p;
if (intersect(p1.plane,l2,obj)) if (obj.getPoint(p)) {
for (size_t i=0;i<3;i++) if (abs(l2.director[i])>geometryEpsilon) {
d=(p[i]-l2.pBase[i])/l2.director[i];
break;
}
if (d<0||d>bestKnown) return false;
TPolygon2D newPoly;
TPoint2D newP;
unsafeProjectPoint(p,p1.inversePose,newP);
unsafeProjectPolygon(p1.poly,p1.inversePose,newPoly);
return newPoly.contains(newP);
}
return false;
}
bool intersect(const TPolygonWithPlane &p1,const TPolygonWithPlane &p2,TObject3D &obj) {
if (!intersect(p1.plane,p2.plane,obj)) return false;
TLine3D lin3D;
TObject3D aux;
if (obj.getLine(lin3D)) {
TLine3D lin3D1,lin3D2;
TLine2D lin2D1,lin2D2;
TObject2D obj2D1,obj2D2;
project3D(lin3D,p1.inversePose,lin3D1);
project3D(lin3D,p2.inversePose,lin3D2);
lin3D1.generate2DObject(lin2D1);
lin3D2.generate2DObject(lin2D2);
if (intersect(p1.poly2D,lin2D1,obj2D1)&&intersect(p2.poly2D,lin2D2,obj2D2)) {
TObject3D obj3D1,obj3D2,obj3Dp1,obj3Dp2;
obj2D1.generate3DObject(obj3D1);
obj2D2.generate3DObject(obj3D2);
project3D(obj3D1,p1.pose,obj3Dp1);
project3D(obj3D2,p2.pose,obj3Dp2);
TPoint3D po1,po2;
TSegment3D s1,s2;
if (obj3D1.getPoint(po1)) s1=TSegment3D(po1,po1);
else obj3D1.getSegment(s1);
if (obj3D2.getPoint(po2)) s2=TSegment3D(po2,po2);
else obj3D2.getSegment(s2);
return intersectInCommonLine(s1,s2,lin3D,obj);
} else return false;
} else {
TObject2D obj2D;
if (intersect(p1.poly2D,p2.poly2D,obj2D)) {
obj2D.generate3DObject(aux);
project3D(aux,p1.pose,obj);
return true;
} else return false;
}
}
//End of auxiliary methods
math::TPolygonWithPlane::TPolygonWithPlane(const TPolygon3D &p):poly(p) {
poly.getBestFittingPlane(plane);
plane.getAsPose3D(pose);
inversePose=-pose;
unsafeProjectPolygon(poly,inversePose,poly2D);
}
void math::TPolygonWithPlane::getPlanes(const vector<TPolygon3D> &oldPolys,vector<TPolygonWithPlane> &newPolys) {
size_t N=oldPolys.size();
newPolys.resize(N);
for (size_t i=0;i<N;i++) newPolys[i]=oldPolys[i];
}
bool math::intersect(const TSegment3D &s1,const TSegment3D &s2,TObject3D &obj) {
TObject3D irr;
TLine3D l=TLine3D(s1);
if (!intersect(l,TLine3D(s2),irr)) return false;
if (irr.isPoint()) {
//Both lines cross in a point.
TPoint3D p;
irr.getPoint(p);
if (s1.contains(p)&&s2.contains(p)) {
obj=p;
return true;
} else return false;
} else return intersectInCommonLine(s1,s2,l,obj);
}
bool math::intersect(const TSegment3D &s1,const TPlane &p1,TObject3D &obj) {
if (!intersect(TLine3D(s1),p1,obj)) return false;
if (obj.isLine()) {
//Segment is fully inside the plane, so it is the return value.
obj=s1;
return true;
} else {
//Segment's line intersects the plane in a point. This may be or not be part of the segment.
TPoint3D p;
if (!obj.getPoint(p)) return false;
return s1.contains(p);
}
}
bool math::intersect(const TSegment3D &s1,const TLine3D &r1,TObject3D &obj) {
if (!intersect(TLine3D(s1),r1,obj)) return false;
if (obj.isLine()) {
//Segment's line is the other line.
obj=s1;
return true;
} else {
//Segment's line and the other line cross in a point, which may be or not be inside the segment.
TPoint3D p;
if (!obj.getPoint(p)) return false;
return s1.contains(p);
}
}
bool math::intersect(const TPlane &p1,const TPlane &p2,TObject3D &obj) {
TLine3D lin;
crossProduct3D(p1.coefs,p2.coefs,lin.director);
if ((abs(lin.director[0])<geometryEpsilon)&&(abs(lin.director[1])<geometryEpsilon)&&(abs(lin.director[2])<geometryEpsilon)) {
//Planes are parallel
for (size_t i=0;i<3;i++) if (abs(p1.coefs[i]*p2.coefs[3]-p1.coefs[3]*p2.coefs[i])>=geometryEpsilon) return false;
//Planes are the same
obj=p1;
return true;
} else {
//Planes cross in a line whose director vector is already calculated (normal to both planes' normal).
//The following process manages to create a random point in the line without loss of generality and almost without conditional sentences.
size_t i1=0;
while (abs(lin.director[i1])<geometryEpsilon) i1++;
//At this point, i1 points to a coordinate (0->x, 1->y, 2->z) in which we can move freely.
//If we arbitrarily assign this coordinate to 0, we'll find a suitable base point by solving both planes' equations.
size_t c1=(i1+1)%3,c2=(i1+2)%3;
lin.pBase[i1]=0.0;
lin.pBase[c1]=(p2.coefs[3]*p1.coefs[c2]-p1.coefs[3]*p2.coefs[c2])/lin.director[i1];
lin.pBase[c2]=(p2.coefs[c1]*p1.coefs[3]-p1.coefs[c1]*p2.coefs[3])/lin.director[i1];
lin.unitarize();
obj=lin;
return true;
}
}
bool math::intersect(const TPlane &p1,const TLine3D &r2,TObject3D &obj) {
//double n=p1.coefs[0]*r2.director[0]+p1.coefs[1]*r2.director[1]+p1.coefs[2]*r2.director[2];
double n=dotProduct<3,double>(p1.coefs,r2.director);
double e=p1.evaluatePoint(r2.pBase);
if (abs(n)<geometryEpsilon) {
//Plane's normal and line's director are orthogonal, so both are parallel
if (abs(e)<geometryEpsilon) {
//Line is contained in plane.
obj=r2;
return true;
} else return false;
} else {
//Plane and line cross in a point.
double t=e/n;
TPoint3D p;
p.x=r2.pBase.x-t*r2.director[0];
p.y=r2.pBase.y-t*r2.director[1];
p.z=r2.pBase.z-t*r2.director[2];
obj=p;
return true;
}
}
bool math::intersect(const TLine3D &r1,const TLine3D &r2,TObject3D &obj) {
double u,d[3];
TPoint3D p;
const static size_t c1[]={1,2,0};
const static size_t c2[]={2,0,1};
//With indirect memory accesses, almost all the code goes in a single loop.
for (size_t i=0;i<3;i++) {
double sysDet=-r1.director[c1[i]]*r2.director[c2[i]]+r2.director[c1[i]]*r1.director[c2[i]];
if (abs(sysDet)<geometryEpsilon) continue;
//We've found a coordinate in which we can solve the associated system
d[c1[i]]=r2.pBase[c1[i]]-r1.pBase[c1[i]];
d[c2[i]]=r2.pBase[c2[i]]-r1.pBase[c2[i]];
u=(r1.director[c1[i]]*d[c2[i]]-r1.director[c2[i]]*d[c1[i]])/sysDet;
for (size_t k=0;k<3;k++) p[k]=r2.pBase[k]+u*r2.director[k];
if (r1.contains(p)) {
obj=p;
return true;
} else return false;
}
//Lines are parallel
if (r1.contains(r2.pBase)) {
//Lines are the same
obj=r1;
return true;
} else return false;
}
bool math::intersect(const TLine2D &r1,const TLine2D &r2,TObject2D &obj) {
double sysDet=r1.coefs[0]*r2.coefs[1]-r1.coefs[1]*r2.coefs[0];
if (abs(sysDet)>=geometryEpsilon) {
//Resulting point comes simply from solving an equation.
TPoint2D p;
p.x=(r1.coefs[1]*r2.coefs[2]-r1.coefs[2]*r2.coefs[1])/sysDet;
p.y=(r1.coefs[2]*r2.coefs[0]-r1.coefs[0]*r2.coefs[2])/sysDet;
obj=p;
return true;
} else {
//Lines are parallel
if (abs(r1.coefs[0]*r2.coefs[2]-r1.coefs[2]*r2.coefs[0])>=geometryEpsilon) return false;
if (abs(r1.coefs[1]*r2.coefs[2]-r1.coefs[2]*r2.coefs[1])>=geometryEpsilon) return false;
//Lines are the same
obj=r1;
return true;
}
}
bool math::intersect(const TLine2D &r1,const TSegment2D &s2,TObject2D &obj) {
if (!intersect(r1,TLine2D(s2),obj)) return false;
TPoint2D p;
if (obj.isLine()) {
//Segment is inside the line
obj=s2;
return true;
} else if (obj.getPoint(p)) return s2.contains(p); //Both lines cross in a point.
return false;
}
bool math::intersect(const TSegment2D &s1,const TSegment2D &s2,TObject2D &obj) {
TLine2D lin=TLine2D(s1);
if (!intersect(lin,TLine2D(s2),obj)) return false;
TPoint2D p;
if (obj.isLine()) return intersectInCommonLine(s1,s2,lin,obj); //Segments' lines are parallel
else if (obj.getPoint(p)) return s1.contains(p)&&s2.contains(p); //Segments' lines cross in a point
return false;
}
double math::getAngle(const TPlane &s1,const TPlane &s2) {
double c=0,n1=0,n2=0;
for (size_t i=0;i<3;i++) {
c+=s1.coefs[i]*s2.coefs[i];
n1+=s1.coefs[i]*s1.coefs[i];
n2+=s2.coefs[i]+s2.coefs[i];
}
double s=sqrt(n1*n2);
if (s<geometryEpsilon) throw std::logic_error("Invalid plane(s)");
if (abs(s)<abs(c)) return (c/s<0)?M_PI:0;
else return acos(c/s);
}
double math::getAngle(const TPlane &s1,const TLine3D &r2) {
double c=0,n1=0,n2=0;
for (size_t i=0;i<3;i++) {
c+=s1.coefs[i]*r2.director[i];
n1+=s1.coefs[i]*s1.coefs[i];
n2+=r2.director[i]*r2.director[i];
}
double s=sqrt(n1*n2);
if (s<geometryEpsilon) throw std::logic_error("Invalid plane or line");
if (abs(s)<abs(c)) return M_PI*sign(c/s)/2;
else return asin(c/s);
}
double math::getAngle(const TLine3D &r1,const TLine3D &r2) {
double c=0,n1=0,n2=0;
for (size_t i=0;i<3;i++) {
c+=r1.director[i]*r2.director[i];
n1+=r1.director[i]*r1.director[i];
n2+=r2.director[i]*r2.director[i];
}
double s=sqrt(n1*n2);
if (s<geometryEpsilon) throw std::logic_error("Invalid line(s)");
if (abs(s)<abs(c)) return (c/s<0)?M_PI:0;
else return acos(c/s);
}
double math::getAngle(const TLine2D &r1,const TLine2D &r2) {
double c=0,n1=0,n2=0;
for (size_t i=0;i<2;i++) {
c+=r1.coefs[i]*r2.coefs[i];
n1+=r1.coefs[i]*r1.coefs[i];
n2+=r2.coefs[i]*r2.coefs[i];
}
double s=sqrt(n1*n2);
if (s<geometryEpsilon) throw std::logic_error("Invalid line(s)");
if (abs(s)<abs(c)) return (c/s<0)?M_PI:0;
else return acos(c/sqrt(n1*n2));
}
//Auxiliary method
void createFromPoseAndAxis(const CPose3D &p,TLine3D &r,size_t axis) {
CMatrixDouble44 m = p.getHomogeneousMatrixVal();
for (size_t i=0;i<3;i++) {
r.pBase[i]=m.get_unsafe(i,3);
r.director[i]=m.get_unsafe(i,axis);
}
}
//End of auxiliary method
void math::createFromPoseX(const CPose3D &p,TLine3D &r) {
createFromPoseAndAxis(p,r,0);
}
void math::createFromPoseY(const CPose3D &p,TLine3D &r) {
createFromPoseAndAxis(p,r,1);
}
void math::createFromPoseZ(const CPose3D &p,TLine3D &r) {
createFromPoseAndAxis(p,r,2);
}
void math::createFromPoseAndVector(const CPose3D &p,const double (&vector)[3],TLine3D &r) {
CMatrixDouble44 m=p.getHomogeneousMatrixVal();
for (size_t i=0;i<3;i++) {
r.pBase[i]=m.get_unsafe(i,3);
r.director[i]=0;
for (size_t j=0;j<3;j++) r.director[i]+=m.get_unsafe(i,j)*vector[j];
}
}
void math::createFromPoseX(const TPose2D &p,TLine2D &r) {
r.coefs[0]=cos(p.phi);
r.coefs[1]=-sin(p.phi);
r.coefs[2]=-r.coefs[0]*p.x-r.coefs[1]*p.y;
}
void math::createFromPoseY(const TPose2D &p,TLine2D &r) {
r.coefs[0]=sin(p.phi);
r.coefs[1]=cos(p.phi);
r.coefs[2]=-r.coefs[0]*p.x-r.coefs[1]*p.y;
}
void math::createFromPoseAndVector(const TPose2D &p,const double (&vector)[2],TLine2D &r) {
double c=cos(p.phi);
double s=sin(p.phi);
r.coefs[0]=vector[0]*c+vector[1]*s;
r.coefs[1]=-vector[0]*s+vector[1]*c;
r.coefs[2]=-r.coefs[0]*p.x-r.coefs[1]*p.y;
}
bool math::conformAPlane(const std::vector<TPoint3D> &points) {
size_t N=points.size();
if (N<3) return false;
CMatrixTemplateNumeric<double> mat(N-1,3);
const TPoint3D &orig=points[N-1];
for (size_t i=0;i<N-1;i++) {
const TPoint3D &p=points[i];
mat(i,0)=p.x-orig.x;
mat(i,1)=p.y-orig.y;
mat(i,2)=p.z-orig.z;
}
return mat.rank(geometryEpsilon)==2;
}
bool math::conformAPlane(const std::vector<TPoint3D> &points,TPlane &p) {
return abs(getRegressionPlane(points,p))<geometryEpsilon;
}
bool math::areAligned(const std::vector<TPoint2D> &points) {
size_t N=points.size();
if (N<2) return false;
CMatrixTemplateNumeric<double> mat(N-1,2);
const TPoint2D &orig=points[N-1];
for (size_t i=0;i<N-1;i++) {
const TPoint2D &p=points[i];
mat(i,0)=p.x-orig.x;
mat(i,1)=p.y-orig.y;
}
return mat.rank(geometryEpsilon)==1;
}
bool math::areAligned(const std::vector<TPoint2D> &points,TLine2D &r) {
if (!areAligned(points)) return false;
const TPoint2D &p0=points[0];
for (size_t i=1;;i++) try {
r=TLine2D(p0,points[i]);
return true;
} catch (logic_error &) {}
}
bool math::areAligned(const std::vector<TPoint3D> &points) {
size_t N=points.size();
if (N<2) return false;
CMatrixTemplateNumeric<double> mat(N-1,3);
const TPoint3D &orig=points[N-1];
for (size_t i=0;i<N-1;i++) {
const TPoint3D &p=points[i];
mat(i,0)=p.x-orig.x;
mat(i,1)=p.y-orig.y;
mat(i,2)=p.z-orig.z;
}
return mat.rank(geometryEpsilon)==1;
}
bool math::areAligned(const std::vector<TPoint3D> &points,TLine3D &r) {
if (!areAligned(points)) return false;
const TPoint3D &p0=points[0];
for (size_t i=1;;i++) try {
r=TLine3D(p0,points[i]);
return true;
} catch (logic_error &) {}
}
void math::project3D(const TLine3D &line,const CPose3D &newXYpose,TLine3D &newLine) {
newXYpose.composePoint(line.pBase.x,line.pBase.y,line.pBase.z,newLine.pBase.x,newLine.pBase.y,newLine.pBase.z);
CMatrixDouble44 mat=newXYpose.getHomogeneousMatrixVal();
for (size_t i=0;i<3;i++) {
newLine.director[i]=0;
for (size_t j=0;j<3;j++) newLine.director[i]+=mat.get_unsafe(i,j)*line.director[j];
}
newLine.unitarize();
}
void math::project3D(const TPlane &plane,const CPose3D &newXYpose,TPlane &newPlane) {
CMatrixDouble44 mat=newXYpose.getHomogeneousMatrixVal();
for (size_t i=0;i<3;i++) {
newPlane.coefs[i]=0;
for (size_t j=0;j<3;j++) newPlane.coefs[i]+=mat.get_unsafe(i,j)*plane.coefs[j];
}
//VORSICHT! NO INTENTEN HACER ESTO EN SUS CASAS (nota: comentar sí o sí, más tarde)
//La idea es mantener la distancia al nuevo origen igual a la distancia del punto original antes de proyectar.
//newPlane.coefs[3]=plane.evaluatePoint(TPoint3D(CPose3D(0,0,0,0,0,0)-newXYpose))*sqrt((newPlane.coefs[0]*newPlane.coefs[0]+newPlane.coefs[1]*newPlane.coefs[1]+newPlane.coefs[2]*newPlane.coefs[2])/(plane.coefs[0]*plane.coefs[0]+plane.coefs[1]*plane.coefs[1]+plane.coefs[2]*plane.coefs[2]));
newPlane.coefs[3]=plane.evaluatePoint(TPoint3D(-newXYpose))*sqrt(squareNorm<3,double>(newPlane.coefs)/squareNorm<3,double>(plane.coefs));
newPlane.unitarize();
}
void math::project3D(const TPolygon3D &polygon,const CPose3D &newXYpose,TPolygon3D &newPolygon) {
size_t N=polygon.size();
newPolygon.resize(N);
for (size_t i=0;i<N;i++) project3D(polygon[i],newXYpose,newPolygon[i]);
}
void math::project3D(const TObject3D &object,const CPose3D &newXYpose,TObject3D &newObject) {
switch (object.getType()) {
case GEOMETRIC_TYPE_POINT:
{
TPoint3D p,p2;
object.getPoint(p);
project3D(p,newXYpose,p2);
newObject=p2;
break;
}
case GEOMETRIC_TYPE_SEGMENT:
{
TSegment3D p,p2;
object.getSegment(p);
project3D(p,newXYpose,p2);
newObject=p2;
break;
}
case GEOMETRIC_TYPE_LINE:
{
TLine3D p,p2;
object.getLine(p);
project3D(p,newXYpose,p2);
newObject=p2;
break;
}
case GEOMETRIC_TYPE_PLANE:
{
TPlane p,p2;
object.getPlane(p);
project3D(p,newXYpose,p2);
newObject=p2;
break;
}
case GEOMETRIC_TYPE_POLYGON:
{
TPolygon3D p,p2;
object.getPolygon(p);
project3D(p,newXYpose,p2);
newObject=p2;
break;
}
default:
newObject=TObject3D();
}
}
void math::project2D(const TPoint2D &point,const mrpt::poses::CPose2D &newXpose,TPoint2D &newPoint) {
newPoint=newXpose+mrpt::poses::CPoint2D(point);
}
void math::project2D(const TLine2D &line,const CPose2D &newXpose,TLine2D &newLine) {
double c=cos(newXpose.phi());
double s=sin(newXpose.phi());
newLine.coefs[0]=line.coefs[0]*c-line.coefs[1]*s;
newLine.coefs[1]=line.coefs[1]*c+line.coefs[0]*s;
newLine.coefs[2]=line.coefs[2]-(newLine.coefs[0]*newXpose.x()+newLine.coefs[1]*newXpose.y());
return;
}
void math::project2D(const TPolygon2D &line,const CPose2D &newXpose,TPolygon2D &newLine) {
size_t N=line.size();
newLine.resize(N);
for (size_t i=0;i<N;i++) newLine[i]=newXpose+line[i];
return;
}
void math::project2D(const TObject2D &obj,const CPose2D &newXpose,TObject2D &newObject) {
switch (obj.getType()) {
case GEOMETRIC_TYPE_POINT:
{
TPoint2D p,p2;
obj.getPoint(p);
project2D(p,newXpose,p2);
newObject=p2;
break;
}
case GEOMETRIC_TYPE_SEGMENT:
{
TSegment2D p,p2;
obj.getSegment(p);
project2D(p,newXpose,p2);
newObject=p2;
break;
}
case GEOMETRIC_TYPE_LINE:
{
TLine2D p,p2;
obj.getLine(p);
project2D(p,newXpose,p2);
newObject=p2;
break;
}
case GEOMETRIC_TYPE_POLYGON:
{
TPolygon2D p,p2;
obj.getPolygon(p);
project2D(p,newXpose,p2);
newObject=p2;
break;
}
default:
newObject=TObject2D();
}
}
bool math::intersect(const TPolygon2D &p1,const TSegment2D &s2,TObject2D &obj) {
TLine2D l2=TLine2D(s2);
if (!intersect(p1,l2,obj)) return false;
TPoint2D p;
TSegment2D s;
if (obj.getPoint(p)) return s2.contains(p);
else if (obj.getSegment(s)) return intersectInCommonLine(s,s2,l2,obj);
return false;
}
bool math::intersect(const TPolygon2D &p1,const TLine2D &r2,TObject2D &obj) {
//Proceeding: project polygon so that the line happens to be y=0 (phi=0).
//Then, search this new polygons for intersections with the X axis (very simple).
if (p1.size()<3) return false;
CPose2D pose,poseNeg;
r2.getAsPose2D(pose);
poseNeg=CPose2D(0,0,0)-pose;
TPolygon2D projPoly;
project2D(p1,poseNeg,projPoly);
size_t N=projPoly.size();
projPoly.push_back(projPoly[0]);
double pre=projPoly[0].y;
vector<TPoint2D> pnts;
pnts.reserve(2);
for (size_t i=1;i<=N;i++) {
double cur=projPoly[i].y;
if (abs(cur)<geometryEpsilon) {
if (abs(pre)<geometryEpsilon) {
pnts.resize(2);
pnts[0]=projPoly[i-1];
pnts[1]=projPoly[i];
break;
} else pnts.push_back(projPoly[i]);
} else if ((abs(pre)>=geometryEpsilon)&&(sign(cur)!=sign(pre))) {
double a=projPoly[i-1].x;
double c=projPoly[i].x;
double x=a-pre*(c-a)/(cur-pre);
pnts.push_back(TPoint2D(x,0));
}
pre=cur;
}
//All results must undo the initial projection
switch (pnts.size()) {
case 0:
return false;
case 1:
{
TPoint2D p;
project2D(pnts[0],pose,p);
obj=p;
return true;
}
case 2:
{
TSegment2D s;
project2D(TSegment2D(pnts[0],pnts[1]),pose,s);
obj=s;
return true;
}
default:
throw std::logic_error("Polygon is not convex");
}
}
//Auxiliary structs and code for 2D polygon intersection
struct T2ListsOfSegments {
vector<TSegment2D> l1;
vector<TSegment2D> l2;
};
struct TCommonRegion {
unsigned char type; //0 -> point, 1-> segment, any other-> empty
union {
TPoint2D *point;
TSegment2D *segment;
} data;
void destroy() {
switch (type) {
case 0:
delete data.point;
break;
case 1:
delete data.segment;
break;
}
type=255;
}
TCommonRegion(const TPoint2D &p):type(0) {
data.point=new TPoint2D(p);
}
TCommonRegion(const TSegment2D &s):type(1) {
data.segment=new TSegment2D(s);
}
~TCommonRegion() {
destroy();
}
TCommonRegion & operator=(const TCommonRegion &r) {
if (&r==this) return *this;
destroy();
switch (type=r.type) {
case 0:
data.point=new TPoint2D(*(r.data.point));
break;
case 1:
data.segment=new TSegment2D(*(r.data.segment));
break;
}
return *this;
}
TCommonRegion(const TCommonRegion &r):type(0) {
operator=(r);
}
};
struct TTempIntersection {
unsigned char type; //0->two lists of segments, 1-> common region
union {
T2ListsOfSegments *segms;
TCommonRegion *common;
} data;
void destroy() {
switch (type) {
case 0:
delete data.segms;
break;
case 1:
delete data.common;
break;
}
type=255;
};
TTempIntersection(const T2ListsOfSegments &segms):type(0) {
data.segms=new T2ListsOfSegments(segms);
}
TTempIntersection(const TCommonRegion &common):type(1) {
data.common=new TCommonRegion(common);
}
~TTempIntersection() {
destroy();
}
TTempIntersection & operator=(const TTempIntersection &t) {
if (&t==this) return *this;
destroy();
switch (type=t.type) {
case 0:
data.segms=new T2ListsOfSegments(*(t.data.segms));
break;
case 1:
data.common=new TCommonRegion(*(t.data.common));
break;
}
return *this;
}
TTempIntersection(const TTempIntersection &t):type(0) {
operator=(t);
}
};
struct TSegmentWithLine {
TSegment2D segment;
TLine2D line;
explicit TSegmentWithLine(const TSegment2D &s):segment(s) {
line=TLine2D(s[0],s[1]);
}
TSegmentWithLine(const TPoint2D &p1,const TPoint2D &p2):segment(p1,p2) {
line=TLine2D(p1,p2);
}
TSegmentWithLine() {}
};
bool intersect(const TSegmentWithLine &s1,const TSegmentWithLine &s2,TObject2D &obj) {
if (!intersect(s1.line,s2.line,obj)) return false;
if (obj.isLine()) return intersectInCommonLine(s1.segment,s2.segment,s1.line,obj);
TPoint2D p;
obj.getPoint(p);
return s1.segment.contains(p)&&s2.segment.contains(p);
}
void getSegmentsWithLine(const TPolygon2D &poly,vector<TSegmentWithLine> &segs) {
size_t N=poly.size();
segs.resize(N);
for (size_t i=0;i<N-1;i++) segs[i]=TSegmentWithLine(poly[i],poly[i+1]);
segs[N-1]=TSegmentWithLine(poly[N-1],poly[0]);
}
inline char fromObject(const TObject2D &obj) {
switch (obj.getType()) {
case GEOMETRIC_TYPE_POINT:return 'P';
case GEOMETRIC_TYPE_SEGMENT:return 'S';
case GEOMETRIC_TYPE_LINE:return 'L';
case GEOMETRIC_TYPE_POLYGON:return 'O';
default:return 'U';
}
}
bool math::intersect(const TPolygon2D &/*p1*/,const TPolygon2D &/*p2*/,TObject2D &/*obj*/) {
THROW_EXCEPTION("TODO");
#if 0
return false; //TODO
CSparseMatrixTemplate<TObject2D> intersections=CSparseMatrixTemplate<TObject2D>(p1.size(),p2.size());
std::vector<TSegmentWithLine> segs1,segs2;
getSegmentsWithLine(p1,segs1);
getSegmentsWithLine(p2,segs2);
unsigned int hmInters=0;
for (size_t i=0;i<segs1.size();i++) {
const TSegmentWithLine &s1=segs1[i];
for (size_t j=0;j<segs2.size();j++) if (intersect(s1,segs2[j],obj)) {
intersections(i,j)=obj;
hmInters++;
}
}
for (size_t i=0;i<intersections.getRowCount();i++) {
for (size_t j=0;j<intersections.getColCount();j++) cout<<fromObject(intersections(i,j));
cout<<'\n';
}
if (hmInters==0) {
if (p1.contains(p2[0])) {
obj=p2;
return true;
} else if (p2.contains(p1[0])) {
obj=p1;
return true;
} else return false;
}
//ESTO ES UNA PESADILLA, HAY CIEN MILLONES DE CASOS DISTINTOS A LA HORA DE RECORRER LAS POSIBILIDADES...
/*
Dividir cada segmento en sus distintas partes según sus intersecciones, y generar un nuevo polígono.
Recorrer de segmento en segmento, por cada uno de los dos lados (recorriendo desde un punto común a otro;
en un polígono se escoge el camino secuencial directo, mientras que del otro se escoge, de los dos posibles,
el que no se corta con ningún elemento del primero).
Seleccionar, para cada segmento, si está dentro o fuera.
Parece fácil, pero es una puta mierda.
TODO: hacer en algún momento de mucho tiempo libre...
*/
/* ¿Seguir? */
return false;
#endif
}
bool math::intersect(const TPolygon3D &p1,const TSegment3D &s2,TObject3D &obj) {
TPlane p;
if (!p1.getPlane(p)) return false;
if (!intersect(p,s2,obj)) return false;
TPoint3D pnt;
TSegment3D sgm;
if (obj.getPoint(pnt)) {
CPose3D pose;
p.getAsPose3DForcingOrigin(p1[0],pose);
CPose3D poseNeg=CPose3D(0,0,0,0,0,0)-pose;
TPolygon3D projPoly;
TPoint3D projPnt;
project3D(p1,poseNeg,projPoly);
project3D(pnt,poseNeg,projPnt);
return TPolygon2D(projPoly).contains(TPoint2D(projPnt));
} else if (obj.getSegment(sgm)) return intersectInCommonPlane<TPolygon2D,TSegment2D>(p1,s2,p,obj);
return false;
}
bool math::intersect(const TPolygon3D &p1,const TLine3D &r2,TObject3D &obj) {
TPlane p;
if (!p1.getPlane(p)) return false;
if (!intersect(p,r2,obj)) return false;
TPoint3D pnt;
if (obj.getPoint(pnt)) {
CPose3D pose;
p.getAsPose3DForcingOrigin(p1[0],pose);
CPose3D poseNeg=CPose3D(0,0,0,0,0,0)-pose;
TPolygon3D projPoly;
TPoint3D projPnt;
project3D(p1,poseNeg,projPoly);
project3D(pnt,poseNeg,projPnt);
return TPolygon2D(projPoly).contains(TPoint2D(projPnt));
} else if (obj.isLine()) return intersectInCommonPlane<TPolygon2D,TLine2D>(p1,r2,p,obj);
return false;
}
bool math::intersect(const TPolygon3D &p1,const TPlane &p2,TObject3D &obj) {
TPlane p;
if (!p1.getPlane(p)) return false;
if (!intersect(p,p2,obj)) return false;
TLine3D ln;
if (obj.isPlane()) {
//Polygon is inside the plane
obj=p1;
return true;
} else if (obj.getLine(ln)) return intersectInCommonPlane<TPolygon2D,TLine2D>(p1,ln,p,obj);
return false;
}
//Auxiliary function2
bool intersectAux(const TPolygon3D &p1,const TPlane &pl1,const TPolygon3D &p2,const TPlane &pl2,TObject3D &obj) {
if (!intersect(pl1,pl2,obj)) return false;
TLine3D ln;
if (obj.isPlane()) return intersectInCommonPlane<TPolygon2D,TPolygon2D>(p1,p2,pl1,obj); //Polygons are on the same plane
else if (obj.getLine(ln)) {
TObject3D obj1,obj2;
if (!intersectInCommonPlane<TPolygon2D,TLine2D>(p1,ln,pl1,obj1)) return false;
if (!intersectInCommonPlane<TPolygon2D,TLine2D>(p2,ln,pl2,obj2)) return false;
TPoint3D po1,po2;
TSegment3D s1,s2;
if (obj1.getPoint(po1)) s1=TSegment3D(po1,po1);
else obj1.getSegment(s1);
if (obj2.getPoint(po2)) s2=TSegment3D(po2,po2);
else obj2.getSegment(s2);
return intersectInCommonLine(s1,s2,ln,obj);
}
return false;
}
bool compatibleBounds(const TPoint3D &min1,const TPoint3D &max1,const TPoint3D &min2,const TPoint3D &max2) {
for (size_t i=0;i<3;i++) if ((min1[i]>max2[i])||(min2[i]>max1[i])) return false;
return true;
}
//End of auxiliary functions
bool math::intersect(const TPolygon3D &p1,const TPolygon3D &p2,TObject3D &obj) {
TPoint3D min1,max1,min2,max2;
getPrismBounds(p1,min1,max1);
getPrismBounds(p2,min2,max2);
if (!compatibleBounds(min1,max1,min2,max2)) return false;
TPlane pl1,pl2;
if (!p1.getPlane(pl1)) return false;
if (!p2.getPlane(pl2)) return false;
return intersectAux(p1,pl1,p2,pl2,obj);
}
//Auxiliary function
inline void getPlanes(const std::vector<TPolygon3D> &polys,std::vector<TPlane> &planes) {
size_t N=polys.size();
planes.resize(N);
for (size_t i=0;i<N;i++) getRegressionPlane(polys[i],planes[i]);
}
//Auxiliary functions
void getMinAndMaxBounds(const std::vector<TPolygon3D> &v1,std::vector<TPoint3D> &minP,std::vector<TPoint3D> &maxP) {
minP.resize(0);
maxP.resize(0);
size_t N=v1.size();
minP.reserve(N);
maxP.reserve(N);
TPoint3D p1,p2;
for (std::vector<TPolygon3D>::const_iterator it=v1.begin();it!=v1.end();++it) {
getPrismBounds(*it,p1,p2);
minP.push_back(p1);
maxP.push_back(p2);
}
}
size_t math::intersect(const std::vector<TPolygon3D> &v1,const std::vector<TPolygon3D> &v2,CSparseMatrixTemplate<TObject3D> &objs) {
std::vector<TPlane> w1,w2;
getPlanes(v1,w1);
getPlanes(v2,w2);
std::vector<TPoint3D> minBounds1,maxBounds1,minBounds2,maxBounds2;
getMinAndMaxBounds(v1,minBounds1,maxBounds1);
getMinAndMaxBounds(v2,minBounds2,maxBounds2);
size_t M=v1.size(),N=v2.size();
objs.clear();
objs.resize(M,N);
TObject3D obj;
for (size_t i=0;i<M;i++) for (size_t j=0;j<N;j++) if (!compatibleBounds(minBounds1[i],maxBounds1[i],minBounds2[j],maxBounds2[j])) continue;
else if (intersectAux(v1[i],w1[i],v2[j],w2[j],obj)) objs(i,j)=obj;
return objs.getNonNullElements();
}
size_t math::intersect(const std::vector<TPolygon3D> &v1,const std::vector<TPolygon3D> &v2,std::vector<TObject3D> &objs) {
objs.resize(0);
std::vector<TPlane> w1,w2;
getPlanes(v1,w1);
getPlanes(v2,w2);
std::vector<TPoint3D> minBounds1,maxBounds1,minBounds2,maxBounds2;
getMinAndMaxBounds(v1,minBounds1,maxBounds1);
getMinAndMaxBounds(v2,minBounds2,maxBounds2);
TObject3D obj;
std::vector<TPlane>::const_iterator itP1=w1.begin();
std::vector<TPoint3D>::const_iterator itMin1=minBounds1.begin();
std::vector<TPoint3D>::const_iterator itMax1=maxBounds1.begin();
for (std::vector<TPolygon3D>::const_iterator it1=v1.begin();it1!=v1.end();++it1,++itP1,++itMin1,++itMax1) {
const TPolygon3D &poly1=*it1;
const TPlane &plane1=*itP1;
std::vector<TPlane>::const_iterator itP2=w2.begin();
const TPoint3D &min1=*itMin1,max1=*itMax1;
std::vector<TPoint3D>::const_iterator itMin2=minBounds2.begin();
std::vector<TPoint3D>::const_iterator itMax2=maxBounds2.begin();
for (std::vector<TPolygon3D>::const_iterator it2=v2.begin();it2!=v2.end();++it2,++itP2,++itMin2,++itMax2) if (!compatibleBounds(min1,max1,*itMin2,*itMax2)) continue;
else if (intersectAux(poly1,plane1,*it2,*itP2,obj)) objs.push_back(obj);
}
return objs.size();
}
bool math::intersect(const TObject2D &o1,const TObject2D &o2,TObject2D &obj) {
TPoint2D p1,p2;
TSegment2D s1,s2;
TLine2D l1,l2;
TPolygon2D po1,po2;
if (o1.getPoint(p1)) {
obj=p1;
if (o2.getPoint(p2)) return distance(p1,p2)<geometryEpsilon;
else if (o2.getSegment(s2)) return s2.contains(p1);
else if (o2.getLine(l2)) return l2.contains(p1);
else if (o2.getPolygon(po2)) return po2.contains(p1); //else return false;
} else if (o1.getSegment(s1)) {
if (o2.getPoint(p2)) {
if (s1.contains(p2)) {
obj=p2;
return true;
} //else return false;
} else if (o2.getSegment(s2)) return intersect(s1,s2,obj);
else if (o2.getLine(l2)) return intersect(s1,l2,obj);
else if (o2.getPolygon(po2)) return intersect(s1,po2,obj); //else return false;
} else if (o1.getLine(l1)) {
if (o2.getPoint(p2)) {
if (l1.contains(p2)) {
obj=p2;
return true;
} //else return false;
} else if (o2.getSegment(s2)) return intersect(l1,s2,obj);
else if (o2.getLine(l2)) return intersect(l1,l2,obj);
else if (o2.getPolygon(po2)) return intersect(l1,po2,obj); //else return false;
} else if (o1.getPolygon(po1)) {
if (o2.getPoint(p2)) {
if (po1.contains(p2)) {
obj=p2;
return true;
} //else return false;
} else if (o2.getSegment(s2)) return intersect(po1,s2,obj);
else if (o2.getLine(l2)) return intersect(po1,l2,obj);
else if (o2.getPolygon(po2)) return intersect(po1,po2,obj); //else return false;
} //else return false;
return false;
}
bool math::intersect(const TObject3D &o1,const TObject3D &o2,TObject3D &obj) {
TPoint3D p1,p2;
TSegment3D s1,s2;
TLine3D l1,l2;
TPolygon3D po1,po2;
TPlane pl1,pl2;
if (o1.getPoint(p1)) {
obj=p1;
if (o2.getPoint(p2)) return distance(p1,p2)<geometryEpsilon;
else if (o2.getSegment(s2)) return s2.contains(p1);
else if (o2.getLine(l2)) return l2.contains(p1);
else if (o2.getPolygon(po2)) return po2.contains(p1);
else if (o2.getPlane(pl2)) return pl2.contains(p1); //else return false;
} else if (o1.getSegment(s1)) {
if (o2.getPoint(p2)) {
if (s1.contains(p2)) {
obj=p2;
return true;
} //else return false;
} else if (o2.getSegment(s2)) return intersect(s1,s2,obj);
else if (o2.getLine(l2)) return intersect(s1,l2,obj);
else if (o2.getPolygon(po2)) return intersect(s1,po2,obj);
else if (o2.getPlane(pl2)) return intersect(s1,pl2,obj); //else return false;
} else if (o1.getLine(l1)) {
if (o2.getPoint(p2)) {
if (l1.contains(p2)) {
obj=p2;
return true;
} //else return false;
} else if (o2.getSegment(s2)) return intersect(l1,s2,obj);
else if (o2.getLine(l2)) return intersect(l1,l2,obj);
else if (o2.getPolygon(po2)) return intersect(l1,po2,obj);
else if (o2.getPlane(pl2)) return intersect(l2,pl2,obj); //else return false;
} else if (o1.getPolygon(po1)) {
if (o2.getPoint(p2)) {
if (po1.contains(p2)) {
obj=p2;
return true;
} //else return false;
} else if (o2.getSegment(s2)) return intersect(po1,s2,obj);
else if (o2.getLine(l2)) return intersect(po1,l2,obj);
else if (o2.getPolygon(po2)) return intersect(po1,po2,obj);
else if (o2.getPlane(pl2)) return intersect(po1,pl2,obj); //else return false;
} else if (o1.getPlane(pl1)) {
if (o2.getPoint(p2)) {
if (pl1.contains(p2)) {
obj=p2;
return true;
} //else return false;
} else if (o2.getSegment(s2)) return intersect(pl1,s2,obj);
else if (o2.getLine(l2)) return intersect(pl1,l2,obj);
else if (o2.getPlane(pl2)) return intersect(pl1,pl2,obj); //else return false;
} //else return false;
return false;
}
double math::distance(const TPoint2D &p1,const TPoint2D &p2) {
double dx=p2.x-p1.x;
double dy=p2.y-p1.y;
return sqrt(dx*dx+dy*dy);
}
double math::distance(const TPoint3D &p1,const TPoint3D &p2) {
double dx=p2.x-p1.x;
double dy=p2.y-p1.y;
double dz=p2.z-p1.z;
return sqrt(dx*dx+dy*dy+dz*dz);
}
void math::getRectangleBounds(const std::vector<TPoint2D> &poly,TPoint2D &pMin,TPoint2D &pMax) {
size_t N=poly.size();
if (N<1) throw logic_error("Empty polygon");
pMin=poly[0];
pMax=poly[0];
for (size_t i=1;i<N;i++) {
pMin.x=min(pMin.x,poly[i].x);
pMin.y=min(pMin.y,poly[i].y);
pMax.x=max(pMax.x,poly[i].x);
pMax.y=max(pMax.y,poly[i].y);
}
}
double math::distance(const TLine2D &r1,const TLine2D &r2) {
if (abs(r1.coefs[0]*r2.coefs[1]-r2.coefs[0]*r1.coefs[1])<geometryEpsilon) {
//Lines are parallel
size_t i1=(abs(r1.coefs[0])<geometryEpsilon)?0:1;
TPoint2D p;
p[i1]=0.0;
p[1-i1]=-r1.coefs[2]/r1.coefs[1-i1];
return r2.distance(p);
} else return 0; //Lines cross in some point
}
double math::distance(const TLine3D &r1,const TLine3D &r2) {
if (abs(getAngle(r1,r2))<geometryEpsilon) return r1.distance(r2.pBase); //Lines are parallel
else {
//We build a plane parallel to r2 which contains r1
TPlane p;
crossProduct3D(r1.director,r2.director,p.coefs);
p.coefs[3]=-(p.coefs[0]*r1.pBase[0]+p.coefs[1]*r1.pBase[1]+p.coefs[2]*r1.pBase[2]);
return p.distance(r2.pBase);
}
}
double math::distance(const TPlane &p1,const TPlane &p2) {
if (abs(getAngle(p1,p2))<geometryEpsilon) {
//Planes are parallel
TPoint3D p(0,0,0);
for (size_t i=0;i<3;i++) if (abs(p1.coefs[i])>=geometryEpsilon) {
p[i]=-p1.coefs[3]/p1.coefs[i];
break;
}
return p2.distance(p);
} else return 0; //Planes cross in a line
}
double math::distance(const TPolygon2D &p1,const TPolygon2D &p2) {
MRPT_UNUSED_PARAM(p1); MRPT_UNUSED_PARAM(p2);
THROW_EXCEPTION("TO DO:distance(TPolygon2D,TPolygon2D)");
}
double math::distance(const TPolygon2D &p1,const TSegment2D &s2) {
MRPT_UNUSED_PARAM(p1); MRPT_UNUSED_PARAM(s2);
THROW_EXCEPTION("TO DO:distance(TPolygon2D,TSegment)");
}
double math::distance(const TPolygon2D &p1,const TLine2D &l2) {
MRPT_UNUSED_PARAM(p1); MRPT_UNUSED_PARAM(l2);
THROW_EXCEPTION("TO DO:distance(TPolygon2D,TLine2D)");
}
double math::distance(const TPolygon3D &p1,const TPolygon3D &p2) {
MRPT_UNUSED_PARAM(p1); MRPT_UNUSED_PARAM(p2);
THROW_EXCEPTION("TO DO:distance(TPolygon3D,TPolygon3D");
}
double math::distance(const TPolygon3D &p1,const TSegment3D &s2) {
MRPT_UNUSED_PARAM(p1); MRPT_UNUSED_PARAM(s2);
THROW_EXCEPTION("TO DO:distance(TPolygon3D,TSegment3D");
}
double math::distance(const TPolygon3D &p1,const TLine3D &l2) {
MRPT_UNUSED_PARAM(p1); MRPT_UNUSED_PARAM(l2);
THROW_EXCEPTION("TO DO:distance(TPolygon3D,TLine3D");
}
double math::distance(const TPolygon3D &po,const TPlane &pl) {
MRPT_UNUSED_PARAM(po); MRPT_UNUSED_PARAM(pl);
THROW_EXCEPTION("TO DO:distance(TPolygon3D,TPlane");
}
void math::getPrismBounds(const std::vector<TPoint3D> &poly,TPoint3D &pMin,TPoint3D &pMax) {
size_t N=poly.size();
if (N<1) throw logic_error("Empty polygon");
pMin=poly[0];
pMax=poly[0];
for (size_t i=1;i<N;i++) {
pMin.x=min(pMin.x,poly[i].x);
pMin.y=min(pMin.y,poly[i].y);
pMin.z=min(pMin.z,poly[i].z);
pMax.x=max(pMax.x,poly[i].x);
pMax.y=max(pMax.y,poly[i].y);
pMax.z=max(pMax.z,poly[i].z);
}
}
void createPlaneFromPoseAndAxis(const CPose3D &pose,TPlane &plane,size_t axis) {
plane.coefs[3]=0;
CMatrixDouble44 m=pose.getHomogeneousMatrixVal();
for (size_t i=0;i<3;i++) {
plane.coefs[i]=m.get_unsafe(i,axis);
plane.coefs[3]-=plane.coefs[i]*m.get_unsafe(i,3);
}
}
void math::createPlaneFromPoseXY(const CPose3D &pose,TPlane &plane) {
createPlaneFromPoseAndAxis(pose,plane,2);
}
void math::createPlaneFromPoseXZ(const CPose3D &pose,TPlane &plane) {
createPlaneFromPoseAndAxis(pose,plane,1);
}
void math::createPlaneFromPoseYZ(const CPose3D &pose,TPlane &plane) {
createPlaneFromPoseAndAxis(pose,plane,0);
}
void math::createPlaneFromPoseAndNormal(const CPose3D &pose,const double (&normal)[3],TPlane &plane) {
plane.coefs[3]=0;
CMatrixDouble44 m=pose.getHomogeneousMatrixVal();
for (size_t i=0;i<3;i++) {
plane.coefs[i]=0;
for (size_t j=0;j<3;j++) plane.coefs[i]+=normal[j]*m.get_unsafe(i,j);
plane.coefs[3]-=plane.coefs[i]*m.get_unsafe(i,3);
}
}
void math::generateAxisBaseFromDirectionAndAxis(const double (&vec)[3],char coord,CMatrixDouble &matrix) {
//Assumes vector is unitary.
//coord: 0=x, 1=y, 2=z.
char coord1=(coord+1)%3;
char coord2=(coord+2)%3;
matrix.setSize(4,4);
for (size_t i=0;i<3;i++) matrix.set_unsafe(i,coord,vec[i]);
matrix.set_unsafe(0,coord1,0);
double h=hypot(vec[1],vec[2]);
if (h<geometryEpsilon) {
matrix.set_unsafe(1,coord1,1);
matrix.set_unsafe(2,coord1,0);
} else {
matrix.set_unsafe(1,coord1,-vec[2]/h);
matrix.set_unsafe(2,coord1,vec[1]/h);
}
matrix.set_unsafe(0,coord2,matrix.get_unsafe(1,coord)*matrix.get_unsafe(2,coord1)-matrix.get_unsafe(2,coord)*matrix.get_unsafe(1,coord1));
matrix.set_unsafe(1,coord2,matrix.get_unsafe(2,coord)*matrix.get_unsafe(0,coord1)-matrix.get_unsafe(0,coord)*matrix.get_unsafe(2,coord1));
matrix.set_unsafe(2,coord2,matrix.get_unsafe(0,coord)*matrix.get_unsafe(1,coord1)-matrix.get_unsafe(1,coord)*matrix.get_unsafe(0,coord1));
}
double math::getRegressionLine(const vector<TPoint2D> &points,TLine2D &line) {
CArrayDouble<2> means;
CMatrixTemplateNumeric<double> covars(2,2),eigenVal(2,2),eigenVec(2,2);
covariancesAndMean(points,covars,means);
covars.eigenVectors(eigenVec,eigenVal);
size_t selected=(eigenVal.get_unsafe(0,0)>=eigenVal.get_unsafe(1,1))?0:1;
line.coefs[0]=-eigenVec.get_unsafe(1,selected);
line.coefs[1]=eigenVec.get_unsafe(0,selected);
line.coefs[2]=-line.coefs[0]*means[0]-line.coefs[1]*means[1];
return sqrt(eigenVal.get_unsafe(1-selected,1-selected)/eigenVal.get_unsafe(selected,selected));
}
template<class T>
inline size_t getIndexOfMin(const T &e1,const T &e2,const T &e3) {
return (e1<e2)?((e1<e3)?0:2):((e2<e3)?1:2);
}
template<class T>
inline size_t getIndexOfMax(const T &e1,const T &e2,const T &e3) {
return (e1>e2)?((e1>e3)?0:2):((e2>e3)?1:2);
}
double math::getRegressionLine(const vector<TPoint3D> &points,TLine3D &line) {
CArrayDouble<3> means;
CMatrixTemplateNumeric<double> covars(3,3),eigenVal(3,3),eigenVec(3,3);
covariancesAndMean(points,covars,means);
covars.eigenVectors(eigenVec,eigenVal);
size_t selected=getIndexOfMax(eigenVal.get_unsafe(0,0),eigenVal.get_unsafe(1,1),eigenVal.get_unsafe(2,2));
for (size_t i=0;i<3;i++) {
line.pBase[i]=means[i];
line.director[i]=eigenVec.get_unsafe(i,selected);
}
size_t i1=(selected+1)%3,i2=(selected+2)%3;
return sqrt((eigenVal.get_unsafe(i1,i1)+eigenVal.get_unsafe(i2,i2))/eigenVal.get_unsafe(selected,selected));
}
double math::getRegressionPlane(const vector<TPoint3D> &points,TPlane &plane) {
vector<double> means;
CMatrixDouble33 covars,eigenVal,eigenVec;
covariancesAndMean(points,covars,means);
covars.eigenVectors(eigenVec,eigenVal);
for (size_t i=0;i<3;++i) if (eigenVal.get_unsafe(i,i)<0&&fabs(eigenVal.get_unsafe(i,i))<geometryEpsilon) eigenVal.set_unsafe(i,i,0);
size_t selected=getIndexOfMin(eigenVal.get_unsafe(0,0),eigenVal.get_unsafe(1,1),eigenVal.get_unsafe(2,2));
plane.coefs[3]=0;
for (size_t i=0;i<3;i++) {
plane.coefs[i]=eigenVec.get_unsafe(i,selected);
plane.coefs[3]-=plane.coefs[i]*means[i];
}
size_t i1=(selected+1)%3,i2=(selected+2)%3;
return sqrt(eigenVal.get_unsafe(selected,selected)/(eigenVal.get_unsafe(i1,i1)+eigenVal.get_unsafe(i2,i2)));
}
void math::assemblePolygons(const std::vector<TSegment3D> &segms,std::vector<TPolygon3D> &polys) {
std::vector<TSegment3D> tmp;
assemblePolygons(segms,polys,tmp);
}
struct MatchingVertex {
size_t seg1;
size_t seg2;
bool seg1Point; //true for point2, false for point1
bool seg2Point; //same
MatchingVertex() {}
MatchingVertex(size_t s1,size_t s2,bool s1p,bool s2p):seg1(s1),seg2(s2),seg1Point(s1p),seg2Point(s2p) {}
};
class FCreatePolygon {
public:
const std::vector<TSegment3D> &segs;
FCreatePolygon(const std::vector<TSegment3D> &s):segs(s) {}
TPolygon3D operator()(const std::vector<MatchingVertex> &vertices) {
TPolygon3D res;
size_t N=vertices.size();
res.reserve(N);
for (std::vector<MatchingVertex>::const_iterator it=vertices.begin();it!=vertices.end();++it) res.push_back(segs[it->seg2][it->seg2Point?1:0]);
return res;
}
};
inline bool firstOrNonPresent(size_t i,const std::vector<MatchingVertex> &v) {
if (v.size()>0&&v[0].seg1==i) return true;
for (std::vector<MatchingVertex>::const_iterator it=v.begin();it!=v.end();++it) if (it->seg1==i||it->seg2==i) return false;
return true;
}
bool depthFirstSearch(const CSparseMatrixTemplate<unsigned char> &mat,std::vector<std::vector<MatchingVertex> > &res,std::vector<bool> &used,size_t searching,unsigned char mask,std::vector<MatchingVertex> ¤t) {
for (size_t i=0;i<mat.getColCount();i++) if (!used[i]&&mat.isNotNull(searching,i)) {
unsigned char match=mat(searching,i)&mask;
if (!match) continue;
else if (firstOrNonPresent(i,current)) {
bool s1p,s2p;
if (true==(s1p=(!(match&3)))) match>>=2;
s2p=!(match&1);
if (current.size()>=2&¤t[0].seg1==i) {
if (s2p!=current[0].seg1Point) {
current.push_back(MatchingVertex(searching,i,s1p,s2p));
for (std::vector<MatchingVertex>::const_iterator it=current.begin();it!=current.end();++it) used[it->seg2]=true;
res.push_back(current);
return true;
} else continue; //Strange shape... not a polygon, although it'll be without the first segment
} else {
current.push_back(MatchingVertex(searching,i,s1p,s2p));
if (depthFirstSearch(mat,res,used,i,s2p?0x3:0xC,current)) return true;
current.pop_back();
}
}
}
//No match has been found. Backtrack
return false;
}
void depthFirstSearch(const CSparseMatrixTemplate<unsigned char> &mat,std::vector<std::vector<MatchingVertex> >&res,std::vector<bool> &used) {
vector<MatchingVertex> cur;
for (size_t i=0;i<used.size();i++) if (!used[i]) if (depthFirstSearch(mat,res,used,i,0xf,cur)) cur.clear();
}
void math::assemblePolygons(const std::vector<TSegment3D> &segms,std::vector<TPolygon3D> &polys,std::vector<TSegment3D> &remainder) {
std::vector<TSegment3D> tmp;
tmp.reserve(segms.size());
for (std::vector<TSegment3D>::const_iterator it=segms.begin();it!=segms.end();++it) if (it->length()>=geometryEpsilon) tmp.push_back(*it);
else remainder.push_back(*it);
size_t N=tmp.size();
CSparseMatrixTemplate<unsigned char> matches(N,N);
for (size_t i=0;i<N-1;i++) for (size_t j=i+1;j<N;j++) {
if (distance(tmp[i].point1,tmp[j].point1)<geometryEpsilon) {
matches(i,j)|=1;
matches(j,i)|=1;
}
if (distance(tmp[i].point1,tmp[j].point2)<geometryEpsilon) {
matches(i,j)|=2;
matches(j,i)|=4;
}
if (distance(tmp[i].point2,tmp[j].point1)<geometryEpsilon) {
matches(i,j)|=4;
matches(j,i)|=2;
}
if (distance(tmp[i].point2,tmp[j].point2)<geometryEpsilon) {
matches(i,j)|=8;
matches(j,i)|=8;
}
}
std::vector<std::vector<MatchingVertex> > results;
std::vector<bool> usedSegments(N,false);
depthFirstSearch(matches,results,usedSegments);
polys.resize(results.size());
transform(results.begin(),results.end(),polys.begin(),FCreatePolygon(segms));
for (size_t i=0;i<N;i++) if (!usedSegments[i]) remainder.push_back(tmp[i]);
}
void math::assemblePolygons(const std::vector<TObject3D> &objs,std::vector<TPolygon3D> &polys) {
std::vector<TObject3D> tmp;
std::vector<TSegment3D> sgms;
TObject3D::getPolygons(objs,polys,tmp);
TObject3D::getSegments(tmp,sgms);
assemblePolygons(sgms,polys);
}
void math::assemblePolygons(const std::vector<TObject3D> &objs,std::vector<TPolygon3D> &polys,std::vector<TObject3D> &remainder) {
std::vector<TObject3D> tmp;
std::vector<TSegment3D> sgms,remainderSgms;
TObject3D::getPolygons(objs,polys,tmp);
TObject3D::getSegments(tmp,sgms,remainder);
assemblePolygons(sgms,polys,remainderSgms);
remainder.insert(remainder.end(),remainderSgms.begin(),remainderSgms.end());
}
void math::assemblePolygons(const std::vector<TObject3D> &objs,std::vector<TPolygon3D> &polys,std::vector<TSegment3D> &remainder1,std::vector<TObject3D> &remainder2) {
std::vector<TObject3D> tmp;
std::vector<TSegment3D> sgms;
TObject3D::getPolygons(objs,polys,tmp);
TObject3D::getSegments(tmp,sgms,remainder2);
assemblePolygons(sgms,polys,remainder1);
}
bool intersect(const TLine2D &l1,const TSegmentWithLine &s2,TObject2D &obj) {
if (intersect(l1,s2.line,obj)) {
if (obj.isLine()) {
obj=s2.segment;
return true;
} else {
TPoint2D p;
obj.getPoint(p);
return s2.segment.contains(p);
}
} else return false;
}
inline bool intersect(const TSegmentWithLine &s1,const TLine2D &l2,TObject2D &obj) {
return intersect(l2,s1,obj);
}
bool math::splitInConvexComponents(const TPolygon2D &poly,vector<TPolygon2D> &components) {
components.clear();
size_t N=poly.size();
if (N<=3) return false;
vector<TSegmentWithLine> segms(N);
for (size_t i=0;i<N-1;i++) segms[i]=TSegmentWithLine(poly[i],poly[i+1]);
segms[N-1]=TSegmentWithLine(poly[N-1],poly[0]);
TObject2D obj;
TPoint2D pnt;
for (size_t i=0;i<N;i++) {
size_t ii=(i+2)%N,i_=(i+N-1)%N;
for (size_t j=ii;j!=i_;j=(j+1)%N) if (intersect(segms[i].line,segms[j],obj)&&obj.getPoint(pnt)) {
TSegmentWithLine sTmp=TSegmentWithLine(pnt,segms[i].segment[(distance(pnt,segms[i].segment.point1)<distance(pnt,segms[i].segment.point2))?0:1]);
bool cross=false;
TPoint2D pTmp;
for (size_t k=0;(k<N)&&!cross;k++) if (intersect(sTmp,segms[k],obj)) {
if (obj.getPoint(pTmp)&&(distance(pTmp,sTmp.segment[0])>=geometryEpsilon)&&(distance(pTmp,sTmp.segment[1])>=geometryEpsilon)) cross=true;
}
if (cross) continue;
//At this point, we have a suitable point, although we must check if the division is right.
//We do this by evaluating, in the expanded segment's line, the next and previous points. If both signs differ, proceed.
if (sign(segms[i].line.evaluatePoint(poly[(i+N-1)%N]))==sign(segms[i].line.evaluatePoint(poly[(i+2)%N]))) continue;
TPolygon2D p1,p2;
if (i>j) {
p1.insert(p1.end(),poly.begin()+i+1,poly.end());
p1.insert(p1.end(),poly.begin(),poly.begin()+j+1);
p2.insert(p2.end(),poly.begin()+j+1,poly.begin()+i+1);
} else {
p1.insert(p1.end(),poly.begin()+i+1,poly.begin()+j+1);
p2.insert(p2.end(),poly.begin()+j+1,poly.end());
p2.insert(p2.end(),poly.begin(),poly.begin()+i+1);
}
if (distance(*(p1.rbegin()),pnt)>=geometryEpsilon) p1.push_back(pnt);
if (distance(*(p2.rbegin()),pnt)>=geometryEpsilon) p2.push_back(pnt);
p1.removeRedundantVertices();
p2.removeRedundantVertices();
vector<TPolygon2D> tempComps;
if (splitInConvexComponents(p1,tempComps)) components.insert(components.end(),tempComps.begin(),tempComps.end());
else components.push_back(p1);
if (splitInConvexComponents(p2,tempComps)) components.insert(components.end(),tempComps.begin(),tempComps.end());
else components.push_back(p2);
return true;
}
}
return false;
}
class FUnprojectPolygon2D {
public:
const CPose3D &pose;
TPolygon3D tmp1,tmp2;
FUnprojectPolygon2D(const CPose3D &p):pose(p),tmp1(0),tmp2(0) {}
TPolygon3D operator()(const TPolygon2D &poly2D) {
tmp1=TPolygon3D(poly2D);
project3D(tmp1,pose,tmp2);
return tmp2;
}
};
bool math::splitInConvexComponents(const TPolygon3D &poly,vector<TPolygon3D> &components) {
TPlane p;
if (!poly.getPlane(p)) throw std::logic_error("Polygon is skew");
CPose3D pose1,pose2;
p.getAsPose3DForcingOrigin(poly[0],pose1);
pose2=-pose1;
TPolygon3D polyTmp;
project3D(poly,pose2,polyTmp);
TPolygon2D poly2D=TPolygon2D(polyTmp);
vector<TPolygon2D> components2D;
if (splitInConvexComponents(poly2D,components2D)) {
components.resize(components2D.size());
transform(components2D.begin(),components2D.end(),components.begin(),FUnprojectPolygon2D(pose1));
return true;
} else return false;
}
void math::getSegmentBisector(const TSegment2D &sgm,TLine2D &bis) {
TPoint2D p;
sgm.getCenter(p);
bis.coefs[0]=sgm.point2.x-sgm.point1.x;
bis.coefs[1]=sgm.point2.y-sgm.point1.y;
bis.coefs[2]=-bis.coefs[0]*p.x-bis.coefs[1]*p.y;
bis.unitarize();
}
void math::getSegmentBisector(const TSegment3D &sgm,TPlane &bis) {
TPoint3D p;
sgm.getCenter(p);
bis.coefs[0]=sgm.point2.x-sgm.point1.x;
bis.coefs[1]=sgm.point2.y-sgm.point1.y;
bis.coefs[2]=sgm.point2.z-sgm.point1.z;
bis.coefs[2]=-bis.coefs[0]*p.x-bis.coefs[1]*p.y-bis.coefs[2]*p.z;
bis.unitarize();
}
void math::getAngleBisector(const TLine2D &l1,const TLine2D &l2,TLine2D &bis) {
TPoint2D p;
TObject2D obj;
if (!intersect(l1,l2,obj)) {
//Both lines are parallel
double mod1=sqrt(square(l1.coefs[0])+square(l1.coefs[1]));
double mod2=sqrt(square(l2.coefs[0])+square(l2.coefs[2]));
bis.coefs[0]=l1.coefs[0]/mod1;
bis.coefs[1]=l1.coefs[1]/mod1;
bool sameSign;
if (abs(bis.coefs[0])<geometryEpsilon) sameSign=(l1.coefs[1]*l2.coefs[1])>0;
else sameSign=(l1.coefs[0]*l2.coefs[0])>0;
if (sameSign) bis.coefs[2]=(l1.coefs[2]/mod1)+(l2.coefs[2]/mod2);
else bis.coefs[2]=(l1.coefs[2]/mod1)-(l2.coefs[2]/mod2);
} else if (obj.getPoint(p)) {
//Both lines cross
double ang1=atan2(-l1.coefs[0],l1.coefs[1]);
double ang2=atan2(-l2.coefs[0],l2.coefs[1]);
double ang=(ang1+ang2)/2;
bis.coefs[0]=-sin(ang);
bis.coefs[1]=cos(ang);
bis.coefs[2]=-bis.coefs[0]*p.x-bis.coefs[1]*p.y;
} else {
bis=l1;
bis.unitarize();
}
}
void math::getAngleBisector(const TLine3D &l1,const TLine3D &l2,TLine3D &bis) {
TPlane p=TPlane(l1,l2); //May throw an exception
TLine3D l1P,l2P;
TLine2D bis2D;
CPose3D pose,pose2;
p.getAsPose3D(pose);
pose2=-pose;
project3D(l1,pose2,l1P);
project3D(l2,pose2,l2P);
getAngleBisector(TLine2D(l1P),TLine2D(l2P),bis2D);
project3D(TLine3D(bis2D),pose,bis);
}
bool math::traceRay(const vector<TPolygonWithPlane> &vec,const CPose3D &pose,double &dist) {
dist=HUGE_VAL;
double nDist=0;
TLine3D lin;
createFromPoseX(pose,lin);
lin.unitarize();
bool res=false;
for (vector<TPolygonWithPlane>::const_iterator it=vec.begin();it!=vec.end();++it) if (::intersect(*it,lin,nDist,dist)) {
res=true;
dist=nDist;
}
return res;
}
| 31.924801 | 291 | 0.668653 | [
"geometry",
"object",
"shape",
"vector",
"transform",
"3d"
] |
acaa2e5611178ee619e165c1b7ade605276b2e36 | 14,178 | cpp | C++ | Intermediate/Build/Win64/UE4/Inc/GameplayHelper/TrackControl.gen.cpp | Monolag/GameplayHelper | a59449b824116f0c785aa4ce0385ccd36041e60e | [
"MIT"
] | 4 | 2020-07-03T01:16:26.000Z | 2022-01-15T09:31:27.000Z | Intermediate/Build/Win32/UE4/Inc/GameplayHelper/TrackControl.gen.cpp | Monolag/GameplayHelper | a59449b824116f0c785aa4ce0385ccd36041e60e | [
"MIT"
] | null | null | null | Intermediate/Build/Win32/UE4/Inc/GameplayHelper/TrackControl.gen.cpp | Monolag/GameplayHelper | a59449b824116f0c785aa4ce0385ccd36041e60e | [
"MIT"
] | 1 | 2020-05-29T04:43:28.000Z | 2020-05-29T04:43:28.000Z | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "GameplayHelper/Public/TrackControl.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeTrackControl() {}
// Cross Module References
GAMEPLAYHELPER_API UClass* Z_Construct_UClass_UTrackControl_NoRegister();
GAMEPLAYHELPER_API UClass* Z_Construct_UClass_UTrackControl();
ENGINE_API UClass* Z_Construct_UClass_UActorComponent();
UPackage* Z_Construct_UPackage__Script_GameplayHelper();
GAMEPLAYHELPER_API UFunction* Z_Construct_UFunction_UTrackControl_Initialize();
ENGINE_API UClass* Z_Construct_UClass_USceneComponent_NoRegister();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FVector();
COREUOBJECT_API UClass* Z_Construct_UClass_UClass();
ENGINE_API UClass* Z_Construct_UClass_AActor_NoRegister();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FRotator();
// End Cross Module References
void UTrackControl::StaticRegisterNativesUTrackControl()
{
UClass* Class = UTrackControl::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "Initialize", &UTrackControl::execInitialize },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_UTrackControl_Initialize_Statics
{
struct TrackControl_eventInitialize_Parms
{
TArray<USceneComponent*> inComponents;
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_inComponents_MetaData[];
#endif
static const UE4CodeGen_Private::FArrayPropertyParams NewProp_inComponents;
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_inComponents_Inner;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UTrackControl_Initialize_Statics::NewProp_inComponents_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UFunction_UTrackControl_Initialize_Statics::NewProp_inComponents = { "inComponents", nullptr, (EPropertyFlags)0x0010008000000080, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(TrackControl_eventInitialize_Parms, inComponents), METADATA_PARAMS(Z_Construct_UFunction_UTrackControl_Initialize_Statics::NewProp_inComponents_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UTrackControl_Initialize_Statics::NewProp_inComponents_MetaData)) };
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UTrackControl_Initialize_Statics::NewProp_inComponents_Inner = { "inComponents", nullptr, (EPropertyFlags)0x0000000000080000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UClass_USceneComponent_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UTrackControl_Initialize_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UTrackControl_Initialize_Statics::NewProp_inComponents,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UTrackControl_Initialize_Statics::NewProp_inComponents_Inner,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UTrackControl_Initialize_Statics::Function_MetaDataParams[] = {
{ "Category", "Initialize" },
{ "ModuleRelativePath", "Public/TrackControl.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UTrackControl_Initialize_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UTrackControl, nullptr, "Initialize", nullptr, nullptr, sizeof(TrackControl_eventInitialize_Parms), Z_Construct_UFunction_UTrackControl_Initialize_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UTrackControl_Initialize_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UTrackControl_Initialize_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UTrackControl_Initialize_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UTrackControl_Initialize()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UTrackControl_Initialize_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UTrackControl_NoRegister()
{
return UTrackControl::StaticClass();
}
struct Z_Construct_UClass_UTrackControl_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_DrawTime_MetaData[];
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_DrawTime;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_DecalScale_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_DecalScale;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_DecalClass_MetaData[];
#endif
static const UE4CodeGen_Private::FClassPropertyParams NewProp_DecalClass;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_LifeSpanTime_MetaData[];
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_LifeSpanTime;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_DecalRotation_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_DecalRotation;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_DecalSize_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_DecalSize;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UTrackControl_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UActorComponent,
(UObject* (*)())Z_Construct_UPackage__Script_GameplayHelper,
};
const FClassFunctionLinkInfo Z_Construct_UClass_UTrackControl_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_UTrackControl_Initialize, "Initialize" }, // 1250942432
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UTrackControl_Statics::Class_MetaDataParams[] = {
{ "BlueprintSpawnableComponent", "" },
{ "ClassGroupNames", "Custom" },
{ "IncludePath", "TrackControl.h" },
{ "ModuleRelativePath", "Public/TrackControl.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UTrackControl_Statics::NewProp_DrawTime_MetaData[] = {
{ "Category", "Setup" },
{ "ModuleRelativePath", "Public/TrackControl.h" },
};
#endif
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UTrackControl_Statics::NewProp_DrawTime = { "DrawTime", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UTrackControl, DrawTime), METADATA_PARAMS(Z_Construct_UClass_UTrackControl_Statics::NewProp_DrawTime_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UTrackControl_Statics::NewProp_DrawTime_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalScale_MetaData[] = {
{ "Category", "Setup" },
{ "ModuleRelativePath", "Public/TrackControl.h" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalScale = { "DecalScale", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UTrackControl, DecalScale), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalScale_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalScale_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalClass_MetaData[] = {
{ "Category", "Setup" },
{ "ModuleRelativePath", "Public/TrackControl.h" },
};
#endif
const UE4CodeGen_Private::FClassPropertyParams Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalClass = { "DecalClass", nullptr, (EPropertyFlags)0x0014000000000001, UE4CodeGen_Private::EPropertyGenFlags::Class, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UTrackControl, DecalClass), Z_Construct_UClass_AActor_NoRegister, Z_Construct_UClass_UClass, METADATA_PARAMS(Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalClass_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalClass_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UTrackControl_Statics::NewProp_LifeSpanTime_MetaData[] = {
{ "Category", "Variables" },
{ "ModuleRelativePath", "Public/TrackControl.h" },
};
#endif
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UTrackControl_Statics::NewProp_LifeSpanTime = { "LifeSpanTime", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UTrackControl, LifeSpanTime), METADATA_PARAMS(Z_Construct_UClass_UTrackControl_Statics::NewProp_LifeSpanTime_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UTrackControl_Statics::NewProp_LifeSpanTime_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalRotation_MetaData[] = {
{ "Category", "Variables" },
{ "ModuleRelativePath", "Public/TrackControl.h" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalRotation = { "DecalRotation", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UTrackControl, DecalRotation), Z_Construct_UScriptStruct_FRotator, METADATA_PARAMS(Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalRotation_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalRotation_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalSize_MetaData[] = {
{ "Category", "Variables" },
{ "ModuleRelativePath", "Public/TrackControl.h" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalSize = { "DecalSize", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UTrackControl, DecalSize), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalSize_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalSize_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UTrackControl_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UTrackControl_Statics::NewProp_DrawTime,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalScale,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalClass,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UTrackControl_Statics::NewProp_LifeSpanTime,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalRotation,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UTrackControl_Statics::NewProp_DecalSize,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_UTrackControl_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UTrackControl>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UTrackControl_Statics::ClassParams = {
&UTrackControl::StaticClass,
"Engine",
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_UTrackControl_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_UTrackControl_Statics::PropPointers),
0,
0x00B000A4u,
METADATA_PARAMS(Z_Construct_UClass_UTrackControl_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UTrackControl_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UTrackControl()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UTrackControl_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UTrackControl, 1521629629);
template<> GAMEPLAYHELPER_API UClass* StaticClass<UTrackControl>()
{
return UTrackControl::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UTrackControl(Z_Construct_UClass_UTrackControl, &UTrackControl::StaticClass, TEXT("/Script/GameplayHelper"), TEXT("UTrackControl"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UTrackControl);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| 64.153846 | 674 | 0.838694 | [
"object"
] |
acaf6e19e757b1dc441862dc8f277a3f02c57080 | 6,970 | cpp | C++ | src/CLSmith/CLProgramGenerator.cpp | jiezzhang/CLSmith | a39a31c43c88352fc65e61dce270d8e1660cbcf0 | [
"BSD-2-Clause"
] | null | null | null | src/CLSmith/CLProgramGenerator.cpp | jiezzhang/CLSmith | a39a31c43c88352fc65e61dce270d8e1660cbcf0 | [
"BSD-2-Clause"
] | null | null | null | src/CLSmith/CLProgramGenerator.cpp | jiezzhang/CLSmith | a39a31c43c88352fc65e61dce270d8e1660cbcf0 | [
"BSD-2-Clause"
] | null | null | null | #include "CLSmith/CLProgramGenerator.h"
#include <cassert>
#include <cmath>
#include <memory>
#include <string>
#include <iostream>
#include "CLSmith/CLExpression.h"
#include "CLSmith/CLOptions.h"
#include "CLSmith/CLVariable.h"
#include "CLSmith/Divergence.h"
#include "CLSmith/ExpressionAtomic.h"
#include "ExpressionID.h"
#include "CLSmith/FunctionInvocationBuiltIn.h"
#include "CLSmith/StatementAtomicResult.h"
#include "CLSmith/Globals.h"
#include "CLSmith/StatementAtomicReduction.h"
#include "CLSmith/StatementBarrier.h"
#include "CLSmith/StatementComm.h"
#include "CLSmith/StatementEMI.h"
#include "CLSmith/StatementMessage.h"
#include "CLSmith/Vector.h"
#include "Function.h"
#include "Type.h"
class OutputMgr;
namespace CLSmith {
namespace {
static const unsigned int max_threads = 10000;
static const unsigned int max_thr_per_dim = 100;
static const unsigned int max_threads_per_group = 256;
static const unsigned int no_dims = 3;
static unsigned int noThreads = 1;
static unsigned int noGroups = 1;
static std::vector<unsigned int> *globalDim;
static std::vector<unsigned int> *localDim;
} // namespace
void CLProgramGenerator::goGenerator() {
// Initialise probabilies.
CLExpression::InitProbabilityTable();
CLStatement::InitProbabilityTable();
// Create vector types.
Vector::GenerateVectorTypes();
// Initialise function tables.
FunctionInvocationBuiltIn::InitTables();
// Initialise Variable objects used for thread identifiers.
ExpressionID::Initialise();
// Initialize runtime parameters;
InitRuntimeParameters();
// Initalize atomic parameters
if (CLOptions::atomics())
ExpressionAtomic::InitAtomics();
// Initialise buffers used for inter-thread communication.
StatementComm::InitBuffers();
// Initialise Message Passing data.
MessagePassing::Initialise();
// Expects argc, argv and seed. These vars should really be in the output_mgr.
output_mgr_->OutputHeader(0, NULL, seed_);
// This creates the random program, the rest handles post-processing and
// outputting the program.
GenerateAllTypes();
GenerateFunctions();
// If tracking divergence is set, perform the tracking now.
std::unique_ptr<Divergence> div;
if (CLOptions::track_divergence()) {
div.reset(new Divergence());
div->ProcessEntryFunction(GetFirstFunction());
}
// If EMI block generation is set, prune them.
if (CLOptions::emi())
EMIController::GetEMIController()->PruneEMISections();
// If atomic blocks are generated, add operations for the special values
if (CLOptions::atomics())
StatementAtomicResult::GenSpecialVals();
// If atomic reductions are generated, add the hash buffer
if (CLOptions::atomic_reductions())
StatementAtomicReduction::RecordBuffer();
// If Message Passing is enabled, create orderings and message updates.
if (CLOptions::message_passing())
MessagePassing::CreateMessageOrderings();
// At this point, all the global variables that have been created throughout
// program generation should have been created. Any global variables added to
// VariableSelector's global list after this point must be added to globals
// manually, or the name will not be prepended with the global struct.
Globals *globals = Globals::GetGlobals();
// Once the global struct is created, we add the global memory buffers.
// Adding global memory buffers to do with atomic expressions.
if (CLOptions::atomics()) {
ExpressionAtomic::AddVarsToGlobals(globals);
}
// Add the reduction variables for atomic reductions to the global struct
if (CLOptions::atomic_reductions())
StatementAtomicReduction::AddVarsToGlobals(globals);
// Now add the input data for EMI sections if specified.
if (CLOptions::emi())
for (MemoryBuffer *mb :
*EMIController::GetEMIController()->GetItemisedEMIInput())
globals->AddGlobalMemoryBuffer(mb);
// Add the 9 variables used for the identifiers.
if (CLOptions::fake_divergence())
ExpressionID::AddVarsToGlobals(globals);
// Add buffers used for inter-thread comm.
if (CLOptions::inter_thread_comm())
StatementComm::AddVarsToGlobals(globals);
// Add messages for message passing.
if (CLOptions::message_passing())
MessagePassing::AddMessageVarsToGlobals(globals);
// If barriers have been set, use the divergence information to place them.
if (CLOptions::barriers()) {
if (CLOptions::divergence()) GenerateBarriers(div.get(), globals);
else { /*TODO Non-div barriers*/ }
}
if (CLOptions::small())
CLSmith::CLVariable::ParseUnusedVars();
// Output the whole program.
output_mgr_->Output();
// Release any singleton instances used.
Globals::ReleaseGlobals();
EMIController::ReleaseEMIController();
}
void CLProgramGenerator::InitRuntimeParameters() {
globalDim = new std::vector<unsigned int>(no_dims, 1);
localDim = new std::vector<unsigned int>(no_dims, 1);
std::vector<unsigned int>& globalDim = *CLSmith::globalDim;
std::vector<unsigned int>& localDim = *CLSmith::localDim;
std::vector<unsigned int> chosen_div;
std::vector<unsigned int> divisors;
for (unsigned int i = 0; i < no_dims; i++) {
globalDim[i] = rnd_upto(std::min(max_thr_per_dim, max_threads / noThreads)) + 1;
noThreads *= globalDim[i];
}
unsigned int curr_thr_p_grp;
do {
curr_thr_p_grp = 1;
for (unsigned int i = 0; i < no_dims; i++) {
get_divisors(globalDim[i], &divisors);
localDim[i] = divisors[rnd_upto(divisors.size())];
curr_thr_p_grp *= localDim[i];
}
} while (curr_thr_p_grp > max_threads_per_group);
for (unsigned int i = 0; i < no_dims; i++)
noGroups *= globalDim[i] / localDim[i];
}
OutputMgr *CLProgramGenerator::getOutputMgr() {
return output_mgr_.get();
}
std::string CLProgramGenerator::get_count_prefix(const std::string& name) {
assert(false);
return "";
}
const unsigned int CLProgramGenerator::get_threads() {
return noThreads;
}
const unsigned int CLProgramGenerator::get_groups() {
return noGroups;
}
const unsigned int CLProgramGenerator::get_total_threads() {
return noThreads * noGroups;
}
const unsigned int CLProgramGenerator::get_threads_per_group() {
return noThreads / noGroups;
}
const std::vector<unsigned int>& CLProgramGenerator::get_global_dims() {
return *globalDim;
}
const std::vector<unsigned int>& CLProgramGenerator::get_local_dims() {
return *localDim;
}
const unsigned int CLProgramGenerator::get_atomic_blocks_no() {
return CLSmith::ExpressionAtomic::get_atomic_blocks_no();
}
void CLProgramGenerator::initialize() {
}
void CLProgramGenerator::get_divisors(
unsigned int val, std::vector<unsigned int> *divisors) {
divisors->clear();
divisors->push_back(1); divisors->push_back(val);
unsigned int i;
for (i = 2; i < sqrt(val); i++) {
if (!(val % i)) {
divisors->push_back(i);
divisors->push_back(val / i);
}
}
if (i * i == val)
divisors->push_back(i);
}
} // namespace CLSmith
| 31.255605 | 84 | 0.729555 | [
"vector"
] |
acb05e07d66f3983d576214cdfb11195f9f5978a | 6,374 | cc | C++ | components/crash/content/browser/crash_dump_observer_android.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/crash/content/browser/crash_dump_observer_android.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/crash/content/browser/crash_dump_observer_android.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/crash/content/browser/crash_dump_observer_android.h"
#include <unistd.h>
#include "base/bind.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
using content::BrowserThread;
namespace breakpad {
namespace {
base::LazyInstance<CrashDumpObserver>::DestructorAtExit g_instance =
LAZY_INSTANCE_INITIALIZER;
}
// static
void CrashDumpObserver::Create() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// If this DCHECK fails in a unit test then a previously executing
// test that makes use of CrashDumpObserver forgot to create a
// ShadowingAtExitManager.
DCHECK(g_instance == nullptr);
g_instance.Get();
}
// static
CrashDumpObserver* CrashDumpObserver::GetInstance() {
DCHECK(!(g_instance == nullptr));
return g_instance.Pointer();
}
CrashDumpObserver::CrashDumpObserver() {
notification_registrar_.Add(this,
content::NOTIFICATION_RENDERER_PROCESS_CREATED,
content::NotificationService::AllSources());
notification_registrar_.Add(this,
content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
content::NotificationService::AllSources());
notification_registrar_.Add(this,
content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
content::NotificationService::AllSources());
BrowserChildProcessObserver::Add(this);
}
CrashDumpObserver::~CrashDumpObserver() {
BrowserChildProcessObserver::Remove(this);
}
void CrashDumpObserver::RegisterClient(std::unique_ptr<Client> client) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::AutoLock auto_lock(registered_clients_lock_);
registered_clients_.push_back(std::move(client));
}
void CrashDumpObserver::OnChildExit(int child_process_id,
base::ProcessHandle pid,
content::ProcessType process_type,
base::TerminationStatus termination_status,
base::android::ApplicationState app_state) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
std::vector<Client*> registered_clients_copy;
{
base::AutoLock auto_lock(registered_clients_lock_);
for (auto& client : registered_clients_)
registered_clients_copy.push_back(client.get());
}
for (auto* client : registered_clients_copy) {
client->OnChildExit(child_process_id, pid, process_type, termination_status,
app_state);
}
}
void CrashDumpObserver::BrowserChildProcessStarted(
int child_process_id,
content::FileDescriptorInfo* mappings) {
std::vector<Client*> registered_clients_copy;
{
base::AutoLock auto_lock(registered_clients_lock_);
for (auto& client : registered_clients_)
registered_clients_copy.push_back(client.get());
}
for (auto* client : registered_clients_copy) {
client->OnChildStart(child_process_id, mappings);
}
}
void CrashDumpObserver::BrowserChildProcessHostDisconnected(
const content::ChildProcessData& data) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
OnChildExit(data.id, data.handle,
static_cast<content::ProcessType>(data.process_type),
base::TERMINATION_STATUS_MAX_ENUM,
base::android::ApplicationStatusListener::GetState());
}
void CrashDumpObserver::BrowserChildProcessCrashed(
const content::ChildProcessData& data,
int exit_code) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
OnChildExit(data.id, data.handle,
static_cast<content::ProcessType>(data.process_type),
base::TERMINATION_STATUS_ABNORMAL_TERMINATION,
base::android::APPLICATION_STATE_UNKNOWN);
}
void CrashDumpObserver::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::RenderProcessHost* rph =
content::Source<content::RenderProcessHost>(source).ptr();
base::TerminationStatus term_status = base::TERMINATION_STATUS_MAX_ENUM;
base::android::ApplicationState app_state =
base::android::APPLICATION_STATE_UNKNOWN;
switch (type) {
case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
// NOTIFICATION_RENDERER_PROCESS_TERMINATED is sent when the renderer
// process is cleanly shutdown.
term_status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
break;
}
case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
// We do not care about android fast shutdowns as it is a known case where
// the renderer is intentionally killed when we are done with it.
if (rph->FastShutdownStarted()) {
break;
}
content::RenderProcessHost::RendererClosedDetails* process_details =
content::Details<content::RenderProcessHost::RendererClosedDetails>(
details)
.ptr();
term_status = process_details->status;
app_state = base::android::ApplicationStatusListener::GetState();
break;
}
case content::NOTIFICATION_RENDERER_PROCESS_CREATED: {
// The child process pid isn't available when process is gone, keep a
// mapping between child_process_id and pid, so we can find it later.
child_process_id_to_pid_[rph->GetID()] = rph->GetHandle();
return;
}
default:
NOTREACHED();
return;
}
base::ProcessHandle pid = rph->GetHandle();
const auto& iter = child_process_id_to_pid_.find(rph->GetID());
if (iter != child_process_id_to_pid_.end()) {
if (pid == base::kNullProcessHandle) {
pid = iter->second;
}
child_process_id_to_pid_.erase(iter);
}
OnChildExit(rph->GetID(), pid, content::PROCESS_TYPE_RENDERER, term_status,
app_state);
}
} // namespace breakpad
| 37.274854 | 80 | 0.698619 | [
"vector"
] |
acb2b830028b74d979556b91eb4fad13bec8ef47 | 2,693 | cpp | C++ | src/LeapSerial/AESStream.cpp | gkontsevich/leapserial | 5177569666153bc4e2569bffcd023a21cde5772b | [
"Apache-2.0"
] | 17 | 2016-02-27T00:05:43.000Z | 2021-02-28T03:12:22.000Z | src/LeapSerial/AESStream.cpp | gkontsevich/leapserial | 5177569666153bc4e2569bffcd023a21cde5772b | [
"Apache-2.0"
] | 47 | 2015-10-16T20:34:30.000Z | 2017-12-12T20:05:42.000Z | src/LeapSerial/AESStream.cpp | gkontsevich/leapserial | 5177569666153bc4e2569bffcd023a21cde5772b | [
"Apache-2.0"
] | 6 | 2015-10-16T21:38:56.000Z | 2019-08-14T20:48:19.000Z | // Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "AESStream.h"
#include <aes/rijndael-alg-fst.h>
#include <memory.h>
using namespace leap;
AES256Base::AES256Base(const std::array<uint8_t, 32>& key) :
ctx(new rijndael_context)
{
rijndaelKeySetup(ctx.get(), key.data(), 256);
memset(feedback, 0, sizeof(feedback));
NextBlock();
}
AES256Base::~AES256Base(void) {}
void AES256Base::NextBlock(void) {
// Encrypt the last fully encrypted block, we will use this as the basis for xoring the next one
rijndaelEncrypt(ctx.get(), feedback, feedback);
feedbackPtr = feedback;
}
AESEncryptionStream::AESEncryptionStream(std::unique_ptr<IOutputStream>&& os, const std::array<uint8_t, 32>& key) :
OutputFilterStreamBase(std::move(os)),
AES256Base(key)
{}
bool AESEncryptionStream::Transform(const void* input, size_t& ncbIn, void* output, size_t& ncbOut, bool) {
size_t nWritten = 0;
while (nWritten < ncbIn && nWritten < ncbOut) {
// Instantiate a block if we have to:
if (feedbackPtr == feedbackEnd)
NextBlock();
// XOR to implement our CBC mode
*feedbackPtr ^= static_cast<const uint8_t*>(input)[nWritten];
reinterpret_cast<uint8_t*>(output)[nWritten] = *feedbackPtr;
// Advance
feedbackPtr++;
nWritten++;
}
ncbOut = nWritten;
ncbIn = nWritten;
return true;
}
AESDecryptionStream::AESDecryptionStream(std::unique_ptr<IInputStream>&& is, const std::array<uint8_t, 32>& key) :
AES256Base(key),
is(std::move(is))
{}
std::streamsize AESDecryptionStream::Length(void) {
// We do not add any bytes relative to the underlying stream, we can just return its
// byte count directly
return is->Length();
}
std::streampos AESDecryptionStream::Tell(void) {
return is->Tell();
}
std::streamsize AESDecryptionStream::Read(void* pBuf, std::streamsize ncb) {
std::streamsize nRead = is->Read(pBuf, ncb);
for (std::streamsize i = 0; i < nRead; i++) {
// Generate next block if needed:
if (feedbackPtr == feedbackEnd)
NextBlock();
uint8_t encrypted = static_cast<uint8_t*>(pBuf)[i];
static_cast<uint8_t*>(pBuf)[i] ^= *feedbackPtr;
*feedbackPtr++ = encrypted;
}
return nRead;
}
std::streamsize AESDecryptionStream::Skip(std::streamsize ncb) {
uint8_t dump[1024];
std::streamsize nReadRemain;
for (nReadRemain = ncb; nReadRemain > 1024;) {
std::streamsize nRead = Read(dump, sizeof(dump));
if (nRead <= 0)
return ncb - nReadRemain;
nReadRemain -= nRead;
}
if(nReadRemain) {
std::streamsize lastRead = Read(dump, nReadRemain);
if (0 < lastRead)
nReadRemain -= lastRead;
}
return ncb - nReadRemain;
}
| 26.93 | 115 | 0.686595 | [
"transform"
] |
acbb3bcaa76d9a2e13952382f0640c3b2d2c7729 | 5,472 | cpp | C++ | trtc/src/v20190722/model/OneSdkAppIdTranscodeTimeUsagesInfo.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | trtc/src/v20190722/model/OneSdkAppIdTranscodeTimeUsagesInfo.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | trtc/src/v20190722/model/OneSdkAppIdTranscodeTimeUsagesInfo.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/trtc/v20190722/model/OneSdkAppIdTranscodeTimeUsagesInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Trtc::V20190722::Model;
using namespace std;
OneSdkAppIdTranscodeTimeUsagesInfo::OneSdkAppIdTranscodeTimeUsagesInfo() :
m_sdkAppIdTranscodeTimeUsagesHasBeenSet(false),
m_totalNumHasBeenSet(false),
m_sdkAppIdHasBeenSet(false)
{
}
CoreInternalOutcome OneSdkAppIdTranscodeTimeUsagesInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("SdkAppIdTranscodeTimeUsages") && !value["SdkAppIdTranscodeTimeUsages"].IsNull())
{
if (!value["SdkAppIdTranscodeTimeUsages"].IsArray())
return CoreInternalOutcome(Error("response `OneSdkAppIdTranscodeTimeUsagesInfo.SdkAppIdTranscodeTimeUsages` is not array type"));
const rapidjson::Value &tmpValue = value["SdkAppIdTranscodeTimeUsages"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
SdkAppIdTrtcMcuTranscodeTimeUsage item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_sdkAppIdTranscodeTimeUsages.push_back(item);
}
m_sdkAppIdTranscodeTimeUsagesHasBeenSet = true;
}
if (value.HasMember("TotalNum") && !value["TotalNum"].IsNull())
{
if (!value["TotalNum"].IsUint64())
{
return CoreInternalOutcome(Error("response `OneSdkAppIdTranscodeTimeUsagesInfo.TotalNum` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_totalNum = value["TotalNum"].GetUint64();
m_totalNumHasBeenSet = true;
}
if (value.HasMember("SdkAppId") && !value["SdkAppId"].IsNull())
{
if (!value["SdkAppId"].IsString())
{
return CoreInternalOutcome(Error("response `OneSdkAppIdTranscodeTimeUsagesInfo.SdkAppId` IsString=false incorrectly").SetRequestId(requestId));
}
m_sdkAppId = string(value["SdkAppId"].GetString());
m_sdkAppIdHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void OneSdkAppIdTranscodeTimeUsagesInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_sdkAppIdTranscodeTimeUsagesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SdkAppIdTranscodeTimeUsages";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_sdkAppIdTranscodeTimeUsages.begin(); itr != m_sdkAppIdTranscodeTimeUsages.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_totalNumHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TotalNum";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_totalNum, allocator);
}
if (m_sdkAppIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SdkAppId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_sdkAppId.c_str(), allocator).Move(), allocator);
}
}
vector<SdkAppIdTrtcMcuTranscodeTimeUsage> OneSdkAppIdTranscodeTimeUsagesInfo::GetSdkAppIdTranscodeTimeUsages() const
{
return m_sdkAppIdTranscodeTimeUsages;
}
void OneSdkAppIdTranscodeTimeUsagesInfo::SetSdkAppIdTranscodeTimeUsages(const vector<SdkAppIdTrtcMcuTranscodeTimeUsage>& _sdkAppIdTranscodeTimeUsages)
{
m_sdkAppIdTranscodeTimeUsages = _sdkAppIdTranscodeTimeUsages;
m_sdkAppIdTranscodeTimeUsagesHasBeenSet = true;
}
bool OneSdkAppIdTranscodeTimeUsagesInfo::SdkAppIdTranscodeTimeUsagesHasBeenSet() const
{
return m_sdkAppIdTranscodeTimeUsagesHasBeenSet;
}
uint64_t OneSdkAppIdTranscodeTimeUsagesInfo::GetTotalNum() const
{
return m_totalNum;
}
void OneSdkAppIdTranscodeTimeUsagesInfo::SetTotalNum(const uint64_t& _totalNum)
{
m_totalNum = _totalNum;
m_totalNumHasBeenSet = true;
}
bool OneSdkAppIdTranscodeTimeUsagesInfo::TotalNumHasBeenSet() const
{
return m_totalNumHasBeenSet;
}
string OneSdkAppIdTranscodeTimeUsagesInfo::GetSdkAppId() const
{
return m_sdkAppId;
}
void OneSdkAppIdTranscodeTimeUsagesInfo::SetSdkAppId(const string& _sdkAppId)
{
m_sdkAppId = _sdkAppId;
m_sdkAppIdHasBeenSet = true;
}
bool OneSdkAppIdTranscodeTimeUsagesInfo::SdkAppIdHasBeenSet() const
{
return m_sdkAppIdHasBeenSet;
}
| 33.365854 | 155 | 0.717654 | [
"vector",
"model"
] |
acbcd3c5df201c47b6c9a6ebfb9b0b5f5a49a376 | 1,172 | cpp | C++ | course2/laba1/S/main.cpp | flydzen/ITMO_algo | ea251dca0fddb0d4d212377c6785cdc3667ece89 | [
"MIT"
] | null | null | null | course2/laba1/S/main.cpp | flydzen/ITMO_algo | ea251dca0fddb0d4d212377c6785cdc3667ece89 | [
"MIT"
] | null | null | null | course2/laba1/S/main.cpp | flydzen/ITMO_algo | ea251dca0fddb0d4d212377c6785cdc3667ece89 | [
"MIT"
] | null | null | null | #include <iostream>
#include <set>
#include <vector>
using namespace std;
vector<vector<int>> ss;
vector<pair<int, int>> result;
vector<int> stack;
vector<bool> used;
void dfs(int v) {
used[v] = true;
if (!stack.empty()) {
result.emplace_back(stack.back(), v);
for (size_t j = 0; j < stack.size() - 1; j++) {
if (stack[j + 1] < v)
result.emplace_back(stack[j], v);
}
}
stack.push_back(v);
for (auto i : ss[v]) {
if (!used[i]) dfs(i);
}
stack.pop_back();
}
int main() {
int n, m, l, c;
cin >> n >> m;
cin >> l;
l--;
set<pair<int, int>> to;
ss = vector<vector<int>>(n);
stack = vector<int>();
used = vector<bool>(n);
for (int i = 0; i < m - 1; i++) {
cin >> c;
c--;
if (to.count({c, l}) == 1) {
ss[c].push_back(l);
} else {
to.insert({l, c});
}
l = c;
}
for (int i = 0; i < n; i++) {
if (!used[i]) dfs(i);
}
cout << result.size() << endl;
for (auto &i : result) {
cout << i.first + 1 << " " << i.second + 1 << endl;
}
return 0;
}
| 20.928571 | 59 | 0.44198 | [
"vector"
] |
acbf8524a3bd9b9ba5c0345294e34f791d08059a | 10,946 | cpp | C++ | src/base/util/RepeatSunSync.cpp | supalogix/GMAT | eea9987ef0978b3e6702e70b587a098b2cbce14e | [
"Apache-2.0"
] | null | null | null | src/base/util/RepeatSunSync.cpp | supalogix/GMAT | eea9987ef0978b3e6702e70b587a098b2cbce14e | [
"Apache-2.0"
] | null | null | null | src/base/util/RepeatSunSync.cpp | supalogix/GMAT | eea9987ef0978b3e6702e70b587a098b2cbce14e | [
"Apache-2.0"
] | null | null | null | //
//------------------------------------------------------------------------------
// RepeatSunSync
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2017 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number S-67573-G
//
// Author: Evelyn Hull
// Created: 2011/07/28
//
/**
* Implements the Repeat Sun Sync base class.
*/
//------------------------------------------------------------------------------
#include "RepeatSunSync.hpp"
#include "GmatDefaults.hpp"
#include "math.h"
#include "GmatConstants.hpp"
#include "RealUtilities.hpp"
//------------------------------------------------------------------------------
// RepeatSunSync()
//------------------------------------------------------------------------------
/**
* This method creates an object of the RepeatSunSync class
* (default constructor).
*
*/
//------------------------------------------------------------------------------
RepeatSunSync::RepeatSunSync()
{
elements.SMA = 0.0;
elements.ECC = 0.0;
elements.INC = 0.0;
elements.daysToRepeat = 0.0;
elements.revsToRepeat = 0.0;
elements.revsPerDay = 0.0;
errormsg = "";
isError = false;
}
//------------------------------------------------------------------------------
// ~RepeatSunSync()
//------------------------------------------------------------------------------
/**
* This method destroys the object of the RepeatSunSync class
* (destructor).
*
*/
//------------------------------------------------------------------------------
RepeatSunSync::~RepeatSunSync()
{
}
//------------------------------------------------------------------------------
// Real GetSMA()
//------------------------------------------------------------------------------
/**
* Returns SMA value.
*
*/
//------------------------------------------------------------------------------
Real RepeatSunSync::GetSMA()
{
return elements.SMA;
}
//------------------------------------------------------------------------------
// Real GetALT()
//------------------------------------------------------------------------------
/**
* Returns ALT value.
*
*/
//------------------------------------------------------------------------------
Real RepeatSunSync::GetALT()
{
return (elements.SMA-GmatSolarSystemDefaults::PLANET_EQUATORIAL_RADIUS[2]);
}
//------------------------------------------------------------------------------
// Real GetECC()
//------------------------------------------------------------------------------
/**
* Returns ECC value.
*
*/
//------------------------------------------------------------------------------
Real RepeatSunSync::GetECC()
{
return elements.ECC;
}
//------------------------------------------------------------------------------
// Real GetINC()
//------------------------------------------------------------------------------
/**
* Returns INC value.
*
*/
//------------------------------------------------------------------------------
Real RepeatSunSync::GetINC()
{
return elements.INC;
}
//------------------------------------------------------------------------------
// Real GetROA()
//------------------------------------------------------------------------------
/**
* Returns ROA value.
*
*/
//------------------------------------------------------------------------------
Real RepeatSunSync::GetROA()
{
return elements.SMA*(1+elements.ECC);
}
//------------------------------------------------------------------------------
// Real GetROP()
//------------------------------------------------------------------------------
/**
* Returns ROP value.
*
*/
//------------------------------------------------------------------------------
Real RepeatSunSync::GetROP()
{
return elements.SMA*(1-elements.ECC);
}
//------------------------------------------------------------------------------
// Real GetP()
//------------------------------------------------------------------------------
/**
* Returns P value.
*
*/
//------------------------------------------------------------------------------
Real RepeatSunSync::GetP()
{
return elements.SMA*(1-pow(elements.ECC,2));
}
//------------------------------------------------------------------------------
// bool IsError()
//------------------------------------------------------------------------------
/**
* Returns a flag indicating whether or not there has been an error.
*
*/
//------------------------------------------------------------------------------
bool RepeatSunSync::IsError()
{
return isError;
}
//------------------------------------------------------------------------------
// std::string GetError()
//------------------------------------------------------------------------------
/**
* Returns the error message.
*
*/
//------------------------------------------------------------------------------
std::string RepeatSunSync::GetError()
{
return errormsg;
}
//------------------------------------------------------------------------------
// void CalculateRepeatSunSync(bool eccVal, Real ECC, bool dtrVal,
// Real daysToRepeat, bool rtrVal,
// Real revsToRepeat, bool rpdVal,
// Real revsPerDay)
//------------------------------------------------------------------------------
/**
* Calculates the RepeatSunSync values.
*
*/
//------------------------------------------------------------------------------
void RepeatSunSync::CalculateRepeatSunSync(bool eccVal, Real ECC, bool dtrVal,
Real daysToRepeat, bool rtrVal, Real revsToRepeat, bool rpdVal,
Real revsPerDay)
{
Real n, inc, a, sun, diff, p, raanDot, omegaDot, MDot, newA, rp, newE;
Real incCheck, newInc;
int count;
Real J2 = 0.0010826267;
Real omegaEarth = 0.000072921158533;
Real omegaSunSync = (2*GmatMathConstants::PI/365.2422)/86400;
Real lambdaDot = 0.985*GmatMathConstants::PI/180;
Real sunTol = .01;
Real smaTol = .000000001;
isError = false;
if (!eccVal)
{
errormsg = "ECC must be selected";
isError = true;
return;
}
if (rtrVal && rpdVal)
{
if (revsToRepeat<1)
{
errormsg =
"Please choose revs to repeat greater than or equal to 1";
isError = true;
return;
}
else if (revsPerDay<1)
{
errormsg =
"Please choose revs per day greater than or equal to 1";
isError = true;
return;
}
else
{
daysToRepeat = revsToRepeat/revsPerDay;
}
}
else if (dtrVal && rpdVal)
{
if (daysToRepeat<1)
{
errormsg =
"Please choose days to repeat greater than or equal to 1";
isError = true;
return;
}
else if (revsPerDay<1)
{
errormsg =
"Please choose revs per day greater than or equal to 1";
isError = true;
return;
}
else
{
revsToRepeat = revsPerDay*daysToRepeat;
}
}
else if (rtrVal && dtrVal)
{
if (revsToRepeat<1)
{
errormsg =
"Please choose revs to repeat greater than or equal to 1";
isError = true;
return;
}
else if (daysToRepeat<1)
{
errormsg =
"Please choose days to repeat greater than or equal to 1";
isError = true;
return;
}
else
{
revsPerDay = revsToRepeat/daysToRepeat;
}
}
else
{
errormsg =
"Please select two of days to repeat, revs to repeat, and revs per day";
isError = true;
return;
}
if ((ECC<0) || (ECC>=1))
{
errormsg = "ECC out of range, 0<=ECC<1";
isError = true;
return;
}
n = revsPerDay*omegaEarth;
count = 0;
sun = 1;
diff = 1;
inc = 98*GmatMathConstants::PI/180;
a = 7000;
errormsg = "";
while ((GmatMathUtil::Abs(sun) > sunTol) && (diff> smaTol) && (count <= 100))
{
p = a*(1 - pow(ECC,2));
raanDot =
(-3*n*J2/2)*
pow((GmatSolarSystemDefaults::PLANET_EQUATORIAL_RADIUS[2]/p),2)
*cos(inc);
omegaDot =
(3*n*J2/4)*
pow((GmatSolarSystemDefaults::PLANET_EQUATORIAL_RADIUS[2]/p),2)*
(4-5*pow(sin(inc),2));
MDot =
(3*n*J2/4)*
pow((GmatSolarSystemDefaults::PLANET_EQUATORIAL_RADIUS[2]/p),2)*
sqrt(1-pow(ECC,2))*(2-3*pow(sin(inc),2));
sun =
cos(inc) +
((2*lambdaDot*pow(a,(3.0/2))*pow((1-pow(ECC,2)),2))/
(3*J2*pow(GmatSolarSystemDefaults::PLANET_EQUATORIAL_RADIUS[2],2)*
sqrt(GmatSolarSystemDefaults::PLANET_MU[2])));
n = revsPerDay*(omegaEarth - raanDot) - (MDot + omegaDot);
newA = pow((GmatSolarSystemDefaults::PLANET_MU[2]/pow(n,2)),(1/3.0));
diff = GmatMathUtil::Abs(newA - a);
rp = newA*(1-ECC);
newE = (newA - rp)/newA;
incCheck =
(2*omegaSunSync*pow((1-pow(ECC,2)),2)*pow(a,(7.0/2)))/
(-3*sqrt(GmatSolarSystemDefaults::PLANET_MU[2])*
pow(GmatSolarSystemDefaults::PLANET_EQUATORIAL_RADIUS[2],2)*J2);
if (GmatMathUtil::Abs(incCheck) > 1)
newInc = inc;
else
newInc = acos(incCheck);
if (newA <= GmatSolarSystemDefaults::PLANET_EQUATORIAL_RADIUS[2])
{
errormsg = "Could not find orbit";
isError = true;
return;
}
else
{
a = newA;
}
if ((newE >= 1) || (newE < 0))
{
errormsg = "Could not find orbit";
isError = true;
return;
}
else
{
ECC = newE;
}
if ((newInc*180/GmatMathConstants::PI >= 110) ||
(newInc*180/GmatMathConstants::PI < 90))
{
errormsg = "Could not find orbit";
isError = true;
newInc = newInc*180/GmatMathConstants::PI;
return;
}
else
{
inc = newInc;
}
count++;
}
elements.INC = newInc*180/GmatMathConstants::PI;
elements.SMA = newA;
elements.ECC = newE;
elements.daysToRepeat = daysToRepeat;
elements.revsToRepeat = revsToRepeat;
elements.revsPerDay = revsPerDay;
if (count > 100)
{
errormsg = "Could not find orbit in 100 iterations";
isError = true;
}
}
| 27.923469 | 80 | 0.425361 | [
"object"
] |
acc867dc46eb02700100cbe6d593f0f452763e09 | 2,222 | hpp | C++ | include/Analytical.hpp | seraco/HeatConduction | 357180848d3de2798e47359691293979f8446500 | [
"MIT"
] | 3 | 2018-04-13T11:16:27.000Z | 2021-05-24T02:51:00.000Z | include/Analytical.hpp | seraco/HeatConduction | 357180848d3de2798e47359691293979f8446500 | [
"MIT"
] | null | null | null | include/Analytical.hpp | seraco/HeatConduction | 357180848d3de2798e47359691293979f8446500 | [
"MIT"
] | null | null | null | /*!
* @file Analytical.hpp
* @brief Headers of the main subroutines for calculating analytical solution and error.
* The implementation is in the <i>Analytical.cpp</i> file.
* @author S.Ramon (seraco)
* @version 0.0.1
*
* Copyright 2018 S.Ramon
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef __ANALYTICAL_HPP
#define __ANALYTICAL_HPP
#include <string>
#include "CMatrix.hpp"
#include "CMesh.hpp"
#include "CBoundaryConditions.hpp"
#include "CMaterial.hpp"
/*!
* @brief Solve the heat problem with the analytical solution.
* @param[in] msh - Mesh.
* @param[in] bnd - Boundary conditions.
* @param[in] mat - Material.
* @param[in] numSol - Numerical solution.
*/
void solveAnalytical(const CMesh& msh,
const CBoundaryConditions& bnd,
const CMaterial& mat,
const CMatrix& numSol);
/*!
* @brief Calculates the error of numerical with analytical solution.
* @param[in] sol1 - First solution.
* @param[in] sol2 - Second solution.
* @param[in] size - Size of the solutions.
*/
void calculateError(const CMatrix& sol1, const CMatrix& sol2,
const unsigned size);
#endif
| 36.42623 | 88 | 0.711521 | [
"mesh"
] |
accacee93695e43811c178ad509dd8614ae5f913 | 2,631 | hpp | C++ | LuaSTGExPlus/LuaSTG/GameObjectBentLaser.hpp | 32th-System/LuaSTG-EX-Plus_Archive | 60e7e776a3da2521f3cf33e95b85d25ab477c3a4 | [
"BSD-3-Clause"
] | 10 | 2018-12-30T07:52:10.000Z | 2021-07-26T09:07:39.000Z | LuaSTGExPlus/LuaSTG/GameObjectBentLaser.hpp | 32th-System/LuaSTG-EX-Plus_Archive | 60e7e776a3da2521f3cf33e95b85d25ab477c3a4 | [
"BSD-3-Clause"
] | 2 | 2019-01-10T07:01:56.000Z | 2021-03-16T17:25:32.000Z | LuaSTGExPlus/LuaSTG/GameObjectBentLaser.hpp | 32th-System/LuaSTG-EX-Plus_Archive | 60e7e776a3da2521f3cf33e95b85d25ab477c3a4 | [
"BSD-3-Clause"
] | 4 | 2018-12-30T07:52:20.000Z | 2021-08-06T13:20:31.000Z | #pragma once
#include "Global.h"
#include "CirularQueue.hpp"
#include "GameObject.hpp"
#define LGOBJ_MAXLASERNODE 512 // 曲线激光最大节点数
namespace LuaSTGPlus
{
class GameObjectBentLaser
{
public:
static GameObjectBentLaser* AllocInstance();
static void FreeInstance(GameObjectBentLaser* p);
struct LaserNode {
fcyVec2 pos; //节点位置
float half_width = 0.0f;//半宽
float rot = 0.0f; //节点朝向
float dis = 0.0f; //到上一个节点的距离
float x_dir = 0.0f; //顶点向量x分量
float y_dir = 0.0f; //顶点向量y分量
bool active = true; //节点活动状况
bool sharp = false; //相对上一个节点的朝向成钝角
};
private:
CirularQueue<LaserNode, LGOBJ_MAXLASERNODE> m_Queue;
float m_fLength = 0.0f; // 记录激光长度
private:
float m_fEnvelopeHeight = 0.0f;
float m_fEnvelopeBase = 1.0f;
float m_fEnvelopeRate = 0.0f;
float m_fEnvelopePower = 0.0f;
// https://www.desmos.com/calculator/i6r2pw90xw
inline float _GetEnvelope(float t) {
float ret = m_fEnvelopeHeight + (m_fEnvelopeBase * (1.0f - m_fEnvelopeRate * std::powf(2.0f * (t - 0.5f), m_fEnvelopePower)));
return (std::max)(0.0f, ret);
}
void _UpdateNode(size_t i)LNOEXCEPT; // 计算节点的渲染顶点
void _UpdateAllNode()LNOEXCEPT; // 重新计算所有节点的朝向和距离
void _PopHead()LNOEXCEPT; // 弹出头部节点,较早的节点
public:
// 读取
int GetSize()LNOEXCEPT; // 获取节点数量
LaserNode* GetNode(size_t i)LNOEXCEPT; // 获取节点,并非长期有效
float GetLength()LNOEXCEPT { return m_fLength; } // 获取曲线激光长度
void GetEnvelope(float& height, float& base, float& rate, float& power)LNOEXCEPT; // 碰撞包络
// 更新
bool Update(size_t id, int length, float width, bool active)LNOEXCEPT; // 根据新的位置更新节点
void SetAllWidth(float width)LNOEXCEPT; // 更改所有节点的碰撞和渲染宽度
// 渲染
bool Render(const char* tex_name, BlendMode blend, fcyColor c, float tex_left, float tex_top, float tex_width, float tex_height, float scale)LNOEXCEPT;
void RenderCollider(fcyColor fillColor)LNOEXCEPT;
// 碰撞检测
void SetEnvelope(float height, float base, float rate, float power)LNOEXCEPT; // 设置碰撞包络
bool BoundCheck()LNOEXCEPT; // 检查是否离开边界
bool CollisionCheck(float x, float y, float rot, float a, float b, bool rect)LNOEXCEPT; // 碰撞检测
// 即将被废弃
bool UpdateByNode(size_t id, int node, int length, float width, bool active)LNOEXCEPT; // 对某个节点开启或关闭并更新
bool UpdatePositionByList(lua_State* L, int length, float width, int index, bool revert)LNOEXCEPT; // 更改所有节点的坐标并更新
bool CollisionCheckW(float x, float y, float rot, float a, float b, bool rect, float width)LNOEXCEPT;
int SampleL(lua_State* L, float length)LNOEXCEPT;
int SampleT(lua_State* L, float delay) LNOEXCEPT;
protected:
GameObjectBentLaser()LNOEXCEPT;
~GameObjectBentLaser()LNOEXCEPT;
};
}
| 38.691176 | 153 | 0.72748 | [
"render"
] |
acceb48c4089e268b64508a56fc9077d69a7f6c6 | 18,364 | cpp | C++ | CloakEngine/DropDownMenu.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | CloakEngine/DropDownMenu.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | CloakEngine/DropDownMenu.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | #include "stdafx.h"
#include "Implementation/Interface/DropDownMenu.h"
#include "CloakEngine/Global/Debug.h"
#include <atomic>
#define SAVE_SWAP(src,dst) if(dst!=src){SAVE_RELEASE(dst); dst=src; if(src!=nullptr){src->AddRef();}}
namespace CloakEngine {
namespace Impl {
namespace Interface {
namespace DropDownMenu_v1 {
CLOAK_CALL DropDownMenu::DropDownMenu()
{
m_usedPoolSize = 0;
m_open = false;
m_btnBackground = nullptr;
m_btnChecked = nullptr;
m_btnHighlight = nullptr;
m_btnHighlightType = API::Interface::HighlightType::OVERRIDE;
m_btnSubMenuOpen = nullptr;
m_btnSubMenuClosed = nullptr;
m_btnTextOffset = { 0,0 };
m_btnWidth = 0;
m_btnHeight = 0;
m_btnSymbolWidth = 0;
m_btnMaxLen = 0;
m_stateSize = 0;
m_btnLetterSpace = 0;
m_btnLineSpace = 0;
m_btnFont = nullptr;
m_btnFontSize = 0;
m_btnJustifyH = API::Files::Justify::LEFT;
m_btnJustifyV = API::Files::AnchorPoint::CENTER;
INIT_EVENT(onMenuButtonClick, m_sync);
}
CLOAK_CALL DropDownMenu::~DropDownMenu()
{
for (size_t a = 0; a < m_pool.size(); a++)
{
SAVE_RELEASE(m_pool[a]);
}
SAVE_RELEASE(m_btnBackground);
SAVE_RELEASE(m_btnChecked);
SAVE_RELEASE(m_btnHighlight);
SAVE_RELEASE(m_btnSubMenuOpen);
SAVE_RELEASE(m_btnSubMenuClosed);
SAVE_RELEASE(m_btnFont);
}
void CLOAK_CALL_THIS DropDownMenu::SetMenu(In const API::Interface::Menu_v1::MENU_DESC& desc)
{
if (CloakCheckOK(desc.IsValid(), API::Global::Debug::Error::INTERFACE_MENU_NOT_VALID, false))
{
API::Helper::Lock lock(m_sync);
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->ResetMenu(); }
m_usedPoolSize = 0;
m_menu.clear();
MenuAnchor anchor;
anchor.CanCheck = false;
for (size_t a = 0; a < desc.MenuSize; a++)
{
if (desc.Menu[a].CanChecked)
{
anchor.CanCheck = true;
break;
}
}
for (size_t a = 0; a < desc.MenuSize; a++)
{
MenuButton* b = GetBtnFromPool();
m_menu.push_back(b);
anchor.MenuNum = a;
anchor.Point = API::Interface::AnchorPoint::TOPLEFT;
anchor.RelativePoint = API::Interface::AnchorPoint::BOTTOMLEFT;
anchor.RelativeAnchor = this;
b->SetMenu(desc.Menu[a], anchor, 0);
}
if (m_open && m_stateSize > 0)
{
for (size_t a = 0; a < m_menu.size(); a++)
{
m_menu[a]->SetOpenState(m_openState, 0, m_stateSize);
}
}
}
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonTexture(In API::Files::ITexture* img)
{
API::Helper::Lock lock(m_sync);
SAVE_SWAP(img, m_btnBackground);
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetBackgroundTexture(img); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonHighlightTexture(In API::Files::ITexture* img, In_opt API::Interface::Frame_v1::HighlightType highlight)
{
API::Helper::Lock lock(m_sync);
SAVE_SWAP(img, m_btnHighlight);
m_btnHighlightType = highlight;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetHighlightTexture(img, highlight); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonCheckTexture(In API::Files::ITexture* img)
{
API::Helper::Lock lock(m_sync);
SAVE_SWAP(img, m_btnChecked);
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetCheckTexture(img); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonSubMenuTexture(In API::Files::ITexture* open, In API::Files::ITexture* closed)
{
API::Helper::Lock lock(m_sync);
SAVE_SWAP(open, m_btnSubMenuOpen);
SAVE_SWAP(closed, m_btnSubMenuClosed);
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetSubMenuTexture(open, closed); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonWidth(In float W)
{
API::Helper::Lock lock(m_sync);
SetButtonSize(W, m_btnHeight);
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonHeight(In float H)
{
API::Helper::Lock lock(m_sync);
SetButtonSize(m_btnWidth, H);
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonSize(In float W, In float H)
{
API::Helper::Lock lock(m_sync);
m_btnWidth = W;
m_btnHeight = H;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetSize(W, H); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonSymbolWidth(In float W)
{
API::Helper::Lock lock(m_sync);
m_btnSymbolWidth = W;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetSymbolWidth(W); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonFont(In API::Files::IFont* font)
{
API::Helper::Lock lock(m_sync);
if (m_btnFont != nullptr) { m_btnFont->unload(); }
SAVE_RELEASE(m_btnFont);
m_btnFont = font;
if (m_btnFont != nullptr)
{
m_btnFont->AddRef();
m_btnFont->load();
}
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetFont(m_btnFont); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonFontSize(In API::Files::FontSize size)
{
API::Helper::Lock lock(m_sync);
m_btnFontSize = size;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetFontSize(m_btnFontSize); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonFontColor(In const API::Interface::FontColor& color)
{
API::Helper::Lock lock(m_sync);
for (unsigned int a = 0; a < 3; a++) { m_btnFontColor.Color[a] = color.Color[a]; }
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetFontColor(m_btnFontColor); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonJustify(In API::Files::Justify hJust)
{
API::Helper::Lock lock(m_sync);
m_btnJustifyH = hJust;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetJustify(m_btnJustifyH); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonJustify(In API::Files::Justify hJust, In API::Files::AnchorPoint vJust)
{
API::Helper::Lock lock(m_sync);
m_btnJustifyH = hJust;
m_btnJustifyV = vJust;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetJustify(m_btnJustifyH, m_btnJustifyV); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonJustify(In API::Files::AnchorPoint vJust)
{
API::Helper::Lock lock(m_sync);
m_btnJustifyV = vJust;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetJustify(m_btnJustifyV); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonLetterSpace(In float space)
{
API::Helper::Lock lock(m_sync);
m_btnLetterSpace = space;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetLetterSpace(m_btnLetterSpace); }
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonLineSpace(In float space)
{
API::Helper::Lock lock(m_sync);
m_btnLineSpace = space;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetLineSpace(m_btnLineSpace); }
}
void CLOAK_CALL_THIS DropDownMenu::Open()
{
API::Helper::Lock lock(m_sync);
if (m_open == false)
{
m_open = true;
for (size_t a = 0; a < m_menu.size(); a++) { m_menu[a]->Show(); }
}
}
void CLOAK_CALL_THIS DropDownMenu::Close()
{
API::Helper::Lock lock(m_sync);
if (m_open == true)
{
m_open = false;
for (size_t a = 0; a < m_menu.size(); a++) { m_menu[a]->Close(); }
m_stateSize = 0;
}
}
void CLOAK_CALL_THIS DropDownMenu::SetButtonTextOffset(In const API::Global::Math::Space2D::Vector& offset)
{
API::Helper::Lock lock(m_sync);
m_btnTextOffset = offset;
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->SetTextOffset(offset); }
}
void CLOAK_CALL_THIS DropDownMenu::CloseLevel(In size_t lvl)
{
API::Helper::Lock lock(m_sync);
for (size_t a = 0; a < m_pool.size(); a++) { m_pool[a]->CloseLevel(lvl); }
}
bool CLOAK_CALL_THIS DropDownMenu::IsOpen() const
{
API::Helper::Lock lock(m_sync);
return m_open;
}
Success(return == true) bool CLOAK_CALL_THIS DropDownMenu::iQueryInterface(In REFIID riid, Outptr void** ptr)
{
if (riid == __uuidof(API::Interface::Menu_v1::IMenu)) { *ptr = (API::Interface::Menu_v1::IMenu*)this; return true; }
else if (riid == __uuidof(API::Interface::DropDownMenu_v1::IDropDownMenu)) { *ptr = (API::Interface::DropDownMenu_v1::IDropDownMenu*)this; return true; }
else if (riid == __uuidof(DropDownMenu)) { *ptr = (DropDownMenu*)this; return true; }
return Button::iQueryInterface(riid, ptr);
}
DropDownMenu::MenuButton* CLOAK_CALL_THIS DropDownMenu::GetBtnFromPool()
{
API::Helper::Lock lock(m_sync);
if (m_usedPoolSize >= m_pool.size())
{
MenuButton* r = new DropDownMenu::MenuButton(this);
r->Initialize();
m_pool.push_back(r);
r->SetParent(this);
r->SetBackgroundTexture(m_btnBackground);
r->SetHighlightTexture(m_btnHighlight, m_btnHighlightType);
r->SetCheckTexture(m_btnChecked);
r->SetSubMenuTexture(m_btnSubMenuOpen, m_btnSubMenuClosed);
r->SetSize(m_btnWidth, m_btnHeight);
r->SetSymbolWidth(m_btnSymbolWidth);
r->SetTextMaxWidth(m_btnMaxLen);
r->SetTextOffset(m_btnTextOffset);
r->SetFont(m_btnFont);
r->SetFontSize(m_btnFontSize);
r->SetFontColor(m_btnFontColor);
r->SetJustify(m_btnJustifyH, m_btnJustifyV);
r->SetLetterSpace(m_btnLetterSpace);
r->SetLineSpace(m_btnLineSpace);
}
return m_pool[m_usedPoolSize++];
}
void CLOAK_CALL_THIS DropDownMenu::RegisterClose()
{
API::Helper::Lock lock(m_sync);
if (m_stateSize > 0) { m_stateSize--; }
}
void CLOAK_CALL_THIS DropDownMenu::RegisterOpen(In API::Interface::Menu_v1::ButtonID id, In size_t lvl)
{
API::Helper::Lock lock(m_sync);
if (m_stateSize == lvl)
{
if (m_openState.size() == m_stateSize) { m_openState.push_back(id); }
else { m_openState[m_stateSize] = id; }
m_stateSize++;
}
}
CLOAK_CALL DropDownMenu::MenuButton::MenuButton(In DropDownMenu* par) : m_menuPar(par)
{
m_open = false;
m_checked = false;
m_canBeChecked = false;
m_checkSpace = false;
m_symWidth = 0;
m_imgChecked = nullptr;
m_imgSubMenuOpen = nullptr;
m_imgSubMenuClosed = nullptr;
m_ID = 0;
}
CLOAK_CALL DropDownMenu::MenuButton::~MenuButton()
{
SAVE_RELEASE(m_imgChecked);
SAVE_RELEASE(m_imgSubMenuOpen);
SAVE_RELEASE(m_imgSubMenuClosed);
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::ResetMenu()
{
Hide();
m_subMenu.clear();
m_open = false;
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::SetMenu(In const API::Interface::Menu_v1::MENU_ITEM& desc, In const MenuAnchor& anchor, In size_t level)
{
API::Helper::Lock lock(m_sync);
SetText(desc.Text);
m_checked = desc.Checked && desc.CanChecked;
m_canBeChecked = desc.CanChecked;
m_checkSpace = anchor.CanCheck;
m_menAnch = anchor;
m_ID = desc.ID;
m_level = level;
UpdateMenuAnchor();
UpdateTextOffset();
if (CloakDebugCheckOK(desc.SubMenuSize == 0 || desc.SubMenu != nullptr, API::Global::Debug::Error::ILLEGAL_ARGUMENT, false))
{
MenuAnchor menAnch;
menAnch.CanCheck = false;
for (size_t a = 0; a < desc.SubMenuSize; a++)
{
if (desc.SubMenu[a].CanChecked == true)
{
menAnch.CanCheck = true;
break;
}
}
for (size_t a = 0; a < desc.SubMenuSize; a++)
{
MenuButton* b = m_menuPar->GetBtnFromPool();
m_subMenu.push_back(b);
menAnch.MenuNum = a;
menAnch.Point = API::Interface::AnchorPoint::TOPLEFT;
menAnch.RelativePoint = API::Interface::AnchorPoint::TOPRIGHT;
menAnch.RelativeAnchor = this;
b->SetMenu(desc.SubMenu[a], menAnch, level + 1);
}
}
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::Open()
{
API::Helper::Lock lock(m_sync);
if (m_open == false)
{
m_menuPar->CloseLevel(m_level);
m_menuPar->RegisterOpen(m_ID, m_level);
m_open = true;
for (size_t a = 0; a < m_subMenu.size(); a++) { m_subMenu[a]->Show(); }
}
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::Close()
{
API::Helper::Lock lock(m_sync);
Hide();
if (m_open == true)
{
m_open = false;
for (size_t a = 0; a < m_subMenu.size(); a++) { m_subMenu[a]->Close(); }
m_menuPar->RegisterClose();
}
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::SetCheckTexture(In API::Files::ITexture* img)
{
API::Helper::Lock lock(m_sync);
GUI_SET_TEXTURE(img, m_imgChecked);
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::SetSubMenuTexture(In API::Files::ITexture* open, In API::Files::ITexture* closed)
{
API::Helper::Lock lock(m_sync);
GUI_SET_TEXTURE(open, m_imgSubMenuOpen);
GUI_SET_TEXTURE(closed, m_imgSubMenuClosed);
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::SetSymbolWidth(In float W)
{
API::Helper::Lock lock(m_sync);
m_symWidth = W;
UpdateTextOffset();
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::SetTextOffset(In const API::Global::Math::Space2D::Vector& offset)
{
API::Helper::Lock lock(m_sync);
m_baseTextOff = offset;
UpdateTextOffset();
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::SetOpenState(In const API::List<API::Interface::Menu_v1::ButtonID>& state, In size_t index, In size_t maxI)
{
API::Helper::Lock lock(m_sync);
if (state[index] == m_ID)
{
m_open = true;
for (size_t a = 0; a < m_subMenu.size(); a++)
{
DropDownMenu::MenuButton* b = m_subMenu[a];
b->Show();
if (index + 1 < maxI) { b->SetOpenState(state, index + 1, maxI); }
}
}
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::CloseLevel(In size_t lvl)
{
API::Helper::Lock lock(m_sync);
if (m_level == lvl) { Close(); }
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::SetSize(In float width, In float height, In_opt API::Interface::SizeType type)
{
API::Helper::Lock lock(m_sync);
Button::SetSize(width, height, type);
UpdateMenuAnchor();
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::OnClick(const API::Global::Events::onClick& ev)
{
API::Helper::Lock lock(m_sync);
if (IS_CLICK(ev, LEFT))
{
API::Helper::Lock parLock(m_menuPar->m_sync);
if (m_canBeChecked) { m_checked = !m_checked; }
if (m_open) { Close(); }
else { Open(); }
API::Global::Events::onMenuButtonClick mbc;
mbc.activeKeys = ev.activeKeys;
mbc.key = ev.key;
mbc.clickPos = ev.clickPos;
mbc.menuButtonID = m_ID;
mbc.moveDir = ev.moveDir;
mbc.pressType = ev.pressType;
mbc.previousType = ev.previousType;
mbc.relativePos = ev.relativePos;
mbc.isChecked = m_checked;
m_menuPar->triggerEvent(mbc);
}
}
bool CLOAK_CALL_THIS DropDownMenu::MenuButton::iUpdateDrawInfo(In unsigned long long time)
{
m_checkedVertex.Position = m_pos;
m_checkedVertex.Color[0] = API::Helper::Color::White;
m_checkedVertex.Size.X = m_symWidth;
m_checkedVertex.Size.Y = m_Height;
m_checkedVertex.TexBottomRight.X = 1;
m_checkedVertex.TexBottomRight.Y = 1;
m_checkedVertex.TexTopLeft.X = 0;
m_checkedVertex.TexTopLeft.Y = 0;
m_checkedVertex.Rotation.Sinus = m_rotation.sin_a;
m_checkedVertex.Rotation.Cosinus = m_rotation.cos_a;
m_checkedVertex.Flags = API::Rendering::Vertex2DFlags::NONE;
const float xoff = m_Width - m_symWidth;
m_subMenuVertex.Position.X = m_pos.X + (m_rotation.cos_a*xoff);
m_subMenuVertex.Position.Y = m_pos.Y + (m_rotation.sin_a*xoff);
m_subMenuVertex.Color[0] = API::Helper::Color::White;
m_subMenuVertex.Size.X = m_symWidth;
m_subMenuVertex.Size.Y = m_Height;
m_subMenuVertex.TexBottomRight.X = 1;
m_subMenuVertex.TexBottomRight.Y = 1;
m_subMenuVertex.TexTopLeft.X = 0;
m_subMenuVertex.TexTopLeft.Y = 0;
m_subMenuVertex.Rotation.Sinus = m_rotation.sin_a;
m_subMenuVertex.Rotation.Cosinus = m_rotation.cos_a;
m_subMenuVertex.Flags = API::Rendering::Vertex2DFlags::NONE;
m_d_checkedInfo.Update(m_imgChecked, m_checked);
m_d_subMenuOpenInfo.Update(m_imgSubMenuOpen, m_subMenu.size() > 0 && m_open == true);
m_d_subMenuClosedInfo.Update(m_imgSubMenuClosed, m_subMenu.size() > 0 && m_open == false);
return Button::iUpdateDrawInfo(time);
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::iDraw(In API::Rendering::Context_v1::IContext2D* context)
{
Button::iDraw(context);
if (m_d_checkedInfo.CanDraw())
{
context->Draw(this, m_d_checkedInfo.GetImage(), m_checkedVertex, 5);
}
if (m_d_subMenuOpenInfo.CanDraw())
{
context->Draw(this, m_d_subMenuOpenInfo.GetImage(), m_subMenuVertex, 5);
}
else if (m_d_subMenuClosedInfo.CanDraw())
{
context->Draw(this, m_d_subMenuClosedInfo.GetImage(), m_subMenuVertex, 5);
}
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::UpdateMenuAnchor()
{
API::Helper::Lock lock(m_sync);
API::Interface::Anchor anch;
anch.point = m_menAnch.Point;
anch.relativePoint = m_menAnch.RelativePoint;
anch.relativeTarget = m_menAnch.RelativeAnchor;
anch.offset.X = 0;
anch.offset.Y = m_menAnch.MenuNum*GetHeight();
SetAnchor(anch);
}
void CLOAK_CALL_THIS DropDownMenu::MenuButton::UpdateTextOffset()
{
API::Helper::Lock lock(m_sync);
m_textOffset.X = m_baseTextOff.X + (m_checkSpace ? m_symWidth : 0);
m_textOffset.Y = m_baseTextOff.Y;
}
}
}
}
} | 36.581673 | 159 | 0.624428 | [
"vector"
] |
acdb195ccefad35ddea4ea67e811a18960a8920f | 11,504 | cpp | C++ | src/poller/PollerImplEpoll.cpp | bexoft/finalmq | 2232074cf448a829ef009185c7eae438ecc2440d | [
"MIT"
] | 11 | 2020-10-13T11:50:29.000Z | 2022-02-27T11:47:34.000Z | src/poller/PollerImplEpoll.cpp | bexoft/finalmq | 2232074cf448a829ef009185c7eae438ecc2440d | [
"MIT"
] | 15 | 2020-10-07T18:01:27.000Z | 2021-07-08T09:09:13.000Z | src/poller/PollerImplEpoll.cpp | bexoft/finalmq | 2232074cf448a829ef009185c7eae438ecc2440d | [
"MIT"
] | 2 | 2020-10-07T21:29:06.000Z | 2020-10-14T18:02:17.000Z | //MIT License
//Copyright (c) 2020 bexoft GmbH (mail@bexoft.de)
//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.
#if !defined(WIN32) && !defined(__MINGW32__)
#include "finalmq/poller/PollerImplEpoll.h"
#include "finalmq/helpers/OperatingSystem.h"
#include "finalmq/helpers/ModulenameFinalmq.h"
#include "finalmq/logger/LogStream.h"
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <assert.h>
namespace finalmq {
PollerImplEpoll::PollerImplEpoll()
: m_socketDescriptorsStable(ATOMIC_FLAG_INIT)
{
m_socketDescriptorsStable.test_and_set();
}
PollerImplEpoll::~PollerImplEpoll()
{
if (m_fdEpoll != -1)
{
OperatingSystem::instance().close(m_fdEpoll);
}
}
void PollerImplEpoll::init()
{
m_fdEpoll = OperatingSystem::instance().epoll_create1(EPOLL_CLOEXEC);
assert(m_fdEpoll != -1);
int res = OperatingSystem::instance().makeSocketPair(m_controlSocketRead, m_controlSocketWrite);
if (res == 0)
{
assert(m_controlSocketWrite);
assert(m_controlSocketRead);
addSocketEnableRead(m_controlSocketRead);
}
}
void PollerImplEpoll::addSocket(const SocketDescriptorPtr& fd)
{
std::unique_lock<std::mutex> locker(m_mutex);
auto result = m_socketDescriptors.insert(std::make_pair(fd, 0));
if (result.second)
{
epoll_event ev;
ev.events = 0;
ev.data.fd = fd->getDescriptor();
int res = OperatingSystem::instance().epoll_ctl(m_fdEpoll, EPOLL_CTL_ADD, fd->getDescriptor(), &ev);
if (res == -1)
{
streamFatal << "epoll_ctl failed with errno: " << errno;
}
assert(res != -1);
sockedDescriptorHasChanged();
}
else
{
// socket already added
}
locker.unlock();
}
void PollerImplEpoll::addSocketEnableRead(const SocketDescriptorPtr& fd)
{
std::unique_lock<std::mutex> locker(m_mutex);
auto result = m_socketDescriptors.insert(std::make_pair(fd, EPOLLIN));
if (result.second)
{
epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = fd->getDescriptor();
int res = OperatingSystem::instance().epoll_ctl(m_fdEpoll, EPOLL_CTL_ADD, fd->getDescriptor(), &ev);
if (res == -1)
{
streamFatal << "epoll_ctl failed with errno: " << errno;
}
assert(res != -1);
sockedDescriptorHasChanged();
}
else
{
// socket already added
}
locker.unlock();
}
void PollerImplEpoll::removeSocket(const SocketDescriptorPtr& fd)
{
std::unique_lock<std::mutex> locker(m_mutex);
auto it = m_socketDescriptors.find(fd);
if (it != m_socketDescriptors.end())
{
epoll_event ev; // to be compatible with linux versions before 2.6.9
ev.events = 0;
ev.data.fd = fd->getDescriptor();
int res = OperatingSystem::instance().epoll_ctl(m_fdEpoll, EPOLL_CTL_DEL, fd->getDescriptor(), &ev);
if (res == -1)
{
streamFatal << "epoll_ctl failed with errno: " << errno;
}
assert(res != -1);
m_socketDescriptors.erase(it);
sockedDescriptorHasChanged();
}
else
{
// socket not added
}
locker.unlock();
}
void PollerImplEpoll::enableRead(const SocketDescriptorPtr& fd)
{
std::unique_lock<std::mutex> locker(m_mutex);
auto it = m_socketDescriptors.find(fd);
if (it != m_socketDescriptors.end())
{
it->second |= EPOLLIN;
epoll_event ev;
ev.events = it->second;
ev.data.fd = fd->getDescriptor();
int res = OperatingSystem::instance().epoll_ctl(m_fdEpoll, EPOLL_CTL_MOD, fd->getDescriptor(), &ev);
if (res == -1)
{
streamFatal << "epoll_ctl failed with errno: " << errno;
}
assert(res != -1);
}
else
{
// error: socket not added
}
locker.unlock();
}
void PollerImplEpoll::disableRead(const SocketDescriptorPtr& fd)
{
std::unique_lock<std::mutex> locker(m_mutex);
auto it = m_socketDescriptors.find(fd);
if (it != m_socketDescriptors.end())
{
it->second &= ~EPOLLIN;
epoll_event ev;
ev.events = it->second;
ev.data.fd = fd->getDescriptor();
int res = OperatingSystem::instance().epoll_ctl(m_fdEpoll, EPOLL_CTL_MOD, fd->getDescriptor(), &ev);
if (res == -1)
{
streamFatal << "epoll_ctl failed with errno: " << errno;
}
assert(res != -1);
}
else
{
// error: socket not added
}
locker.unlock();
}
void PollerImplEpoll::enableWrite(const SocketDescriptorPtr& fd)
{
std::unique_lock<std::mutex> locker(m_mutex);
auto it = m_socketDescriptors.find(fd);
if (it != m_socketDescriptors.end())
{
it->second |= EPOLLOUT;
epoll_event ev;
ev.events = it->second;
ev.data.fd = fd->getDescriptor();
int res = OperatingSystem::instance().epoll_ctl(m_fdEpoll, EPOLL_CTL_MOD, fd->getDescriptor(), &ev);
if (res == -1)
{
streamFatal << "epoll_ctl failed with errno: " << errno;
}
assert(res != -1);
}
else
{
// error: socket not added
}
locker.unlock();
}
void PollerImplEpoll::disableWrite(const SocketDescriptorPtr& fd)
{
std::unique_lock<std::mutex> locker(m_mutex);
auto it = m_socketDescriptors.find(fd);
if (it != m_socketDescriptors.end())
{
it->second &= ~EPOLLOUT;
epoll_event ev;
ev.events = it->second;
ev.data.fd = fd->getDescriptor();
int res = OperatingSystem::instance().epoll_ctl(m_fdEpoll, EPOLL_CTL_MOD, fd->getDescriptor(), &ev);
if (res == -1)
{
streamFatal << "epoll_ctl failed with errno: " << errno;
}
assert(res != -1);
}
else
{
// error: socket not added
}
locker.unlock();
}
void PollerImplEpoll::sockedDescriptorHasChanged()
{
m_socketDescriptorsStable.clear(std::memory_order_release);
}
void PollerImplEpoll::updateSocketDescriptors()
{
m_socketDescriptorsConstForEpoll.clear();
m_socketDescriptorsConstForEpoll.reserve(m_socketDescriptors.size());
for (auto it = m_socketDescriptors.begin(); it != m_socketDescriptors.end(); ++it)
{
m_socketDescriptorsConstForEpoll.push_back(it->first);
}
}
void PollerImplEpoll::collectSockets(int res)
{
m_result.clear();
if (res > 0)
{
assert(res <= static_cast<int>(m_events.size()));
for (int i = 0; i < res; i++)
{
const epoll_event& pe = m_events[i];
SOCKET sd = pe.data.fd;
DescriptorInfo* descriptorInfo = nullptr;
if (pe.events & (EPOLLERR | EPOLLHUP))
{
descriptorInfo = &m_result.descriptorInfos.add();
descriptorInfo->sd = sd;
descriptorInfo->disconnected = true;
}
if (pe.events & EPOLLOUT)
{
if (descriptorInfo == nullptr)
{
descriptorInfo = &m_result.descriptorInfos.add();
descriptorInfo->sd = sd;
}
assert(descriptorInfo);
assert(descriptorInfo->sd == sd);
if (!descriptorInfo->disconnected)
{
descriptorInfo->writable = true;
}
}
if (pe.events & EPOLLIN)
{
int countRead = 0;
int resIoCtl = OperatingSystem::instance().ioctlInt(sd, FIONREAD, &countRead);
if (resIoCtl == -1)
{
countRead = 0;
}
if (sd == m_controlSocketRead->getDescriptor())
{
if (countRead > 0)
{
// read pending bytes from control socket
std::vector<char> buffer(countRead);
OperatingSystem::instance().recv(sd, buffer.data(), buffer.size(), 0);
char info = 0;
for (size_t i = 0; i < buffer.size(); ++i)
{
info |= buffer[i];
}
m_result.releaseWait = info;
}
else
{
// control socket broken
}
}
else
{
if (descriptorInfo == nullptr)
{
descriptorInfo = &m_result.descriptorInfos.add();
descriptorInfo->sd = sd;
}
assert(descriptorInfo);
assert(descriptorInfo->sd == sd);
if (!descriptorInfo->disconnected)
{
descriptorInfo->readable = true;
descriptorInfo->bytesToRead = countRead;
}
}
}
}
}
else if (res == 0)
{
// timeout
m_result.timeout = true;
}
else
{
// error
m_result.error = true;
}
}
const PollerResult& PollerImplEpoll::wait(std::int32_t timeout)
{
// check if init happened
assert(m_fdEpoll != -1);
int res = 0;
int err = 0;
if (!m_socketDescriptorsStable.test_and_set(std::memory_order_acquire))
{
std::unique_lock<std::mutex> locker(m_mutex);
updateSocketDescriptors();
}
do
{
res = OperatingSystem::instance().epoll_pwait(m_fdEpoll, &m_events[0], m_events.size(), timeout, nullptr);
if (res == -1)
{
err = OperatingSystem::instance().getLastError();
}
} while (res == -1 && (err == SOCKETERROR(EINTR) || err == SOCKETERROR(EAGAIN)));
if (res == -1)
{
streamError << "epoll_pwait failed with errno: " << err;
}
collectSockets(res);
if (!m_socketDescriptorsStable.test_and_set(std::memory_order_acquire))
{
std::unique_lock<std::mutex> locker(m_mutex);
updateSocketDescriptors();
}
return m_result;
}
void PollerImplEpoll::releaseWait(char info)
{
if (m_controlSocketWrite)
{
OperatingSystem::instance().send(m_controlSocketWrite->getDescriptor(), &info, 1, 0);
}
}
} // namespace finalmq
#endif
| 28.127139 | 114 | 0.571888 | [
"vector"
] |
acdc8530d3f22c990e84cd44f427e4109a663db4 | 1,232 | cpp | C++ | UVa-problems/10583.cpp | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | UVa-problems/10583.cpp | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | UVa-problems/10583.cpp | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | /* UVa 10583 - Ubiquitous Religions */
// https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1524
// Date: 2021-08-18 04:55:10
// Run time: 0.160
// Verdict: AC
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
class UFDS {
private:
vector<int> p, rank;
int num_of_sets;
public:
UFDS(int n) {
p.assign(n + 1, 0); for (int i = 1; i <= n; i++) p[i] = i;
rank.assign(n + 1, 0);
num_of_sets = n;
}
int find_set(int i) { return (p[i] == i ? i : (p[i] = find_set(p[i]))); }
bool is_same_set(int a, int b) { return find_set(a) == find_set(b); }
void union_set(int a, int b) {
if (!is_same_set(a, b)) {
int x = find_set(a), y = find_set(b);
if (rank[x] > rank[y]) swap(x, y);
if (rank[x] == rank[y]) ++rank[y];
p[x] = y;
--num_of_sets;
}
}
int count() { return num_of_sets; }
};
int main() {
int n, m, a, b, c = 0;
while (cin >> n >> m, n | m) {
UFDS ufds(n);
while (m--) {
cin >> a >> b;
ufds.union_set(a, b);
}
printf("Case %d: %d\n", ++c, ufds.count());
}
} | 24.64 | 99 | 0.499188 | [
"vector"
] |
ace16959de4dcda7ac22c8c7342a853fb61c70e3 | 8,113 | cc | C++ | runtime/onert/core/src/util/ShapeInference.cc | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | runtime/onert/core/src/util/ShapeInference.cc | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | runtime/onert/core/src/util/ShapeInference.cc | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd. 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 "util/Utils.h"
#include "ir/InternalType.h"
#include "ir/Shape.h"
#include "ir/operation/AvgPool2D.h"
#include "ir/operation/MaxPool2D.h"
#include "util/ShapeInference.h"
namespace onert
{
namespace shape_inference
{
//
// Helper functions
//
namespace
{
template <typename T, typename U>
typename std::enable_if<std::is_integral<T>::value && std::is_integral<U>::value,
typename std::common_type<T, U>::type>::type
ceil_div(T dividend, U divisor)
{
assert(dividend > 0 && divisor > 0 && "this implementations is for positive numbers only");
return (dividend + divisor - 1) / divisor;
}
// Calculate the result of broadcast of two shapes
ir::Shape broadcastShapes(const ir::Shape &lhs_shape, const ir::Shape &rhs_shape)
{
ir::Shape out_shape;
auto max_rank = std::max(lhs_shape.rank(), rhs_shape.rank());
for (int idx = 0; idx < max_rank; ++idx)
{
// Go over operands dimensions from right to left
int lhs_idx = lhs_shape.rank() - idx - 1;
int rhs_idx = rhs_shape.rank() - idx - 1;
int32_t lhs_dim = lhs_idx >= 0 ? lhs_shape.dim(lhs_idx) : 1;
int32_t rhs_dim = rhs_idx >= 0 ? rhs_shape.dim(rhs_idx) : 1;
if (lhs_dim != 1 && rhs_dim != 1 && lhs_dim != rhs_dim)
throw std::runtime_error("Incompatible shapes for broadcast");
out_shape.prepend(std::max(lhs_dim, rhs_dim));
}
return out_shape;
}
// Calculate output height and width of convolution-like operation
std::pair<int, int> calcConvLikeHeightAndWidth(const int in_h, const int in_w, const int ker_h,
const int ker_w, const ir::Padding pad,
const ir::Stride stride)
{
int32_t out_h = 0, out_w = 0;
switch (pad.type)
{
case ir::PaddingType::SAME:
out_h = ceil_div(in_h, stride.vertical);
out_w = ceil_div(in_w, stride.horizontal);
break;
case ir::PaddingType::VALID:
out_h = ceil_div(in_h - ker_h + 1, stride.vertical);
out_w = ceil_div(in_w - ker_w + 1, stride.horizontal);
break;
case ir::PaddingType::EXPLICIT:
out_h = (in_h + pad.param.top + pad.param.bottom - ker_h) / stride.vertical + 1;
out_w = (in_w + pad.param.left + pad.param.right - ker_w) / stride.horizontal + 1;
break;
default:
assert(false);
}
return {out_h, out_w};
}
} // namespace
//
// Shape inference
//
Shapes inferEltwiseShape(const ir::Shape &lhs_shape, const ir::Shape &rhs_shape)
{
return {broadcastShapes(lhs_shape, rhs_shape)};
}
Shapes inferAvgPoolShape(const ir::Shape &in_shape, const ir::operation::AvgPool2D::Param ¶m,
const ir::Layout layout)
{
assert(layout == ir::Layout::NHWC);
auto ifm_shape = in_shape.asFeature(layout);
const auto out_h_w = calcConvLikeHeightAndWidth(ifm_shape.H, ifm_shape.W, param.kh, param.kw,
param.padding, param.stride);
// Pooling don't change number of channels and batch size
return {ir::Shape{ifm_shape.N, out_h_w.first, out_h_w.second, ifm_shape.C}};
}
Shapes inferConcatShape(const Shapes &in_shapes, const ir::operation::Concat::Param ¶m)
{
const int32_t concat_axis = param.axis;
const auto &first_in_shape = in_shapes[0];
// Check that all shapes are equal except for concat axis dimension
for (const auto &in_shape : in_shapes)
{
assert(in_shape.rank() == first_in_shape.rank());
for (int64_t dim_idx = 0; dim_idx < in_shape.rank(); ++dim_idx)
assert(dim_idx == concat_axis || in_shape.dim(dim_idx) == first_in_shape.dim(dim_idx));
}
// Calculate output shape
ir::Shape out_shape(first_in_shape);
out_shape.dim(concat_axis) = 0;
for (const auto &in_shape : in_shapes)
out_shape.dim(concat_axis) += in_shape.dim(concat_axis);
return {out_shape};
}
Shapes inferMaxPoolShape(const ir::Shape &in_shape, const ir::operation::MaxPool2D::Param ¶m,
const ir::Layout layout)
{
assert(layout == ir::Layout::NHWC);
auto ifm_shape = in_shape.asFeature(layout);
const auto out_h_w = calcConvLikeHeightAndWidth(ifm_shape.H, ifm_shape.W, param.kh, param.kw,
param.padding, param.stride);
// Pooling don't change number of channels and batch size
return {ir::Shape{ifm_shape.N, out_h_w.first, out_h_w.second, ifm_shape.C}};
}
Shapes inferConv2DShape(const ir::Shape &in_shape, const ir::Shape &ker_shape,
const ir::operation::Conv2D::Param ¶m, ir::Layout layout)
{
assert(layout == ir::Layout::NHWC);
auto ifm_shape = in_shape.asFeature(layout);
// Kernel format is [depth_out, kernel_height, kernel_width, depth_in]
auto kf_shape = ker_shape.asFeature(layout);
assert(ifm_shape.C == kf_shape.C);
const auto out_h_w = calcConvLikeHeightAndWidth(ifm_shape.H, ifm_shape.W, kf_shape.H, kf_shape.W,
param.padding, param.stride);
return {ir::Shape{ifm_shape.N, out_h_w.first, out_h_w.second, kf_shape.N}};
}
Shapes inferDepthwiseConv2DShape(const ir::Shape &in_shape, const ir::Shape &ker_shape,
const ir::operation::DepthwiseConv2D::Param ¶m,
ir::Layout layout)
{
assert(layout == ir::Layout::NHWC);
auto ifm_shape = in_shape.asFeature(layout);
// Kernel format is [1, kernel_height, kernel_width, depth_out]
auto kf_shape = ker_shape.asFeature(layout);
assert(kf_shape.C == static_cast<int32_t>(ifm_shape.C * param.multiplier));
assert(kf_shape.N == 1);
const auto out_h_w = calcConvLikeHeightAndWidth(ifm_shape.H, ifm_shape.W, kf_shape.H, kf_shape.W,
param.padding, param.stride);
return {ir::Shape{ifm_shape.N, out_h_w.first, out_h_w.second, kf_shape.C}};
}
Shapes inferFullyConnectedShape(const ir::Shape &in_shape, const ir::Shape &ker_shape)
{
assert(in_shape.rank() >= 2);
assert(ker_shape.rank() == 2);
const auto input_size_with_batch = in_shape.num_elements();
const auto num_units = ker_shape.dim(0);
const auto input_size = ker_shape.dim(1);
const auto batch_size = input_size_with_batch / input_size;
assert(input_size_with_batch % input_size == 0);
return {{ir::Shape({static_cast<int32_t>(batch_size), num_units})}};
}
/*
StaticInferer
*/
void StaticInferer::visit(const ir::operation::Reshape &op)
{
const auto input_idx{op.getInputs().at(ir::operation::Reshape::Input::INPUT)};
const auto &input = _operands.at(input_idx);
// get mutable output operand
const auto output_idx = op.getOutputs().at(0);
ir::Operand &output = _operands.at(output_idx);
// if input is dynamic, output also becomes dynamic
if (input.info().memAllocType() == ir::MemAllocType::DYNAMIC)
{
output.info().memAllocType(ir::MemAllocType::DYNAMIC);
return;
}
if (op.getInputs().size() == 1)
{
// no change on output shape
return;
}
// Let's check the second input
const auto shape_idx{op.getInputs().at(ir::operation::Reshape::Input::SHAPE)};
const auto &shape = _operands.at(shape_idx);
if (shape.isConstant())
{
// if shape is from Const, TFLC put the shape of output into tensor
// no change on output shape
return;
}
// if shape is NOT Const, set output shape to be dynamic_
output.info().memAllocType(ir::MemAllocType::DYNAMIC);
}
} // namespace shape_inference
} // namespace onert
| 33.524793 | 99 | 0.669543 | [
"shape"
] |
ace86d8ad18227cbbedc8519ae6e56d8704cd88f | 9,455 | cpp | C++ | Project/Riaju1/Plugins/SpriteStudio5/Source/SpriteStudio5/Private/Player/SsPlayer.cpp | SpriteStudio/RiaJuSniper_UnrealEngine4Project | 5b7ffb0e4161eaa9249c164c0dfeb16b636ff6ae | [
"MIT"
] | 3 | 2018-04-16T23:58:23.000Z | 2020-10-24T04:42:43.000Z | Project/Riaju1/Plugins/SpriteStudio5/Source/SpriteStudio5/Private/Player/SsPlayer.cpp | SpriteStudio/RiaJuSniper_UnrealEngine4Project | 5b7ffb0e4161eaa9249c164c0dfeb16b636ff6ae | [
"MIT"
] | null | null | null | Project/Riaju1/Plugins/SpriteStudio5/Source/SpriteStudio5/Private/Player/SsPlayer.cpp | SpriteStudio/RiaJuSniper_UnrealEngine4Project | 5b7ffb0e4161eaa9249c164c0dfeb16b636ff6ae | [
"MIT"
] | 6 | 2018-04-12T20:27:12.000Z | 2021-03-07T19:54:49.000Z | #include "SpriteStudio5PrivatePCH.h"
#include "SsPlayer.h"
#include "SsProject.h"
#include "SsAnimePack.h"
#include "SsPlayerCellmap.h"
#include "SsPlayerAnimedecode.h"
#include "SsString_uty.h"
#include "SsPlayerPartState.h"
// コンストラクタ
FSsPlayer::FSsPlayer()
: PlayRate(1.f)
, LoopCount(-1)
, bRoundTrip(false)
, bFlipH(false)
, bFlipV(false)
, SsProject(NULL)
, bPlaying(false)
, bFirstTick(false)
, AnimPivot(0.f,0.f)
, PlayingAnimPackIndex(-1)
, PlayingAnimationIndex(-1)
{
}
// SsProjectアセットをセット
void FSsPlayer::SetSsProject(TWeakObjectPtr<USsProject> InSsProject)
{
SsProject = InSsProject;
if(!SsProject.IsValid())
{
return;
}
Decoder = MakeShareable(new FSsAnimeDecoder());
CellMapList = MakeShareable(new FSsCellMapList());
PlayingAnimPackIndex = -1;
PlayingAnimationIndex = -1;
}
// 更新
FSsPlayerTickResult FSsPlayer::Tick(float DeltaSeconds)
{
FSsPlayerTickResult Result;
if(bPlaying)
{
TickAnimation(DeltaSeconds, Result);
}
return Result;
}
// アニメーションの更新
void FSsPlayer::TickAnimation(float DeltaSeconds, FSsPlayerTickResult& Result)
{
if(!Decoder.IsValid())
{
return;
}
// 更新後のフレーム
float BkAnimeFrame = Decoder->GetPlayFrame();
float AnimeFrame = BkAnimeFrame + (PlayRate * DeltaSeconds * Decoder->GetAnimeFPS());
// 再生開始フレームと同フレームに設定されたユーザーデータを拾うため、初回更新時のみBkAnimeFrameを誤魔化す
if(bFirstTick)
{
BkAnimeFrame -= (.0f <= PlayRate) ? .1f : -.1f;
}
// 0フレームを跨いだか
bool bBeyondZeroFrame = false;
// 最終フレーム以降で順方向再生
if((Decoder->GetAnimeEndFrame() <= AnimeFrame) && (0.f < PlayRate))
{
if(0 < LoopCount)
{
// ループ回数更新
--LoopCount;
// ループ回数の終了
if(0 == LoopCount)
{
AnimeFrame = (float)Decoder->GetAnimeEndFrame();
Pause();
Result.bEndPlay = true;
}
}
FindUserDataInInterval(Result, BkAnimeFrame, (float)Decoder->GetAnimeEndFrame());
if(bPlaying)
{
float AnimeFrameSurplus = AnimeFrame - Decoder->GetAnimeEndFrame(); // 極端に大きなDeltaSecondsは考慮しない
// 往復
if(bRoundTrip)
{
AnimeFrame = Decoder->GetAnimeEndFrame() - AnimeFrameSurplus;
PlayRate *= -1.f;
FindUserDataInInterval(Result, (float)Decoder->GetAnimeEndFrame(), AnimeFrame);
}
// ループ
else
{
AnimeFrame = AnimeFrameSurplus;
FindUserDataInInterval(Result, -.1f, AnimeFrame);
}
}
bBeyondZeroFrame = true;
}
// 0フレーム以前で逆方向再生
else if((AnimeFrame < 0.f) && (PlayRate < 0.f))
{
if(0 < LoopCount)
{
// ループ回数更新
--LoopCount;
// ループ回数の終了
if(0 == LoopCount)
{
AnimeFrame = 0.f;
Pause();
Result.bEndPlay = true;
}
}
FindUserDataInInterval(Result, BkAnimeFrame, 0.f);
if(bPlaying)
{
// 往復
if(bRoundTrip)
{
AnimeFrame = -AnimeFrame;
PlayRate *= -1.f;
FindUserDataInInterval(Result, 0.f, AnimeFrame);
}
// ループ
else
{
AnimeFrame = Decoder->GetAnimeEndFrame() + AnimeFrame;
FindUserDataInInterval(Result, (float)Decoder->GetAnimeEndFrame()+.1f, AnimeFrame);
}
}
bBeyondZeroFrame = true;
}
else
{
FindUserDataInInterval(Result, BkAnimeFrame, AnimeFrame);
}
Decoder->SetPlayFrame( AnimeFrame );
Decoder->SetDeltaForIndependentInstance( DeltaSeconds );
if(bBeyondZeroFrame)
{
Decoder->ReloadEffects();
}
Decoder->Update();
RenderParts.Empty();
Decoder->CreateRenderParts(RenderParts);
// 水平反転
if(bFlipH)
{
for(int32 i = 0; i < RenderParts.Num(); ++i)
{
for(int32 v = 0; v < 4; ++v)
{
RenderParts[i].Vertices[v].Position.X = 1.f - RenderParts[i].Vertices[v].Position.X;
}
}
}
// 垂直反転
if(bFlipV)
{
for(int32 i = 0; i < RenderParts.Num(); ++i)
{
for(int32 v = 0; v < 4; ++v)
{
RenderParts[i].Vertices[v].Position.Y = 1.f - RenderParts[i].Vertices[v].Position.Y;
}
}
}
// テクスチャ差し替え
if(0 < TextureReplacements.Num())
{
for(int32 i = 0; i < RenderParts.Num(); ++i)
{
TWeakObjectPtr<UTexture>* ReplaceTexture = TextureReplacements.Find(RenderParts[i].PartIndex);
if(ReplaceTexture && (*ReplaceTexture).IsValid())
{
RenderParts[i].Texture = (*ReplaceTexture).Get();
}
}
}
Result.bUpdate = true;
bFirstTick = false;
}
// 指定区間内のUserDataキーをResultに格納する
// Start < Key <= End
void FSsPlayer::FindUserDataInInterval(FSsPlayerTickResult& Result, float Start, float End)
{
float IntervalMin = FMath::Min(Start, End);
float IntervalMax = FMath::Max(Start, End);
const TArray<FSsPartAndAnime>& PartAnime = Decoder->GetPartAnime();
for(int32 i = 0; i < PartAnime.Num(); ++i)
{
FSsPart* Part = PartAnime[i].Key;
FSsPartAnime* Anime = PartAnime[i].Value;
if((NULL == Part) || (NULL == Anime))
{
continue;
}
for(int32 j = 0; j < Anime->Attributes.Num(); ++j)
{
FSsAttribute* Attr = &(Anime->Attributes[j]);
if(Attr->Tag != SsAttributeKind::User)
{
continue;
}
for(int32 k = 0; k < Attr->Key.Num(); ++k)
{
float FloatTime = (float)Attr->Key[k].Time;
if( ((IntervalMin < FloatTime) && (FloatTime < IntervalMax))
|| (FloatTime == End)
)
{
FSsUserData NewUserData;
NewUserData.PartName = Part->PartName;
NewUserData.PartIndex = i;
NewUserData.KeyFrame = Attr->Key[k].Time;
FSsValue& Value = Attr->Key[k].Value;
if((Value.Type == SsValueType::HashType) && (Value._Hash))
{
for(int32 l = 0; l < Value._Hash->Num(); ++l)
{
if(Value._Hash->Contains(TEXT("integer")))
{
NewUserData.Value.bUseInteger = true;
NewUserData.Value.Integer = (*Value._Hash)[TEXT("integer")].get<int>();
}
if(Value._Hash->Contains(TEXT("rect")))
{
NewUserData.Value.bUseRect = true;
FString temp = (*Value._Hash)[TEXT("rect")].get<FString>();
TArray<FString> tempArr;
tempArr.Empty(4);
split_string(temp, ' ', tempArr);
if(4 == tempArr.Num())
{
NewUserData.Value.Rect.Left = (float)FCString::Atof(*tempArr[0]);
NewUserData.Value.Rect.Top = (float)FCString::Atof(*tempArr[1]);
NewUserData.Value.Rect.Right = (float)FCString::Atof(*tempArr[2]);
NewUserData.Value.Rect.Bottom = (float)FCString::Atof(*tempArr[3]);
}
}
if(Value._Hash->Contains(TEXT("point")))
{
NewUserData.Value.bUsePoint = true;
FString temp = (*Value._Hash)[TEXT("point")].get<FString>();
TArray<FString> tempArr;
tempArr.Empty(2);
split_string(temp, ' ', tempArr);
if(2 == tempArr.Num())
{
NewUserData.Value.Point.X = (float)FCString::Atof(*tempArr[0]);
NewUserData.Value.Point.Y = (float)FCString::Atof(*tempArr[1]);
}
}
if(Value._Hash->Contains(TEXT("string")))
{
NewUserData.Value.bUseString = true;
NewUserData.Value.String = (*Value._Hash)[TEXT("string")].get<FString>();
}
}
}
Result.UserData.Add(NewUserData);
}
}
}
}
}
const FVector2D FSsPlayer::GetAnimCanvasSize() const
{
return Decoder.IsValid() ? Decoder->GetAnimeCanvasSize() : FVector2D(0,0);
}
// 再生
bool FSsPlayer::Play(int32 InAnimPackIndex, int32 InAnimationIndex, int32 StartFrame, float InPlayRate, int32 InLoopCount, bool bInRoundTrip)
{
if(NULL == SsProject){ return false; }
FSsAnimePack* AnimPack = (InAnimPackIndex < SsProject->AnimeList.Num()) ? &(SsProject->AnimeList[InAnimPackIndex]) : NULL;
if(NULL == AnimPack){ return false; }
FSsAnimation* Animation = (InAnimationIndex < AnimPack->AnimeList.Num()) ? &(AnimPack->AnimeList[InAnimationIndex]) : NULL;
if(NULL == Animation){ return false; }
CellMapList->Set(SsProject.Get(), AnimPack);
Decoder->SetAnimation(&AnimPack->Model, Animation, CellMapList.Get(), SsProject.Get());
Decoder->SetPlayFrame( (float)StartFrame );
bPlaying = true;
bFirstTick = true;
PlayRate = InPlayRate;
LoopCount = InLoopCount;
bRoundTrip = bInRoundTrip;
AnimPivot = Animation->Settings.Pivot;
PlayingAnimPackIndex = InAnimPackIndex;
PlayingAnimationIndex = InAnimationIndex;
return true;
}
// 再開
bool FSsPlayer::Resume()
{
if(Decoder.IsValid() && Decoder->IsAnimationValid())
{
bPlaying = true;
return true;
}
return false;
}
// アニメーション名からインデックスを取得
bool FSsPlayer::GetAnimationIndex(const FName& InAnimPackName, const FName& InAnimationName, int32& OutAnimPackIndex, int32& OutAnimationIndex)
{
if(SsProject.IsValid())
{
return SsProject->FindAnimationIndex(InAnimPackName, InAnimationName, OutAnimPackIndex, OutAnimationIndex);
}
return false;
}
// 指定フレーム送り
void FSsPlayer::SetPlayFrame(float Frame)
{
if(Decoder.IsValid())
{
Decoder->SetPlayFrame( Frame );
}
}
// 現在フレーム取得
float FSsPlayer::GetPlayFrame() const
{
if(Decoder.IsValid())
{
return Decoder->GetPlayFrame();
}
return 0.f;
}
// 最終フレーム取得
float FSsPlayer::GetAnimeEndFrame() const
{
if(Decoder.IsValid())
{
return Decoder->GetAnimeEndFrame();
}
return 0.f;
}
// パーツ名からインデックスを取得
int32 FSsPlayer::GetPartIndexFromName(FName PartName) const
{
if(Decoder.IsValid())
{
return Decoder->GetPartIndexFromName(PartName);
}
return -1;
}
// パーツのTransformを取得
bool FSsPlayer::GetPartTransform(int32 PartIndex, FVector2D& OutPosition, float& OutRotate, FVector2D& OutScale) const
{
if(Decoder.IsValid())
{
return Decoder->GetPartTransform(PartIndex, OutPosition, OutRotate, OutScale);
}
return false;
}
// パーツのColorLabelを取得
FName FSsPlayer::GetPartColorLabel(int32 PartIndex)
{
if(Decoder.IsValid())
{
return Decoder->GetPartColorLabel(PartIndex);
}
return FName();
}
| 23.17402 | 143 | 0.662084 | [
"model"
] |
aceac092c363fc449d7faaf260cdd80b06c7707c | 10,273 | cpp | C++ | GATE_Engine/ModuleEditor.cpp | DocDonkeys/3D_Engine | bb2868884c6eec0ef619a45b7e21f5cf3857fe1b | [
"MIT"
] | 1 | 2019-10-14T00:35:48.000Z | 2019-10-14T00:35:48.000Z | GATE_Engine/ModuleEditor.cpp | DocDonkeys/3D_Engine | bb2868884c6eec0ef619a45b7e21f5cf3857fe1b | [
"MIT"
] | null | null | null | GATE_Engine/ModuleEditor.cpp | DocDonkeys/3D_Engine | bb2868884c6eec0ef619a45b7e21f5cf3857fe1b | [
"MIT"
] | 3 | 2020-02-13T22:52:44.000Z | 2020-10-21T06:55:45.000Z | #include "ModuleEditor.h"
#include "Application.h"
#include "ModuleWindow.h"
#include "ModuleRenderer3D.h"
#include "ModuleInput.h"
#include "GeometryLoader.h"
#include "ModuleSceneIntro.h"
#include "ComponentTransform.h"
// Windows
#include "EditorConfiguration.h"
#include "EditorConsole.h"
#include "EditorGame.h"
#include "EditorHierarchy.h"
#include "EditorInspector.h"
#include "EditorProject.h"
#include "EditorScene.h"
#include "EditorToolbar.h"
// Elements
#include "EditorMenuBar.h"
#include "libs/ImGuizmo/ImGuizmo.h"
#include "libs/Brofiler/Brofiler.h"
#include "libs/MathGeoLib/include/Math/MathFunc.h"
// Memory Leak Detection
#include "MemLeaks.h"
ModuleEditor::ModuleEditor(Application * app, const char* name, bool start_enabled) : Module(app, name, start_enabled)
{
// Windows
editor_configuration = new EditorConfiguration("Configuration", false, ImGuiWindowFlags_MenuBar);
editor_console = new EditorConsole("Console", true);
editor_game = new EditorGame("Game", true);
editor_hierarchy = new EditorHierarchy("Hierarchy", true);
editor_inspector = new EditorInspector("Inspector", true);
editor_project = new EditorProject("Project", true);
editor_scene = new EditorScene("Scene", true);
editor_toolbar = new EditorToolbar("Toolbar", true, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove);
// Elements
editor_menu_bar = new EditorMenuBar();
#ifndef _DEBUG
ui_debug_mode = false;
#endif
}
ModuleEditor::~ModuleEditor()
{
// Windows
RELEASE(editor_configuration);
RELEASE(editor_console);
RELEASE(editor_game);
RELEASE(editor_hierarchy);
RELEASE(editor_inspector);
RELEASE(editor_project);
RELEASE(editor_scene);
RELEASE(editor_toolbar);
// Elements
RELEASE(editor_menu_bar);
}
bool ModuleEditor::Init()
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
io = &ImGui::GetIO(); (void)io;
//io->ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
io->ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
//io->ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
//io.ConfigViewportsNoAutoMerge = true;
//io.ConfigViewportsNoTaskBarIcon = true;
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
/*ImGuiStyle& style = ImGui::GetStyle();
if (io->ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}*/
ImGui_ImplSDL2_InitForOpenGL(App->window->window, App->renderer3D->context);
ImGui_ImplOpenGL3_Init();
bool show_another_window = false; //CHANGE/FIX: Remove
return true;
}
bool ModuleEditor::Start()
{
// After loading the mode value (integer ID) from JSON, we actually apply the needed changes depending on the current mode
DrawModeChange();
TextureModeChange();
ByteSizeModeChange();
editor_project->Start();
return true;
}
update_status ModuleEditor::Update(float dt)
{
BROFILER_CATEGORY("Renderer pre-Update", Profiler::Color::Green);
update_status ret = update_status::UPDATE_CONTINUE;
//Before we start with ImGui menus & stuff, we check for windows and menus that can be opened or closed with keyboard keys
// Poll and handle events (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
SDL_Event event;
while (SDL_PollEvent(&event))
{
ImGui_ImplSDL2_ProcessEvent(&event);
}
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(App->window->window);
ImGui::NewFrame();
if (BeginRootWindow("Root Window 1", main_dockSpace, ImGuiWindowFlags_MenuBar)) { //CHANGE/FIX: Create a root window class with docking that can be turned on/off?
editor_menu_bar->Update();
ImGui::End();
}
// Check all windows for updates if they're activated
editor_toolbar->RequestUpdate();
editor_configuration->RequestUpdate();
editor_console->RequestUpdate();
editor_game->RequestUpdate();
editor_hierarchy->RequestUpdate();
editor_inspector->RequestUpdate();
editor_project->RequestUpdate();
editor_scene->RequestUpdate();
if (App->mustShutDown) {
ImGui::OpenPopup("Exit GATE?");
if (ImGui::BeginPopupModal("Exit GATE?", &App->mustShutDown, ImGuiWindowFlags_AlwaysAutoResize))
{
if (ImGui::Button("Yes", { 90.f, 30.f })) {
App->mustShutDown = true;
ret = update_status::UPDATE_STOP;
} ImGui::SameLine();
if (ImGui::Button("No", { 90.f, 30.f })) {
App->mustShutDown = false;
}
ImGui::EndPopup();
}
}
//IMPROVE: Make "Hotkeys" files
if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_S) == KEY_DOWN) {
std::string scene_name = "scene_1";
App->scene_intro->scene_ie.SaveScene(App->scene_intro->root, scene_name, FileType::SCENE);
}
// Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()!
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
//If we are using a Imgui Menu, we update the bool that indicates so
using_menu = io->WantCaptureMouse;
// ImGuizmo
if (/*!App->IsGamePlaying() && */App->scene_intro->gizmos && App->scene_intro->selected_go != nullptr) //NOTE: ImGuizmo doesn't work well with ortographic camera, careful if it's implemented!
DrawImGuizmo();
return ret;
}
bool ModuleEditor::BeginRootWindow(char* id, bool docking, ImGuiWindowFlags winFlags)
{
ImGuiViewport* viewport = ImGui::GetWindowViewport();
ImGui::SetNextWindowPos(viewport->Pos);
ImGui::SetNextWindowSize(viewport->Size);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
winFlags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
winFlags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
winFlags |= ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoBackground;
bool temp = true;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
temp = ImGui::Begin(id, &temp, winFlags);
ImGui::PopStyleVar(3);
if (docking) {
BeginDockingSpace(id, ImGuiDockNodeFlags_PassthruCentralNode);
//ImGui::DockSpaceOverViewport(viewport, ImGuiDockNodeFlags_PassthruCentralNode); //Note: This is an automated way of doing the same, but lacks the capability of having a menuBar
}
return temp;
}
void ModuleEditor::BeginDockingSpace(char* dockSpaceId, ImGuiDockNodeFlags dockFlags, ImVec2 size)
{
// DockSpace
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) {
ImGuiID dockspace_id = ImGui::GetID(dockSpaceId);
ImGui::DockSpace(dockspace_id, size, dockFlags);
}
}
// ---------------------------------
void ModuleEditor::RenderEditorUI()
{
ImGuiIO& test_io = *io;
// Rendering
ImGui::Render();
glViewport(0, 0, (int)test_io.DisplaySize.x, (int)test_io.DisplaySize.y);
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
//glClear(GL_COLOR_BUFFER_BIT); //DIDAC/CARLES: This line renders a plain color over the axis + grid plane of SceneIntro Module
//glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
// Modes & Radio Buttons
void ModuleEditor::DrawModeChange()
{
switch (drawMode) {
case (int)draw_mode::MESH:
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
break;
case (int)draw_mode::WIREFRAME:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
break;
case (int)draw_mode::VERTEX:
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
break;
}
}
void ModuleEditor::TextureModeChange()
{
switch (textureMode) {
case (int)texture_mode::TWO_D:
App->renderer3D->SwitchGroupGLSetting(App->renderer3D->GL_Texture2D, App->renderer3D->GL_Texture2D.group);
break;
case (int)texture_mode::CUBEMAP:
App->renderer3D->SwitchGroupGLSetting(App->renderer3D->GL_TextureCubeMap, App->renderer3D->GL_TextureCubeMap.group);
break;
}
}
void ModuleEditor::ByteSizeModeChange()
{
switch (byteSizeMode) {
case (int)byte_size_mode::KB:
byteAlt = 1.0;
byteText.assign("KB");
break;
case (int)byte_size_mode::MB:
byteAlt = 1.0 / 1024.0;
byteText.assign("MB");
break;
case (int)byte_size_mode::GB:
byteAlt = 1.0 / 1024.0 / 1024.0;
byteText.assign("GB");
break;
}
}
void ModuleEditor::DrawImGuizmo() //IMPROVE: Add ImViewGizmo and Bounds
{
ImGuizmo::BeginFrame();
float4x4 projection;
float4x4 view;
glGetFloatv(GL_MODELVIEW_MATRIX, (float*)view.v);
glGetFloatv(GL_PROJECTION_MATRIX, (float*)projection.v);
ImGuiIO& io = ImGui::GetIO();
ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y);
ComponentTransform* trs = (ComponentTransform*)App->scene_intro->selected_go->GetComponent(COMPONENT_TYPE::TRANSFORM);
//if (App->scene_intro->handlePositionMode == (int)handle_position::CENTER) //IMPROVE: Make rotation axis be in the AABB center (which should include all children?)
// mat.SetTranslatePart(transform->my_go->aabb.CenterPoint());
bool snap = false;
for (int i = 0; i < 3; ++i)
if (snap = App->scene_intro->snapActivated[i]) // The single "=" is on purpose, not a typo
break;
float4x4 mat = trs->globalTrs.Transposed();
ImGuizmo::Manipulate((float*)view.v, (float*)projection.v,
(ImGuizmo::OPERATION)App->scene_intro->toolMode, (ImGuizmo::MODE)App->scene_intro->handleRotationMode,
(float*)mat.v, NULL, snap ? App->scene_intro->snapTools.ptr() : NULL); //CHANGE/FIX: The resulting matrix suffers from Gimbal Lock!
trs->globalTrs = mat.Transposed();
if (ImGuizmo::IsUsing())
trs->needsUpdateLocal = true;
} | 32.821086 | 193 | 0.746228 | [
"mesh",
"render",
"transform"
] |
aceb2bc8d106f7efb67ae4fe4aafa1ba8527f313 | 611 | hpp | C++ | src/game/world/animations/aspects/update_slide_ceiling_sky_aspect.hpp | jdmclark/gorc | a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8 | [
"Apache-2.0"
] | 97 | 2015-02-24T05:09:24.000Z | 2022-01-23T12:08:22.000Z | src/game/world/animations/aspects/update_slide_ceiling_sky_aspect.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 8 | 2015-03-27T23:03:23.000Z | 2020-12-21T02:34:33.000Z | src/game/world/animations/aspects/update_slide_ceiling_sky_aspect.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 10 | 2016-03-24T14:32:50.000Z | 2021-11-13T02:38:53.000Z | #pragma once
#include "game/world/animations/components/slide_ceiling_sky.hpp"
#include "game/world/level_model.hpp"
#include "ecs/inner_join_aspect.hpp"
namespace gorc {
namespace game {
namespace world {
namespace animations {
namespace aspects {
class update_slide_ceiling_sky_aspect : public inner_join_aspect<thing_id, components::slide_ceiling_sky> {
private:
level_model& model;
public:
update_slide_ceiling_sky_aspect(entity_component_system<thing_id>& cs, level_model& model);
virtual void update(time_delta t, thing_id id, components::slide_ceiling_sky& anim) override;
};
}
}
}
}
}
| 21.821429 | 107 | 0.787234 | [
"model"
] |
acf157cd3df88bb0305e04cdfc4c9be76e92ea7a | 2,870 | cc | C++ | src/brandes.cc | chivay/betweenness-centrality | 66805ed0e290ac52a7bf951851976dbb9a734673 | [
"MIT"
] | 2 | 2018-11-22T15:30:10.000Z | 2019-01-12T01:20:30.000Z | src/brandes.cc | chivay/betweenness-centrality | 66805ed0e290ac52a7bf951851976dbb9a734673 | [
"MIT"
] | null | null | null | src/brandes.cc | chivay/betweenness-centrality | 66805ed0e290ac52a7bf951851976dbb9a734673 | [
"MIT"
] | 1 | 2021-03-30T05:30:56.000Z | 2021-03-30T05:30:56.000Z | #include "brandes.h"
#include <algorithm>
#include <iostream>
#include <queue>
#include <stack>
#include <thread>
#include <vector>
template <typename T>
void Brandes<T>::process(const size_t& vertex_id, std::vector<fType>* BC_local)
{
size_t vec_size = BC_local->size();
std::stack<size_t> S;
std::vector<std::vector<size_t> > P(vec_size);
std::vector<int> sigma(vec_size);
std::vector<int> d(vec_size);
std::vector<fType> delta(vec_size);
for (size_t w = 0; w < graph_.get_vertex_num(); w++) {
sigma[w] = 0;
d[w] = -1;
delta[w] = 0;
}
sigma[vertex_id] = 1;
d[vertex_id] = 0;
std::queue<size_t> Q;
Q.push(vertex_id);
while (!Q.empty()) {
size_t v = Q.front();
Q.pop();
S.push(v);
for (const auto& w : graph_.get_neighbor_aliases(v)) {
if (d[w] < 0) {
Q.push(w);
d[w] = d[v] + 1;
}
if (d[w] == d[v] + 1) {
sigma[w] += sigma[v];
P[w].emplace_back(v);
}
}
}
while (!S.empty()) {
size_t v = S.top();
S.pop();
for (size_t p : P[v]) {
double result = (fType(sigma[p]) / sigma[v]) * (1.0 + delta[v]);
delta[p] += result;
}
if (v != vertex_id) {
(*BC_local)[v] += delta[v];
}
}
}
template <typename T>
void Brandes<T>::run_worker(std::atomic<size_t>* idx)
{
std::vector<fType> BC_local(graph_.get_vertex_num());
std::fill(begin(BC_local), end(BC_local), 0.0);
while (true) {
int my_index = (*idx)--;
if (my_index < 0)
break;
process(my_index, &BC_local);
}
// Synchronized section
{
std::lock_guard<std::mutex> guard(bc_mutex_);
for (size_t i = 0; i < BC_local.size(); i++) {
BC_[i] += BC_local[i];
}
}
}
template <typename T>
void Brandes<T>::run(const size_t thread_num)
{
std::vector<std::thread> threads;
std::atomic<size_t> index;
index.store(graph_.get_vertex_num() - 1);
// run threads
for (size_t i = 0; i < thread_num - 1; i++)
threads.emplace_back(std::thread([this, &index] { run_worker(&index); }));
// start working
run_worker(&index);
// wait for others to finish
for (auto& thread : threads)
thread.join();
}
template <typename T>
const std::vector<std::pair<T, typename Brandes<T>::fType> > Brandes<T>::get_result_vector()
{
std::vector<std::pair<T, fType> > results;
results.reserve(BC_.size());
for (size_t i = 0; i < BC_.size(); i++) {
if (graph_.get_neighbor_aliases(i).size() > 0)
results.emplace_back(std::make_pair(graph_.get_id_from_alias(i), BC_[i]));
}
sort(begin(results), end(results));
return results;
}
| 23.333333 | 92 | 0.533101 | [
"vector"
] |
acf3ccb9a31dfa9e0a0ab4314caffa93f1c7fa4d | 9,394 | cxx | C++ | graphics/VTK-7.0.0/Interaction/Style/vtkInteractorStyleMultiTouchCamera.cxx | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | graphics/VTK-7.0.0/Interaction/Style/vtkInteractorStyleMultiTouchCamera.cxx | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | graphics/VTK-7.0.0/Interaction/Style/vtkInteractorStyleMultiTouchCamera.cxx | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkInteractorStyleMultiTouchCamera.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkInteractorStyleMultiTouchCamera.h"
#include "vtkCamera.h"
#include "vtkCallbackCommand.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
vtkStandardNewMacro(vtkInteractorStyleMultiTouchCamera);
//----------------------------------------------------------------------------
vtkInteractorStyleMultiTouchCamera::vtkInteractorStyleMultiTouchCamera()
{
this->MotionFactor = 10.0;
this->PointersDownCount = 0;
for (int i = 0; i < VTKI_MAX_POINTERS; ++i)
{
this->PointersDown[i] = 0;
}
}
//----------------------------------------------------------------------------
vtkInteractorStyleMultiTouchCamera::~vtkInteractorStyleMultiTouchCamera()
{
}
//----------------------------------------------------------------------------
void vtkInteractorStyleMultiTouchCamera::OnMouseMove()
{
int pointer = this->Interactor->GetPointerIndex();
this->FindPokedRenderer(this->Interactor->GetEventPositions(pointer)[0],
this->Interactor->GetEventPositions(pointer)[1]);
if (this->State == VTKIS_TWO_POINTER)
{
this->AdjustCamera();
this->InvokeEvent(vtkCommand::InteractionEvent, NULL);
}
else
{
this->Superclass::OnMouseMove();
}
}
//----------------------------------------------------------------------------
void vtkInteractorStyleMultiTouchCamera::OnLeftButtonDown()
{
int pointer = this->Interactor->GetPointerIndex();
vtkDebugMacro("pointer index down for " << pointer);
// if it is already down ignore this event
if (this->PointersDown[pointer])
{
return;
}
this->FindPokedRenderer(this->Interactor->GetEventPositions(pointer)[0],
this->Interactor->GetEventPositions(pointer)[1]);
if (this->CurrentRenderer == NULL)
{
return;
}
this->PointersDown[pointer] = 1;
this->PointersDownCount++;
// do the standard single pointer event handling
if (this->PointersDownCount == 1)
{
this->Superclass::OnLeftButtonDown();
return;
}
// if going from 1 to 2 pointers stop the one pointer action
if (this->PointersDownCount == 2)
{
this->LastState = this->State;
switch (this->State)
{
case VTKIS_DOLLY:
this->EndDolly();
break;
case VTKIS_PAN:
this->EndPan();
break;
case VTKIS_SPIN:
this->EndSpin();
break;
case VTKIS_ROTATE:
this->EndRotate();
break;
}
// start the multipointer action
this->StartTwoPointer();
return;
}
// if going from 2 to 3 pointers stop the two pointer action
if (this->PointersDownCount == 3 && this->State == VTKIS_TWO_POINTER)
{
this->EndTwoPointer();
}
}
//----------------------------------------------------------------------------
void vtkInteractorStyleMultiTouchCamera::OnLeftButtonUp()
{
int pointer = this->Interactor->GetPointerIndex();
vtkDebugMacro("pointer index up for " << pointer);
// if it is already up, ignore this event
if (!this->PointersDown[pointer])
{
return;
}
this->PointersDownCount--;
this->PointersDown[pointer] = 0;
// if we were just one pointer then do the usual handling
if (this->PointersDownCount == 0)
{
this->Superclass::OnLeftButtonUp();
return;
}
switch (this->State)
{
case VTKIS_TWO_POINTER:
this->EndTwoPointer();
for (int i = 0; i < VTKI_MAX_POINTERS; ++i)
{
if (this->PointersDown[i] != 0)
this->Interactor->SetPointerIndex(i);
switch (this->LastState)
{
case VTKIS_DOLLY:
this->StartDolly();
break;
case VTKIS_PAN:
this->StartPan();
break;
case VTKIS_SPIN:
this->StartSpin();
break;
case VTKIS_ROTATE:
this->StartRotate();
break;
}
}
break;
}
if ( this->Interactor )
{
this->ReleaseFocus();
}
}
double distance2D(int *a, int *b)
{
return sqrt((double)(a[0] - b[0])*(a[0] - b[0]) + (double)(a[1]-b[1])*(a[1]-b[1]));
}
//----------------------------------------------------------------------------
void vtkInteractorStyleMultiTouchCamera::AdjustCamera()
{
if ( this->CurrentRenderer == NULL )
{
return;
}
vtkRenderWindowInteractor *rwi = this->Interactor;
// OK we have two pointers, that means 4 constraints
// P1.x P1.y P2.x P2.y
//
// We use those 4 contraints to control:
// Zoom (variant is the distance between points - 1 DOF)
// Roll (variant is the angle formed by the line connecting the points - 1 DOF)
// Position (variant is the X,Y position of the midpoint of the line - 2 DOF)
//
// find the moving and non moving points
int eventPI = rwi->GetPointerIndex();
int otherPI = 0;
for (int i = 0; i < VTKI_MAX_POINTERS; ++i)
{
if (this->PointersDown[i] > 0 && i != eventPI)
{
otherPI = i;
break;
}
}
// compute roll - 1 DOF
double oldAngle =
vtkMath::DegreesFromRadians( atan2( (double)rwi->GetLastEventPositions(eventPI)[1] - rwi->GetLastEventPositions(otherPI)[1],
(double)rwi->GetLastEventPositions(eventPI)[0] - rwi->GetLastEventPositions(otherPI)[0] ) );
double newAngle =
vtkMath::DegreesFromRadians( atan2( (double)rwi->GetEventPositions(eventPI)[1] - rwi->GetEventPositions(otherPI)[1],
(double)rwi->GetEventPositions(eventPI)[0] - rwi->GetEventPositions(otherPI)[0] ) );
vtkCamera *camera = this->CurrentRenderer->GetActiveCamera();
camera->Roll( newAngle - oldAngle );
// compute dolly/scale - 1 DOF
double oldDist = distance2D(rwi->GetLastEventPositions(otherPI), rwi->GetLastEventPositions(eventPI));
double newDist = distance2D(rwi->GetEventPositions(otherPI), rwi->GetEventPositions(eventPI));
double dyf = newDist/oldDist;
if (camera->GetParallelProjection())
{
camera->SetParallelScale(camera->GetParallelScale() / dyf);
}
else
{
camera->Dolly(dyf);
if (this->AutoAdjustCameraClippingRange)
{
this->CurrentRenderer->ResetCameraClippingRange();
}
}
// handle panning - 2 DOF
double viewFocus[4], focalDepth, viewPoint[3];
double newPickPoint[4], oldPickPoint[4], motionVector[3];
// Calculate the focal depth since we'll be using it a lot
camera->GetFocalPoint(viewFocus);
this->ComputeWorldToDisplay(viewFocus[0], viewFocus[1], viewFocus[2],
viewFocus);
focalDepth = viewFocus[2];
this->ComputeDisplayToWorld((rwi->GetEventPositions(eventPI)[0] + rwi->GetEventPositions(otherPI)[0])/2.0,
(rwi->GetEventPositions(eventPI)[1] + rwi->GetEventPositions(otherPI)[1])/2.0,
focalDepth,
newPickPoint);
// Has to recalc old mouse point since the viewport has moved,
// so can't move it outside the loop
this->ComputeDisplayToWorld((rwi->GetLastEventPositions(eventPI)[0] + rwi->GetLastEventPositions(otherPI)[0])/2.0,
(rwi->GetLastEventPositions(eventPI)[1] + rwi->GetLastEventPositions(otherPI)[1])/2.0,
focalDepth,
oldPickPoint);
// Camera motion is reversed
motionVector[0] = oldPickPoint[0] - newPickPoint[0];
motionVector[1] = oldPickPoint[1] - newPickPoint[1];
motionVector[2] = oldPickPoint[2] - newPickPoint[2];
camera->GetFocalPoint(viewFocus);
camera->GetPosition(viewPoint);
camera->SetFocalPoint(motionVector[0] + viewFocus[0],
motionVector[1] + viewFocus[1],
motionVector[2] + viewFocus[2]);
camera->SetPosition(motionVector[0] + viewPoint[0],
motionVector[1] + viewPoint[1],
motionVector[2] + viewPoint[2]);
// clean up
if (this->Interactor->GetLightFollowCamera())
{
this->CurrentRenderer->UpdateLightsGeometryToFollowCamera();
}
camera->OrthogonalizeViewUp();
rwi->Render();
}
//----------------------------------------------------------------------------
void vtkInteractorStyleMultiTouchCamera::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "MotionFactor: " << this->MotionFactor << "\n";
}
| 30.599349 | 133 | 0.567809 | [
"render"
] |
acf933dc6abc469e5697130c83cc12309c93b45e | 20,080 | cpp | C++ | Source/Storm-Physics/include/PhysXHandler.cpp | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | 3 | 2021-11-27T04:56:12.000Z | 2022-02-14T04:02:10.000Z | Source/Storm-Physics/include/PhysXHandler.cpp | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | Source/Storm-Physics/include/PhysXHandler.cpp | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | #include "PhysXHandler.h"
#include "CustomPhysXLogger.h"
#include "PhysXDebugger.h"
#include "Version.h"
#include "PhysXCoordHelpers.h"
#include "SingletonHolder.h"
#include "IConfigManager.h"
#include "ITimeManager.h"
#include "IOSManager.h"
#include "SceneSimulationConfig.h"
#include "SceneRigidBodyConfig.h"
#include "SceneConstraintConfig.h"
#include "ScenePhysicsConfig.h"
#include "GeneralApplicationConfig.h"
#include "CollisionType.h"
#define STORM_USE_FAST_SPHERE_SHAPE_ALGO true
#if !STORM_USE_FAST_SPHERE_SHAPE_ALGO
# include "RunnerHelper.h"
#endif
namespace
{
physx::PxDefaultAllocator g_defaultAllocator;
Storm::CustomPhysXLogger g_physXLogger;
Storm::UniquePointer<physx::PxShape> createSphereShape(physx::PxPhysics &physics, const std::vector<Storm::Vector3> &vertices, physx::PxMaterial* rbMaterial)
{
#if STORM_USE_FAST_SPHERE_SHAPE_ALGO
// This algo supposes the sphere is uniform.
auto oppositeVertexes = std::minmax_element(std::execution::par, std::begin(vertices), std::end(vertices), [](const Storm::Vector3 &vect1, const Storm::Vector3 &vect2)
{
return vect1.x() < vect2.x();
});
const float maxDistance = std::fabs(oppositeVertexes.first->x() - oppositeVertexes.second->x());
return physics.createShape(physx::PxSphereGeometry{ maxDistance / 2.f }, &rbMaterial, 1, true);
#else
// This is the brute force algorithm that always works, but is really slow...
std::mutex mutex;
std::atomic<float> maxDistance = 0.f;
Storm::runParallel(vertices, [&vertices, &mutex, &maxDistance, vertexCount = vertices.size()](const Storm::Vector3 &vect, std::size_t verticeIndex)
{
// Skip the current.
++verticeIndex;
float maxDistanceTmp = 0.f;
float val;
for (; verticeIndex < vertexCount; ++verticeIndex)
{
const Storm::Vector3 &vertex = vertices[verticeIndex];
val = (vertex - vect).squaredNorm();
if (val > maxDistanceTmp)
{
maxDistanceTmp = val;
}
}
if (maxDistanceTmp > maxDistance)
{
std::lock_guard<std::mutex> lock{ mutex };
if (maxDistanceTmp > maxDistance)
{
maxDistance = maxDistanceTmp;
}
}
});
maxDistance = std::sqrtf(maxDistance);
return physics.createShape(physx::PxSphereGeometry{ maxDistance / 2.f }, &rbMaterial, 1, true);
#endif
}
Storm::UniquePointer<physx::PxShape> createBoxShape(physx::PxPhysics &physics, const std::vector<Storm::Vector3> &vertices, physx::PxMaterial* rbMaterial)
{
float maxX = 0.f;
float maxY = 0.f;
float maxZ = 0.f;
const std::size_t verticeCount = vertices.size();
for (std::size_t iter = 0; iter < verticeCount; ++iter)
{
const Storm::Vector3 &vertex = vertices[iter];
for (std::size_t jiter = iter + 1; jiter < verticeCount; ++jiter)
{
Storm::Vector3 diff = vertex - vertices[jiter];
diff.x() = std::abs(diff.x());
diff.y() = std::abs(diff.y());
diff.z() = std::abs(diff.z());
if (diff.x() > maxX)
{
maxX = diff.x();
}
if (diff.y() > maxY)
{
maxY = diff.y();
}
if (diff.z() > maxZ)
{
maxZ = diff.z();
}
}
}
return physics.createShape(physx::PxBoxGeometry{ maxX / 2.f, maxY / 2.f, maxZ / 2.f }, &rbMaterial, 1, true);
}
Storm::UniquePointer<physx::PxShape> createCustomShape(physx::PxPhysics &physics, const physx::PxCooking &cooking, const Storm::SceneRigidBodyConfig &rbSceneConfig, const std::vector<Storm::Vector3> &vertices, const std::vector<uint32_t> &indexes, physx::PxMaterial* rbMaterial, std::vector<Storm::UniquePointer<physx::PxTriangleMesh>> &inOutRegisteredRef)
{
physx::PxTriangleMeshDesc meshDesc;
meshDesc.points.count = static_cast<physx::PxU32>(vertices.size());
meshDesc.points.stride = sizeof(Storm::Vector3);
meshDesc.points.data = vertices.data();
// We need to invert the clock wise rotation of triangles if the rigid body collision is pointing inside (like in the case of a wall).
std::vector<uint32_t> indexSwapped;
if (rbSceneConfig._isWall)
{
indexSwapped.resize(indexes.size());
for (std::size_t index = 0; index < indexes.size(); index += 3)
{
indexSwapped[index] = indexes[index];
indexSwapped[index + 1] = indexes[index + 2];
indexSwapped[index + 2] = indexes[index + 1];
}
meshDesc.triangles.count = static_cast<physx::PxU32>(indexSwapped.size() / 3);
meshDesc.triangles.stride = 3 * sizeof(uint32_t);
meshDesc.triangles.data = indexSwapped.data();
}
else
{
meshDesc.triangles.count = static_cast<physx::PxU32>(indexes.size() / 3);
meshDesc.triangles.stride = 3 * sizeof(uint32_t);
meshDesc.triangles.data = indexes.data();
}
physx::PxDefaultMemoryOutputStream writeBuffer;
physx::PxTriangleMeshCookingResult::Enum res = physx::PxTriangleMeshCookingResult::eFAILURE;
if (!cooking.cookTriangleMesh(meshDesc, writeBuffer, &res))
{
LOG_ERROR << "Cannot cook mesh... Res was " << res;
return nullptr;
}
switch (res)
{
case physx::PxTriangleMeshCookingResult::eFAILURE:
LOG_ERROR << "Mesh cooking result resulted in a failure " << res;
return nullptr;
case physx::PxTriangleMeshCookingResult::eLARGE_TRIANGLE:
LOG_WARNING << "Mesh will have large triangle resulting in poor performance (from the PhysX guide)... Beware. " << res;
break;
}
Storm::UniquePointer<physx::PxTriangleMesh> ownedPtr = cooking.createTriangleMesh(meshDesc, physics.getPhysicsInsertionCallback());
physx::PxTriangleMeshGeometry geometry;
geometry.triangleMesh = ownedPtr.get();
if (!geometry.isValid())
{
LOG_ERROR << "Triangle mesh geometry isn't valid!";
return nullptr;
}
Storm::UniquePointer<physx::PxShape> result = physics.createShape(geometry, *rbMaterial, true);
inOutRegisteredRef.emplace_back(std::move(ownedPtr));
return result;
}
physx::PxFilterFlags customCollisionFilterShader(physx::PxFilterObjectAttributes /*attributes0*/, physx::PxFilterData /*filterData0*/, physx::PxFilterObjectAttributes /*attributes1*/, physx::PxFilterData /*filterData1*/, physx::PxPairFlags &retPairFlags, const void* /*constantBlock*/, physx::PxU32 /*constantBlockSize*/)
{
retPairFlags =
physx::PxPairFlag::eCONTACT_DEFAULT |
physx::PxPairFlag::eNOTIFY_TOUCH_PERSISTS |
physx::PxPairFlag::eNOTIFY_CONTACT_POINTS
;
return physx::PxFilterFlag::eNOTIFY;
}
}
Storm::PhysXHandler::PhysXHandler() :
_foundationInstance{ PxCreateFoundation(PX_PHYSICS_VERSION, g_defaultAllocator, g_physXLogger) }
{
constexpr Storm::Version currentPhysXVersion{ PX_PHYSICS_VERSION_MAJOR, PX_PHYSICS_VERSION_MINOR, PX_PHYSICS_VERSION_BUGFIX };
if (currentPhysXVersion != Storm::Version{ 4, 0, 0 })
{
LOG_WARNING << "PhysX version mismatches with what we used in our development. What we use currently is PhysX version " << currentPhysXVersion << " and what we used was PhysX version 4.0.0...";
}
if (!_foundationInstance)
{
Storm::throwException<Storm::Exception>("PhysX foundation couldn't be created!");
}
// Create the physics debugger network object.
_physXDebugger = std::make_unique<Storm::PhysXDebugger>(*_foundationInstance);
// Create the Physics object.
#if defined(_DEBUG) || defined(DEBUG)
constexpr bool recordMemoryAlloc = true;
#else
constexpr bool recordMemoryAlloc = false;
#endif
physx::PxTolerancesScale toleranceScale;
_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *_foundationInstance, toleranceScale, recordMemoryAlloc, _physXDebugger->getPvd());
if (!_physics)
{
Storm::throwException<Storm::Exception>("PxCreatePhysics failed! We cannot use PhysX features, aborting!");
}
_physics->registerDeletionListener(*this, physx::PxDeletionEventFlag::Enum::eUSER_RELEASE);
// Create the cooking object.
physx::PxTolerancesScale scale;
scale.length = 0.00001f;
physx::PxCookingParams cookingParams{ scale };
_cooking = PxCreateCooking(PX_PHYSICS_VERSION, *_foundationInstance, cookingParams);
if (!_cooking)
{
Storm::throwException<Storm::Exception>("PxCreateCooking failed! We cannot use PhysX cooking, aborting!");
}
// Create the PhysX Scene
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
const Storm::IConfigManager &configMgr = singletonHolder.getSingleton<Storm::IConfigManager>();
const Storm::SceneSimulationConfig &sceneSimulationConfig = configMgr.getSceneSimulationConfig();
_shouldQuitOnContactWithFloor = !std::isnan(sceneSimulationConfig._exitSimulationFloorLevel);
_lowestFloorY = sceneSimulationConfig._exitSimulationFloorLevel;
physx::PxSceneDesc sceneDesc{ _physics->getTolerancesScale() };
sceneDesc.gravity = Storm::convertToPx(sceneSimulationConfig._gravity);
const Storm::ScenePhysicsConfig &scenePhysicsConfig = configMgr.getScenePhysicsConfig();
# define STORM_ADD_FLAG_IF_CONFIG(configFlag, flagName) if (scenePhysicsConfig.configFlag) sceneDesc.flags |= physx::PxSceneFlag::flagName
STORM_ADD_FLAG_IF_CONFIG(_enablePCM, eENABLE_PCM);
STORM_ADD_FLAG_IF_CONFIG(_enableAdaptiveForce, eADAPTIVE_FORCE);
STORM_ADD_FLAG_IF_CONFIG(_enableFrictionEveryIteration, eENABLE_FRICTION_EVERY_ITERATION);
STORM_ADD_FLAG_IF_CONFIG(_enableStabilization, eENABLE_STABILIZATION);
STORM_ADD_FLAG_IF_CONFIG(_enableKinematicPairs, eENABLE_KINEMATIC_PAIRS);
STORM_ADD_FLAG_IF_CONFIG(_enableKinematicStaticPairs, eENABLE_KINEMATIC_STATIC_PAIRS);
STORM_ADD_FLAG_IF_CONFIG(_enableAveragePoint, eENABLE_AVERAGE_POINT);
STORM_ADD_FLAG_IF_CONFIG(_enableEnhancedDeterminism, eENABLE_ENHANCED_DETERMINISM);
STORM_ADD_FLAG_IF_CONFIG(_enableCCD, eENABLE_CCD);
#undef STORM_ADD_FLAG_IF_CONFIG
sceneDesc.gpuMaxNumPartitions = 8;
if (_shouldQuitOnContactWithFloor)
{
sceneDesc.filterShader = customCollisionFilterShader;
}
else
{
sceneDesc.filterShader = physx::PxDefaultSimulationFilterShader;
}
sceneDesc.simulationEventCallback = this;
if (!sceneDesc.cpuDispatcher)
{
_cpuDispatcher = physx::PxDefaultCpuDispatcherCreate(1);
if (!_cpuDispatcher)
{
Storm::throwException<Storm::Exception>("PhysX Cpu dispatcher creation failed!");
}
sceneDesc.cpuDispatcher = _cpuDispatcher.get();
}
_scene = _physics->createScene(sceneDesc);
if (!_scene)
{
Storm::throwException<Storm::Exception>("PhysX main scene creation failed!");
}
_physXDebugger->finishSetup(_scene.get());
}
Storm::PhysXHandler::~PhysXHandler()
{
_triangleMeshReferences.clear();
_physics->unregisterDeletionListener(*this);
_physXDebugger->prepareDestroy();
_scene.reset();
_cpuDispatcher.reset();
_physics.reset();
_physXDebugger.reset();
}
physx::PxPhysics& Storm::PhysXHandler::getPhysics() const
{
return *_physics;
}
void Storm::PhysXHandler::onRelease(const physx::PxBase* observed, void* userData, physx::PxDeletionEventFlag::Enum deletionEvent)
{
PX_UNUSED(userData);
PX_UNUSED(deletionEvent);
if (observed->is<physx::PxRigidActor>())
{
LOG_DEBUG << "A PhysX actor was just released!";
// TODO : Do more than this...
}
}
void Storm::PhysXHandler::setGravity(const Storm::Vector3 &newGravity)
{
const physx::PxVec3 physXGravity = Storm::convertToPx(newGravity);
LOG_COMMENT << "Gravity set to { x=" << newGravity.x() << ", y=" << newGravity.y() << ", z=" << newGravity.z() << " }";
physx::PxSceneWriteLock lock{ *_scene };
_scene->setGravity(physXGravity);
}
Storm::Vector3 Storm::PhysXHandler::getGravity() const
{
return Storm::convertToStorm(_scene->getGravity());
}
void Storm::PhysXHandler::update(std::mutex &fetchingMutex, float deltaTime)
{
_scene->simulate(deltaTime);
physx::PxU32 errorCode = 0;
{
std::lock_guard<std::mutex> lock{ fetchingMutex };
_scene->fetchResults(true, &errorCode);
}
if (errorCode != 0)
{
LOG_ERROR << "Error happened in Physics simulation. Error code was " << errorCode;
}
_physXDebugger->reconnectIfNeeded();
}
Storm::UniquePointer<physx::PxRigidStatic> Storm::PhysXHandler::createStaticRigidBody(const Storm::SceneRigidBodyConfig &rbSceneConfig)
{
const physx::PxTransform initialPose = Storm::convertToPx(rbSceneConfig._translation, rbSceneConfig._rotation);
Storm::UniquePointer<physx::PxRigidStatic> result{ _physics->createRigidStatic(initialPose) };
_scene->addActor(*result);
return result;
}
Storm::UniquePointer<physx::PxRigidDynamic> Storm::PhysXHandler::createDynamicRigidBody(const Storm::SceneRigidBodyConfig &rbSceneConfig)
{
const physx::PxTransform initialPose = Storm::convertToPx(rbSceneConfig._translation, rbSceneConfig._rotation);
Storm::UniquePointer<physx::PxRigidDynamic> result{ _physics->createRigidDynamic(initialPose) };
result->setMass(rbSceneConfig._mass);
#if false
result->setLinearDamping(0.5f);
result->setAngularDamping(PX_MAX_F32);
result->setStabilizationThreshold(1.f);
#endif
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
const Storm::IConfigManager &configMgr = singletonHolder.getSingleton<Storm::IConfigManager>();
const Storm::ScenePhysicsConfig &physXConfig = configMgr.getScenePhysicsConfig();
if (physXConfig._removeDamping)
{
result->setAngularDamping(0.f);
result->setLinearDamping(0.f);
}
#if true
// Normally this is already the case but just in case...
result->setCMassLocalPose(physx::PxTransform{ physx::PxIDENTITY::PxIdentity });
#endif
if (_shouldQuitOnContactWithFloor)
{
result->setRigidBodyFlag(physx::PxRigidBodyFlag::Enum::eENABLE_CCD, true);
}
_scene->addActor(*result);
return result;
}
Storm::UniquePointer<physx::PxMaterial> Storm::PhysXHandler::createRigidBodyMaterial(const Storm::SceneRigidBodyConfig &rbSceneConfig)
{
return Storm::UniquePointer<physx::PxMaterial>{ _physics->createMaterial(rbSceneConfig._staticFrictionCoefficient, rbSceneConfig._dynamicFrictionCoefficient, rbSceneConfig._restitutionCoefficient) };
}
Storm::UniquePointer<physx::PxShape> Storm::PhysXHandler::createRigidBodyShape(const Storm::SceneRigidBodyConfig &rbSceneConfig, const std::vector<Storm::Vector3> &vertices, const std::vector<uint32_t> &indexes, physx::PxMaterial* rbMaterial)
{
Storm::UniquePointer<physx::PxShape> result;
switch (rbSceneConfig._collisionShape)
{
case Storm::CollisionType::IndividualParticle:
case Storm::CollisionType::Sphere:
result = createSphereShape(*_physics, vertices, rbMaterial);
break;
case Storm::CollisionType::Cube:
result = createBoxShape(*_physics, vertices, rbMaterial);
break;
case Storm::CollisionType::Custom:
if (indexes.empty())
{
Storm::throwException<Storm::Exception>("To create a custom shape, we need indexes set (like creating a custom mesh)!");
}
result = createCustomShape(*_physics, *_cooking, rbSceneConfig, vertices, indexes, rbMaterial, _triangleMeshReferences);
break;
case Storm::CollisionType::None:
default:
return Storm::UniquePointer<physx::PxShape>{};
}
if (_shouldQuitOnContactWithFloor)
{
result->setFlag(physx::PxShapeFlag::Enum::eSIMULATION_SHAPE, true);
}
return result;
}
Storm::UniquePointer<physx::PxJoint> Storm::PhysXHandler::createDistanceJoint(const Storm::SceneConstraintConfig &constraintConfig, physx::PxRigidActor* actor1, physx::PxRigidActor* actor2)
{
physx::PxTransform actor1LinkTransformFrame = physx::PxTransform{ physx::PxIDENTITY::PxIdentity };
actor1LinkTransformFrame.p += Storm::convertToPx(constraintConfig._rigidBody1LinkTranslationOffset);
physx::PxTransform actor2LinkTransformFrame = physx::PxTransform{ physx::PxIDENTITY::PxIdentity };
actor2LinkTransformFrame.p += Storm::convertToPx(constraintConfig._rigidBody2LinkTranslationOffset);
physx::PxDistanceJoint* tmp = physx::PxDistanceJointCreate(*_physics,
actor1, actor1LinkTransformFrame,
actor2, actor2LinkTransformFrame
);
Storm::UniquePointer<physx::PxJoint> result{ tmp };
tmp->setConstraintFlag(physx::PxConstraintFlag::Enum::eCOLLISION_ENABLED, true);
tmp->setConstraintFlag(physx::PxConstraintFlag::Enum::eENABLE_EXTENDED_LIMITS, false);
const float maxDistance = constraintConfig._constraintsLength;
tmp->setDistanceJointFlag(physx::PxDistanceJointFlag::eSPRING_ENABLED, false);
tmp->setMaxDistance(maxDistance);
tmp->setTolerance(0.f);
tmp->setStiffness(PX_MAX_F32);
tmp->setDamping(PX_MAX_F32);
tmp->setDistanceJointFlag(physx::PxDistanceJointFlag::eMAX_DISTANCE_ENABLED, true);
tmp->setDistanceJointFlag(physx::PxDistanceJointFlag::eMIN_DISTANCE_ENABLED, false);
return result;
}
std::pair<Storm::UniquePointer<physx::PxJoint>, Storm::UniquePointer<physx::PxJoint>> Storm::PhysXHandler::createSpinnableJoint(const Storm::SceneConstraintConfig &/*constraintConfig*/, physx::PxRigidActor* /*actor1*/, physx::PxRigidActor* /*actor2*/)
{
// TODO
std::pair<Storm::UniquePointer<physx::PxJoint>, Storm::UniquePointer<physx::PxJoint>> result;
return result;
}
void Storm::PhysXHandler::reconnectPhysicsDebugger()
{
_physXDebugger->reconnectIfNeeded();
}
bool Storm::PhysXHandler::shouldExitIfHitFloor() const
{
return _shouldQuitOnContactWithFloor;
}
void Storm::PhysXHandler::onConstraintBreak(physx::PxConstraintInfo* /*constraints*/, physx::PxU32 /*count*/)
{
}
void Storm::PhysXHandler::onContact(const physx::PxContactPairHeader &pairHeader, const physx::PxContactPair* pairs, physx::PxU32 nbPairs)
{
if (_shouldQuitOnContactWithFloor)
{
std::vector<physx::PxContactPairPoint> contacts;
for (physx::PxU32 iter = 0; iter < nbPairs; ++iter)
{
const physx::PxContactPair ¤tPair = pairs[iter];
if (currentPair.events & physx::PxPairFlag::eNOTIFY_TOUCH_PERSISTS)
{
const physx::PxRigidDynamic* rb;
if (pairHeader.actors[0]->getConcreteType() == physx::PxConcreteType::Enum::eRIGID_DYNAMIC)
{
rb = static_cast<physx::PxRigidDynamic*>(pairHeader.actors[0]);
}
else if (pairHeader.actors[1]->getConcreteType() == physx::PxConcreteType::Enum::eRIGID_DYNAMIC)
{
rb = static_cast<physx::PxRigidDynamic*>(pairHeader.actors[1]);
}
else
{
continue;
}
const physx::PxRigidStatic* floor;
if (pairHeader.actors[0]->getConcreteType() == physx::PxConcreteType::Enum::eRIGID_STATIC)
{
floor = static_cast<physx::PxRigidStatic*>(pairHeader.actors[0]);
}
else if (pairHeader.actors[1]->getConcreteType() == physx::PxConcreteType::Enum::eRIGID_STATIC)
{
floor = static_cast<physx::PxRigidStatic*>(pairHeader.actors[1]);
}
else
{
continue;
}
// If we have a contact between a static and a dynamic body (the floor would always be static)
if (rb && floor)
{
contacts.resize(currentPair.contactCount);
contacts.resize(currentPair.extractContacts(contacts.data(), currentPair.contactCount));
if (std::find_if(std::begin(contacts), std::end(contacts), [this](const physx::PxContactPairPoint &contact)
{
return std::fabs(Storm::convertToStorm(contact.position).y() - _lowestFloorY) < 0.0001f;
}) != std::end(contacts))
{
LOG_COMMENT <<
"A contact with the floor was triggered.\n" <<
rb->getName() << " hit the lowest level of " << floor->getName() << ".\n"
"Therefore, as requested in the global configuration, we'll exit the simulation because it is deemed useless to continue."
;
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
singletonHolder.getSingleton<Storm::ITimeManager>().quit();
const Storm::GeneralApplicationConfig &generalAppConfig = singletonHolder.getSingleton<Storm::IConfigManager>().getGeneralApplicationConfig();
if (generalAppConfig._bipSoundOnFinish)
{
const Storm::IOSManager &osMgr = singletonHolder.getSingleton<Storm::IOSManager>();
osMgr.makeBipSound(std::chrono::milliseconds{ 500 });
}
}
}
}
}
}
}
void Storm::PhysXHandler::onWake(physx::PxActor** /*actors*/, physx::PxU32 /*count*/)
{
}
void Storm::PhysXHandler::onSleep(physx::PxActor** /*actors*/, physx::PxU32 /*count*/)
{
}
void Storm::PhysXHandler::onTrigger(physx::PxTriggerPair* /*pairs*/, physx::PxU32 /*count*/)
{
}
void Storm::PhysXHandler::onAdvance(const physx::PxRigidBody*const* /*bodyBuffer*/, const physx::PxTransform* /*poseBuffer*/, const physx::PxU32 /*count*/)
{
}
| 33.135314 | 357 | 0.744124 | [
"mesh",
"geometry",
"object",
"shape",
"vector"
] |
acfa81f54b90d544e363cb0820ba40ee10747611 | 12,510 | cpp | C++ | src/fume/library_context.cpp | ekhidbor/FUMe | de50357efcb6dbfd0114802bc72ad316daca0ce3 | [
"CC0-1.0"
] | null | null | null | src/fume/library_context.cpp | ekhidbor/FUMe | de50357efcb6dbfd0114802bc72ad316daca0ce3 | [
"CC0-1.0"
] | null | null | null | src/fume/library_context.cpp | ekhidbor/FUMe | de50357efcb6dbfd0114802bc72ad316daca0ce3 | [
"CC0-1.0"
] | null | null | null | /**
* This file is a part of the FUMe project.
*
* To the extent possible under law, the person who associated CC0 with
* FUMe has waived all copyright and related or neighboring rights
* to FUMe.
* You should have received a copy of the CC0 legalcode along with this
* work. If not, see http://creativecommons.org/publicdomain/zero/1.0/.
*/
// std
#include <cassert>
#include <ctime>
#include <limits>
#include <memory>
#include <algorithm>
#include <string>
// local public
#include "mc3msg.h"
// local private
#include "fume/library_context.h"
#include "fume/application.h"
#include "fume/file_object.h"
#include "fume/dicomdir_object.h"
#include "fume/item_object.h"
#include "fume/record_object.h"
#include "fume/vr_factory.h"
#include "fume/value_representation.h"
using std::numeric_limits;
using std::unordered_map;
using std::lock_guard;
using std::mutex;
using std::unique_ptr;
using std::all_of;
using std::pair;
using std::string;
using std::default_random_engine;
namespace fume
{
unique_ptr<library_context> g_context;
library_context::library_context()
// Generate IDs greater than 0
: m_tag_vr_dict( create_default_tag_vr_dict() ),
m_config_maps( create_config_maps() ),
m_rng( static_cast<default_random_engine::result_type>( clock() ) ),
m_id_gen( 1, numeric_limits<int>::max() )
{
}
library_context::~library_context()
{
}
int library_context::create_file_object( const char* filename,
const char* service_name,
MC_COMMAND command )
{
// NOTE: error codes from this function are NEGATIVE because the
// positive values indicate file IDs returned
int ret = -MC_CANNOT_COMPLY;
if( service_name != nullptr )
{
// TODO: don't create empty
ret = create_empty_file_object( filename );
}
else
{
ret = -MC_NULL_POINTER_PARM;
}
return ret;
}
int library_context::create_empty_file_object( const char* filename )
{
// NOTE: error codes from this function are NEGATIVE because the
// positive values indicate file IDs returned
int ret = -MC_CANNOT_COMPLY;
if( filename != nullptr )
{
lock_guard<mutex> lock(m_mutex);
const int id = generate_id();
// generate_id shall maintain uniqueness, but assert here
assert( m_data_dictionaries.count( id ) == 0 );
// Create empty file object
data_dictionary_ptr file_obj( new file_object( id, filename, true ) );
// TODO: initialize file object dictionary based on service name/command
// Insert the file object into the dictionary. Two-step process
// (create then swap) to prevent memory leak in case operator[]
// throws an exception
m_data_dictionaries[id].swap( file_obj );
ret = id;
}
else
{
ret = -MC_NULL_POINTER_PARM;
}
return ret;
}
int library_context::create_dicomdir_object( const char* filename,
const char* fileset,
file_object* template_file )
{
// NOTE: error codes from this function are NEGATIVE because the
// positive values indicate file IDs returned
int ret = -MC_CANNOT_COMPLY;
if( filename != nullptr )
{
lock_guard<mutex> lock(m_mutex);
const int id = generate_id();
// generate_id shall maintain uniqueness, but assert here
assert( m_data_dictionaries.count( id ) == 0 );
// Create empty dicomdir object
// TODO: figure out how to populate with record type
data_dictionary_ptr dicomdir_obj( new dicomdir_object( id,
filename,
template_file,
true ) );
// TODO: initialize item object dictionary based on service name/command
m_data_dictionaries[id].swap( dicomdir_obj );
ret = id;
}
else
{
ret = -MC_NULL_POINTER_PARM;
}
return ret;
}
MC_STATUS library_context::free_file_object( int id )
{
return free_dictionary_object<file_object>( id, MC_INVALID_FILE_ID );
}
int library_context::create_empty_item_object()
{
// NOTE: error codes from this function are NEGATIVE because the
// positive values indicate file IDs returned
int ret = -MC_CANNOT_COMPLY;
lock_guard<mutex> lock(m_mutex);
const int id = generate_id();
// generate_id shall maintain uniqueness, but assert here
assert( m_data_dictionaries.count( id ) == 0 );
// Create file object out of lock scope
// TODO: don't create empty
data_dictionary_ptr item_obj( new item_object( id, true ) );
// TODO: initialize item object dictionary based on item name
// Insert the file object into the dictionary. Two-step process
// (create then swap) to prevent memory leak in case operator[]
// throws an exception
m_data_dictionaries[id].swap( item_obj );
ret = id;
return ret;
}
int library_context::create_item_object( const char* item_name )
{
// TODO: initialize item object dictionary based on item name
// TODO: don't create empty
return item_name != nullptr ? create_empty_item_object() :
-MC_NULL_POINTER_PARM;
}
int library_context::create_record_object( int file_id,
int parent_id,
const char* record_type )
{
// NOTE: error codes from this function are NEGATIVE because the
// positive values indicate file IDs returned
int ret = -MC_CANNOT_COMPLY;
//if( record_type != nullptr )
//{
lock_guard<mutex> lock(m_mutex);
const int id = generate_id();
// generate_id shall maintain uniqueness, but assert here
assert( m_data_dictionaries.count( id ) == 0 );
// Create empty record object
// TODO: figure out how to populate with record type
data_dictionary_ptr item_obj( new record_object( file_id,
parent_id,
id,
record_type,
true ) );
// TODO: initialize item object dictionary based on service name/command
// Insert the item object into the dictionary. Two-step process
// (create then swap) to prevent memory leak in case operator[]
// throws an exception
m_data_dictionaries[id].swap( item_obj );
ret = id;
//}
//else
//{
// ret = -MC_NULL_POINTER_PARM;
//}
return ret;
}
MC_STATUS library_context::free_item_object( int id )
{
return free_dictionary_object<item_object>( id, MC_INVALID_ITEM_ID );
}
data_dictionary* library_context::get_object( int id )
{
lock_guard<mutex> lock(m_mutex);
data_dictionary_map::const_iterator itr( m_data_dictionaries.find( id ) );
return itr == m_data_dictionaries.cend() ? nullptr : itr->second.get();
}
unique_ptr<value_representation>
library_context::create_vr( uint32_t tag,
data_dictionary* dict ) const
{
unique_vr_ptr ret = nullptr;
MC_VR type = UNKNOWN_VR;
unsigned short min_vals = 0;
unsigned short max_vals = 0;
unsigned short multiple = 0;
if( get_vr_info( tag,
dict,
type,
min_vals,
max_vals,
multiple ) == MC_NORMAL_COMPLETION )
{
ret = fume::create_vr( type, min_vals, max_vals, multiple );
}
else
{
ret = nullptr;
}
return ret;
}
MC_STATUS library_context::get_vr_type( uint32_t tag,
data_dictionary* dict,
MC_VR& type ) const
{
unsigned short min_vals = 0;
unsigned short max_vals = 0;
unsigned short multiple = 0;
return get_vr_info( tag, dict, type, min_vals, max_vals, multiple );
}
MC_STATUS library_context::get_vr_info( uint32_t tag,
data_dictionary* dict,
MC_VR& type,
unsigned short& min_vals,
unsigned short& max_vals,
unsigned short& multiple ) const
{
MC_STATUS ret = MC_CANNOT_COMPLY;
tag_to_vr_map::const_iterator itr = m_tag_vr_dict.find( tag );
if( itr != m_tag_vr_dict.cend() )
{
if( dict == nullptr ||
get_conditional_tag_vr( tag, *dict, type ) == false )
{
type = static_cast<MC_VR>( itr->second.vr );
}
else
{
// Do nothing. get_conditional_tag_vr provided a value
// for actual_vr
}
min_vals = itr->second.min_vals;
max_vals = itr->second.max_vals;
multiple = itr->second.multiple;
ret = MC_NORMAL_COMPLETION;
}
else
{
ret = MC_INVALID_TAG;
}
return ret;
}
MC_STATUS library_context::get_string_config_value( StringParm parm,
const std::string*& value ) const
{
MC_STATUS ret = MC_CANNOT_COMPLY;
string_parm_map_t::const_iterator itr = m_config_maps.strings.find( parm );
if( itr != m_config_maps.strings.cend() )
{
value = &itr->second;
ret = MC_NORMAL_COMPLETION;
}
else
{
ret = MC_INVALID_PARAMETER_NAME;
}
return ret;
}
int library_context::register_application( const char* ae_title )
{
// NOTE: error codes from this function are NEGATIVE because the
// positive values indicate file IDs returned
int ret = -MC_CANNOT_COMPLY;
if( ae_title != nullptr )
{
lock_guard<mutex> lock(m_mutex);
// Make sure application with the given AE Title doesn't already
// exist
if( all_of( m_applications.cbegin(),
m_applications.cend(),
[ae_title]( const application_map::value_type& entry )
{
return entry.second->ae_title() != ae_title;
} ) == true )
{
// Create file object out of lock scope
application_ptr app_obj( new application( ae_title ) );
const int id = generate_id();
// generate_id shall maintain uniqueness, but assert here
assert( m_applications.count( id ) == 0 );
// Insert the file object into the dictionary. Two-step process
// (create then swap) to prevent memory leak in case operator[]
// throws an exception
m_applications[id].swap( app_obj );
ret = id;
}
else
{
ret = -MC_ALREADY_REGISTERED;
}
}
else
{
ret = -MC_NULL_POINTER_PARM;
}
return ret;
}
MC_STATUS library_context::release_application( int id )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
// Delete application pointer outside of lock scope. No
// need to do this except for performance and consistency
// with file/message/item freeing logic
application_ptr to_free = nullptr;
lock_guard<mutex> lock(m_mutex);
application_map::iterator itr( m_applications.find( id ) );
if( itr != m_applications.cend() )
{
to_free.swap( itr->second );
m_applications.erase( itr );
ret = MC_NORMAL_COMPLETION;
}
else
{
ret = MC_INVALID_APPLICATION_ID;
}
return ret;
}
application* library_context::get_application( int id )
{
lock_guard<mutex> lock(m_mutex);
application_map::const_iterator itr( m_applications.find( id ) );
return itr == m_applications.cend() ? nullptr : itr->second.get();
}
int library_context::generate_id()
{
// This function must only be called by a function which performs
// its own locking.
int ret = -1;
do
{
ret = m_id_gen( m_rng );
}
while( m_data_dictionaries.count( ret ) != 0 ||
m_applications.count( ret ) != 0 );
return ret;
}
}
| 28.627002 | 85 | 0.588329 | [
"object"
] |
4a16062f4f95ffe7ec73a44e042137f84161147d | 1,699 | cpp | C++ | Leetcode/2001-3000/2019. The Score of Students Solving Math Expression/2019.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/2001-3000/2019. The Score of Students Solving Math Expression/2019.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/2001-3000/2019. The Score of Students Solving Math Expression/2019.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
int scoreOfStudents(string s, vector<int>& answers) {
const int n = s.length() / 2 + 1;
const unordered_map<char, function<int(int, int)>> func{
{'+', plus<int>()}, {'*', multiplies<int>()}};
int ans = 0;
vector<vector<unordered_set<int>>> dp(n, vector<unordered_set<int>>(n));
unordered_map<int, int> count;
for (int i = 0; i < n; ++i)
dp[i][i].insert(s[i * 2] - '0');
for (int d = 1; d < n; ++d)
for (int i = 0; i + d < n; ++i) {
const int j = i + d;
for (int k = i; k < j; ++k) {
const char op = s[k * 2 + 1];
for (const int a : dp[i][k])
for (const int b : dp[k + 1][j]) {
const int res = func.at(op)(a, b);
if (res <= 1000)
dp[i][j].insert(res);
}
}
}
const int correctAnswer = eval(s);
for (const int answer : answers)
++count[answer];
for (const auto& [answer, freq] : count)
if (answer == correctAnswer)
ans += 5 * freq;
else if (dp[0][n - 1].count(answer))
ans += 2 * freq;
return ans;
}
private:
int eval(const string& s) {
int ans = 0;
int prevNum = 0;
int currNum = 0;
char op = '+';
for (int i = 0; i < s.length(); ++i) {
const char c = s[i];
if (isdigit(c))
currNum = currNum * 10 + (c - '0');
if (!isdigit(c) || i == s.length() - 1) {
if (op == '+') {
ans += prevNum;
prevNum = currNum;
} else if (op == '*') {
prevNum = prevNum * currNum;
}
op = c;
currNum = 0;
}
}
return ans + prevNum;
}
};
| 24.985294 | 76 | 0.449676 | [
"vector"
] |
4a1c76b0d996ac310aed1c239ff8b69f7020cc40 | 1,800 | hh | C++ | RAVL2/Math/Geometry/Euclidean/2D/HEMesh2d.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Geometry/Euclidean/2D/HEMesh2d.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Geometry/Euclidean/2D/HEMesh2d.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2002, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
#ifndef RAVL_HEMESH2D_HEADER
#define RAVL_HEMESH2D_HEADER 1
////////////////////////////////////////////////////////////
//! rcsid="$Id: HEMesh2d.hh 5240 2005-12-06 17:16:50Z plugger $"
//! author="Charles Galambos"
//! docentry="Ravl.API.Math.Geometry.2D"
//! lib=RavlMath
//! example=exHEMesh2d.cc
#include "Ravl/THEMesh.hh"
#include "Ravl/Point2d.hh"
#include "Ravl/RealRange2d.hh"
//! file="Ravl/Math/Geometry/Euclidean/2D/HEMesh2d.hh"
namespace RavlN {
class TriMesh2dC;
//! userlevel=Normal
//: 2D Half edge mesh.
class HEMesh2dC
: public THEMeshC<Point2dC>
{
public:
HEMesh2dC();
//: Default constructor.
// Creates an invalid handle.
explicit HEMesh2dC(bool);
//: Constructor.
// Creates an empty mesh.
Point2dC Mean() const;
//: Compute the mean position of points in the mesh.
THEMeshFaceC<Point2dC> FindFace(const Point2dC &pnt);
//: Find face containing point 'pnt'.
// Returns an invalid handle if none found. <p>
// This assumes the edges around a face are ordered clockwise.
// Note: This does a linear searh through the faces, it doesn't
// use any clever indexing/search scheme at the moment
RealRange2dC BoundingRectangle() const;
//: Compute the bounding rectangle for the points in the mesh.
TriMesh2dC TriMesh() const;
//: Convert this mesh to a tri mesh.
// Note: This mesh must contain only triangular faces.
};
}
#endif
| 30 | 74 | 0.664444 | [
"mesh",
"geometry"
] |
4a1c858fcdd9243e93b65d551ff8fa20ee81e0cb | 547 | cpp | C++ | tournaments/zigzag/zigzag.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | 5 | 2020-02-06T09:51:22.000Z | 2021-03-19T00:18:44.000Z | tournaments/zigzag/zigzag.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | null | null | null | tournaments/zigzag/zigzag.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | 3 | 2019-09-27T13:06:21.000Z | 2021-04-20T23:13:17.000Z | int zigzag(std::vector<int> a) {
int best = 1;
int left = 0;
while (left < a.size()) {
int right = left + 1;
while (right < a.size()) {
if (right == left + 1) {
if (a[left] == a[right]) {
break;
}
} else {
if ((a[right - 1] - a[right - 2]) * (a[right - 1] - a[right]) <= 0) {
break;
}
}
right++;
}
best = std::max(best, right - left);
left = right;
if (left < a.size() && a[left - 1] != a[left]) {
left--;
}
}
return best;
}
| 19.535714 | 77 | 0.40585 | [
"vector"
] |
4a1f9dcfadadbedbea14c9a4176e2f9cb0ad2586 | 3,612 | cpp | C++ | examples/plugin/com_osvr_example_Locomotion.cpp | ethanpeng/OSVR-Core | 59405fc1b1a25aea051dfbba0be5171fa19b8b30 | [
"Apache-2.0"
] | 369 | 2015-03-08T03:12:41.000Z | 2022-02-08T22:15:39.000Z | examples/plugin/com_osvr_example_Locomotion.cpp | ethanpeng/OSVR-Core | 59405fc1b1a25aea051dfbba0be5171fa19b8b30 | [
"Apache-2.0"
] | 486 | 2015-03-09T13:29:00.000Z | 2020-10-16T00:41:26.000Z | examples/plugin/com_osvr_example_Locomotion.cpp | ethanpeng/OSVR-Core | 59405fc1b1a25aea051dfbba0be5171fa19b8b30 | [
"Apache-2.0"
] | 166 | 2015-03-08T12:03:56.000Z | 2021-12-03T13:56:21.000Z | /** @date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/LocomotionInterfaceC.h>
// Generated JSON header file
#include "com_osvr_example_Locomotion_json.h"
// Library/third-party includes
// Standard includes
#include <iostream>
#include <chrono>
#include <thread>
#include <random>
#include <ctime>
// Anonymous namespace to avoid symbol collision
namespace {
class LocomotionDevice {
public:
LocomotionDevice(OSVR_PluginRegContext ctx) {
/// Create the initialization options
OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);
osvrDeviceLocomotionConfigure(opts, &m_locomotion);
/// Create the device token with the options
m_dev.initAsync(ctx, "Locomotion", opts);
/// Send JSON descriptor
m_dev.sendJsonDescriptor(com_osvr_example_Locomotion_json);
/// Register update callback
m_dev.registerUpdateCallback(this);
/// Seed pseudo random generator.
std::srand(std::time(0));
}
OSVR_ReturnCode update() {
std::this_thread::sleep_for(std::chrono::milliseconds(
250)); // Simulate waiting a quarter second for data.
OSVR_TimeValue times;
osvrTimeValueGetNow(×);
int randVel = rand() % (int)(11);
int randPos = rand();
OSVR_NaviVelocityState velo;
OSVR_NaviPositionState posn;
velo.data[0] = randVel * std::abs(std::sin(randVel));
velo.data[1] = randVel * randVel * std::abs(std::sin(randVel));
posn.data[0] = std::abs(std::sin(randPos));
posn.data[1] = std::abs(std::cos(randPos));
osvrDeviceLocomotionReportNaviVelocity(m_locomotion, velo, 0, ×);
osvrDeviceLocomotionReportNaviPosition(m_locomotion, posn, 0, ×);
return OSVR_RETURN_SUCCESS;
}
private:
osvr::pluginkit::DeviceToken m_dev;
OSVR_LocomotionDeviceInterface m_locomotion;
};
class HardwareDetection {
public:
HardwareDetection() : m_found(false) {}
OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
if (m_found) {
return OSVR_RETURN_SUCCESS;
}
std::cout << "PLUGIN: Got a hardware detection request" << std::endl;
/// we always detect device in sample plugin
m_found = true;
std::cout << "PLUGIN: We have detected Locomotion device! "
<< std::endl;
/// Create our device object
osvr::pluginkit::registerObjectForDeletion(ctx,
new LocomotionDevice(ctx));
return OSVR_RETURN_SUCCESS;
}
private:
bool m_found;
};
} // namespace
OSVR_PLUGIN(com_osvr_example_Locomotion) {
osvr::pluginkit::PluginContext context(ctx);
/// Register a detection callback function object.
context.registerHardwareDetectCallback(new HardwareDetection());
return OSVR_RETURN_SUCCESS;
}
| 28 | 78 | 0.669435 | [
"object"
] |
4a2171b066958a5a900887d9b85aabee8770202b | 1,597 | cpp | C++ | aws-cpp-sdk-rds/source/model/PurchaseReservedDBInstancesOfferingRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-rds/source/model/PurchaseReservedDBInstancesOfferingRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-rds/source/model/PurchaseReservedDBInstancesOfferingRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/rds/model/PurchaseReservedDBInstancesOfferingRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::RDS::Model;
using namespace Aws::Utils;
PurchaseReservedDBInstancesOfferingRequest::PurchaseReservedDBInstancesOfferingRequest() :
m_reservedDBInstancesOfferingIdHasBeenSet(false),
m_reservedDBInstanceIdHasBeenSet(false),
m_dBInstanceCount(0),
m_dBInstanceCountHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
Aws::String PurchaseReservedDBInstancesOfferingRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=PurchaseReservedDBInstancesOffering&";
if(m_reservedDBInstancesOfferingIdHasBeenSet)
{
ss << "ReservedDBInstancesOfferingId=" << StringUtils::URLEncode(m_reservedDBInstancesOfferingId.c_str()) << "&";
}
if(m_reservedDBInstanceIdHasBeenSet)
{
ss << "ReservedDBInstanceId=" << StringUtils::URLEncode(m_reservedDBInstanceId.c_str()) << "&";
}
if(m_dBInstanceCountHasBeenSet)
{
ss << "DBInstanceCount=" << m_dBInstanceCount << "&";
}
if(m_tagsHasBeenSet)
{
unsigned tagsCount = 1;
for(auto& item : m_tags)
{
item.OutputToStream(ss, "Tags.member.", tagsCount, "");
tagsCount++;
}
}
ss << "Version=2014-10-31";
return ss.str();
}
void PurchaseReservedDBInstancesOfferingRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
uri.SetQueryString(SerializePayload());
}
| 26.616667 | 117 | 0.732624 | [
"model"
] |
4a241860dedba0fa801bdd3ec26777285469644a | 13,519 | cpp | C++ | zh_back/zh_rpc_server/system_management_imp.cpp | marklion/zhuochuangzhihui | 31ba95e4cc7e73648c1cf0f29b951c2e56cb4af4 | [
"MIT"
] | null | null | null | zh_back/zh_rpc_server/system_management_imp.cpp | marklion/zhuochuangzhihui | 31ba95e4cc7e73648c1cf0f29b951c2e56cb4af4 | [
"MIT"
] | 30 | 2021-12-28T03:51:30.000Z | 2022-03-22T07:58:35.000Z | zh_back/zh_rpc_server/system_management_imp.cpp | marklion/zhuochuangzhihui | 31ba95e4cc7e73648c1cf0f29b951c2e56cb4af4 | [
"MIT"
] | null | null | null | #include "system_management_imp.h"
#include "../zh_database/zh_db_config.h"
#include "zh_rpc_util.h"
#include <iostream>
#include <iosfwd>
#include <fstream>
#include "../zh_raster/lib/zh_raster.h"
#include "../zh_id_reader/lib/zh_id_reader.h"
#include "../zh_hk_gate/lib/zh_hk_gate.h"
#include "../zh_scale/lib/zh_scale.h"
#include "../zh_printer/lib/zh_printer.h"
#include "vehicle_order_center_imp.h"
#include <fstream>
system_management_handler *system_management_handler::m_inst = nullptr;
bool system_management_handler::reboot_system(const std::string &ssid)
{
if (!zh_rpc_util_get_online_user(ssid, 0))
{
ZH_RETURN_NO_PRAVILIGE();
}
exit(-1);
}
void system_management_handler::current_version(std::string &_return)
{
std::ifstream version_file("/conf/version.txt");
std::getline(version_file, _return);
}
void system_management_handler::internal_get_device_config(device_config &_return)
{
std::ifstream config_file("/conf/device/device_config.json", std::ios::in);
std::istreambuf_iterator<char> beg(config_file), end;
std::string config_string(beg, end);
neb::CJsonObject config(config_string);
auto gate_config = config["gate"];
auto scale_config = config["scale"];
for (int i = 0; i < gate_config.GetArraySize(); i++)
{
device_gate_config tmp;
tmp.name = gate_config[i]("name");
tmp.entry_id_reader_ip = gate_config[i]("entry_id_reader_ip");
tmp.exit_id_reader_ip = gate_config[i]("exit_id_reader_ip");
tmp.entry_config.cam_ip = gate_config[i]("entry_cam_ip");
tmp.entry_config.led_ip = gate_config[i]("entry_led_ip");
tmp.exit_config.cam_ip = gate_config[i]("exit_cam_ip");
tmp.exit_config.led_ip = gate_config[i]("exit_led_ip");
tmp.entry_qr_ip = gate_config[i]("entry_qr_ip");
tmp.exit_qr_ip = gate_config[i]("exit_qr_ip");
gate_config[i].Get("entry_need_id", tmp.entry_need_id);
gate_config[i].Get("exit_need_id", tmp.exit_need_id);
gate_config[i].Get("entry_need_qr", tmp.entry_need_qr);
gate_config[i].Get("exit_need_qr", tmp.exit_need_qr);
gate_config[i].Get("entry_nvr_ip", tmp.entry_nvr_ip);
gate_config[i].Get("exit_nvr_ip", tmp.exit_nvr_ip);
gate_config[i].Get("entry_channel", tmp.entry_channel);
gate_config[i].Get("exit_channel", tmp.exit_channel);
_return.gate.push_back(tmp);
}
for (int i = 0; i < scale_config.GetArraySize(); i++)
{
device_scale_config tmp;
tmp.entry_printer_ip = scale_config[i]("entry_printer_ip");
tmp.exit_printer_ip = scale_config[i]("exit_printer_ip");
tmp.name = scale_config[i]("name");
tmp.raster_ip.push_back(scale_config[i]["raster_ip"](0));
tmp.raster_ip.push_back(scale_config[i]["raster_ip"](1));
tmp.scale_ip = scale_config[i]("scale_ip");
tmp.scale_brand = scale_config[i]("scale_brand");
tmp.entry_id_reader_ip = scale_config[i]("entry_id_reader_ip");
tmp.exit_id_reader_ip = scale_config[i]("exit_id_reader_ip");
tmp.entry_config.cam_ip = scale_config[i]("entry_cam_ip");
tmp.entry_config.led_ip = scale_config[i]("entry_led_ip");
tmp.exit_config.cam_ip = scale_config[i]("exit_cam_ip");
tmp.exit_config.led_ip = scale_config[i]("exit_led_ip");
tmp.entry_qr_ip = scale_config[i]("entry_qr_ip");
tmp.exit_qr_ip = scale_config[i]("exit_qr_ip");
scale_config[i].Get("need_id", tmp.need_id);
scale_config[i].Get("need_qr", tmp.need_qr);
scale_config[i].Get("entry_nvr_ip", tmp.entry_nvr_ip);
scale_config[i].Get("exit_nvr_ip", tmp.exit_nvr_ip);
scale_config[i].Get("entry_channel", tmp.entry_channel);
scale_config[i].Get("exit_channel", tmp.exit_channel);
_return.scale.push_back(tmp);
}
}
void system_management_handler::get_device_config(device_config &_return, const std::string &ssid)
{
auto opt_user = zh_rpc_util_get_online_user(ssid, 0);
if (!opt_user)
{
ZH_RETURN_NO_PRAVILIGE();
}
internal_get_device_config(_return);
}
bool system_management_handler::edit_device_config(const std::string &ssid, const device_config &config)
{
bool ret = false;
auto opt_user = zh_rpc_util_get_online_user(ssid, 0);
if (!opt_user)
{
ZH_RETURN_NO_PRAVILIGE();
}
std::ofstream config_file("/conf/device/device_config.json", std::ios::out);
neb::CJsonObject tmp;
vehicle_order_center_handler::gsm_map.clear();
vehicle_order_center_handler::ssm_map.clear();
tmp.AddEmptySubArray("gate");
tmp.AddEmptySubArray("scale");
for (auto &itr : config.gate)
{
neb::CJsonObject gate;
gate.Add("entry_id_reader_ip", itr.entry_id_reader_ip);
gate.Add("exit_id_reader_ip", itr.exit_id_reader_ip);
gate.Add("name", itr.name);
gate.Add("entry_cam_ip", itr.entry_config.cam_ip);
gate.Add("entry_led_ip", itr.entry_config.led_ip);
gate.Add("exit_cam_ip", itr.exit_config.cam_ip);
gate.Add("exit_led_ip", itr.exit_config.led_ip);
gate.Add("entry_need_id", itr.entry_need_id, itr.entry_need_id);
gate.Add("exit_need_id", itr.exit_need_id, itr.exit_need_id);
gate.Add("entry_need_qr", itr.entry_need_qr, itr.entry_need_qr);
gate.Add("exit_need_qr", itr.exit_need_qr, itr.exit_need_qr);
gate.Add("entry_qr_ip", itr.entry_qr_ip);
gate.Add("exit_qr_ip", itr.exit_qr_ip);
gate.Add("entry_nvr_ip", itr.entry_nvr_ip);
gate.Add("exit_nvr_ip", itr.exit_nvr_ip);
gate.Add("entry_channel", itr.entry_channel);
gate.Add("exit_channel", itr.exit_channel);
tmp["gate"].Add(gate);
}
for (auto &itr : config.scale)
{
neb::CJsonObject scale;
scale.Add("name", itr.name);
scale.Add("scale_ip", itr.scale_ip);
scale.Add("scale_brand", itr.scale_brand);
scale.Add("entry_printer_ip", itr.entry_printer_ip);
scale.Add("exit_printer_ip", itr.exit_printer_ip);
scale.AddEmptySubArray("raster_ip");
scale["raster_ip"].Add(itr.raster_ip[0]);
scale["raster_ip"].Add(itr.raster_ip[1]);
scale.Add("entry_id_reader_ip", itr.entry_id_reader_ip);
scale.Add("exit_id_reader_ip", itr.exit_id_reader_ip);
scale.Add("entry_cam_ip", itr.entry_config.cam_ip);
scale.Add("entry_led_ip", itr.entry_config.led_ip);
scale.Add("exit_cam_ip", itr.exit_config.cam_ip);
scale.Add("exit_led_ip", itr.exit_config.led_ip);
scale.Add("entry_qr_ip", itr.entry_qr_ip);
scale.Add("exit_qr_ip", itr.exit_qr_ip);
scale.Add("need_id", itr.need_id, itr.need_id);
scale.Add("need_qr", itr.need_qr, itr.need_qr);
scale.Add("entry_nvr_ip", itr.entry_nvr_ip);
scale.Add("exit_nvr_ip", itr.exit_nvr_ip);
scale.Add("entry_channel", itr.entry_channel);
scale.Add("exit_channel", itr.exit_channel);
tmp["scale"].Add(scale);
}
config_file << tmp.ToFormattedString();
config_file.close();
for (auto &itr:config.gate)
{
vehicle_order_center_handler::gsm_map[itr.entry_config.cam_ip] = std::make_shared<gate_state_machine>(itr.entry_config.cam_ip, itr.entry_id_reader_ip, itr.entry_qr_ip, true);
vehicle_order_center_handler::gsm_map[itr.entry_config.cam_ip]->ctrl_policy.set_policy(itr.entry_need_id, itr.entry_need_qr);
vehicle_order_center_handler::gsm_map[itr.exit_config.cam_ip] = std::make_shared<gate_state_machine>(itr.exit_config.cam_ip, itr.exit_id_reader_ip, itr.exit_qr_ip, false);
vehicle_order_center_handler::gsm_map[itr.exit_config.cam_ip]->ctrl_policy.set_policy(itr.exit_need_id, itr.exit_need_qr);
}
for (auto &itr:config.scale)
{
vehicle_order_center_handler::ssm_map[itr.name] = std::make_shared<scale_state_machine>(itr);
vehicle_order_center_handler::ssm_map[itr.name]->ctrl_policy.set_policy(itr.need_id, itr.need_qr);
}
return true;
}
bool system_management_handler::raster_is_block(const std::string &raster_ip)
{
return raster_was_block(raster_ip, ZH_RASTER_PORT);
}
bool system_management_handler::print_content(const std::string &printer_ip, const std::string &content, const std::string &qr_code)
{
tdf_log tmp_log("printer " + printer_ip);
tmp_log.log("print:content:%s, qr_code:%s", content.c_str(), qr_code.c_str());
zh_printer_dev tmp(printer_ip);
tmp.print_string(content);
if (qr_code.length() > 0)
{
tmp.print_qr(qr_code);
}
return true;
}
void system_management_handler::read_id_no(std::string &_return, const std::string &id_reader_ip)
{
_return = id_result[id_reader_ip];
}
bool system_management_handler::ctrl_gate(const std::string &road_ip, const int64_t cmd)
{
return zh_hk_ctrl_gate(road_ip, (zh_hk_gate_control_cmd)cmd);
}
road_status system_management_handler::get_status_by_road(const std::string &_road)
{
road_status ret;
if (0 == pthread_mutex_lock(&m_road_status_map_lock))
{
ret = m_road_status_map[_road];
pthread_mutex_unlock(&m_road_status_map_lock);
}
else
{
tdf_log tmp("road_status");
tmp.err("failed to lock status map");
}
return ret;
}
void system_management_handler::set_status_by_road(const std::string &_road, road_status &status)
{
if (0 == pthread_mutex_lock(&m_road_status_map_lock))
{
m_road_status_map[_road] = status;
pthread_mutex_unlock(&m_road_status_map_lock);
}
else
{
tdf_log tmp("road_status");
tmp.err("failed to lock status map");
}
}
void system_management_handler::get_road_status(road_status &_return, const std::string &gate_code)
{
_return.coming_vehicle = cam_result[gate_code];
}
double system_management_handler::read_scale(const std::string &scale_ip)
{
return 0;
}
void system_management_handler::run_update(const std::string &ssid, const std::string &pack_path)
{
auto user = zh_rpc_util_get_online_user(ssid, 0);
if (!user)
{
ZH_RETURN_NO_PRAVILIGE();
}
int orig_fd = open(pack_path.c_str(), O_RDONLY);
int new_fd = open("/root/install.sh", O_WRONLY | O_CREAT | O_TRUNC, 0777);
if (orig_fd >= 0 && new_fd >= 0)
{
long buf;
int read_len = 0;
while ((read_len = read(orig_fd, &buf, sizeof(buf))) > 0)
{
write(new_fd, &buf, read_len);
}
}
if (orig_fd >= 0)
{
close(orig_fd);
}
if (new_fd >= 0)
{
close(new_fd);
}
exit(-1);
}
void system_management_handler::get_domain_name(std::string &_return)
{
_return = std::string(getenv("BASE_URL")) + std::string(getenv("URL_REMOTE"));
}
void system_management_handler::get_oem_name(std::string &_return)
{
_return = std::string(getenv("OEM_NAME"));
}
void system_management_handler::get_all_scale_brand(std::vector<std::string> &_return)
{
_return = zh_scale_if::get_all_brand();
}
#define ZH_GET_DEVICE_HEALTH(_X) (_X.length() == 0?-1:m_get_device_health_map()[_X])
void system_management_handler::get_device_health(std::vector<device_health> &_return, const std::string &ssid)
{
auto opt_user = zh_rpc_util_get_online_user(ssid, 2);
if (!opt_user)
{
ZH_RETURN_NO_PRAVILIGE();
}
device_config dc;
internal_get_device_config(dc);
for (auto &itr : dc.gate)
{
device_health tmp;
tmp.name = itr.name;
tmp.entry_cam = ZH_GET_DEVICE_HEALTH(itr.entry_config.cam_ip);
tmp.entry_led = ZH_GET_DEVICE_HEALTH(itr.entry_config.led_ip);
tmp.entry_id = ZH_GET_DEVICE_HEALTH(itr.entry_id_reader_ip);
tmp.entry_qr = ZH_GET_DEVICE_HEALTH(itr.entry_qr_ip);
tmp.exit_cam = ZH_GET_DEVICE_HEALTH(itr.exit_config.cam_ip);
tmp.exit_led = ZH_GET_DEVICE_HEALTH(itr.exit_config.led_ip);
tmp.exit_id = ZH_GET_DEVICE_HEALTH(itr.exit_id_reader_ip);
tmp.exit_qr = ZH_GET_DEVICE_HEALTH(itr.exit_qr_ip);
_return.push_back(tmp);
}
for (auto &itr : dc.scale)
{
device_health tmp;
tmp.name = itr.name;
tmp.entry_cam = ZH_GET_DEVICE_HEALTH(itr.entry_config.cam_ip);
tmp.entry_led = ZH_GET_DEVICE_HEALTH(itr.entry_config.led_ip);
tmp.entry_id = ZH_GET_DEVICE_HEALTH(itr.entry_id_reader_ip);
tmp.entry_qr = ZH_GET_DEVICE_HEALTH(itr.entry_qr_ip);
tmp.entry_printer = ZH_GET_DEVICE_HEALTH(itr.entry_printer_ip);
tmp.raster1 = ZH_GET_DEVICE_HEALTH(itr.raster_ip[0]);
tmp.raster2 = ZH_GET_DEVICE_HEALTH(itr.raster_ip[1]);
tmp.scale = ZH_GET_DEVICE_HEALTH(itr.scale_ip);
tmp.exit_cam = ZH_GET_DEVICE_HEALTH(itr.exit_config.cam_ip);
tmp.exit_led = ZH_GET_DEVICE_HEALTH(itr.exit_config.led_ip);
tmp.exit_id = ZH_GET_DEVICE_HEALTH(itr.exit_id_reader_ip);
tmp.exit_qr = ZH_GET_DEVICE_HEALTH(itr.exit_qr_ip);
tmp.exit_printer = ZH_GET_DEVICE_HEALTH(itr.exit_printer_ip);
_return.push_back(tmp);
}
}
std::map<std::string, long> &system_management_handler::m_get_device_health_map()
{
return zh_runtime_get_device_health();
}
void system_management_handler::read_qr(std::string &_return, const std::string &id_reader_ip)
{
_return = qr_result[id_reader_ip];
}
bool system_management_handler::led_cast_welcome(const std::string &led_ip)
{
return zh_hk_cast_welcome(led_ip, "蒙A12345");
} | 37.974719 | 182 | 0.68866 | [
"vector"
] |
4a24c7bd89e9be8ee7cf4b4c93e4a334993ca49f | 4,031 | cpp | C++ | soccer/src/soccer/planning/tests/bezier_path_test.cpp | xiaoqingyu0113/robocup-software | 6127d25fc455051ef47610d0e421b2ca7330b4fa | [
"Apache-2.0"
] | 200 | 2015-01-26T01:45:34.000Z | 2022-03-19T13:05:31.000Z | soccer/src/soccer/planning/tests/bezier_path_test.cpp | xiaoqingyu0113/robocup-software | 6127d25fc455051ef47610d0e421b2ca7330b4fa | [
"Apache-2.0"
] | 1,254 | 2015-01-03T01:57:35.000Z | 2022-03-16T06:32:21.000Z | soccer/src/soccer/planning/tests/bezier_path_test.cpp | xiaoqingyu0113/robocup-software | 6127d25fc455051ef47610d0e421b2ca7330b4fa | [
"Apache-2.0"
] | 206 | 2015-01-21T02:03:18.000Z | 2022-02-01T17:57:46.000Z | #include <fstream>
#include <gtest/gtest.h>
#include "planning/primitives/path_smoothing.hpp"
using rj_geometry::Point;
static void check_bezier_low_curvature(const planning::BezierPath& path) {
// Expected error is O(1/N)
constexpr int kN = 1000;
double ds = 1.0 / static_cast<double>(kN);
for (int i = 0; i <= kN; i++) {
double s = i * ds;
double curvature = 0;
Point tangent;
path.evaluate(s, nullptr, &tangent, &curvature);
if (tangent.mag() > 1e-3) {
EXPECT_LE(std::abs(curvature), 100);
}
}
}
static void check_bezier_smooth(const planning::BezierPath& path) {
// Expected error decreases with high N
constexpr int kN = 100;
constexpr double kEpsilon = 1e-2;
double ds = 1.0 / static_cast<double>(kN);
for (int i = 0; i < kN; i++) {
double s = i * ds;
Point position;
Point tangent;
double curvature = 0;
path.evaluate(s, &position, &tangent, &curvature);
Point position_next;
Point tangent_next;
double curvature_next = 0;
double h = 1e-6;
path.evaluate(s + h, &position_next, &tangent_next, &curvature_next);
EXPECT_LE((0.5 * (tangent + tangent_next)).dist_to((position_next - position) / h),
kEpsilon);
double curvature_expected = tangent_next.angle_between(tangent) / h / tangent.mag();
if (tangent.mag() > 1e-3 && tangent_next.mag() > 1e-3) {
// Make sure that the approximate curvature is consistent with the
// calculated exact value.
EXPECT_NEAR(curvature, std::abs(curvature_expected), kEpsilon) << " at s = " << s;
}
}
}
TEST(BezierPath, two_points_path_smooth_and_consistent) {
planning::MotionConstraints constraints;
std::vector<Point> points{Point{0, 0}, Point{1, 1}};
planning::BezierPath path(std::move(points), Point(1, 0), Point(1, 0), constraints);
check_bezier_smooth(path);
}
TEST(BezierPath, multiple_points_path_smooth_and_consistent) {
planning::MotionConstraints constraints;
std::vector<Point> points{Point{0, 0}, Point{1, 1}, Point{2, 0}};
planning::BezierPath path(std::move(points), Point(1, 0), Point(1, 0), constraints);
check_bezier_smooth(path);
}
// Smoothed paths should have reasonably low curvature everywhere on the
// path. Sadly, this does not hold with our current system, which uses
// Bezier curves and places keypoints in a fairly naive manner.
// All examples with zero-velocity endpoints are broken because of numerical
// issues (in this case, the second and third control points go on top of the
// first and fourth, respectively).
// TODO(#1539): Switch to a scheme that minimizes sum of squared
// {acceleration/curvature/etc}. This should be fairly simple with Hermite
// splines, as acceleration on a point in a curve is a linear function of
// the endpoints' positions and velocities (so sub of squared acceleration
// is a quadratic in the velocities (decision variables))
TEST(BezierPath, zero_velocity_endpoints_straight_smooth_and_consistent) {
planning::MotionConstraints constraints;
std::vector<Point> points{Point{0, 0}, Point{2, 0}};
planning::BezierPath path(std::move(points), Point(0, 0), Point(0, 0), constraints);
check_bezier_smooth(path);
}
TEST(BezierPath, zero_endpoints_curved_smooth_and_consistent) {
planning::MotionConstraints constraints;
std::vector<Point> points{Point{0, 0}, Point{1, 1}, Point{2, 0}};
planning::BezierPath path(std::move(points), Point(0, 0), Point(0, 0), constraints);
check_bezier_smooth(path);
check_bezier_low_curvature(path);
}
TEST(BezierPath, nonzero_start_zero_end_curved_smooth_and_consistent) {
planning::MotionConstraints constraints;
std::vector<Point> points{Point{0, 0}, Point{2, 2}};
planning::BezierPath path(std::move(points), Point(1, 0), Point(0, 0), constraints);
check_bezier_smooth(path);
check_bezier_low_curvature(path);
}
| 37.324074 | 94 | 0.679484 | [
"vector"
] |
4a2d36f170a1d75e9ea69e9ec2d768c7ea684fca | 5,738 | hpp | C++ | src/meshNekSetupHex3D.hpp | yslan/nekRS | eff5749af935f1d56f67c12244fa246fe696db8c | [
"BSD-3-Clause"
] | null | null | null | src/meshNekSetupHex3D.hpp | yslan/nekRS | eff5749af935f1d56f67c12244fa246fe696db8c | [
"BSD-3-Clause"
] | null | null | null | src/meshNekSetupHex3D.hpp | yslan/nekRS | eff5749af935f1d56f67c12244fa246fe696db8c | [
"BSD-3-Clause"
] | null | null | null | #include "libParanumal.hpp"
#include "meshNekReaderHex3D.hpp"
void meshBoxSetupHex3D(int N, mesh_t *mesh) {
mesh->Nfields = 1;
mesh->dim = 3;
mesh->Nverts = 8; // number of vertices per element
mesh->Nfaces = 6;
mesh->NfaceVertices = 4;
// vertices on each face
int faceVertices[6][4] =
{{0,1,2,3},{0,1,5,4},{1,2,6,5},{2,3,7,6},{3,0,4,7},{4,5,6,7}};
mesh->faceVertices =
(int*) calloc(mesh->NfaceVertices*mesh->Nfaces, sizeof(int));
memcpy(mesh->faceVertices, faceVertices[0], mesh->NfaceVertices*mesh->Nfaces*sizeof(int));
// build an NX x NY x NZ periodic box grid
hlong NX = 3, NY = 3, NZ = 3; // defaults
dfloat XMIN = -1, XMAX = +1;
dfloat YMIN = -1, YMAX = +1;
dfloat ZMIN = -1, ZMAX = +1;
hlong allNelements = NX*NY*NZ;
hlong chunkNelements = allNelements/mesh->size;
hlong start = chunkNelements*mesh->rank;
hlong end = chunkNelements*(mesh->rank+1);
if(mesh->rank==(mesh->size-1))
end = allNelements;
mesh->Nnodes = NX*NY*NZ; // assume periodic and global number of nodes
mesh->Nelements = end-start;
mesh->NboundaryFaces = 0;
mesh->EToV = (hlong*) calloc(mesh->Nelements*mesh->Nverts, sizeof(hlong));
mesh->EX = (dfloat*) calloc(mesh->Nelements*mesh->Nverts, sizeof(dfloat));
mesh->EY = (dfloat*) calloc(mesh->Nelements*mesh->Nverts, sizeof(dfloat));
mesh->EZ = (dfloat*) calloc(mesh->Nelements*mesh->Nverts, sizeof(dfloat));
mesh->elementInfo = (hlong*) calloc(mesh->Nelements, sizeof(hlong));
// [0,NX]
dfloat dx = (XMAX-XMIN)/NX; // xmin+0*dx, xmin + NX*(XMAX-XMIN)/NX
dfloat dy = (YMAX-YMIN)/NY;
dfloat dz = (ZMAX-ZMIN)/NZ;
for(hlong n=start;n<end;++n){
int i = n%NX; // [0, NX)
int j = (n/NY)%NZ; // [0, NY)
int k = n/(NX*NY); // [0, NZ)
hlong e = n-start;
int ip = (i+1)%NX;
int jp = (j+1)%NY;
int kp = (k+1)%NZ;
// do not use for coordinates
mesh->EToV[e*mesh->Nverts+0] = i + j*NX + k*NX*NY;
mesh->EToV[e*mesh->Nverts+1] = ip + j*NX + k*NX*NY;
mesh->EToV[e*mesh->Nverts+2] = ip + jp*NX + k*NX*NY;
mesh->EToV[e*mesh->Nverts+3] = i + jp*NX + k*NX*NY;
mesh->EToV[e*mesh->Nverts+4] = i + j*NX + kp*NX*NY;
mesh->EToV[e*mesh->Nverts+5] = ip + j*NX + kp*NX*NY;
mesh->EToV[e*mesh->Nverts+6] = ip + jp*NX + kp*NX*NY;
mesh->EToV[e*mesh->Nverts+7] = i + jp*NX + kp*NX*NY;
dfloat xo = XMIN + dx*i;
dfloat yo = YMIN + dy*j;
dfloat zo = ZMIN + dz*k;
dfloat *ex = mesh->EX+e*mesh->Nverts;
dfloat *ey = mesh->EY+e*mesh->Nverts;
dfloat *ez = mesh->EZ+e*mesh->Nverts;
ex[0] = xo; ey[0] = yo; ez[0] = zo;
ex[1] = xo+dx; ey[1] = yo; ez[1] = zo;
ex[2] = xo+dx; ey[2] = yo+dy; ez[2] = zo;
ex[3] = xo; ey[3] = yo+dy; ez[3] = zo;
ex[4] = xo; ey[4] = yo; ez[4] = zo+dz;
ex[5] = xo+dx; ey[5] = yo; ez[5] = zo+dz;
ex[6] = xo+dx; ey[6] = yo+dy; ez[6] = zo+dz;
ex[7] = xo; ey[7] = yo+dy; ez[7] = zo+dz;
mesh->elementInfo[e] = 1; // ?
}
mesh->EToB = (int*) calloc(mesh->Nelements*mesh->Nfaces, sizeof(int));
mesh->boundaryInfo = NULL; // no boundaries
// connect elements using parallel sort
libParanumal::meshParallelConnect(mesh);
// load reference (r,s,t) element nodes
libParanumal::meshLoadReferenceNodesHex3D(mesh, N);
// compute physical (x,y) locations of the element nodes
meshPhysicalNodesHex3D(mesh);
// compute geometric factors
libParanumal::meshGeometricFactorsHex3D(mesh);
// set up halo exchange info for MPI (do before connect face nodes)
libParanumal::meshHaloSetup(mesh);
// connect face nodes (find trace indices)
meshConnectPeriodicFaceNodes3D(mesh,XMAX-XMIN,YMAX-YMIN,ZMAX-ZMIN);
// compute surface geofacs (including halo)
libParanumal::meshSurfaceGeometricFactorsHex3D(mesh);
// global nodes
libParanumal::meshParallelConnectNodes(mesh);
}
void meshNekSetupHex3D(int N, mesh_t *mesh) {
// get mesh from nek
meshNekReaderHex3D(N, mesh);
mesh->Nfields = 1; // TW: note this is a temporary patch (halo exchange depends on nfields)
// connect elements using parallel sort
libParanumal::meshParallelConnect(mesh);
// connect elements to boundary faces
libParanumal::meshConnectBoundary(mesh);
// load reference (r,s,t) element nodes
libParanumal::meshLoadReferenceNodesHex3D(mesh, N);
// compute physical (x,y) locations of the element nodes
meshPhysicalNodesHex3D(mesh);
// compute geometric factors
libParanumal::meshGeometricFactorsHex3D(mesh);
// set up halo exchange info for MPI (do before connect face nodes)
libParanumal::meshHaloSetup(mesh);
// connect face nodes (find trace indices)
libParanumal::meshConnectFaceNodes3D(mesh);
// compute surface geofacs (including halo)
libParanumal::meshSurfaceGeometricFactorsHex3D(mesh);
// global nodes
libParanumal::meshParallelConnectNodes(mesh);
// initialize LSERK4 time stepping coefficients
int Nrk = 5;
dfloat rka[5] = {0.0,
-567301805773.0/1357537059087.0 ,
-2404267990393.0/2016746695238.0 ,
-3550918686646.0/2091501179385.0 ,
-1275806237668.0/842570457699.0};
dfloat rkb[5] = { 1432997174477.0/9575080441755.0 ,
5161836677717.0/13612068292357.0 ,
1720146321549.0/2090206949498.0 ,
3134564353537.0/4481467310338.0 ,
2277821191437.0/14882151754819.0};
dfloat rkc[6] = {0.0 ,
1432997174477.0/9575080441755.0 ,
2526269341429.0/6820363962896.0 ,
2006345519317.0/3224310063776.0 ,
2802321613138.0/2924317926251.0,
1.};
mesh->Nrk = Nrk;
memcpy(mesh->rka, rka, Nrk*sizeof(dfloat));
memcpy(mesh->rkb, rkb, Nrk*sizeof(dfloat));
memcpy(mesh->rkc, rkc, (Nrk+1)*sizeof(dfloat));
}
| 31.016216 | 93 | 0.637679 | [
"mesh"
] |
4a30e37e3c2dfbbdaf7ad0ad929e70fca399dcce | 1,952 | hpp | C++ | proposals/ProposalGen.hpp | kurff/kurff | e6f166216623e87229d190f9aa4d5acb3f55f190 | [
"MIT"
] | null | null | null | proposals/ProposalGen.hpp | kurff/kurff | e6f166216623e87229d190f9aa4d5acb3f55f190 | [
"MIT"
] | null | null | null | proposals/ProposalGen.hpp | kurff/kurff | e6f166216623e87229d190f9aa4d5acb3f55f190 | [
"MIT"
] | null | null | null | #ifndef __PROPOSAL_GEN_HPP__
#define __PROPOSAL_GEN_HPP__
#include "proposals/Proposal.hpp"
#include "proposals/MSERProposal.hpp"
#include "proposals/CannyProposal.hpp"
#include "proposals/FASTProposal.hpp"
#include "proposals/Merge.hpp"
#include <vector>
#include <string>
namespace kurff{
class ProposalGen{
public:
ProposalGen(std::vector<std::string> proposal_names): proposal_names_(proposal_names), number_(100){
}
~ProposalGen(){
}
void create(){
proposal_methods_.clear();
for(auto name : proposal_names_){
LOG(INFO)<<"create proposal methods: "<< name;
proposal_methods_.push_back(ProposalRegistry()->Create(name+"Proposal", number_));
}
merge_.reset(new Merge());
}
void run(const cv::Mat& image, std::vector<Box>& proposals ){
proposals_.resize(proposal_methods_.size());
int cnt = -1;
for(auto proposal_method : proposal_methods_){
++ cnt;
proposal_method->run(image, proposals_[cnt]);
LOG(INFO)<<proposal_method->name()<<" get proposals: "<<proposals_[cnt].size();
}
for(int i = 0; i < proposal_methods_.size(); ++ i){
merge_->simple_merge(proposals, proposals_[i], proposals);
}
LOG(INFO)<<"final proposal size: "<< proposals.size();
}
protected:
std::vector<std::shared_ptr<Proposal> > proposal_methods_;
std::shared_ptr<Merge> merge_;
std::vector<std::vector<Box> > proposals_;
std::vector<std::string> proposal_names_;
int number_;
};
}
#endif
| 27.885714 | 112 | 0.523566 | [
"vector"
] |
4a310a77ea50494ebfcfc8c37483ef5f2a92b718 | 5,394 | hpp | C++ | src/containers/intrusive_priority_queue.hpp | zadcha/rethinkdb | bb4f5cc28242dc1e29e9a46a8a931ec54420070c | [
"Apache-2.0"
] | 21,684 | 2015-01-01T03:42:20.000Z | 2022-03-30T13:32:44.000Z | src/containers/intrusive_priority_queue.hpp | RethonkDB/rethonkdb | 8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee | [
"Apache-2.0"
] | 4,067 | 2015-01-01T00:04:51.000Z | 2022-03-30T13:42:56.000Z | src/containers/intrusive_priority_queue.hpp | RethonkDB/rethonkdb | 8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee | [
"Apache-2.0"
] | 1,901 | 2015-01-01T21:05:59.000Z | 2022-03-21T08:14:25.000Z | // Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef CONTAINERS_INTRUSIVE_PRIORITY_QUEUE_HPP_
#define CONTAINERS_INTRUSIVE_PRIORITY_QUEUE_HPP_
#include <utility>
#include <vector>
#include "errors.hpp"
// TODO: For some reason I wanted this to not use an O(n) vector.
template <class node_t>
class intrusive_priority_queue_t;
template <class node_t>
class intrusive_priority_queue_node_t {
public:
intrusive_priority_queue_node_t()
#ifndef NDEBUG
: queue(NULL)
#endif
{ }
protected:
~intrusive_priority_queue_node_t() {
rassert(queue == NULL);
}
private:
friend class intrusive_priority_queue_t<node_t>;
#ifndef NDEBUG
intrusive_priority_queue_t<node_t> *queue;
#endif
size_t index;
DISABLE_COPYING(intrusive_priority_queue_node_t);
};
template <class node_t>
class intrusive_priority_queue_t {
public:
intrusive_priority_queue_t() { }
~intrusive_priority_queue_t() {
rassert(empty());
}
bool empty() {
return nodes.empty();
}
size_t size() {
return nodes.size();
}
void push(node_t *x) {
rassert(x != NULL);
rassert(node_queue(x) == NULL);
DEBUG_ONLY_CODE(node_queue(x) = this);
nodes.push_back(x);
node_index(x) = nodes.size() - 1;
bubble_towards_root(x);
}
void remove(node_t *x) {
rassert(x);
rassert(node_queue(x) == this);
DEBUG_ONLY_CODE(node_queue(x) = NULL);
if (node_index(x) == nodes.size() - 1) {
nodes.pop_back();
} else {
node_t *replacement = nodes[node_index(x)] = nodes.back();
node_index(replacement) = node_index(x);
nodes.pop_back();
bubble_towards_root(replacement);
bubble_towards_leaves(replacement);
}
}
node_t *peek() {
if (nodes.empty()) {
return nullptr;
} else {
return nodes.front();
}
}
node_t *pop() {
if (nodes.empty()) {
return nullptr;
} else {
node_t *x = nodes.front();
rassert(node_queue(x) == this);
DEBUG_ONLY_CODE(x->queue = NULL);
if (nodes.size() == 1) {
nodes.pop_back();
} else {
node_t *replacement = nodes[0] = nodes.back();
node_index(replacement) = 0;
nodes.pop_back();
bubble_towards_leaves(replacement);
}
return x;
}
}
void update(node_t *node) {
rassert(node);
bubble_towards_root(node);
bubble_towards_leaves(node);
}
void swap_in_place(node_t *to_remove, node_t *to_insert) {
rassert(to_remove);
rassert(to_insert);
rassert(node_queue(to_remove) == this);
rassert(node_queue(to_insert) == NULL);
// Pass const pointers to one call of left_is_higher_priority to enforce that it be const.
rassert(!left_is_higher_priority(const_cast<const node_t *>(to_remove), const_cast<const node_t *>(to_insert)));
rassert(!left_is_higher_priority(to_insert, to_remove));
DEBUG_ONLY_CODE(node_queue(to_insert) = this);
node_index(to_insert) = node_index(to_remove);
nodes[node_index(to_remove)] = to_insert;
DEBUG_ONLY_CODE(node_queue(to_remove) = NULL);
}
private:
static size_t& node_index(node_t *x) {
intrusive_priority_queue_node_t<node_t> *node = x;
return node->index;
}
static intrusive_priority_queue_t<node_t> *& node_queue(node_t *x) {
intrusive_priority_queue_node_t<node_t> *node = x;
return node->queue;
}
static size_t parent_index(size_t index) {
rassert(index != 0);
return (index + (index % 2) - 2) / 2;
}
static size_t left_child_index(size_t index) {
return index * 2 + 1;
}
static size_t right_child_index(size_t index) {
return index * 2 + 2;
}
void swap_nodes(size_t i, size_t j) {
node_index(nodes[i]) = j;
node_index(nodes[j]) = i;
std::swap(nodes[i], nodes[j]);
}
void bubble_towards_root(node_t *node) {
while (node_index(node) != 0 &&
left_is_higher_priority(node, nodes[parent_index(node_index(node))])) {
swap_nodes(node_index(node), parent_index(node_index(node)));
}
}
void bubble_towards_leaves(node_t *node) {
while (true) {
const size_t left_index = left_child_index(node_index(node));
const size_t right_index = right_child_index(node_index(node));
size_t winner = node_index(node);
if (left_index < nodes.size() &&
left_is_higher_priority(nodes[left_index], nodes[winner])) {
winner = left_index;
}
if (right_index < nodes.size() &&
left_is_higher_priority(nodes[right_index], nodes[winner])) {
winner = right_index;
}
if (winner == node->index) {
break;
} else {
swap_nodes(winner, node->index);
}
}
}
// TODO: Vectors are O(n).
std::vector<node_t *> nodes;
DISABLE_COPYING(intrusive_priority_queue_t);
};
#endif // CONTAINERS_INTRUSIVE_PRIORITY_QUEUE_HPP_
| 27.948187 | 120 | 0.591212 | [
"vector"
] |
4a38f49dda03af2f9fe61f6e1fd67fb7d06e056a | 1,270 | cpp | C++ | bubble_th.cpp | NashL/SortingAlgorithms | 9e84b1c887afbabb454a39ebcad796d69c5d5b69 | [
"Unlicense"
] | null | null | null | bubble_th.cpp | NashL/SortingAlgorithms | 9e84b1c887afbabb454a39ebcad796d69c5d5b69 | [
"Unlicense"
] | null | null | null | bubble_th.cpp | NashL/SortingAlgorithms | 9e84b1c887afbabb454a39ebcad796d69c5d5b69 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <thread>
using namespace std;
int NN = 100000;
int n_threads;
int RandomNumber () { return (rand()%NN); }
void imprimir(vector<int> a){
cout << "[ ";
ostream_iterator<int> out_it (cout, " ");
copy(a.begin(),a.end(), out_it );
cout << "]\n";
}
void bubble_sort_ini(int* a , int n){
int st = n>>1;
for(int i=1; i<st ; i++){
for(int j=0; j<n-i ; j++){
//cout << "j = " << j << endl;
if(a[j] > a[j+1])
swap(a[j],a[j+1]);
}
}
}
void bubble_sort_end(int* a , int n){
int st= n>>1;
for(int i=1; i<st ; i++){
for(int j = n-1; j>=i; j--){
//cout << "j = " << j << endl;
if(a[j] < a[j-1])
swap(a[j],a[j-1]);
}
}
}
void launch_threads(int *a,int n){
thread t1( bubble_sort_ini, a, n);
thread t2( bubble_sort_end, a, n);
t1.join();
t2.join();
}
int main(){
srand(time(NULL));
vector<int> a(NN);
generate(a.begin(),a.end(), RandomNumber); // Gen va
launch_threads(&a[0],NN);
//bubble_sort(&a[0],n);
// thread th1(bubbles_threads,&a[0],n);
// thread th2(bubbles_threads,&a[0],n);
// th1.join();
// th2.join();
// imprimir(a);
}
| 19.242424 | 54 | 0.523622 | [
"vector"
] |
66589e933db85902fb8f51b9934adc10ffd39d76 | 2,861 | cpp | C++ | nesloader/src/nesloader.cpp | Granahir2/Nematod | 795aca41770c4fc1247f5170ca1a3a0ab6439363 | [
"MIT"
] | null | null | null | nesloader/src/nesloader.cpp | Granahir2/Nematod | 795aca41770c4fc1247f5170ca1a3a0ab6439363 | [
"MIT"
] | null | null | null | nesloader/src/nesloader.cpp | Granahir2/Nematod | 795aca41770c4fc1247f5170ca1a3a0ab6439363 | [
"MIT"
] | null | null | null | /*
nesloader.cpp
Copyright (c) 17 Yann BOUCHER (yann)
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 "nesloader.hpp"
#include <cstring>
#include <cassert>
#include <fstream>
void report_error(const std::string& str)
{
throw cartdrige_loader_error(str.c_str());
}
bool is_nes_file(const std::vector<uint8_t> &file_data)
{
if (file_data.size() < 16) return false;
return memcmp(file_data.data(), "NES\x1A", 4) == 0;
}
cartdrige_data load_nes_file(const std::vector<uint8_t> &file_data)
{
assert(is_nes_file(file_data));
cartdrige_data cart;
cart.prg_rom.resize(file_data[4] * 0x4000);
cart.chr_rom.resize(file_data[5] * 0x2000);
cart.mapper = (file_data[6] >> 4) | (file_data[7] & 0xF0);
if (file_data[6] & (1<<3))
cart.mirroring = cartdrige_data::MirroringType::FourScreen;
else
cart.mirroring = (file_data[6] & 0b1) ? cartdrige_data::Vertical
: cartdrige_data::Horizontal;
if (file_data.size() < 16 + cart.prg_rom.size() + cart.chr_rom.size())
report_error("invalid iNES file");
if (file_data[6] & (1<<2))
report_error("trainers are unsupported");
memcpy(cart.prg_rom.data(), file_data.data() + 16 , cart.prg_rom.size());
if (!cart.chr_rom.empty())
memcpy(cart.chr_rom.data(), file_data.data() + 16 + cart.prg_rom.size(), cart.chr_rom.size());
return cart;
}
cartdrige_data load_nes_file(const std::string &filename)
{
std::ifstream file(filename);
if (!file)
report_error("cannot load file '" + filename + "'");
file.seekg(0, std::ios::end );
size_t size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> data(size);
if (!file.read((char*)data.data(), size))
report_error("cannot load file '" + filename + "'");
return load_nes_file(data);
}
| 32.511364 | 102 | 0.693813 | [
"vector"
] |
665e2fc3197e120d0776db2e886cc4a1ea8609be | 1,262 | cc | C++ | MyWPdfRenderer.cc | RekGRpth/pg_html2pdf | dc68969a4821945d7743cd4ab4b93258dd365251 | [
"MIT"
] | 1 | 2019-07-30T08:39:33.000Z | 2019-07-30T08:39:33.000Z | MyWPdfRenderer.cc | RekGRpth/pg_wthtmltopdf | dc68969a4821945d7743cd4ab4b93258dd365251 | [
"MIT"
] | null | null | null | MyWPdfRenderer.cc | RekGRpth/pg_wthtmltopdf | dc68969a4821945d7743cd4ab4b93258dd365251 | [
"MIT"
] | null | null | null | #include <Wt/Render/WPdfRenderer.h>
#include "MyWPdfRenderer.h"
namespace Wt { namespace rapidxml {
class parse_error: public std::exception {
public:
parse_error(const char *what, void *location) : m_what(what), m_where(location) { }
virtual const char *what() const throw() {
return m_what;
}
template<class Ch> Ch *where() const {
return reinterpret_cast<Ch *>(m_where);
}
private:
const char *m_what;
void *m_where;
};
}}
extern "C" {
bool MyWPdfRenderer_render(MyWPdfRenderer_error error, HPDF_Doc pdf, HPDF_Page page, const char *html) {
try {
Wt::Render::WPdfRenderer renderer(pdf, page);
renderer.setMargin(1.0);
renderer.setDpi(96);
renderer.render(html);
return true;
} catch (const Wt::rapidxml::parse_error &e) {
char msg[200];
snprintf(msg, 200, "wt exception: what = %s, where = %s", e.what(), e.where<char>());
error(msg);
} catch (const std::exception &e) {
char msg[200];
snprintf(msg, 200, "wt exception: what = %s", e.what());
error(msg);
} catch (...) {
error("wt exception");
}
return false;
}
} | 30.780488 | 108 | 0.567353 | [
"render"
] |
6662af870c21959f9c92d8e3b71e93e5aaa4b469 | 1,390 | cpp | C++ | libcaf_core/test/async/blocking_for_each.cpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | libcaf_core/test/async/blocking_for_each.cpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | libcaf_core/test/async/blocking_for_each.cpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#define CAF_SUITE async.blocking_for_each
#include "caf/async/publisher.hpp"
#include "core-test.hpp"
#include "caf/flow/coordinator.hpp"
#include "caf/flow/observable.hpp"
#include "caf/flow/observable_builder.hpp"
#include "caf/flow/observer.hpp"
#include "caf/scheduled_actor/flow.hpp"
using namespace caf;
namespace {
struct fixture {
actor_system_config cfg;
actor_system sys;
fixture() : sys(cfg.set("caf.scheduler.max-threads", 2)) {
// nop
}
};
using ctx_impl = event_based_actor;
} // namespace
BEGIN_FIXTURE_SCOPE(fixture)
SCENARIO("blocking_for_each iterates all values in a stream") {
GIVEN("an asynchronous source") {
WHEN("subscribing to its output via blocking_for_each") {
THEN("the observer blocks until it has received all values") {
auto inputs = std::vector<int>(2539, 42);
auto outputs = std::vector<int>{};
async::publisher_from<ctx_impl>(sys, [](auto* self) {
return self->make_observable().repeat(42).take(2539);
}).blocking_for_each([&outputs](int x) { outputs.emplace_back(x); });
CHECK_EQ(inputs, outputs);
}
}
}
}
END_FIXTURE_SCOPE()
| 26.730769 | 77 | 0.701439 | [
"vector"
] |
666e1d4b84ca5213b642ce43b399bcd58faa09fe | 7,703 | cpp | C++ | thirdparty/ULib/src/ulib/utility/semaphore.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/utility/semaphore.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/utility/semaphore.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | // ============================================================================
//
// = LIBRARY
// ULib - c++ library
//
// = FILENAME
// semaphore.cpp
//
// = AUTHOR
// Stefano Casazza
//
// ============================================================================
#include <ulib/file.h>
#include <ulib/timeval.h>
#include <ulib/utility/interrupt.h>
#include <ulib/utility/semaphore.h>
#ifdef U_LINUX
U_DUMP_KERNEL_VERSION(LINUX_VERSION_CODE)
#endif
USemaphore* USemaphore::first;
/**
* The initial value of the semaphore can be specified. An initial value is often used when used to lock a finite
* resource or to specify the maximum number of thread instances that can access a specified resource.
*
* @param resource specify initial resource count or 1 default
*/
void USemaphore::init(sem_t* ptr, int resource)
{
U_TRACE(1, "USemaphore::init(%p,%d)", ptr, resource)
U_INTERNAL_ASSERT_EQUALS(psem, 0)
#if defined(__MACOSX__) || defined(__APPLE__)
(void) u__snprintf(name, sizeof(name), U_CONSTANT_TO_PARAM("/sem%X"), ptr);
psem = (sem_t*) U_SYSCALL(sem_open, "%S,%d,%d,%u", name, O_CREAT, 0644, 1);
if (psem == SEM_FAILED)
{
U_ERROR_SYSCALL("USemaphore::init() failed");
}
#elif defined(HAVE_SEM_INIT) && (!defined(U_LINUX) || LINUX_VERSION_CODE > KERNEL_VERSION(2,6,7))
U_INTERNAL_ASSERT_POINTER(ptr)
// initialize semaphore object sem to value, share it with other processes
if (U_SYSCALL(sem_init, "%p,%d,%u", psem = ptr, 1, resource) == -1) // 1 -> semaphore is shared between processes
{
U_ERROR("USemaphore::init(%p,%u) failed", ptr, resource);
}
#elif defined(_MSWINDOWS_)
psem = (sem_t*) ::CreateSemaphore((LPSECURITY_ATTRIBUTES)NULL, (LONG)resource, 1000000, (LPCTSTR)NULL);
#else
psem = UFile::mkTemp();
if (psem == -1) U_ERROR("USemaphore::init(%p,%u) failed", ptr, resource);
#endif
#if !defined(__MACOSX__) && !defined(__APPLE__) && defined(HAVE_SEM_GETVALUE)
next = first;
first = this;
# ifdef DEBUG
U_INTERNAL_DUMP("first = %p next = %p", first, next)
U_INTERNAL_ASSERT_DIFFERS(first, next)
int _value = getValue();
if (_value != resource) U_ERROR("USemaphore::init(%p,%u) failed - value = %d", ptr, resource, _value);
# endif
#endif
}
/**
* Destroying a semaphore also removes any system resources associated with it. If a semaphore has threads currently
* waiting on it, those threads will all continue when a semaphore is destroyed
*/
USemaphore::~USemaphore()
{
U_TRACE_UNREGISTER_OBJECT(0, USemaphore)
U_INTERNAL_ASSERT_POINTER(psem)
#if defined(__MACOSX__) || defined(__APPLE__)
(void) U_SYSCALL(sem_close, "%p", psem);
(void) U_SYSCALL(sem_unlink, "%S", name);
#elif defined(HAVE_SEM_INIT) && (!defined(U_LINUX) || LINUX_VERSION_CODE > KERNEL_VERSION(2,6,7))
(void) sem_destroy(psem); // Free resources associated with semaphore object sem
#elif defined(_MSWINDOWS_)
(void) ::CloseHandle((HANDLE)psem);
#else
UFile::close(psem);
#endif
}
/**
* Posting to a semaphore increments its current value and releases the first thread waiting for the semaphore
* if it is currently at 0. Interestingly, there is no support to increment a semaphore by any value greater than 1
* to release multiple waiting threads in either pthread or the win32 API. Hence, if one wants to release
* a semaphore to enable multiple threads to execute, one must perform multiple post operations
*/
void USemaphore::post()
{
U_TRACE_NO_PARAM(1, "USemaphore::post()")
U_INTERNAL_ASSERT_POINTER(psem)
U_INTERNAL_DUMP("value = %d", getValue())
#if defined(__MACOSX__) || defined(__APPLE__)
(void) U_SYSCALL(sem_post, "%p", psem); // unlock a semaphore
#elif defined(HAVE_SEM_INIT) && (!defined(U_LINUX) || LINUX_VERSION_CODE > KERNEL_VERSION(2,6,7))
(void) U_SYSCALL(sem_post, "%p", psem); // unlock a semaphore
#elif defined(_MSWINDOWS_)
::ReleaseSemaphore((HANDLE)psem, 1, (LPLONG)NULL);
#else
(void) UFile::unlock(psem);
#endif
U_INTERNAL_DUMP("value = %d", getValue())
}
// NB: check if process has restarted and it had a lock armed (DEADLOCK)...
bool USemaphore::checkForDeadLock(UTimeVal& time)
{
U_TRACE(1, "USemaphore::checkForDeadLock(%p)", &time)
#if !defined(__MACOSX__) && !defined(__APPLE__) && defined(HAVE_SEM_GETVALUE)
bool sleeped = false;
for (USemaphore* item = first; item; item = item->next)
{
if (item->getValue() <= 0)
{
sleeped = true;
time.nanosleep();
if (item->getValue() <= 0)
{
time.nanosleep();
if (item->getValue() <= 0) item->post(); // unlock the semaphore
}
}
}
U_RETURN(sleeped);
#else
U_RETURN(false);
#endif
}
/**
* Wait is used to keep a thread held until the semaphore counter is greater than 0. If the current thread is held, then
* another thread must increment the semaphore. Once the thread is accepted, the semaphore is automatically decremented,
* and the thread continues execution.
*
* @return false if timed out
* @param timeout period in milliseconds to wait
*/
bool USemaphore::wait(time_t timeoutMS)
{
U_TRACE(1, "USemaphore::wait(%ld)", timeoutMS) // problem with sanitize address
U_INTERNAL_ASSERT_POINTER(psem)
U_INTERNAL_ASSERT_MAJOR(timeoutMS, 0)
U_INTERNAL_DUMP("value = %d", getValue())
#if defined(__MACOSX__) || defined(__APPLE__) || \
(defined(HAVE_SEM_INIT) && (!defined(U_LINUX) || LINUX_VERSION_CODE > KERNEL_VERSION(2,6,7)))
// Wait for sem being posted
U_INTERNAL_ASSERT(u_now->tv_sec > 1260183779) // 07/12/2009
struct timespec abs_timeout = { u_now->tv_sec + timeoutMS / 1000L, 0 };
U_INTERNAL_DUMP("abs_timeout = { %d, %d }", abs_timeout.tv_sec, abs_timeout.tv_nsec)
int rc = U_SYSCALL(sem_timedwait, "%p,%p", psem, &abs_timeout);
U_INTERNAL_DUMP("value = %d", getValue())
if (rc == 0) U_RETURN(true);
#elif defined(_MSWINDOWS_)
if (::WaitForSingleObject((HANDLE)psem, timeoutMS) == WAIT_OBJECT_0) U_RETURN(true);
#else
if (UFile::lock(psem)) U_RETURN(true);
#endif
U_RETURN(false);
}
void USemaphore::lock()
{
U_TRACE_NO_PARAM(1, "USemaphore::lock()")
U_INTERNAL_ASSERT_POINTER(psem)
U_INTERNAL_DUMP("value = %d", getValue())
#if defined(__MACOSX__) || defined(__APPLE__)
(void) U_SYSCALL(sem_wait, "%p", psem);
#elif defined(HAVE_SEM_INIT) && (!defined(U_LINUX) || LINUX_VERSION_CODE > KERNEL_VERSION(2,6,7))
/**
* sem_wait() decrements (locks) the semaphore pointed to by sem. If the semaphore's value is greater than zero,
* then the decrement proceeds, and the function returns, immediately. * If the semaphore currently has the value
* zero, then the call blocks until either it becomes possible to perform the decrement (i.e., the semaphore value
* rises above zero), or a * signal handler interrupts the call
*/
wait:
int rc = U_SYSCALL(sem_wait, "%p", psem);
if (rc == -1)
{
U_INTERNAL_DUMP("errno = %d", errno)
if (errno == EINTR)
{
UInterrupt::checkForEventSignalPending();
goto wait;
}
}
U_INTERNAL_ASSERT_EQUALS(rc, 0)
#elif defined(_MSWINDOWS_)
(void) ::WaitForSingleObject((HANDLE)psem, INFINITE);
#else
(void) UFile::lock(psem);
#endif
U_INTERNAL_DUMP("value = %d", getValue())
}
// DEBUG
#if defined(U_STDCPP_ENABLE) && defined(DEBUG)
const char* USemaphore::dump(bool reset) const
{
*UObjectIO::os << "next " << (void*)next << '\n'
<< "psem " << (void*)psem;
if (reset)
{
UObjectIO::output();
return UObjectIO::buffer_output;
}
return 0;
}
#endif
| 28.850187 | 120 | 0.66156 | [
"object"
] |
6675c22c3321a7dc5a3afcdb602a64d7f1676fd5 | 19,115 | cpp | C++ | src/qt/src/3rdparty/webkit/Source/WebCore/inspector/InspectorPageAgent.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 46 | 2015-01-08T14:32:34.000Z | 2022-02-05T16:48:26.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/inspector/InspectorPageAgent.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 7 | 2015-01-20T14:28:12.000Z | 2017-01-18T17:21:44.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/inspector/InspectorPageAgent.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 14 | 2015-10-27T06:17:48.000Z | 2020-03-03T06:15:50.000Z | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "InspectorPageAgent.h"
#if ENABLE(INSPECTOR)
#include "Base64.h"
#include "CachedCSSStyleSheet.h"
#include "CachedResource.h"
#include "CachedResourceLoader.h"
#include "CachedScript.h"
#include "Cookie.h"
#include "CookieJar.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "Frame.h"
#include "FrameLoadRequest.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLNames.h"
#include "InjectedScriptManager.h"
#include "InspectorFrontend.h"
#include "InspectorValues.h"
#include "InstrumentingAgents.h"
#include "MemoryCache.h"
#include "Page.h"
#include "ScriptObject.h"
#include "SharedBuffer.h"
#include "TextEncoding.h"
#include "UserGestureIndicator.h"
#include "WindowFeatures.h"
#include <wtf/CurrentTime.h>
#include <wtf/ListHashSet.h>
namespace WebCore {
static bool decodeSharedBuffer(PassRefPtr<SharedBuffer> buffer, const String& textEncodingName, String* result)
{
if (buffer) {
TextEncoding encoding(textEncodingName);
if (!encoding.isValid())
encoding = WindowsLatin1Encoding();
*result = encoding.decode(buffer->data(), buffer->size());
return true;
}
return false;
}
static bool prepareCachedResourceBuffer(CachedResource* cachedResource, bool* hasZeroSize)
{
*hasZeroSize = false;
if (!cachedResource)
return false;
// Zero-sized resources don't have data at all -- so fake the empty buffer, instead of indicating error by returning 0.
if (!cachedResource->encodedSize()) {
*hasZeroSize = true;
return true;
}
if (cachedResource->isPurgeable()) {
// If the resource is purgeable then make it unpurgeable to get
// get its data. This might fail, in which case we return an
// empty String.
// FIXME: should we do something else in the case of a purged
// resource that informs the user why there is no data in the
// inspector?
if (!cachedResource->makePurgeable(false))
return false;
}
return true;
}
static bool decodeCachedResource(CachedResource* cachedResource, String* result)
{
bool hasZeroSize;
bool prepared = prepareCachedResourceBuffer(cachedResource, &hasZeroSize);
if (!prepared)
return false;
if (cachedResource) {
switch (cachedResource->type()) {
case CachedResource::CSSStyleSheet:
*result = static_cast<CachedCSSStyleSheet*>(cachedResource)->sheetText();
return true;
case CachedResource::Script:
*result = static_cast<CachedScript*>(cachedResource)->script();
return true;
default:
if (hasZeroSize) {
*result = "";
return true;
}
return decodeSharedBuffer(cachedResource->data(), cachedResource->encoding(), result);
}
}
return false;
}
PassOwnPtr<InspectorPageAgent> InspectorPageAgent::create(InstrumentingAgents* instrumentingAgents, Page* page, InjectedScriptManager* injectedScriptManager)
{
return adoptPtr(new InspectorPageAgent(instrumentingAgents, page, injectedScriptManager));
}
void InspectorPageAgent::resourceContent(ErrorString* errorString, Frame* frame, const KURL& url, String* result)
{
if (!frame) {
*errorString = "No frame to get resource content for";
return;
}
FrameLoader* frameLoader = frame->loader();
DocumentLoader* loader = frameLoader->documentLoader();
RefPtr<SharedBuffer> buffer;
bool success = false;
if (equalIgnoringFragmentIdentifier(url, loader->url())) {
String textEncodingName = frame->document()->inputEncoding();
buffer = frameLoader->documentLoader()->mainResourceData();
success = decodeSharedBuffer(buffer, textEncodingName, result);
}
if (!success)
success = decodeCachedResource(cachedResource(frame, url), result);
if (!success)
*errorString = "No resource with given URL found";
}
void InspectorPageAgent::resourceContentBase64(ErrorString* errorString, Frame* frame, const KURL& url, String* result)
{
String textEncodingName;
RefPtr<SharedBuffer> data = InspectorPageAgent::resourceData(frame, url, &textEncodingName);
if (!data) {
*result = String();
*errorString = "No resource with given URL found";
return;
}
*result = base64Encode(data->data(), data->size());
}
PassRefPtr<SharedBuffer> InspectorPageAgent::resourceData(Frame* frame, const KURL& url, String* textEncodingName)
{
RefPtr<SharedBuffer> buffer;
FrameLoader* frameLoader = frame->loader();
DocumentLoader* loader = frameLoader->documentLoader();
if (equalIgnoringFragmentIdentifier(url, loader->url())) {
*textEncodingName = frame->document()->inputEncoding();
buffer = frameLoader->documentLoader()->mainResourceData();
if (buffer)
return buffer;
}
CachedResource* cachedResource = InspectorPageAgent::cachedResource(frame, url);
if (!cachedResource)
return 0;
bool hasZeroSize;
bool prepared = prepareCachedResourceBuffer(cachedResource, &hasZeroSize);
if (!prepared)
return 0;
*textEncodingName = cachedResource->encoding();
return hasZeroSize ? SharedBuffer::create() : cachedResource->data();
}
CachedResource* InspectorPageAgent::cachedResource(Frame* frame, const KURL& url)
{
CachedResource* cachedResource = frame->document()->cachedResourceLoader()->cachedResource(url);
if (!cachedResource)
cachedResource = memoryCache()->resourceForURL(url);
return cachedResource;
}
String InspectorPageAgent::resourceTypeString(InspectorPageAgent::ResourceType resourceType)
{
switch (resourceType) {
case DocumentResource:
return "Document";
case ImageResource:
return "Image";
case FontResource:
return "Font";
case StylesheetResource:
return "Stylesheet";
case ScriptResource:
return "Script";
case XHRResource:
return "XHR";
case WebSocketResource:
return "WebSocket";
case OtherResource:
return "Other";
}
return "Other";
}
InspectorPageAgent::ResourceType InspectorPageAgent::cachedResourceType(const CachedResource& cachedResource)
{
switch (cachedResource.type()) {
case CachedResource::ImageResource:
return InspectorPageAgent::ImageResource;
case CachedResource::FontResource:
return InspectorPageAgent::FontResource;
case CachedResource::CSSStyleSheet:
// Fall through.
#if ENABLE(XSLT)
case CachedResource::XSLStyleSheet:
#endif
return InspectorPageAgent::StylesheetResource;
case CachedResource::Script:
return InspectorPageAgent::ScriptResource;
default:
break;
}
return InspectorPageAgent::OtherResource;
}
String InspectorPageAgent::cachedResourceTypeString(const CachedResource& cachedResource)
{
return resourceTypeString(cachedResourceType(cachedResource));
}
InspectorPageAgent::InspectorPageAgent(InstrumentingAgents* instrumentingAgents, Page* page, InjectedScriptManager* injectedScriptManager)
: m_instrumentingAgents(instrumentingAgents)
, m_page(page)
, m_injectedScriptManager(injectedScriptManager)
, m_frontend(0)
{
}
void InspectorPageAgent::setFrontend(InspectorFrontend* frontend)
{
m_frontend = frontend->page();
m_instrumentingAgents->setInspectorPageAgent(this);
}
void InspectorPageAgent::clearFrontend()
{
m_instrumentingAgents->setInspectorPageAgent(0);
m_frontend = 0;
}
void InspectorPageAgent::addScriptToEvaluateOnLoad(ErrorString*, const String& source)
{
m_scriptsToEvaluateOnLoad.append(source);
}
void InspectorPageAgent::removeAllScriptsToEvaluateOnLoad(ErrorString*)
{
m_scriptsToEvaluateOnLoad.clear();
}
void InspectorPageAgent::reload(ErrorString*, const bool* const optionalIgnoreCache)
{
m_page->mainFrame()->loader()->reload(optionalIgnoreCache ? *optionalIgnoreCache : false);
}
void InspectorPageAgent::open(ErrorString*, const String& url, const bool* const inNewWindow)
{
Frame* mainFrame = m_page->mainFrame();
Frame* frame;
if (inNewWindow && *inNewWindow) {
FrameLoadRequest request(mainFrame->document()->securityOrigin(), ResourceRequest(), "_blank");
bool created;
WindowFeatures windowFeatures;
frame = WebCore::createWindow(mainFrame, mainFrame, request, windowFeatures, created);
if (!frame)
return;
frame->loader()->setOpener(mainFrame);
frame->page()->setOpenedByDOM();
} else
frame = mainFrame;
UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
frame->loader()->changeLocation(mainFrame->document()->securityOrigin(), frame->loader()->completeURL(url), "", false, false);
}
static PassRefPtr<InspectorObject> buildObjectForCookie(const Cookie& cookie)
{
RefPtr<InspectorObject> value = InspectorObject::create();
value->setString("name", cookie.name);
value->setString("value", cookie.value);
value->setString("domain", cookie.domain);
value->setString("path", cookie.path);
value->setNumber("expires", cookie.expires);
value->setNumber("size", (cookie.name.length() + cookie.value.length()));
value->setBoolean("httpOnly", cookie.httpOnly);
value->setBoolean("secure", cookie.secure);
value->setBoolean("session", cookie.session);
return value;
}
static PassRefPtr<InspectorArray> buildArrayForCookies(ListHashSet<Cookie>& cookiesList)
{
RefPtr<InspectorArray> cookies = InspectorArray::create();
ListHashSet<Cookie>::iterator end = cookiesList.end();
ListHashSet<Cookie>::iterator it = cookiesList.begin();
for (int i = 0; it != end; ++it, i++)
cookies->pushObject(buildObjectForCookie(*it));
return cookies;
}
void InspectorPageAgent::getCookies(ErrorString*, RefPtr<InspectorArray>* cookies, WTF::String* cookiesString)
{
// If we can get raw cookies.
ListHashSet<Cookie> rawCookiesList;
// If we can't get raw cookies - fall back to String representation
String stringCookiesList;
// Return value to getRawCookies should be the same for every call because
// the return value is platform/network backend specific, and the call will
// always return the same true/false value.
bool rawCookiesImplemented = false;
for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext(mainFrame())) {
Document* document = frame->document();
const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it) {
Vector<Cookie> docCookiesList;
rawCookiesImplemented = getRawCookies(document, KURL(ParsedURLString, it->second->url()), docCookiesList);
if (!rawCookiesImplemented) {
// FIXME: We need duplication checking for the String representation of cookies.
ExceptionCode ec = 0;
stringCookiesList += document->cookie(ec);
// Exceptions are thrown by cookie() in sandboxed frames. That won't happen here
// because "document" is the document of the main frame of the page.
ASSERT(!ec);
} else {
int cookiesSize = docCookiesList.size();
for (int i = 0; i < cookiesSize; i++) {
if (!rawCookiesList.contains(docCookiesList[i]))
rawCookiesList.add(docCookiesList[i]);
}
}
}
}
if (rawCookiesImplemented)
*cookies = buildArrayForCookies(rawCookiesList);
else
*cookiesString = stringCookiesList;
}
void InspectorPageAgent::deleteCookie(ErrorString*, const String& cookieName, const String& domain)
{
for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext(m_page->mainFrame())) {
Document* document = frame->document();
if (document->url().host() != domain)
continue;
const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it)
WebCore::deleteCookie(document, KURL(ParsedURLString, it->second->url()), cookieName);
}
}
void InspectorPageAgent::getResourceTree(ErrorString*, RefPtr<InspectorObject>* object)
{
*object = buildObjectForFrameTree(m_page->mainFrame());
}
void InspectorPageAgent::getResourceContent(ErrorString* errorString, const String& frameId, const String& url, const bool* const optionalBase64Encode, String* content)
{
Frame* frame = frameForId(frameId);
if (!frame) {
*errorString = "No frame for given id found";
return;
}
if (optionalBase64Encode ? *optionalBase64Encode : false)
InspectorPageAgent::resourceContentBase64(errorString, frame, KURL(ParsedURLString, url), content);
else
InspectorPageAgent::resourceContent(errorString, frame, KURL(ParsedURLString, url), content);
}
void InspectorPageAgent::domContentEventFired()
{
m_frontend->domContentEventFired(currentTime());
}
void InspectorPageAgent::loadEventFired()
{
m_frontend->loadEventFired(currentTime());
}
void InspectorPageAgent::frameNavigated(DocumentLoader* loader)
{
m_frontend->frameNavigated(buildObjectForFrame(loader->frame()), loaderId(loader));
}
void InspectorPageAgent::frameDetached(Frame* frame)
{
m_frontend->frameDetached(frameId(frame));
}
void InspectorPageAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world)
{
if (world != mainThreadNormalWorld())
return;
if (frame == m_page->mainFrame())
m_injectedScriptManager->discardInjectedScripts();
if (m_scriptsToEvaluateOnLoad.size()) {
ScriptState* scriptState = mainWorldScriptState(frame);
for (Vector<String>::iterator it = m_scriptsToEvaluateOnLoad.begin();
it != m_scriptsToEvaluateOnLoad.end(); ++it) {
m_injectedScriptManager->injectScript(*it, scriptState);
}
}
}
Frame* InspectorPageAgent::mainFrame()
{
return m_page->mainFrame();
}
static String pointerAsId(void* pointer)
{
unsigned long long address = reinterpret_cast<uintptr_t>(pointer);
// We want 0 to be "", so that JavaScript checks for if (frameId) worked.
return String::format("%.0llX", address);
}
Frame* InspectorPageAgent::frameForId(const String& frameId)
{
Frame* mainFrame = m_page->mainFrame();
for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext(mainFrame)) {
if (pointerAsId(frame) == frameId)
return frame;
}
return 0;
}
String InspectorPageAgent::frameId(Frame* frame)
{
return pointerAsId(frame);
}
String InspectorPageAgent::loaderId(DocumentLoader* loader)
{
return pointerAsId(loader);
}
PassRefPtr<InspectorObject> InspectorPageAgent::buildObjectForFrame(Frame* frame)
{
RefPtr<InspectorObject> frameObject = InspectorObject::create();
frameObject->setString("id", frameId(frame));
frameObject->setString("parentId", frameId(frame->tree()->parent()));
if (frame->ownerElement()) {
String name = frame->ownerElement()->getAttribute(HTMLNames::nameAttr);
if (name.isEmpty())
name = frame->ownerElement()->getAttribute(HTMLNames::idAttr);
frameObject->setString("name", name);
}
frameObject->setString("url", frame->document()->url().string());
frameObject->setString("loaderId", loaderId(frame->loader()->documentLoader()));
return frameObject;
}
PassRefPtr<InspectorObject> InspectorPageAgent::buildObjectForFrameTree(Frame* frame)
{
RefPtr<InspectorObject> result = InspectorObject::create();
RefPtr<InspectorObject> frameObject = buildObjectForFrame(frame);
result->setObject("frame", frameObject);
RefPtr<InspectorArray> subresources = InspectorArray::create();
result->setArray("resources", subresources);
const CachedResourceLoader::DocumentResourceMap& allResources = frame->document()->cachedResourceLoader()->allCachedResources();
CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it) {
CachedResource* cachedResource = it->second.get();
RefPtr<InspectorObject> resourceObject = InspectorObject::create();
resourceObject->setString("url", cachedResource->url());
resourceObject->setString("type", cachedResourceTypeString(*cachedResource));
subresources->pushValue(resourceObject);
}
RefPtr<InspectorArray> childrenArray;
for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
if (!childrenArray) {
childrenArray = InspectorArray::create();
result->setArray("childFrames", childrenArray);
}
childrenArray->pushObject(buildObjectForFrameTree(child));
}
return result;
}
} // namespace WebCore
#endif // ENABLE(INSPECTOR)
| 35.998117 | 168 | 0.702014 | [
"object",
"vector"
] |
667acf1f1cc368bbee065fadc1c3e7cbaef92b01 | 15,103 | cxx | C++ | ds/security/azroles/scope.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/azroles/scope.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/azroles/scope.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 2001 Microsoft Corporation
Module Name:
scope.cxx
Abstract:
Routines implementing the Scope object
Author:
Cliff Van Dyke (cliffv) 11-Apr-2001
--*/
#include "pch.hxx"
DWORD
AzpScopeInit(
IN PGENERIC_OBJECT ParentGenericObject,
IN PGENERIC_OBJECT ChildGenericObject
)
/*++
Routine Description:
This routine is a worker routine for AzScopeCreate. It does any object specific
initialization that needs to be done.
On entry, AzGlResource must be locked exclusively.
Arguments:
ParentGenericObject - Specifies the parent object to add the child object onto.
The reference count has been incremented on this object.
ChildGenericObject - Specifies the newly allocated child object.
The reference count has been incremented on this object.
Return Value:
NO_ERROR - The operation was successful
ERROR_NOT_ENOUGH_MEMORY - not enough memory
Other exception status codes
--*/
{
DWORD WinStatus = NO_ERROR;
PAZP_SCOPE Scope = (PAZP_SCOPE) ChildGenericObject;
//
// Initialization
//
ASSERT( AzpIsLockedExclusive( &AzGlResource ) );
//
// Sanity check the parent
//
ASSERT( ParentGenericObject->ObjectType == OBJECT_TYPE_APPLICATION );
UNREFERENCED_PARAMETER( ParentGenericObject );
//
// Initialize the lists of child objects
// Let the generic object manager know all of the types of children we support
//
ChildGenericObject->ChildGenericObjectHead = &Scope->Tasks;
// List of child Tasks
ObInitGenericHead( &Scope->Tasks,
OBJECT_TYPE_TASK,
ChildGenericObject,
&Scope->Groups );
// List of child groups
ObInitGenericHead( &Scope->Groups,
OBJECT_TYPE_GROUP,
ChildGenericObject,
&Scope->Roles );
// List of child roles
ObInitGenericHead( &Scope->Roles,
OBJECT_TYPE_ROLE,
ChildGenericObject,
&ChildGenericObject->AzpSids );
// List of child AzpSids
ObInitGenericHead( &ChildGenericObject->AzpSids,
OBJECT_TYPE_SID,
ChildGenericObject,
NULL );
//
// If the parent application object's parent AzAuthorizationStore object supports delegation,
// then the scope object supports the following options:
// . AZPE_OPTIONS_SUPPORTS_DACL
// . AZPE_OPTIONS_SUPPORTS_SACL
//
if ( CHECK_DELEGATION_SUPPORT( (PGENERIC_OBJECT) ParentGenericObject->AzStoreObject ) ==
NO_ERROR ) {
ChildGenericObject->IsAclSupported = TRUE;
ChildGenericObject->IsSACLSupported = TRUE;
}
//
// If the provider does not support Lazy load, set the AreChildrenLoaded to
// TRUE. Else leave it as FALSE. This will be set to true during the call
// to AzPersistUpdateChildrenCache
//
if ( !(ParentGenericObject->AzStoreObject)->ChildLazyLoadSupported ) {
ChildGenericObject->AreChildrenLoaded = TRUE;
} else {
ChildGenericObject->AreChildrenLoaded = FALSE;
}
return WinStatus;
}
VOID
AzpScopeFree(
IN PGENERIC_OBJECT GenericObject
)
/*++
Routine Description:
This routine is a worker routine for Scope object free. It does any object specific
cleanup that needs to be done.
On entry, AzGlResource must be locked exclusively.
Arguments:
GenericObject - Specifies a pointer to the object to be deleted.
Return Value:
None
--*/
{
// PAZP_SCOPE Scope = (PAZP_SCOPE) GenericObject;
UNREFERENCED_PARAMETER( GenericObject );
//
// Initialization
//
ASSERT( AzpIsLockedExclusive( &AzGlResource ) );
//
// Free any local strings
//
}
DWORD
WINAPI
AzScopeCreate(
IN AZ_HANDLE ApplicationHandle,
IN LPCWSTR ScopeName,
IN DWORD Reserved,
OUT PAZ_HANDLE ScopeHandle
)
/*++
Routine Description:
This routine adds a scope into the scope of the specified application. It also sets
Scope object specific optional characteristics using the parent Application object's
parent AzAuthorizationStore object.
Arguments:
ApplicationHandle - Specifies a handle to the application.
ScopeName - Specifies the name of the scope to add.
Reserved - Reserved. Must by zero.
ScopeHandle - Return a handle to the scope.
The caller must close this handle by calling AzCloseHandle.
Return Value:
NO_ERROR - The operation was successful
ERROR_ALREADY_EXISTS - An object by that name already exists
--*/
{
//
// Call the common routine to do most of the work
//
return ObCommonCreateObject(
(PGENERIC_OBJECT) ApplicationHandle,
OBJECT_TYPE_APPLICATION,
&(((PAZP_APPLICATION)ApplicationHandle)->Scopes),
OBJECT_TYPE_SCOPE,
ScopeName,
Reserved,
(PGENERIC_OBJECT *) ScopeHandle );
}
DWORD
WINAPI
AzScopeOpen(
IN AZ_HANDLE ApplicationHandle,
IN LPCWSTR ScopeName,
IN DWORD Reserved,
OUT PAZ_HANDLE ScopeHandle
)
/*++
Routine Description:
This routine opens a scope into the scope of the specified application.
Arguments:
ApplicationHandle - Specifies a handle to the application.
ScopeName - Specifies the name of the scope to open
Reserved - Reserved. Must by zero.
ScopeHandle - Return a handle to the scope.
The caller must close this handle by calling AzCloseHandle.
Return Value:
NO_ERROR - The operation was successful
ERROR_NOT_FOUND - There is no scope by that name
--*/
{
DWORD WinStatus = 0;
//
// Call the common routine to do most of the work
//
WinStatus = ObCommonOpenObject(
(PGENERIC_OBJECT) ApplicationHandle,
OBJECT_TYPE_APPLICATION,
&(((PAZP_APPLICATION)ApplicationHandle)->Scopes),
OBJECT_TYPE_SCOPE,
ScopeName,
Reserved,
(PGENERIC_OBJECT *) ScopeHandle );
if ( WinStatus == NO_ERROR ) {
//
// Load the children if the Scope object has already been submitted to
// the store
//
if ( !((PGENERIC_OBJECT) *ScopeHandle)->AreChildrenLoaded ) {
//
// Grab the global resource lock
//
AzpLockResourceExclusive( &AzGlResource );
WinStatus = AzPersistUpdateChildrenCache(
(PGENERIC_OBJECT) *ScopeHandle
);
AzpUnlockResource( &AzGlResource );
if ( WinStatus != NO_ERROR ) {
//
// Derefence the scope handle and return nothing to the caller
//
AzCloseHandle( (PGENERIC_OBJECT)*ScopeHandle, 0 );
*ScopeHandle = NULL;
}
}
}
return WinStatus;
}
DWORD
WINAPI
AzScopeEnum(
IN AZ_HANDLE ApplicationHandle,
IN DWORD Reserved,
IN OUT PULONG EnumerationContext,
OUT PAZ_HANDLE ScopeHandle
)
/*++
Routine Description:
Enumerates all of the scopes for the specified application.
Arguments:
ApplicationHandle - Specifies a handle to the application.
Reserved - Reserved. Must by zero.
EnumerationContext - Specifies a context indicating the next scope to return
On input for the first call, should point to zero.
On input for subsequent calls, should point to the value returned on the previous call.
On output, returns a value to be passed on the next call.
ScopeHandle - Returns a handle to the next scope object.
The caller must close this handle by calling AzCloseHandle.
Return Value:
NO_ERROR - The operation was successful (a handle was returned)
ERROR_NO_MORE_ITEMS - No more items were available for enumeration
--*/
{
//
// Call the common routine to do most of the work
//
return ObCommonEnumObjects(
(PGENERIC_OBJECT) ApplicationHandle,
OBJECT_TYPE_APPLICATION,
&(((PAZP_APPLICATION)ApplicationHandle)->Scopes),
EnumerationContext,
Reserved,
(PGENERIC_OBJECT *) ScopeHandle );
}
DWORD
WINAPI
AzScopeDelete(
IN AZ_HANDLE ApplicationHandle,
IN LPCWSTR ScopeName,
IN DWORD Reserved
)
/*++
Routine Description:
This routine deletes a scope from the scope of the specified application.
Also deletes any child objects of ScopeName.
Arguments:
ApplicationHandle - Specifies a handle to the application.
ScopeName - Specifies the name of the scope to delete.
Reserved - Reserved. Must by zero.
Return Value:
NO_ERROR - The operation was successful
ERROR_NOT_FOUND - An object by that name cannot be found
--*/
{
//
// Call the common routine to do most of the work
//
return ObCommonDeleteObject(
(PGENERIC_OBJECT) ApplicationHandle,
OBJECT_TYPE_APPLICATION,
&(((PAZP_APPLICATION)ApplicationHandle)->Scopes),
OBJECT_TYPE_SCOPE,
ScopeName,
Reserved );
}
DWORD
AzpScopeGetProperty(
IN PGENERIC_OBJECT GenericObject,
IN ULONG Flags,
IN ULONG PropertyId,
OUT PVOID *PropertyValue
)
/*++
Routine Description:
This routine is the Scope specific worker routine for AzGetProperty.
It does any object specific property gets.
On entry, AzGlResource must be locked shared.
Arguments:
GenericObject - Specifies a pointer to the object to be queried
Flags - ignored
PropertyId - Specifies which property to return.
PropertyValue - Specifies a pointer to return the property in.
The returned pointer must be freed using AzFreeMemory.
The returned value and type depends in PropertyId.
Return Value:
Status of the operation
--*/
{
DWORD WinStatus = NO_ERROR;
UNREFERENCED_PARAMETER(Flags); //ignore
*PropertyValue = NULL;
//
// Initialization
//
ASSERT( AzpIsLockedShared( &AzGlResource ) );
//
// Return any object specific attribute
//
switch ( PropertyId ) {
//
// if the scope can be deleted (already has bizrule defined)
//
case AZ_PROP_SCOPE_CAN_BE_DELEGATED:
if ( AzpScopeCanBeDelegated(GenericObject, TRUE) == ERROR_SUCCESS ) {
*PropertyValue = AzpGetUlongProperty( 1 );
} else {
*PropertyValue = AzpGetUlongProperty( 0 );
}
break;
//
// if bizrule attributes under the scope can be created/modified
//
case AZ_PROP_SCOPE_BIZRULES_WRITABLE:
if ( GenericObject->IsWritable &&
GenericObject->PolicyAdmins.GenericObjects.UsedCount == 0 ) {
//
// scope has not been delegated and is writable.
// for XML store that doesn't support delegation, PolicyAdmins should be empty
//
*PropertyValue = AzpGetUlongProperty( 1);
} else {
//
// scope is not writable, or already been delegated
//
*PropertyValue = AzpGetUlongProperty(0);
}
break;
default:
AzPrint(( AZD_INVPARM, "AzScopeGetProperty: invalid prop id %ld\n", PropertyId ));
WinStatus = ERROR_INVALID_PARAMETER;
}
return WinStatus;
}
DWORD
AzpScopeCanBeDelegated(
IN PGENERIC_OBJECT GenericObject,
IN BOOL bLockedShared
)
/*
Routine Description:
This routine determines if the scope passed in can be delegated. The logic here
is to check if there is any task object under the scope that has bizrules defined.
If there is task with bizrule, the scope cannot be delegated; otherwise, it can.
Note that the scope may not be loaded in cache yet (with the lazy bit set), in which
case, this routine will load the scope first then perform the check.
Arguments
GenericObject - pointer to the scope object
bLockedShared - TRUE if the global resource is shared
Return
ERROR_SUCCESS if the scope can be delegated
ERROR_NOT_SUPPORTED if the scope cannot be delegated
other error if cannot determine
*/
{
DWORD WinStatus = NO_ERROR;
//
// check input
//
if ( GenericObject == NULL ||
GenericObject->ObjectType != OBJECT_TYPE_SCOPE ) {
WinStatus = ERROR_INVALID_PARAMETER;
goto Cleanup;
}
if ( GenericObject->PolicyAdmins.GenericObjects.UsedCount != 0 ) {
//
// this scope is already delegated
//
WinStatus = ERROR_SUCCESS;
goto Cleanup;
}
PAZP_SCOPE Scope = (PAZP_SCOPE)GenericObject;
//
// check if we need to load the scope first
//
if ( !(GenericObject->AreChildrenLoaded) ) {
if ( bLockedShared ) {
//
// Grab the resource exclusively
//
AzpLockResourceSharedToExclusive( &AzGlResource );
}
WinStatus = AzPersistUpdateChildrenCache(
GenericObject
);
if ( bLockedShared ) {
AzpLockResourceExclusiveToShared( &AzGlResource );
}
if ( WinStatus != NO_ERROR ) {
goto Cleanup;
}
}
PLIST_ENTRY ListEntry;
BOOL BizRuleTaskFound = FALSE;
for ( ListEntry = Scope->Tasks.Head.Flink ;
ListEntry != &(Scope->Tasks.Head) ;
ListEntry = ListEntry->Flink ) {
PGENERIC_OBJECT MyGO;
//
// Grab a pointer to the next task to process
//
MyGO = CONTAINING_RECORD( ListEntry,
GENERIC_OBJECT,
Next );
ASSERT( MyGO->ObjectType == OBJECT_TYPE_TASK );
//
// check if there is bizrule defined in this task
//
PAZP_TASK Task = (PAZP_TASK)MyGO;
if ( Task->BizRule.String != NULL ||
Task->BizRuleLanguage.String != NULL ||
Task->BizRuleImportedPath.String != NULL ) {
BizRuleTaskFound = TRUE;
break;
}
}
if ( BizRuleTaskFound ) {
//
// there are bizrule defined.
//
WinStatus = ERROR_NOT_SUPPORTED;
}
Cleanup:
return WinStatus;
}
| 23.784252 | 98 | 0.602529 | [
"object"
] |
667b83b6da4af8f033c674d7064173480cca76f9 | 7,581 | cpp | C++ | 2 course/model_coursework/demo/p_semiconductor.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | 2 course/model_coursework/demo/p_semiconductor.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | 2 course/model_coursework/demo/p_semiconductor.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | #include "p_semiconductor.h"
#include <QSequentialAnimationGroup>
#include <QPropertyAnimation>
#include <QPen>
#include <vector>
#include <QDebug>
#include "demo.h"
#include <thread>
using namespace std;
P_semiconductor::P_semiconductor() : particleArr(10), animationArr(11)
{
group = new QGraphicsItemGroup();
animation_group = new QSequentialAnimationGroup();
}
P_semiconductor::~P_semiconductor()
{
delete group;
delete animation_group;
}
void P_semiconductor::draw()
{
QPen penBlack(Qt::black);
penBlack.setWidth(3);
// рисуем полупроводник
QGraphicsRectItem* rect = new QGraphicsRectItem(0,0,w,h);
rect->setRect(0,0,w,h);
rect->setPen(penBlack);
rect->setBrush(Qt::white);
group->addToGroup(rect);
// рисуем атомы
drawAtoms(rect,{30,halfH-halfAtomSize});
double xForElec = w-30-halfParticleSize;
double yForElec = halfH-halfParticleSize;
// рисуем электроны
drawElectrons({xForElec,yForElec});
// рисуем зоны, в которую должны уходить атомы (для эффекта исчезания)
drawBounds();
// рисуем схему от источника тока
drawPowerSource();
// анимации (последовательная группа анимаций)
prepareAnim({xForElec,yForElec});
readyToShow = true;
active = true;
}
void P_semiconductor::drawPowerSource()
{
// рисуем схему источника тока
QPainterPath* path = new QPainterPath();
QPen pen = {Qt::black};
pen.setWidth(2);
path->moveTo(-2,halfH);
path->lineTo(-30,halfH);
path->lineTo(-30,halfH-140);
path->lineTo(340,halfH-140);
path->moveTo(702,halfH);
path->lineTo(700+30,halfH);
path->lineTo(700+30,halfH-140);
path->lineTo(360,halfH-140);
path->lineTo(360,halfH-170);
path->lineTo(360,halfH-110);
QGraphicsPathItem* mainLine = new QGraphicsPathItem(*path);
mainLine->setPath(*path);
mainLine->setPen(pen);
mainLine->setZValue(5);
group->addToGroup(mainLine);
// добавляем жирную линию со стороны минуса у источника тока
QGraphicsLineItem* minusLine = new QGraphicsLineItem();
minusLine->setLine(340,halfH-155,340,halfH-125);
pen.setWidth(6);
minusLine->setPen(pen);
minusLine->setParentItem(mainLine);
// знаки + и -
PictureBox::drawSigns("+",{700+40,halfH-40},group);
PictureBox::drawSigns("-",{-68,halfH-40},group);
PictureBox::drawSigns("+",{365,halfH-186},group);
PictureBox::drawSigns("-",{300,halfH-185},group);
}
void P_semiconductor::drawAtom(QGraphicsItem *parent, const QPointF &coords)
{
QGraphicsEllipseItem* circle = new QGraphicsEllipseItem(0,0,80,80,parent);
circle->setPos(coords);
QPen pen = {Qt::black};
pen.setWidth(2);
circle->setPen(pen);
circle->setBrush(Qt::white);
Particle *elec1 = new Particle();
Particle *elec2 = new Particle();
Particle *hole1 = new Particle(Particle::ParticleType::hole);
Particle *hole2 = new Particle(Particle::ParticleType::hole);
elec1->setParentItem(circle);
elec1->setGeometry({40-8,-7,16,16});
elec1->setZValue(1);
elec2->setParentItem(circle);
elec2->setGeometry({40-8,80-10,16,16});
elec2->setZValue(1);
hole1->setParentItem(circle);
hole1->setGeometry({80-8,40-8,16,16});
hole1->setZValue(1);
hole2->setParentItem(circle);
hole2->setGeometry({-8,40-8,16,16});
hole2->setZValue(1);
}
void P_semiconductor::drawAtoms(QGraphicsItem *rect, const QPointF &coords)
{
double x = coords.x();
double y = coords.y();
drawAtom(rect,{x,y});
x += betweenAtoms + atomSize;
drawAtom(rect,{x,y});
x += betweenAtoms + atomSize;
drawAtom(rect,{x,y});
x += betweenAtoms + atomSize;
drawAtom(rect,{x,y});
x += betweenAtoms + atomSize;
drawAtom(rect,{x,y});
}
void P_semiconductor::drawElectrons(const QPointF &coords)
{
double x = coords.x();
double y = coords.y();
for (int i = 0; i < 10; ++i)
{
particleArr[i] = new Particle();
particleArr[i]->setZValue(2);
particleArr[i]->setGeometry({x,y,particleSize,particleSize});
if (i % 2 == 1) x -= betweenAtoms;
else x -= atomSize;
group->addToGroup(particleArr[i]);
}
}
void P_semiconductor::drawBounds()
{
QGraphicsRectItem *outRight = new QGraphicsRectItem(w+2,0,30,h);
QGraphicsRectItem *outLeft = new QGraphicsRectItem(-4-30,0,particleSize*2,h);
outRight->setBrush(Qt::white);
outLeft->setBrush(Qt::white);
outRight->setPen(QPen(Qt::NoPen));
outLeft->setPen(QPen(Qt::NoPen));
outRight->setZValue(5);
outLeft->setZValue(5);
group->addToGroup(outRight);
group->addToGroup(outLeft);
}
void P_semiconductor::prepareAnim(const QPointF &coords)
{
// создадим последовательную группу анимаций
double xForElec = coords.x();
double yForElec = coords.y();
// настроим вручную первую и последнюю
prepareAnimFirstAndLast({xForElec,yForElec});
xForElec -= atomSize;
// настраиваем все остальные анимации, стартовые и конечные позиции
// длительность анимации и пауз, добавляем анимации в группу
for (int i = 1; i < 10; ++i)
{
animationArr[i] = new QPropertyAnimation(particleArr[i],"geometry");
animationArr[i]->setDuration(animDuration);
double startX = xForElec;
double endX;
if (i % 2 == 1)
{
endX = xForElec + atomSize;
xForElec -= betweenAtoms;
}
else
{
endX = xForElec + betweenAtoms;
xForElec -= atomSize;
}
animationArr[i]->setStartValue(QRectF(startX,yForElec,particleSize,particleSize));
animationArr[i]->setEndValue(QRectF(endX,yForElec,particleSize,particleSize));
animation_group->addPause(pauseDuration);
animation_group->addAnimation(animationArr[i]);
}
// добавляем последнюю анимацию в группу
animation_group->addPause(pauseDuration);
animation_group->addAnimation(animationArr[10]);
animation_group->addPause(pauseDuration*3);
// ставим бесконечный цикл
animation_group->setLoopCount(-1);
animation_group->start();
}
void P_semiconductor::prepareAnimFirstAndLast(const QPointF &coords)
{
double xForElec = coords.x();
double yForElec = coords.y();
// первая
animationArr[0] = new QPropertyAnimation(particleArr[0],"geometry");
animationArr[0]->setDuration(animDuration);
animationArr[0]->setStartValue(QRectF(xForElec,yForElec,particleSize,particleSize));
animationArr[0]->setEndValue(QRectF(xForElec+30+particleSize,yForElec,particleSize,particleSize));
animation_group->addAnimation(animationArr[0]);
animation_group->addPause(pauseDuration);
// последняя
animationArr[10] = new QPropertyAnimation(particleArr[0],"geometry");
animationArr[10]->setDuration(animDuration);
animationArr[10]->setStartValue(QRectF(-particleSize,yForElec,particleSize,particleSize));
animationArr[10]->setEndValue(QRectF(30-halfParticleSize,yForElec,particleSize,particleSize));
}
void P_semiconductor::resetAnimations()
{
qDebug() << "reset";
// проходим по всем анимациям в массиве анимаций и устанавливаем их на стартовые позиции
for (auto &anim : animationArr)
{
anim->targetObject()->setProperty(anim->propertyName(),anim->startValue());
}
}
void P_semiconductor::pause()
{
if (active && readyToShow)
{
animation_group->pause();
active = false;
}
}
void P_semiconductor::unpause()
{
if (!active && readyToShow)
{
animation_group->resume();
active = true;
}
}
| 31.456432 | 102 | 0.670492 | [
"geometry",
"vector"
] |
6685ec134056f5d9e4fba8f396fd947bced732d7 | 3,095 | hpp | C++ | src/types/amfvector.hpp | Ventero/amf-cpp | e49c308e79e4467ccc42b42995ef2979ff5232e9 | [
"MIT"
] | 39 | 2015-03-20T16:40:01.000Z | 2021-06-07T21:24:40.000Z | src/types/amfvector.hpp | Ventero/amf-cpp | e49c308e79e4467ccc42b42995ef2979ff5232e9 | [
"MIT"
] | 5 | 2015-01-03T14:50:27.000Z | 2022-02-28T22:22:21.000Z | src/types/amfvector.hpp | Ventero/amf-cpp | e49c308e79e4467ccc42b42995ef2979ff5232e9 | [
"MIT"
] | 9 | 2015-03-24T03:55:46.000Z | 2020-11-17T09:23:41.000Z | #pragma once
#ifndef AMFVECTOR_HPP
#define AMFVECTOR_HPP
#include <string>
#include <vector>
#include "types/amfitem.hpp"
#include "utils/amfitemptr.hpp"
namespace amf {
class SerializationContext;
template<typename T>
struct VectorProperties;
template<typename T, class Enable = void>
class AmfVector;
template<>
struct VectorProperties<int> {
static const u8 marker = AMF_VECTOR_INT;
static const unsigned int size = 4;
typedef void type;
};
template<>
struct VectorProperties<unsigned int> {
static const u8 marker = AMF_VECTOR_UINT;
static const unsigned int size = 4;
typedef void type;
};
template<>
struct VectorProperties<double> {
static const u8 marker = AMF_VECTOR_DOUBLE;
static const unsigned int size = 8;
typedef void type;
};
template<typename T>
class AmfVector<T, typename VectorProperties<T>::type> : public AmfItem {
public:
AmfVector() : values({}), fixed(false) { }
AmfVector(std::vector<T> vector, bool fixed = false) :
values(vector), fixed(fixed) { }
bool operator==(const AmfItem& other) const;
void push_back(T item) {
values.push_back(item);
}
T& at(int index) {
return values.at(index);
}
std::vector<u8> serialize(SerializationContext& ctx) const;
static AmfVector<T> deserialize(v8::const_iterator& it, v8::const_iterator end, SerializationContext& ctx);
std::vector<T> values;
bool fixed;
};
template<>
class AmfVector<AmfItem> : public AmfItem {
public:
AmfVector(std::string type, bool fixed = false) : type(type), fixed(fixed) { }
bool operator==(const AmfItem& other) const;
std::vector<u8> serialize(SerializationContext& ctx) const;
static AmfItemPtr deserializePtr(v8::const_iterator& it, v8::const_iterator end, SerializationContext& ctx);
static AmfVector<AmfItem> deserialize(v8::const_iterator& it, v8::const_iterator end, SerializationContext& ctx);
template<typename V, typename std::enable_if<std::is_base_of<AmfItem, V>::value, int>::type = 0>
AmfVector<V> as() {
AmfVector<V> ret({}, type, fixed);
ret.values = values;
return ret;
}
std::vector<AmfItemPtr> values;
std::string type;
bool fixed;
};
template<typename T>
class AmfVector<T, typename std::enable_if<
std::is_base_of<AmfItem, T>::value>::type> : public AmfVector<AmfItem> {
public:
AmfVector(std::vector<T> vector, std::string type, bool fixed = false) :
AmfVector<AmfItem>(type, fixed) {
for (const auto& it : vector)
push_back(it);
}
bool operator==(const AmfItem& other) const {
const AmfVector<T>* p = dynamic_cast<const AmfVector<T>*>(&other);
return p != nullptr && fixed == p->fixed && type == p->type && values == p->values;
}
void push_back(const T& item) {
values.emplace_back(new T(item));
}
T& at(int index) {
return values.at(index).template as<T>();
}
static AmfVector<T> deserialize(v8::const_iterator& it, v8::const_iterator end, SerializationContext& ctx) {
return AmfVector<AmfItem>::deserialize(it, end, ctx).as<T>();
}
private:
static AmfItemPtr deserializePtr(v8::const_iterator& it, v8::const_iterator end, SerializationContext& ctx);
};
} // namespace amf
#endif
| 25.368852 | 114 | 0.721809 | [
"vector"
] |
66902b1a717fb07a86a394449357a4fb84ccec3b | 19,177 | cpp | C++ | reference/test/factorization/ilu_kernels.cpp | kliegeois/ginkgo | 4defcc07f77828393cc5b4a735a00e50da2cbab0 | [
"BSD-3-Clause"
] | null | null | null | reference/test/factorization/ilu_kernels.cpp | kliegeois/ginkgo | 4defcc07f77828393cc5b4a735a00e50da2cbab0 | [
"BSD-3-Clause"
] | null | null | null | reference/test/factorization/ilu_kernels.cpp | kliegeois/ginkgo | 4defcc07f77828393cc5b4a735a00e50da2cbab0 | [
"BSD-3-Clause"
] | null | null | null | /*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2022, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder 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.
******************************<GINKGO LICENSE>*******************************/
#include <ginkgo/core/factorization/ilu.hpp>
#include <algorithm>
#include <initializer_list>
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include <ginkgo/core/base/executor.hpp>
#include <ginkgo/core/matrix/coo.hpp>
#include <ginkgo/core/matrix/csr.hpp>
#include <ginkgo/core/matrix/dense.hpp>
#include "core/test/utils.hpp"
namespace {
class DummyLinOp : public gko::EnableLinOp<DummyLinOp>,
public gko::EnableCreateMethod<DummyLinOp> {
public:
DummyLinOp(std::shared_ptr<const gko::Executor> exec,
gko::dim<2> size = gko::dim<2>{})
: EnableLinOp<DummyLinOp>(exec, size)
{}
protected:
void apply_impl(const gko::LinOp* b, gko::LinOp* x) const override {}
void apply_impl(const gko::LinOp* alpha, const gko::LinOp* b,
const gko::LinOp* beta, gko::LinOp* x) const override
{}
};
template <typename ValueIndexType>
class Ilu : public ::testing::Test {
protected:
using value_type =
typename std::tuple_element<0, decltype(ValueIndexType())>::type;
using index_type =
typename std::tuple_element<1, decltype(ValueIndexType())>::type;
using Dense = gko::matrix::Dense<value_type>;
using Coo = gko::matrix::Coo<value_type, index_type>;
using Csr = gko::matrix::Csr<value_type, index_type>;
using ilu_type = gko::factorization::Ilu<value_type, index_type>;
Ilu()
: ref(gko::ReferenceExecutor::create()),
exec(std::static_pointer_cast<const gko::Executor>(ref)),
// clang-format off
identity(gko::initialize<Dense>(
{{1., 0., 0.},
{0., 1., 0.},
{0., 0., 1.}}, exec)),
lower_triangular(gko::initialize<Dense>(
{{1., 0., 0.},
{1., 1., 0.},
{1., 1., 1.}}, exec)),
upper_triangular(gko::initialize<Dense>(
{{1., 1., 1.},
{0., 1., 1.},
{0., 0., 1.}}, exec)),
mtx_small(gko::initialize<Dense>(
{{4., 6., 8.},
{2., 2., 5.},
{1., 1., 1.}}, exec)),
mtx_csr_small(nullptr),
small_l_expected(gko::initialize<Dense>(
{{1., 0., 0.},
{0.5, 1., 0.},
{0.25, 0.5, 1.}}, exec)),
small_u_expected(gko::initialize<Dense>(
{{4., 6., 8.},
{0., -1., 1.},
{0., 0., -1.5}}, exec)),
mtx_small2(gko::initialize<Dense>(
{{8., 8., 0},
{2., 0., 5.},
{1., 1., 1}}, exec)),
mtx_csr_small2(nullptr),
small2_l_expected(gko::initialize<Dense>(
{{1., 0., 0},
{.25, 1., 0.},
{.125, 0., 1}}, exec)),
small2_u_expected(gko::initialize<Dense>(
{{8., 8., 0},
{0., -2., 5.},
{0., 0., 1}}, exec)),
mtx_big(gko::initialize<Dense>({{1., 1., 1., 0., 1., 3.},
{1., 2., 2., 0., 2., 0.},
{0., 2., 3., 3., 3., 5.},
{1., 0., 3., 4., 4., 4.},
{1., 2., 0., 4., 5., 6.},
{0., 2., 3., 4., 5., 8.}},
exec)),
big_l_expected(gko::initialize<Dense>({{1., 0., 0., 0., 0., 0.},
{1., 1., 0., 0., 0., 0.},
{0., 2., 1., 0., 0., 0.},
{1., 0., 2., 1., 0., 0.},
{1., 1., 0., -2., 1., 0.},
{0., 2., 1., -0.5, 0.5, 1.}},
exec)),
big_u_expected(gko::initialize<Dense>({{1., 1., 1., 0., 1., 3.},
{0., 1., 1., 0., 1., 0.},
{0., 0., 1., 3., 1., 5.},
{0., 0., 0., -2., 1., -9.},
{0., 0., 0., 0., 5., -15.},
{0., 0., 0., 0., 0., 6.}},
exec)),
mtx_big_nodiag(gko::initialize<Csr>({{1., 1., 1., 0., 1., 3.},
{1., 2., 2., 0., 2., 0.},
{0., 2., 0., 3., 3., 5.},
{1., 0., 3., 4., 4., 4.},
{1., 2., 0., 4., 1., 6.},
{0., 2., 3., 4., 5., 8.}},
exec)),
big_nodiag_l_expected(gko::initialize<Dense>(
{{1., 0., 0., 0., 0., 0.},
{1., 1., 0., 0., 0., 0.},
{0., 2., 1., 0., 0., 0.},
{1., 0., -1., 1., 0., 0.},
{1., 1., 0., 0.571428571428571, 1., 0.},
{0., 2., -0.5, 0.785714285714286, -0.108695652173913, 1.}},
exec)),
big_nodiag_u_expected(gko::initialize<Dense>(
{{1., 1., 1., 0., 1., 3.},
{0., 1., 1., 0., 1., 0.},
{0., 0., -2., 3., 1., 5.},
{0., 0., 0., 7., 4., 6.},
{0., 0., 0., 0., -3.28571428571429, -0.428571428571429},
{0., 0., 0., 0., 0., 5.73913043478261}},
exec)),
// clang-format on
ilu_factory_skip(ilu_type::build().with_skip_sorting(true).on(exec)),
ilu_factory_sort(ilu_type::build().with_skip_sorting(false).on(exec))
{
auto tmp_csr = Csr::create(exec);
mtx_small->convert_to(gko::lend(tmp_csr));
mtx_csr_small = std::move(tmp_csr);
auto tmp_csr2 = Csr::create(exec);
mtx_small2->convert_to(gko::lend(tmp_csr2));
mtx_csr_small2 = std::move(tmp_csr2);
}
std::shared_ptr<const gko::ReferenceExecutor> ref;
std::shared_ptr<const gko::Executor> exec;
std::shared_ptr<const Dense> identity;
std::shared_ptr<const Dense> lower_triangular;
std::shared_ptr<const Dense> upper_triangular;
std::shared_ptr<const Dense> mtx_small;
std::shared_ptr<const Csr> mtx_csr_small;
std::shared_ptr<const Dense> small_l_expected;
std::shared_ptr<const Dense> small_u_expected;
std::shared_ptr<const Dense> mtx_small2;
std::shared_ptr<const Csr> mtx_csr_small2;
std::shared_ptr<const Dense> small2_l_expected;
std::shared_ptr<const Dense> small2_u_expected;
std::shared_ptr<const Dense> mtx_big;
std::shared_ptr<const Dense> big_l_expected;
std::shared_ptr<const Dense> big_u_expected;
std::shared_ptr<const Csr> mtx_big_nodiag;
std::shared_ptr<const Dense> big_nodiag_l_expected;
std::shared_ptr<const Dense> big_nodiag_u_expected;
std::unique_ptr<typename ilu_type::Factory> ilu_factory_skip;
std::unique_ptr<typename ilu_type::Factory> ilu_factory_sort;
};
TYPED_TEST_SUITE(Ilu, gko::test::ValueIndexTypes, PairTypenameNameGenerator);
TYPED_TEST(Ilu, ThrowNotSupportedForWrongLinOp1)
{
auto linOp = DummyLinOp::create(this->ref);
ASSERT_THROW(this->ilu_factory_skip->generate(gko::share(linOp)),
gko::NotSupported);
}
TYPED_TEST(Ilu, ThrowNotSupportedForWrongLinOp2)
{
auto linOp = DummyLinOp::create(this->ref);
ASSERT_THROW(this->ilu_factory_sort->generate(gko::share(linOp)),
gko::NotSupported);
}
TYPED_TEST(Ilu, ThrowDimensionMismatch)
{
using Csr = typename TestFixture::Csr;
auto matrix = Csr::create(this->ref, gko::dim<2>{2, 3}, 4);
ASSERT_THROW(this->ilu_factory_sort->generate(gko::share(matrix)),
gko::DimensionMismatch);
}
TYPED_TEST(Ilu, SetLStrategy)
{
using Csr = typename TestFixture::Csr;
using ilu_type = typename TestFixture::ilu_type;
auto l_strategy = std::make_shared<typename Csr::classical>();
auto factory = ilu_type::build().with_l_strategy(l_strategy).on(this->ref);
auto ilu = factory->generate(this->mtx_small);
ASSERT_EQ(factory->get_parameters().l_strategy, l_strategy);
ASSERT_EQ(ilu->get_l_factor()->get_strategy()->get_name(),
l_strategy->get_name());
}
TYPED_TEST(Ilu, SetUStrategy)
{
using Csr = typename TestFixture::Csr;
using ilu_type = typename TestFixture::ilu_type;
auto u_strategy = std::make_shared<typename Csr::classical>();
auto factory = ilu_type::build().with_u_strategy(u_strategy).on(this->ref);
auto ilu = factory->generate(this->mtx_small);
ASSERT_EQ(factory->get_parameters().u_strategy, u_strategy);
ASSERT_EQ(ilu->get_u_factor()->get_strategy()->get_name(),
u_strategy->get_name());
}
TYPED_TEST(Ilu, LUFactorFunctionsSetProperly)
{
auto factors = this->ilu_factory_skip->generate(this->mtx_small);
auto lin_op_l_factor =
static_cast<const gko::LinOp*>(gko::lend(factors->get_l_factor()));
auto lin_op_u_factor =
static_cast<const gko::LinOp*>(gko::lend(factors->get_u_factor()));
auto first_operator = gko::lend(factors->get_operators()[0]);
auto second_operator = gko::lend(factors->get_operators()[1]);
ASSERT_EQ(lin_op_l_factor, first_operator);
ASSERT_EQ(lin_op_u_factor, second_operator);
}
TYPED_TEST(Ilu, GenerateForCooIdentity)
{
using Coo = typename TestFixture::Coo;
using value_type = typename TestFixture::value_type;
auto coo_mtx = gko::share(Coo::create(this->exec));
this->identity->convert_to(gko::lend(coo_mtx));
auto factors = this->ilu_factory_skip->generate(coo_mtx);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->identity, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->identity, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForCsrIdentity)
{
using Csr = typename TestFixture::Csr;
using value_type = typename TestFixture::value_type;
auto csr_mtx = gko::share(Csr::create(this->exec));
this->identity->convert_to(gko::lend(csr_mtx));
auto factors = this->ilu_factory_skip->generate(csr_mtx);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->identity, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->identity, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForDenseIdentity)
{
using value_type = typename TestFixture::value_type;
auto factors = this->ilu_factory_skip->generate(this->identity);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->identity, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->identity, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForDenseLowerTriangular)
{
using value_type = typename TestFixture::value_type;
auto factors = this->ilu_factory_skip->generate(this->lower_triangular);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->lower_triangular, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->identity, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForDenseUpperTriangular)
{
using value_type = typename TestFixture::value_type;
auto factors = this->ilu_factory_skip->generate(this->upper_triangular);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->identity, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->upper_triangular, r<value_type>::value);
}
TYPED_TEST(Ilu, ApplyMethodDenseSmall)
{
using value_type = typename TestFixture::value_type;
using Dense = typename TestFixture::Dense;
const auto x = gko::initialize<Dense>({1., 2., 3.}, this->exec);
auto b_lu = Dense::create_with_config_of(gko::lend(x));
auto b_ref = Dense::create_with_config_of(gko::lend(x));
auto factors = this->ilu_factory_skip->generate(this->mtx_small);
factors->apply(gko::lend(x), gko::lend(b_lu));
this->mtx_small->apply(gko::lend(x), gko::lend(b_ref));
GKO_ASSERT_MTX_NEAR(b_lu, b_ref, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForDenseSmall)
{
using value_type = typename TestFixture::value_type;
auto factors = this->ilu_factory_skip->generate(this->mtx_small);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->small_l_expected, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->small_u_expected, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForCsrSmall)
{
using value_type = typename TestFixture::value_type;
auto factors = this->ilu_factory_skip->generate(this->mtx_csr_small);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->small_l_expected, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->small_u_expected, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForCsrSmall2ZeroDiagonal)
{
using value_type = typename TestFixture::value_type;
auto factors = this->ilu_factory_skip->generate(this->mtx_csr_small2);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->small2_l_expected,
r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->small2_u_expected,
r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForCsrBigWithDiagonalZeros)
{
using value_type = typename TestFixture::value_type;
auto factors = this->ilu_factory_skip->generate(this->mtx_big_nodiag);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->big_nodiag_l_expected,
r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->big_nodiag_u_expected,
r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForDenseBig)
{
using value_type = typename TestFixture::value_type;
auto factors = this->ilu_factory_skip->generate(this->mtx_big);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->big_l_expected, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->big_u_expected, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForDenseBigSort)
{
using value_type = typename TestFixture::value_type;
auto factors = this->ilu_factory_sort->generate(this->mtx_big);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->big_l_expected, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->big_u_expected, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForReverseCooSmall)
{
using value_type = typename TestFixture::value_type;
using Coo = typename TestFixture::Coo;
const auto size = this->mtx_small->get_size();
const auto nnz = size[0] * size[1];
auto reverse_coo = gko::share(Coo::create(this->exec, size, nnz));
// Fill the Coo matrix in reversed row order (right to left)
for (size_t i = 0; i < size[0]; ++i) {
for (size_t j = 0; j < size[1]; ++j) {
const auto coo_idx = i * size[1] + (size[1] - 1 - j);
reverse_coo->get_row_idxs()[coo_idx] = i;
reverse_coo->get_col_idxs()[coo_idx] = j;
reverse_coo->get_values()[coo_idx] = this->mtx_small->at(i, j);
}
}
auto factors = this->ilu_factory_sort->generate(reverse_coo);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(reverse_coo, this->mtx_small, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(l_factor, this->small_l_expected, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->small_u_expected, r<value_type>::value);
}
TYPED_TEST(Ilu, GenerateForReverseCsrSmall)
{
using value_type = typename TestFixture::value_type;
using Csr = typename TestFixture::Csr;
const auto size = this->mtx_csr_small->get_size();
const auto nnz = size[0] * size[1];
auto reverse_csr = gko::share(gko::clone(this->exec, this->mtx_csr_small));
// Fill the Csr matrix rows in reverse order
for (size_t i = 0; i < size[0]; ++i) {
const auto row_start = reverse_csr->get_row_ptrs()[i];
const auto row_end = reverse_csr->get_row_ptrs()[i + 1];
for (size_t j = row_start; j < row_end; ++j) {
const auto reverse_j = row_end - 1 - (j - row_start);
reverse_csr->get_values()[reverse_j] =
this->mtx_csr_small->get_const_values()[j];
reverse_csr->get_col_idxs()[reverse_j] =
this->mtx_csr_small->get_const_col_idxs()[j];
}
}
auto factors = this->ilu_factory_sort->generate(reverse_csr);
auto l_factor = factors->get_l_factor();
auto u_factor = factors->get_u_factor();
GKO_ASSERT_MTX_NEAR(l_factor, this->small_l_expected, r<value_type>::value);
GKO_ASSERT_MTX_NEAR(u_factor, this->small_u_expected, r<value_type>::value);
}
} // namespace
| 38.354 | 80 | 0.607238 | [
"vector"
] |
6692d4328efbea05534e94f4183e15544ad92baa | 2,950 | cpp | C++ | leetcode.com/0803 Bricks Falling When Hit/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2020-08-20T11:02:49.000Z | 2020-08-20T11:02:49.000Z | leetcode.com/0803 Bricks Falling When Hit/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | null | null | null | leetcode.com/0803 Bricks Falling When Hit/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2022-01-01T23:23:13.000Z | 2022-01-01T23:23:13.000Z | #include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
// ref: Python Solution by reversely adding hits bricks back
// https://leetcode.com/problems/bricks-falling-when-hit/discuss/119829/Python-Solution-by-reversely-adding-hits-bricks-back
// ref: Union-find Logical Thinking
// https://leetcode.com/problems/bricks-falling-when-hit/discuss/195781/Union-find-Logical-Thinking
// use union find
int di[] = {0, 0, -1, 1};
int dj[] = {-1, 1, 0, 0};
class Solution {
private:
vector<int> ids, counts;
int n, R, C;
int F(int x) {
int p = x;
while (p != ids[p]) {
p = ids[p];
}
// optimization, change parent of nodes on the path to the root node
int p2 = x;
while (ids[p2] != p) {
int next_p2 = ids[p2];
ids[p2] = p;
p2 = next_p2;
}
return p;
}
void U(int p, int q) {
int pid = F(p), qid = F(q);
if (pid != qid) {
ids[qid] = pid;
counts[pid] += counts[qid];
}
}
void U_around(int i, int j, vector<vector<int>>& grid) {
int p = i * C + j + 1;
for (int k = 0; k < 4; ++k) {
int ni = i + di[k], nj = j + dj[k];
if (ni >= 0 && ni < R && nj >= 0 && nj < C && grid[ni][nj] == 1) {
int q = ni * C + nj + 1;
U(p, q);
}
}
if (i == 0) U(0, p);
}
public:
vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) {
n = hits.size(), R = grid.size(), C = grid[0].size();
/* mark cells to hit (=1) as 2 */
// (0: empty cell, 1: brick, 2: brick removed, but will be added back later)
for (auto& hit : hits)
if (grid[hit[0]][hit[1]] == 1) grid[hit[0]][hit[1]] = 2;
/* setup disjoint set */
ids.clear(), counts.clear();
ids.resize(R * C + 1);
iota(ids.begin(), ids.end(), 0);
counts.resize(R * C + 1, 1);
// union neighboring brick cells
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j)
if (grid[i][j] == 1) {
U_around(i, j, grid);
}
}
/* counts[0] also ok for my implementation of func U */
int bricks_left = counts[F(0)];
vector<int> res(n);
// add bricks back
for (int i = n - 1; i >= 0; --i) {
auto& hit = hits[i];
if (grid[hit[0]][hit[1]] == 2) {
grid[hit[0]][hit[1]] = 1; // Restore to last erasure.
U_around(hit[0], hit[1], grid);
int new_bricks_left = counts[F(0)];
res[i] = max(new_bricks_left - bricks_left - 1,
0); // Excluding the brick to erase.
bricks_left = new_bricks_left;
}
}
return res;
}
};
template <typename T>
void printArr(const vector<T>& arr) {
for (const T& t : arr) cout << t << " ";
cout << endl;
}
int main(int argc, char const* argv[]) {
vector<vector<int>> grid = {{1, 0, 0, 0}, {1, 1, 1, 0}};
vector<vector<int>> hits = {{1, 0}};
Solution s;
printArr(s.hitBricks(grid, hits));
return 0;
}
| 25.652174 | 124 | 0.528814 | [
"vector"
] |
6695a88b3c6732829c13179de875cd7b0ffb097b | 2,685 | hpp | C++ | include/tao/pegtl/contrib/print.hpp | edhall/PEGTL | 0d107c3e6d7d8428cb105e788ff36a8d579de296 | [
"MIT"
] | null | null | null | include/tao/pegtl/contrib/print.hpp | edhall/PEGTL | 0d107c3e6d7d8428cb105e788ff36a8d579de296 | [
"MIT"
] | null | null | null | include/tao/pegtl/contrib/print.hpp | edhall/PEGTL | 0d107c3e6d7d8428cb105e788ff36a8d579de296 | [
"MIT"
] | null | null | null | // Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_PRINT_HPP
#define TAO_PEGTL_CONTRIB_PRINT_HPP
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <ios>
#include <ostream>
#include <string_view>
#include <vector>
#include "../config.hpp"
#include "../demangle.hpp"
#include "../visit.hpp"
#include "print_rules_traits.hpp"
#include "internal/print_utility.hpp"
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< typename Name >
struct print_names
{
static void visit( std::ostream& os )
{
os << demangle< Name >() << '\n';
}
};
template< typename Name >
struct print_debug
{
static void visit( std::ostream& os )
{
const auto first = demangle< Name >();
os << first << '\n';
const auto second = demangle< typename Name::rule_t >();
if( first != second ) {
os << " (aka) " << second << '\n';
}
print_subs( os, typename Name::subs_t() );
os << '\n';
}
private:
template< typename... Rules >
static void print_subs( std::ostream& os, type_list< Rules... > /*unused*/ )
{
( print_sub< Rules >( os ), ... );
}
template< typename Rule >
static void print_sub( std::ostream& os )
{
os << " (sub) " << demangle< Rule >() << '\n';
}
};
template< typename Rule >
struct print_rules
{
static void visit( std::ostream& os, const print_rules_config& pc )
{
if( const auto rule = pc.template name< Rule >(); !rule.empty() ) {
os << std::string( std::string::size_type( std::max( pc.width - int( rule.size() ), 0 ) ), ' ' ) << pc.user( rule ) << " = ";
print_rules_traits< typename Rule::rule_t >::print( os, pc );
os << '\n';
}
}
};
} // namespace internal
template< typename Grammar >
void print_names( std::ostream& os )
{
visit< Grammar, internal::print_names >( os );
}
template< typename Grammar >
void print_debug( std::ostream& os )
{
visit< Grammar, internal::print_debug >( os );
}
template< typename Grammar, typename... Args >
void print_rules( std::ostream& os, Args&&... args )
{
const internal::print_rules_config pc( args... );
visit< Grammar, internal::print_rules >( os, pc );
}
} // namespace TAO_PEGTL_NAMESPACE
#endif
| 25.571429 | 140 | 0.543017 | [
"vector"
] |
66a91a9620b80efbcd58034db6dd33315c550650 | 10,786 | cpp | C++ | CPP/Modules/QueueSerial/QueueSerial.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 6 | 2015-12-01T01:12:33.000Z | 2021-07-24T09:02:34.000Z | CPP/Modules/QueueSerial/QueueSerial.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | null | null | null | CPP/Modules/QueueSerial/QueueSerial.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 2 | 2017-02-02T19:31:29.000Z | 2018-12-17T21:00:45.000Z | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 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 Vodafone Group Services Ltd 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 "arch.h"
#include "MsgBufferEnums.h"
#include "Module.h"
#include "Serial.h"
#include "Mutex.h"
#include "QueueSerial.h"
#include <map>
#include "GuiProt/GuiProtEnums.h"
#ifndef NO_LOG_OUTPUT
# define NO_LOG_OUTPUT
#endif
#include "LogMacros.h"
#include "Buffer.h"
#include "MsgBuffer.h"
/// The number of buffers that can be stored in the outbound queue
/// before the overflow policy is invoked.
#define QS_OVERFLOW_LIMIT 200
isab::QueueSerial::QueueSerial(const char* name, class OverflowPolicy* policy,
int microSecondsPoll) :
Module(name), m_connectState(CONNECTING), m_pollInterval(microSecondsPoll),
m_policy(policy)
#ifdef __SYMBIAN32__
,m_guiSideRequestStatus(NULL)
#endif
{
}
void isab::QueueSerial::decodedStartupComplete()
{
DBG("decodedStartupComplete");
if(!m_incoming.empty() && rootPublic()){
connect();
while(! m_incoming.empty()){
Buffer* buf = m_incoming.front();
m_incoming.pop();
write(buf->accessRawData(0), buf->getLength());
delete buf;
}
} else if(rootPublic()){
rootPublic()->connectionNotify(m_connectState);
}
}
bool isab::QueueSerial::write(const uint8* data, int length)
{
bool ret = false;
if(isAlive()){
if(rootPublic() && m_connectState != CONNECTED){
m_connectState = CONNECTED;
rootPublic()->connectionNotify(CONNECTED);
}
m_queue->lock();
if(rootPublic()){
//DBGDUMP("write", data, length);
uint32 src = rootPublic()->receiveData(length, data);
src = src;
DBG("Message sent with id: %0#10"PRIx32, src);
ret = true;
} else {
Buffer* buf = new Buffer(0);
buf->writeNextByteArray(data, length);
m_incoming.push(buf);
}
m_queue->unlock();
}
return ret;
}
void isab::QueueSerial::connect(){
DBG("connect");
m_connectState = CONNECTED;
if(rootPublic()){
rootPublic()->connectionNotify(CONNECTED);
}
}
void isab::QueueSerial::disconnect(){
DBG("disconnect");
m_connectState = DISCONNECTING;
if(isAlive()){
rootPublic()->connectionNotify(DISCONNECTING);
}
}
int isab::QueueSerial::read( uint8* data, int maxlength)
{
if(m_connectState != CONNECTED){
m_connectState = CONNECTED;
rootPublic()->connectionNotify(CONNECTED);
}
int retval = 0;
m_outMutex.lock();
while(!m_outQue.empty() && retval < maxlength){
Buffer* front = m_outQue.front();
int n = front->readNextByteArray(data + retval, maxlength - retval);
retval += n;
if(front->remaining() <= 0){
m_outQue.pop_front();
delete front;
}
}
m_outMutex.unlock();
//DBGDUMP("read data", data, retval);
return retval;
}
bool isab::QueueSerial::read(isab::Buffer* buf)
{
bool ret = false;
if((ret = isAlive())){
if(m_connectState != CONNECTED){
m_connectState = CONNECTED;
rootPublic()->connectionNotify(CONNECTED);
}
m_outMutex.lock();
buf->reserve(buf->getLength() + internalAvailable());
DBG("read: outque size: %d", m_outQue.size());
while(!m_outQue.empty()){
Buffer* front = m_outQue.front();
//DBGDUMP("front", front->accessRawData(0), front->getLength());
buf->writeNextByteArray(front->accessRawData(0), front->getLength());
m_outQue.pop_front();
delete front;
}
//DBGDUMP("read", buf->accessRawData(0), buf->getLength());
m_outMutex.unlock();
}
return ret;
}
#ifdef __SYMBIAN32__
void isab::QueueSerial::armReader(TRequestStatus *aStatus)
{
m_outMutex.lock();
// It is a major error if this object already is armed. FIMXE - check.
if (m_outQue.empty()) {
m_guiSideRequestStatus = aStatus;
RThread thisThread;
m_guiSideThread = thisThread.Id();
thisThread.Close();
*aStatus = KRequestPending;
} else {
User::RequestComplete(aStatus, KErrNone);
}
m_outMutex.unlock();
}
void isab::QueueSerial::cancelArm()
{
m_outMutex.lock();
if (m_guiSideRequestStatus) {
RThread otherThread;
otherThread.Open(m_guiSideThread);
otherThread.RequestComplete(m_guiSideRequestStatus, KErrCancel);
otherThread.Close();
m_guiSideRequestStatus=NULL;
}
m_outMutex.unlock();
}
#endif
int isab::QueueSerial::internalAvailable() const
{
int retval = 0;
Container::const_iterator q;
for(q = m_outQue.begin(); q != m_outQue.end(); ++q){
retval = (*q)->remaining();
}
return retval;
}
int isab::QueueSerial::available() const
{
m_outMutex.lock();
int retval = internalAvailable();
m_outMutex.unlock();
DBG("Available: %d", retval);
return retval;
}
bool isab::QueueSerial::empty() const
{
DBG("empty? %s", m_outQue.empty() ? "true": "false");
return m_outQue.empty();
}
isab::SerialProviderPublic * isab::QueueSerial::newPublicSerial()
{
DBG("newPublicSerial");
SerialProviderPublic* spp = new SerialProviderPublic(m_queue);
return spp;
}
void isab::QueueSerial::decodedSendData(int length, const uint8 *data,
uint32 /*src*/)
{
DBG("enter decodedSendData");
m_outMutex.lock();
//DBGDUMP("decodedSendData", data, length);
Buffer* buf = new Buffer(length);
buf->writeNextByteArray(data, length);
m_outQue.push_back(buf);
DBG("push_back, outque size: %d", m_outQue.size());
if(m_outQue.size() > QS_OVERFLOW_LIMIT){
INFO("Queue overflow, removing excess messages now");
removeOverflow();
}
#ifdef __SYMBIAN32__
if (m_guiSideRequestStatus) {
DBG("complete sprocket, outque size: %d", m_outQue.size());
// Notify the other (non-Nav2) side reader
RThread otherThread;
otherThread.Open(m_guiSideThread);
otherThread.RequestComplete(m_guiSideRequestStatus, KErrNone);
otherThread.Close();
m_guiSideRequestStatus=NULL;
}
#endif
m_outMutex.unlock();
DBG("exit decodedSendData");
}
void isab::QueueSerial::decodedConnectionCtrl(enum ConnectionCtrl ctrl,
const char *method,
uint32 /*src*/)
{
switch(ctrl){
case Module::CONNECT:
WARN("CONNECT %s", method);
break;
case Module::DISCONNECT:
WARN("DISCONNECT %s", method);
break;
case Module::QUERY:
WARN("QUERY %s", method);
rootPublic()->connectionNotify(m_connectState);
break;
default:
ERR("ConnectionCtrl: Unknown ctrl value: %d", ctrl);
}
}
isab::SerialConsumerPublic * isab::QueueSerial::rootPublic()
{
return static_cast<SerialConsumerPublic*>(m_rawRootPublic);
}
isab::MsgBuffer * isab::QueueSerial::dispatch(MsgBuffer *buf)
{
if(buf) buf = m_providerDecoder.dispatch(buf, this);
if(buf) buf = Module::dispatch(buf);
return buf;
}
isab::QueueSerial::~QueueSerial()
{
delete m_policy;
while(!m_outQue.empty()){
Buffer* front = m_outQue.front();
m_outQue.pop_front();
delete front;
}
}
void isab::KeepLatestGuiMessage::clean(QueueSerial::Container& deq)
{
//this method presumes that each buffer in the deque contains
//exactly one complete Gui-message
typedef std::map<uint16, Buffer*> Tree;
Tree keepers;
while(!deq.empty()){
Buffer* front = deq.front();
deq.pop_front();
int pos = front->setReadPos(0);
uint8 protocol = *(front->accessRawData(0));
uint32 length = front->readNextUnaligned32bit() & 0x0ffffff;
length = length;
uint16 message = front->readNextUnaligned16bit();
switch(protocol){
case 0:
case 3:
break;
}
std::map<uint16, Buffer*>::iterator prev = keepers.find(message);
if(prev != keepers.end()){
delete (*prev).second;
(*prev).second = front;
} else {
keepers[message] = front;
}
front->setReadPos(pos);
}
for(Tree::iterator p = keepers.begin(); p != keepers.end(); ++p){
deq.push_back((*p).second);
}
}
void isab::KeepLatestBuffer::clean(QueueSerial::Container& deq)
{
while(deq.size() > 1){
Buffer* tmp = deq.front();
deq.pop_front();
delete tmp;
}
}
void isab::RemoveGpsAndRoute::clean(QueueSerial::Container& deq)
{
QueueSerial::Container tmp;
while(!deq.empty()){
Buffer* front = deq.front();
deq.pop_front();
front->setReadPos(0);
/*uint32 length = */ front->readNextUnaligned32bit();
/*uint8 datatype = */front->readNext8bit();
uint8 message = front->readNext8bit();
front->setReadPos(0);
switch(message){
case isab::GuiProtEnums::UPDATE_POSITION_INFO:
// case isab::GuiProtEnums::UPDATE_ROUTE_INFO:
delete front;
default:
tmp.push_back(front);
}
}
std::swap(tmp,deq);
}
| 31.083573 | 758 | 0.633321 | [
"object"
] |
66af5c43923dabaa8c36fdcdd80c27e9b6c56924 | 750 | cpp | C++ | April/Week3/CountSquareSubmatrices.cpp | nimishbongale/leetcode-30days-solutions-scratchpad | 56aa989907e5c9bb2657292434ef2174b525aeb2 | [
"MIT"
] | null | null | null | April/Week3/CountSquareSubmatrices.cpp | nimishbongale/leetcode-30days-solutions-scratchpad | 56aa989907e5c9bb2657292434ef2174b525aeb2 | [
"MIT"
] | null | null | null | April/Week3/CountSquareSubmatrices.cpp | nimishbongale/leetcode-30days-solutions-scratchpad | 56aa989907e5c9bb2657292434ef2174b525aeb2 | [
"MIT"
] | null | null | null | class Solution {
public:
int countSquares(vector<vector<int>>& matrix)
{
vector<vector<int>> dp(matrix.size(), vector<int>(matrix[0].size(), 0));
for(int i=0;i<matrix.size();i++)
if(matrix[i][0]==1)
dp[i][0]=1;
for(int i=0;i<matrix[0].size();i++)
if(matrix[0][i]==1)
dp[0][i]=1;
for(int i=1; i<matrix.size(); i++)
for(int j=1; j<matrix[0].size(); j++)
if(matrix[i][j]==1)
dp[i][j]=1+min(dp[i-1][j],min(dp[i][j-1], dp[i-1][j-1]));
int sum=0;
for(int i=0; i<matrix.size(); i++)
for(int j=0; j<matrix[0].size(); j++)
sum=sum+dp[i][j];
return sum;
}
};
| 32.608696 | 80 | 0.429333 | [
"vector"
] |
66b5de4b8424d34010c5bb9c21a4a422dc9e5812 | 3,138 | cpp | C++ | packages/geometry/legacy/test/tstCellBoundingBox.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/geometry/legacy/test/tstCellBoundingBox.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/geometry/legacy/test/tstCellBoundingBox.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file tstCellBoundingBox.cpp
//! \author Alex Robinson
//! \brief Cell bounding box unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
#include <string>
#include <map>
// Trilinos Includes
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_RCP.hpp>
// FRENSIE Includes
#include "Geometry_Cell.hpp"
#include "Geometry_Surface.hpp"
#include "Geometry_CellBoundingBox.hpp"
#include "Utility_PhysicalConstants.hpp"
#include "Utility_UnitTestHarnessExtensions.hpp"
#define UNIT_TEST_INSTANTIATION( type, name ) \
TEUCHOS_UNIT_TEST_TEMPLATE_3_INSTANT( type, name, int, int, float ) \
TEUCHOS_UNIT_TEST_TEMPLATE_3_INSTANT( type, name, int, int, double )
//---------------------------------------------------------------------------//
// Testing Functions.
//---------------------------------------------------------------------------//
// Create the testing cell (unit sphere)
template<typename Cell>
void createTestingCell( Teuchos::RCP<Cell> &cell_ptr )
{
typedef typename Cell::surfaceOrdinalType ordinalType;
typedef typename Cell::scalarType scalarType;
typedef Geometry::Surface<ordinalType,scalarType> Surface;
// Create the cell definition
std::string cell_definition( "-1" );
// Create the surface map
std::map<ordinalType,Teuchos::RCP<Surface> > surface_map;
// Create the spherical surface
Teuchos::RCP<Surface> surface_ptr( new Surface( 1,
1, 1, 1,
0, 0, 0,
-1 ) );
surface_map[1] = surface_ptr;
// Create the cell
cell_ptr.reset( new Cell( 0, cell_definition, surface_map ) );
}
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that a cell's volume can be numerically integrated
TEUCHOS_UNIT_TEST_TEMPLATE_3_DECL( CellBoundingBox,
calculateCellVolume,
CellOrdinalType,
OrdinalType,
ScalarType )
{
typedef Geometry::Cell<CellOrdinalType,OrdinalType,ScalarType> Cell;
typedef Teuchos::ScalarTraits<ScalarType> ST;
// Create a unit sphere
Teuchos::RCP<Cell> unit_sphere;
createTestingCell( unit_sphere );
// Create a bounding box for the unit sphere
Geometry::CellBoundingBox<Cell>
unit_sphere_bounding_box( unit_sphere, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0 );
// Initialize the random number generator
Utility::RandomNumberGenerator::initialize();
// Calculate the cell volume
unit_sphere_bounding_box.calculateCellVolume();
// Reference cell volume
ScalarType ref_unit_sphere_vol = 4.0/3.0*Utility::PhysicalConstants::pi;
TEST_FLOATING_EQUALITY( unit_sphere->getVolume(),
ref_unit_sphere_vol,
static_cast<ScalarType>( 1e-3 ) );
}
UNIT_TEST_INSTANTIATION( CellBoundingBox, calculateCellVolume );
//---------------------------------------------------------------------------//
// end tstCellBoundingBox.cpp
//---------------------------------------------------------------------------//
| 31.69697 | 79 | 0.586679 | [
"geometry"
] |
66ba0c19a9d2970a4ad45e588efad5b94ee54028 | 19,720 | cpp | C++ | Example/Apns2Client.cpp | JiekeZhu/Apn2Client | 42973f6d6f0bc2b17896c992bd33bc80c3612877 | [
"MIT"
] | 5 | 2017-07-11T05:38:15.000Z | 2022-01-11T14:48:46.000Z | Example/Apns2Client.cpp | JiekeZhu/Apn2Client | 42973f6d6f0bc2b17896c992bd33bc80c3612877 | [
"MIT"
] | 1 | 2017-07-11T10:17:40.000Z | 2017-07-12T01:05:40.000Z | Example/Apns2Client.cpp | JiekeZhu/Apn2Client | 42973f6d6f0bc2b17896c992bd33bc80c3612877 | [
"MIT"
] | 3 | 2017-06-12T08:24:57.000Z | 2021-08-16T06:28:08.000Z | #include "Apns2Client.h"
#include <time.h>
#include <vector>
#define MAX_MSGSIZE (16 * 1024)
#define BLOCK_SECONDS (30)
#define INBUFF_SIZE (64 * 1024)
#define OUTBUFF_SIZE (64 * 1024)
#if _WIN32
#pragma comment(lib, "ws2_32.lib")
#endif
int PrivateKeyPassphraseCallback(char* pBuf, int size, int flag, void* userData)
{
return Apns2Client::Instance()->OnPrivateKeyPassphraseCallback(pBuf, size, flag, userData);
}
#pragma region Nghttp2 callbacks.
/*
* The implementation of nghttp2_send_callback type. Here we write
* |data| with size |length| to the network and return the number of
* bytes actually written. See the documentation of
* nghttp2_send_callback for the details.
*/
ssize_t Nghttp2SendCallback(nghttp2_session *session, const uint8_t *data, size_t length, int flags, void *user_data)
{
Apns2Client* sender = (Apns2Client*)user_data;
return sender->OnNghttp2SendCallback(session, data, length, flags, user_data);
}
/*
* The implementation of nghttp2_recv_callback type. Here we read data
* from the network and write them in |buf|. The capacity of |buf| is
* |length| bytes. Returns the number of bytes stored in |buf|. See
* the documentation of nghttp2_recv_callback for the details.
*/
ssize_t Nghttp2ReceiveCallback(nghttp2_session *session, uint8_t *buf, size_t length, int flags, void *user_data)
{
Apns2Client* sender = (Apns2Client*)user_data;
return sender->OnNghttp2ReceiveCallback(session, buf, length, flags, user_data);
}
static int Nghttp2OnFrameSendCallback(nghttp2_session *session, const nghttp2_frame *frame, void *user_data)
{
size_t i;
switch (frame->hd.type)
{
case NGHTTP2_HEADERS:
if (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id))
{
const nghttp2_nv *nva = frame->headers.nva;
printf("[INFO] C ----------------------------> S (HEADERS)\n");
for (i = 0; i < frame->headers.nvlen; ++i)
{
fwrite(nva[i].name, nva[i].namelen, 1, stdout);
printf(": ");
fwrite(nva[i].value, nva[i].valuelen, 1, stdout);
printf("\n");
}
}
break;
case NGHTTP2_RST_STREAM:
printf("[INFO] C ----------------------------> S (RST_STREAM)\n");
break;
case NGHTTP2_GOAWAY:
printf("[INFO] C ----------------------------> S (GOAWAY)\n");
break;
}
return 0;
}
static int Nghttp2OnFrameReceiveCallback(nghttp2_session *session, const nghttp2_frame *frame, void *user_data)
{
switch (frame->hd.type)
{
case NGHTTP2_HEADERS:
if (frame->headers.cat == NGHTTP2_HCAT_RESPONSE)
{
Apns2Client* sender = (Apns2Client*)user_data;//nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
if (sender)
{
printf("[INFO] C <---------------------------- S (HEADERS end)\n");
}
}
else
{
printf("other header: %d", frame->headers.cat);
}
break;
case NGHTTP2_RST_STREAM:
printf("[INFO] C <---------------------------- S (RST_STREAM)\n");
break;
case NGHTTP2_GOAWAY:
printf("[INFO] C <---------------------------- S (GOAWAY)\n");
break;
}
return 0;
}
static int Nghttp2OnHeaderCallback(nghttp2_session *session, const nghttp2_frame *frame,
const uint8_t *name, size_t namelen, const uint8_t *value, size_t valuelen, uint8_t flags, void *user_data)
{
if (frame->hd.type == NGHTTP2_HEADERS)
{
fwrite(name, namelen, 1, stdout);
printf(": ");
fwrite(value, valuelen, 1, stdout);
printf("\n");
}
return 0;
}
static int Nghttp2OnBeginHeadersCallback(nghttp2_session *session, const nghttp2_frame *frame, void *user_data)
{
printf("[INFO] C <---------------------------- S (HEADERS begin)\n");
return 0;
}
/*
* The implementation of nghttp2_on_stream_close_callback type. We use
* this function to know the response is fully received. Since we just
* fetch 1 resource in this program, after reception of the response,
* we submit GOAWAY and close the session.
*/
static int Nghttp2OnStreamCloseCallback(nghttp2_session *session, int32_t stream_id, uint32_t error_code, void *user_data)
{
Apns2Client* sender = (Apns2Client*)user_data;
return sender->OnNghttp2StreamCloseCallback(session, stream_id, error_code, user_data);
}
/*
* The implementation of nghttp2_on_data_chunk_recv_callback type. We
* use this function to print the received response body.
*/
static int Nghttp2OnDataChunkRecvCallback(nghttp2_session *session, uint8_t flags, int32_t stream_id, const uint8_t *data, size_t len, void *user_data)
{
printf("%s\n", __FUNCTION__);
char buf[1024] = { 0 };
memcpy(buf, data, len);
buf[len] = 0;
printf("%s\n", buf);
return 0;
}
ssize_t Nghttp2DataProviderReadCallback(nghttp2_session *session, int32_t stream_id,
uint8_t *buf, size_t length, uint32_t *data_flags, nghttp2_data_source *source, void *user_data)
{
Apns2Client* sender = (Apns2Client*)user_data;
return sender->OnNghttp2DataProviderReadcallback(session, stream_id, buf, length, data_flags, source, user_data);
}
#pragma endregion //Nghttp2 callbacks.
Apns2Client::Apns2Client()
{
_socket = INVALID_SOCKET;
_sslContext = 0;
_ssl = 0;
_nghttp2Session = 0;
_isNghttp2StreamClosed = false;
_privateKeyPath = GetApplicationPath() + "NotificationAppKey.pem";
_certificatePath = GetApplicationPath() + "NotificationApp.pem";
_password = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // TODO: Replace this with your password.
}
Apns2Client::~Apns2Client()
{
Release();
}
Apns2Client* Apns2Client::Instance()
{
static Apns2Client Apns2ClientInstance;
return &Apns2ClientInstance;
}
bool Apns2Client::Init()
{
bool result = false;
do
{
if (!InitSocket("api.development.push.apple.com", 443))
break;
if (!InitSSL())
break;
if (!InitNghttp2())
break;
result = true;
} while (false);
return result;
}
void Apns2Client::Release()
{
ReleaseNghttp2();
ReleaseSSL();
ReleaseSocket();
}
bool Apns2Client::InitSocket(const char* host, int port, bool keepAlive /*= false*/)
{
if (_socket != INVALID_SOCKET)
return true;
bool result = false;
SOCKET socketResult = INVALID_SOCKET;
do
{
struct hostent *remoteHost;
struct in_addr remoteAddr;
std::vector<std::string> remoteAddrs;
if (!host)
{
break;
}
WSADATA wsaData;
WORD version = MAKEWORD(2, 0);
int ret = WSAStartup(version, &wsaData);
if (ret)
{
break;
}
remoteHost = gethostbyname(host);
if (remoteHost == nullptr)
{
int dwError = WSAGetLastError();
if (dwError != 0)
{
if (dwError == WSAHOST_NOT_FOUND)
{
printf("Host not found\n");
break;
}
else if (dwError == WSANO_DATA)
{
printf("No data record found\n");
break;
}
else
{
printf("Function failed with error: %ld\n", dwError);
break;
}
}
}
else
{
if (remoteHost->h_addrtype == AF_INET)
{
int i = 0;
while (remoteHost->h_addr_list[i] != 0)
{
remoteAddr.s_addr = *(u_long *)remoteHost->h_addr_list[i++];
remoteAddrs.push_back(inet_ntoa(remoteAddr));
printf("\tIPv4 Address %d: %s\n", i, inet_ntoa(remoteAddr));
}
}
else if (remoteHost->h_addrtype == AF_INET6)
{
printf("\tRemotehost is an IPv6 address\n");
break;
}
}
unsigned long addr = INADDR_NONE;
for (auto& remoteAddr : remoteAddrs)
{
unsigned long remote = inet_addr(remoteAddr.c_str());
if (remote != INADDR_NONE)
{
addr = remote;
break;
}
}
if (addr == INADDR_NONE)
{
break;
}
socketResult = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socketResult == INVALID_SOCKET)
{
break;
}
if (keepAlive)
{
int optval = 1;
if (setsockopt(socketResult, SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, sizeof(optval)))
{
break;
}
}
sockaddr_in addr_in;
memset((void*)&addr_in, 0, sizeof(addr_in));
addr_in.sin_family = AF_INET;
addr_in.sin_port = htons(port);
addr_in.sin_addr.s_addr = addr;
if (connect(socketResult, (sockaddr *)&addr_in, sizeof(addr_in)) == SOCKET_ERROR)
{
break;
}
/*timeval timeout;
timeout.tv_sec = BLOCK_SECONDS;
timeout.tv_usec = 0;
fd_set writeset, exceptset;
FD_ZERO(&writeset);
FD_ZERO(&exceptset);
FD_SET(socketResult, &writeset);
FD_SET(socketResult, &exceptset);
if (select(FD_SETSIZE, NULL, &writeset, &exceptset, &timeout) <= 0)
{
break;
}
else
{
if (FD_ISSET(socketResult, &exceptset))
{
break;
}
}
struct linger ling;
ling.l_onoff = 1;
ling.l_linger = 500;
setsockopt(socketResult, SOL_SOCKET, SO_LINGER, (const char*)&ling, sizeof(ling));*/
// switch to async mode.
/*
#if _WIN32
DWORD mode = 1;
if (ioctlsocket(socketResult, FIONBIO, &mode) == SOCKET_ERROR)
{
break;
}
#else
fcntl(m_Socket, F_SETFL, O_NONBLOCK);
#endif*/
result = true;
} while (false);
if (!result)
{
if (socketResult != INVALID_SOCKET)
{
closesocket(socketResult);
WSACleanup();
socketResult = INVALID_SOCKET;
}
}
_socket = socketResult;
return result;
}
void Apns2Client::ReleaseSocket()
{
if (_socket == INVALID_SOCKET)
return;
closesocket(_socket);
WSACleanup();
_socket = INVALID_SOCKET;
}
bool Apns2Client::InitSSL()
{
if (_ssl != nullptr)
return true;
if (!InitSSLContext(_privateKeyPath, _certificatePath))
return false;
if (!ConnectSSL())
return false;
return true;
}
int Apns2Client::OnPrivateKeyPassphraseCallback(char* pBuf, int size, int flag, void* userData)
{
std::string pwd = _password;
strncpy(pBuf, (char *)(pwd.c_str()), size);
pBuf[size - 1] = '\0';
if (size > pwd.length())
{
size = (int)pwd.length();
}
return size;
}
bool Apns2Client::InitSSLContext(const std::string& privateKeyPath, const std::string& certificatePath)
{
if (_sslContext != nullptr)
return true;
static bool isSSLInitialized = false;
if (!isSSLInitialized)
{
SSL_library_init();
SSL_load_error_strings();
isSSLInitialized = true;
}
int errorCode = 0;
SSL_CTX* sslContext = 0;
do
{
sslContext = SSL_CTX_new(SSLv23_client_method());
SSL_CTX_set_options(sslContext, SSL_OP_ALL);
SSL_CTX_set_mode(sslContext, SSL_MODE_AUTO_RETRY);
SSL_CTX_set_session_cache_mode(sslContext, SSL_SESS_CACHE_OFF);
SSL_CTX_set_default_passwd_cb(sslContext, PrivateKeyPassphraseCallback);
errorCode = SSL_CTX_use_PrivateKey_file(sslContext, privateKeyPath.c_str(), SSL_FILETYPE_PEM);
if (errorCode != 1)
{
break;
}
errorCode = SSL_CTX_use_certificate_chain_file(sslContext, certificatePath.c_str());
if (errorCode != 1)
{
break;
}
_sslContext = sslContext;
} while (false);
if (errorCode != 1 && sslContext != 0)
{
SSL_CTX_free(sslContext);
sslContext = 0;
}
return _sslContext != nullptr;
}
void Apns2Client::ReleaseSSLContext()
{
if (_sslContext != nullptr)
{
SSL_CTX_free(_sslContext);
_sslContext = nullptr;
}
}
bool Apns2Client::ConnectSSL()
{
if (_ssl != nullptr)
return true;
bool result = false;
SSL* ssl = nullptr;
BIO* bio = nullptr;
do
{
bio = BIO_new(BIO_s_socket());
if (bio == nullptr)
{
printf("Cannot create SSL BIO object");
break;
}
BIO_set_fd(bio, static_cast<int>(_socket), BIO_NOCLOSE);
ssl = SSL_new(_sslContext);
if (ssl == nullptr)
{
printf("Cannot create SSL object");
break;
}
SSL_set_bio(ssl, bio, bio);
int ret = SSL_connect(ssl);
HandlerSSLError(ssl, ret);
result = true;
_ssl = ssl;
} while (false);
if (!result)
{
if (bio != nullptr)
BIO_free(bio);
if (ssl != nullptr)
SSL_free(ssl);
_ssl = nullptr;
}
return result;
}
int Apns2Client::HandlerSSLError(SSL* ssl, int rc)
{
if (rc > 0) return rc;
int sslError = SSL_get_error(ssl, rc);
int error = WSAGetLastError();
switch (sslError)
{
case SSL_ERROR_ZERO_RETURN:
return 0;
case SSL_ERROR_WANT_READ:
return SSL_ERROR_WANT_READ; //SecureStreamSocket::ERR_SSL_WANT_READ;
case SSL_ERROR_WANT_WRITE:
return SSL_ERROR_WANT_WRITE; //SecureStreamSocket::ERR_SSL_WANT_WRITE;
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_ACCEPT:
case SSL_ERROR_WANT_X509_LOOKUP:
// these should not occur
#if _DEBUG
throw;
#endif
return rc;
case SSL_ERROR_SYSCALL:
// fallthrough
default:
{
long lastError = ERR_get_error();
if (lastError == 0)
{
}
else
{
char buffer[256];
ERR_error_string_n(lastError, buffer, sizeof(buffer));
std::string msg(buffer);
}
}
break;
}
return rc;
}
void Apns2Client::ReleaseSSL()
{
if (_ssl)
{
SSL_shutdown(_ssl);
SSL_free(_ssl);
_ssl = 0;
}
ReleaseSSLContext();
}
bool Apns2Client::InitNghttp2()
{
if (_nghttp2Session != nullptr)
return true;
bool result = false;
nghttp2_session_callbacks *callbacks = nullptr;
do
{
int rv;
nghttp2_session_callbacks *callbacks;
rv = nghttp2_session_callbacks_new(&callbacks);
if (rv != 0)
{
fprintf(stderr, "nghttp2_session_callbacks_new");
break;
}
/*
* Setup callback functions. nghttp2 API offers many callback
* functions, but most of them are optional. The send_callback is
* always required. Since we use nghttp2_session_recv(), the
* recv_callback is also required.
*/
nghttp2_session_callbacks_set_send_callback(callbacks, Nghttp2SendCallback);
nghttp2_session_callbacks_set_recv_callback(callbacks, Nghttp2ReceiveCallback);
nghttp2_session_callbacks_set_on_frame_send_callback(callbacks, Nghttp2OnFrameSendCallback);
nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks, Nghttp2OnFrameReceiveCallback);
nghttp2_session_callbacks_set_on_header_callback(callbacks, Nghttp2OnHeaderCallback);
nghttp2_session_callbacks_set_on_begin_headers_callback(callbacks, Nghttp2OnBeginHeadersCallback);
nghttp2_session_callbacks_set_on_stream_close_callback(callbacks, Nghttp2OnStreamCloseCallback);
nghttp2_session_callbacks_set_on_data_chunk_recv_callback(callbacks, Nghttp2OnDataChunkRecvCallback);
rv = nghttp2_session_client_new(&_nghttp2Session, callbacks, this);
if (rv != 0)
{
fprintf(stderr, "nghttp2_session_client_new");
break;
}
rv = nghttp2_submit_settings(_nghttp2Session, NGHTTP2_FLAG_NONE, NULL, 0);
if (rv != 0)
{
fprintf(stderr, "nghttp2_submit_settings %d", rv);
break;
}
result = true;
} while (false);
if (!result)
{
if (callbacks != nullptr)
nghttp2_session_callbacks_del(callbacks);
if (_nghttp2Session != nullptr)
{
nghttp2_session_del(_nghttp2Session);
_nghttp2Session = nullptr;
}
}
return result;
}
void Apns2Client::ReleaseNghttp2()
{
if (_nghttp2Session)
{
nghttp2_session_del(_nghttp2Session);
_nghttp2Session = 0;
}
}
ssize_t Apns2Client::OnNghttp2SendCallback(nghttp2_session *session, const uint8_t *data, size_t length, int flags, void *user_data)
{
Apns2Client* sender = (Apns2Client*)user_data;
ERR_clear_error();
int rv = SSL_write(sender->_ssl, data, (int)length);
if (rv <= 0)
{
int err = SSL_get_error(_ssl, rv);
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ)
{
rv = NGHTTP2_ERR_WOULDBLOCK;
}
else
{
rv = NGHTTP2_ERR_CALLBACK_FAILURE;
}
}
return rv;
}
ssize_t Apns2Client::OnNghttp2ReceiveCallback(nghttp2_session *session, uint8_t *buf, size_t length, int flags, void *user_data)
{
Apns2Client* sender = (Apns2Client*)user_data;
ERR_clear_error();
int rv = 0;
if (!sender->_isNghttp2StreamClosed && sender->_nghttp2Session != nullptr)
{
rv = SSL_read(sender->_ssl, buf, length);
}
if (rv < 0)
{
int err = SSL_get_error(_ssl, rv);
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ)
{
rv = NGHTTP2_ERR_WOULDBLOCK;
}
else
{
rv = NGHTTP2_ERR_CALLBACK_FAILURE;
}
}
else if (rv == 0)
{
rv = NGHTTP2_ERR_EOF;
}
return rv;
}
int Apns2Client::OnNghttp2StreamCloseCallback(nghttp2_session *session, int32_t stream_id, uint32_t error_code, void *user_data)
{
Apns2Client* apns2Client = (Apns2Client*)user_data;//nghttp2_session_get_stream_user_data(session, stream_id);
if (apns2Client)
{
/*int rv;
rv = nghttp2_session_terminate_session(session, NGHTTP2_NO_ERROR);
if (rv != 0)
{
diec("nghttp2_session_terminate_session", rv);
}*/
apns2Client->_isNghttp2StreamClosed = true;
}
return 0;
}
ssize_t Apns2Client::OnNghttp2DataProviderReadcallback(nghttp2_session *session, int32_t stream_id,
uint8_t *buf, size_t length, uint32_t *data_flags, nghttp2_data_source *source, void *user_data)
{
int rv = 0;
Apns2Client* apns2Client = (Apns2Client*)nghttp2_session_get_stream_user_data(session, stream_id);
if (apns2Client)
{
memcpy(buf, apns2Client->_notificationMessage.c_str(), apns2Client->_notificationMessage.length());
*data_flags |= NGHTTP2_DATA_FLAG_EOF;
rv = (int)apns2Client->_notificationMessage.length();
printf("[INFO] C ----------------------------> S (DATA post body)\n");
printf("%s\n", apns2Client->_notificationMessage.c_str());
}
return rv;
}
std::string Apns2Client::GetApplicationPath()
{
static std::string applicationPath;
if (applicationPath.empty())
{
char path[1024] = { 0 };
GetModuleFileNameA(0, path, sizeof(path) / sizeof(char));
applicationPath = path;
applicationPath = applicationPath.substr(0, applicationPath.rfind('\\') + 1);
}
return applicationPath;
}
#include <Objbase.h>
std::string Apns2Client::CreateGUID()
{
char chBuf[48] = { 0 };
GUID guid;
if (S_OK == CoCreateGuid(&guid))
{
sprintf(chBuf, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
}
return std::string(chBuf);
}
#define CharArrayToNV(name, value) \
{ \
(uint8_t *) name, (uint8_t *)value, sizeof(name) - 1, sizeof(value) - 1, NGHTTP2_NV_FLAG_NONE \
}
#define StringToNV(name, value) \
{ \
(uint8_t *)name, (uint8_t *)value, sizeof(name) - 1, strlen(value), NGHTTP2_NV_FLAG_NONE \
}
bool Apns2Client::PushNotification(const std::string& appBundleId, const std::string& deviceToken, const std::string& notificationMessage)
{
if (appBundleId.empty() || deviceToken.empty() || notificationMessage.empty())
return false;
if (!Init())
return false;
_appBundleId = appBundleId;
_deviceToken = deviceToken;
// {\"aps\":{\"alert\":\"nghttp2 test.\",\"sound\":\"default\"}}
_notificationMessage = notificationMessage;
std::string guid = CreateGUID();
std::string path = "/3/device/" + deviceToken;
int32_t stream_id;
nghttp2_nv nva[] =
{
CharArrayToNV(":method", "POST"),
StringToNV(":path", path.c_str()),
StringToNV("apns-topic", appBundleId.c_str()),
StringToNV("apns-id", guid.c_str())
};
nghttp2_data_provider data_prd;
data_prd.source.ptr = (void*)this;
data_prd.read_callback = Nghttp2DataProviderReadCallback;
_isNghttp2StreamClosed = false;
stream_id = nghttp2_submit_request(_nghttp2Session, nullptr, nva, sizeof(nva) / sizeof(nva[0]), &data_prd, this);
if (stream_id < 0)
return false;
int rv = 0;
if (nghttp2_session_want_write(_nghttp2Session))
{
rv = nghttp2_session_send(_nghttp2Session);
}
if (nghttp2_session_want_read(_nghttp2Session))
{
rv = nghttp2_session_recv(_nghttp2Session);
}
return stream_id >= 0;
}
int main(int argc, const char *argv[])
{
Apns2Client::Instance()->PushNotification("com.xxx.notificationapp", // TODO: Replace this with your app's bunld id.
"72bf24178967ee4359bc7de2aeabXXXXX8d594f2b2459acc43a286e1db7e9XX", // TODO: Replace this with your user's device token.
"{\"aps\":{\"alert\":\"nghttp2 test.\",\"sound\":\"default\"}}");
Apns2Client::Instance()->PushNotification("com.xxx.notificationapp", // TODO: Replace this with your app's bunld id.
"72bf24178967ee4359bc7de2aeabXXXXX8d594f2b2459acc43a286e1db7e9XX", // TODO: Replace this with your user's device token.
"{ \"aps\" : { \"alert\" : \"Hi U\\r\\n This is your gift X!\", \"badge\" : 1, \"sound\" : \"blank.aiff\" } }");
return 0;
} | 24.285714 | 152 | 0.69929 | [
"object",
"vector"
] |
66c032a2e7c5246a224772b9f5f93f89f62363a6 | 1,538 | cpp | C++ | data-mining/cluster-analysis/assignment/clustering-data/c++/src/kmeans_main.cpp | 4979/courses | dd9efa0a6b60cead833f36a6bfa518dd4fece17f | [
"Apache-2.0"
] | null | null | null | data-mining/cluster-analysis/assignment/clustering-data/c++/src/kmeans_main.cpp | 4979/courses | dd9efa0a6b60cead833f36a6bfa518dd4fece17f | [
"Apache-2.0"
] | null | null | null | data-mining/cluster-analysis/assignment/clustering-data/c++/src/kmeans_main.cpp | 4979/courses | dd9efa0a6b60cead833f36a6bfa518dd4fece17f | [
"Apache-2.0"
] | null | null | null | #include "clustering/k_means.h"
#include "evaluation/supervised_evaluation.h"
using std::cout;
using std::endl;
using std::vector;
using std::string;
vector< vector<double> > loadPoints(string filename)
{
FILE* in = fopen(filename.c_str(), "r");
int n, d;
fscanf(in, "%d%d", &n, &d);
vector< vector<double> > data(n, vector<double>(d, 0));
for (int i = 0; i < n; ++ i) {
for (int j = 0; j < d; ++ j) {
fscanf(in, "%lf", &data[i][j]);
}
}
fclose(in);
return data;
}
vector<int> loadClusters(string filename)
{
FILE* in = fopen(filename.c_str(), "r");
int n;
fscanf(in, "%d", &n);
vector<int> clusters(n, 0);
for (int i = 0; i < n; ++ i) {
fscanf(in, "%d", &clusters[i]);
}
fclose(in);
return clusters;
}
int main(int argc, char* argv[])
{
if (argc != 3) {
cout << "[usage] <data-file> <ground-truth-file>" << endl;
exit(-1);
}
string dataFilename = argv[1];
string groundtruthFilename = argv[2];
// load data
vector< vector<double> > data = loadPoints(dataFilename);
vector<int> groundtruth = loadClusters(groundtruthFilename);
vector< vector<double> > centers;
centers.push_back(data[0]);
centers.push_back(data[1]);
vector<int>result = KMeans::kmeans(data, centers);
cout << "Purity = " << SupervisedEvaluation::purity(groundtruth, result) << endl;
cout << "NMI = " << SupervisedEvaluation::NMI(groundtruth, result) << endl;
return 0;
}
| 24.412698 | 85 | 0.574122 | [
"vector"
] |
66c30a64e2a6b3b85d336595723b75cece1412ad | 14,538 | cpp | C++ | src/rocksample.cpp | secury/CC-POMCP | d8e76de20b566da9fde922232010d150498c7976 | [
"MIT"
] | 8 | 2018-12-20T08:07:14.000Z | 2021-12-16T22:30:49.000Z | src/rocksample.cpp | secury/CC-POMCP | d8e76de20b566da9fde922232010d150498c7976 | [
"MIT"
] | 1 | 2018-11-05T12:47:28.000Z | 2018-11-05T12:47:28.000Z | src/rocksample.cpp | secury/CC-POMCP | d8e76de20b566da9fde922232010d150498c7976 | [
"MIT"
] | 2 | 2020-04-21T11:47:06.000Z | 2021-05-28T06:42:15.000Z | #include "rocksample.h"
#include "utils.h"
using namespace std;
using namespace UTILS;
ROCKSAMPLE::ROCKSAMPLE(int size, int rocks)
: Grid(size, size),
Size(size),
NumRocks(rocks),
SmartMoveProb(0.95),
UncertaintyCount(0)
{
NumActions = NumRocks + 5;
NumObservations = 3;
RewardRange = 20;
Discount = 0.95;
if (size == 5 && rocks == 5)
Init_5_5();
else if (size == 5 && rocks == 7)
Init_5_7();
else if (size == 7 && rocks == 8)
Init_7_8();
else if (size == 11 && rocks == 11)
Init_11_11();
else
InitGeneral();
}
void ROCKSAMPLE::InitGeneral()
{
HalfEfficiencyDistance = 20;
StartPos = COORD(0, Size / 2);
RandomSeed(0);
Grid.SetAllValues(-1);
for (int i = 0; i < NumRocks; ++i)
{
COORD pos;
do
{
pos = COORD(Random(Size), Random(Size));
}
while (Grid(pos) >= 0);
Grid(pos) = i;
RockPos.push_back(pos);
}
}
void ROCKSAMPLE::Init_5_5()
{
cout << "Using special layout for rocksample(5, 5)" << endl;
COORD rocks[] =
{
COORD(2, 4),
COORD(0, 4),
COORD(3, 3),
COORD(2, 2),
COORD(4, 1)
};
HalfEfficiencyDistance = 4;
StartPos = COORD(0, 2);
Grid.SetAllValues(-1);
for (int i = 0; i < NumRocks; ++i)
{
Grid(rocks[i]) = i;
RockPos.push_back(rocks[i]);
}
}
void ROCKSAMPLE::Init_5_7()
{
cout << "Using special layout for rocksample(5, 7)" << endl;
COORD rocks[] =
{
COORD(1, 0),
COORD(2, 1),
COORD(1, 2),
COORD(2, 2),
COORD(4, 2),
COORD(0, 3),
COORD(3, 4)
};
HalfEfficiencyDistance = 20;
StartPos = COORD(0, 2);
Grid.SetAllValues(-1);
for (int i = 0; i < NumRocks; ++i)
{
Grid(rocks[i]) = i;
RockPos.push_back(rocks[i]);
}
}
void ROCKSAMPLE::Init_7_8()
{
// Equivalent to RockSample_7_8.pomdpx
cout << "Using special layout for rocksample(7, 8)" << endl;
COORD rocks[] =
{
COORD(2, 0),
COORD(0, 1),
COORD(3, 1),
COORD(6, 3),
COORD(2, 4),
COORD(3, 4),
COORD(5, 5),
COORD(1, 6)
};
HalfEfficiencyDistance = 20;
StartPos = COORD(0, 3);
Grid.SetAllValues(-1);
for (int i = 0; i < NumRocks; ++i)
{
Grid(rocks[i]) = i;
RockPos.push_back(rocks[i]);
}
}
void ROCKSAMPLE::Init_11_11()
{
// Equivalent to RockSample_11_11.pomdp(x)
cout << "Using special layout for rocksample(11, 11)" << endl;
COORD rocks[] =
{
COORD(0, 3),
COORD(0, 7),
COORD(1, 8),
COORD(2, 4),
COORD(3, 3),
COORD(3, 8),
COORD(4, 3),
COORD(5, 8),
COORD(6, 1),
COORD(9, 3),
COORD(9, 9)
};
HalfEfficiencyDistance = 20;
StartPos = COORD(0, 5);
Grid.SetAllValues(-1);
for (int i = 0; i < NumRocks; ++i)
{
Grid(rocks[i]) = i;
RockPos.push_back(rocks[i]);
}
}
STATE* ROCKSAMPLE::Copy(const STATE& state) const
{
const ROCKSAMPLE_STATE& rockstate = safe_cast<const ROCKSAMPLE_STATE&>(state);
ROCKSAMPLE_STATE* newstate = MemoryPool.Allocate();
*newstate = rockstate;
return newstate;
}
void ROCKSAMPLE::Validate(const STATE& state) const
{
const ROCKSAMPLE_STATE& rockstate = safe_cast<const ROCKSAMPLE_STATE&>(state);
assert(Grid.Inside(rockstate.AgentPos));
}
STATE* ROCKSAMPLE::CreateStartState() const
{
ROCKSAMPLE_STATE* rockstate = MemoryPool.Allocate();
rockstate->AgentPos = StartPos;
rockstate->Rocks.clear();
for (int i = 0; i < NumRocks; i++)
{
ROCKSAMPLE_STATE::ENTRY entry;
entry.Collected = false;
entry.Valuable = Bernoulli(0.5);
entry.Count = 0;
entry.Measured = 0;
entry.ProbValuable = 0.5;
entry.LikelihoodValuable = 1.0;
entry.LikelihoodWorthless = 1.0;
rockstate->Rocks.push_back(entry);
}
rockstate->Target = SelectTarget(*rockstate);
return rockstate;
}
void ROCKSAMPLE::FreeState(STATE* state) const
{
ROCKSAMPLE_STATE* rockstate = safe_cast<ROCKSAMPLE_STATE*>(state);
MemoryPool.Free(rockstate);
}
bool ROCKSAMPLE::Step(STATE& state, int action,
int& observation, RC& rewardcost) const
{
ROCKSAMPLE_STATE& rockstate = safe_cast<ROCKSAMPLE_STATE&>(state);
rewardcost.R = 0;
rewardcost.C = 0; // Default cost is 0
observation = E_NONE;
if (action < E_SAMPLE) // move
{
switch (action)
{
case COORD::E_EAST:
if (rockstate.AgentPos.X + 1 < Size)
{
rockstate.AgentPos.X++;
break;
}
else
{
rewardcost.R = +10;
return true;
}
case COORD::E_NORTH:
if (rockstate.AgentPos.Y + 1 < Size)
rockstate.AgentPos.Y++;
else
rewardcost.R = -100;
break;
case COORD::E_SOUTH:
if (rockstate.AgentPos.Y - 1 >= 0)
rockstate.AgentPos.Y--;
else
rewardcost.R = -100;
break;
case COORD::E_WEST:
if (rockstate.AgentPos.X - 1 >= 0)
rockstate.AgentPos.X--;
else
rewardcost.R = -100;
break;
}
}
if (action == E_SAMPLE) // sample
{
int rock = Grid(rockstate.AgentPos);
if (rock >= 0 && !rockstate.Rocks[rock].Collected)
{
rockstate.Rocks[rock].Collected = true;
if (rockstate.Rocks[rock].Valuable)
rewardcost.R = +10;
else
rewardcost.R = -10;
}
else
{
rewardcost.R = -100;
}
}
if (action > E_SAMPLE) // check
{
rewardcost.C = 1;
int rock = action - E_SAMPLE - 1;
assert(rock < NumRocks);
observation = GetObservation(rockstate, rock);
rockstate.Rocks[rock].Measured++;
double distance = COORD::EuclideanDistance(rockstate.AgentPos, RockPos[rock]);
double efficiency = (1 + pow(2, -distance / HalfEfficiencyDistance)) * 0.5;
if (observation == E_GOOD)
{
rockstate.Rocks[rock].Count++;
rockstate.Rocks[rock].LikelihoodValuable *= efficiency;
rockstate.Rocks[rock].LikelihoodWorthless *= 1.0 - efficiency;
}
else
{
rockstate.Rocks[rock].Count--;
rockstate.Rocks[rock].LikelihoodWorthless *= efficiency;
rockstate.Rocks[rock].LikelihoodValuable *= 1.0 - efficiency;
}
double denom = (0.5 * rockstate.Rocks[rock].LikelihoodValuable) +
(0.5 * rockstate.Rocks[rock].LikelihoodWorthless);
rockstate.Rocks[rock].ProbValuable = (0.5 * rockstate.Rocks[rock].LikelihoodValuable) / denom;
}
if (rockstate.Target < 0 || rockstate.AgentPos == RockPos[rockstate.Target])
rockstate.Target = SelectTarget(rockstate);
if (rewardcost.R < 0) {
rewardcost.C = 1;
}
assert(rewardcost.R != -100);
return false;
}
bool ROCKSAMPLE::LocalMove(STATE& state, const HISTORY& history,
int stepObs, const STATUS& status) const
{
ROCKSAMPLE_STATE& rockstate = safe_cast<ROCKSAMPLE_STATE&>(state);
int rock = Random(NumRocks);
rockstate.Rocks[rock].Valuable = !rockstate.Rocks[rock].Valuable;
if (history.Back().Action > E_SAMPLE) // check rock
{
rock = history.Back().Action - E_SAMPLE - 1;
int realObs = history.Back().Observation;
// Condition new state on real observation
int newObs = GetObservation(rockstate, rock);
if (newObs != realObs)
return false;
// Update counts to be consistent with real observation
if (realObs == E_GOOD && stepObs == E_BAD)
rockstate.Rocks[rock].Count += 2;
if (realObs == E_BAD && stepObs == E_GOOD)
rockstate.Rocks[rock].Count -= 2;
}
return true;
}
void ROCKSAMPLE::GenerateLegal(const STATE& state, const HISTORY& history,
vector<int>& legal, const STATUS& status) const
{
const ROCKSAMPLE_STATE& rockstate =
safe_cast<const ROCKSAMPLE_STATE&>(state);
if (rockstate.AgentPos.Y + 1 < Size)
legal.push_back(COORD::E_NORTH);
legal.push_back(COORD::E_EAST);
if (rockstate.AgentPos.Y - 1 >= 0)
legal.push_back(COORD::E_SOUTH);
if (rockstate.AgentPos.X - 1 >= 0)
legal.push_back(COORD::E_WEST);
int rock = Grid(rockstate.AgentPos);
if (rock >= 0 && !rockstate.Rocks[rock].Collected)
legal.push_back(E_SAMPLE);
for (rock = 0; rock < NumRocks; ++rock)
if (!rockstate.Rocks[rock].Collected)
legal.push_back(rock + 1 + E_SAMPLE);
}
void ROCKSAMPLE::GeneratePreferred(const STATE& state, const HISTORY& history,
vector<int>& actions, const STATUS& status) const
{
static const bool UseBlindPolicy = false;
if (UseBlindPolicy)
{
actions.push_back(COORD::E_EAST);
return;
}
const ROCKSAMPLE_STATE& rockstate =
safe_cast<const ROCKSAMPLE_STATE&>(state);
// Sample rocks with more +ve than -ve observations
int rock = Grid(rockstate.AgentPos);
if (rock >= 0 && !rockstate.Rocks[rock].Collected)
{
int total = 0;
for (int t = 0; t < history.Size(); ++t)
{
if (history[t].Action == rock + 1 + E_SAMPLE)
{
if (history[t].Observation == E_GOOD)
total++;
if (history[t].Observation == E_BAD)
total--;
}
}
if (total > 0)
{
actions.push_back(E_SAMPLE);
return;
}
}
// processes the rocks
bool all_bad = true;
bool north_interesting = false;
bool south_interesting = false;
bool west_interesting = false;
bool east_interesting = false;
for (int rock = 0; rock < NumRocks; ++rock)
{
const ROCKSAMPLE_STATE::ENTRY& entry = rockstate.Rocks[rock];
if (!entry.Collected)
{
int total = 0;
for (int t = 0; t < history.Size(); ++t)
{
if (history[t].Action == rock + 1 + E_SAMPLE)
{
if (history[t].Observation == E_GOOD)
total++;
if (history[t].Observation == E_BAD)
total--;
}
}
if (total >= 0)
{
all_bad = false;
if (RockPos[rock].Y > rockstate.AgentPos.Y)
north_interesting = true;
if (RockPos[rock].Y < rockstate.AgentPos.Y)
south_interesting = true;
if (RockPos[rock].X < rockstate.AgentPos.X)
west_interesting = true;
if (RockPos[rock].X > rockstate.AgentPos.X)
east_interesting = true;
}
}
}
// if all remaining rocks seem bad, then head east
if (all_bad)
{
actions.push_back(COORD::E_EAST);
return;
}
// generate a random legal move, with the exceptions that:
// a) there is no point measuring a rock that is already collected
// b) there is no point measuring a rock too often
// c) there is no point measuring a rock which is clearly bad or good
// d) we never sample a rock (since we need to be sure)
// e) we never move in a direction that doesn't take us closer to
// either the edge of the map or an interesting rock
if (rockstate.AgentPos.Y + 1 < Size && north_interesting)
actions.push_back(COORD::E_NORTH);
if (east_interesting)
actions.push_back(COORD::E_EAST);
if (rockstate.AgentPos.Y - 1 >= 0 && south_interesting)
actions.push_back(COORD::E_SOUTH);
if (rockstate.AgentPos.X - 1 >= 0 && west_interesting)
actions.push_back(COORD::E_WEST);
for (rock = 0; rock < NumRocks; ++rock)
{
if (!rockstate.Rocks[rock].Collected &&
rockstate.Rocks[rock].ProbValuable != 0.0 &&
rockstate.Rocks[rock].ProbValuable != 1.0 &&
rockstate.Rocks[rock].Measured < 5 &&
std::abs(rockstate.Rocks[rock].Count) < 2)
{
actions.push_back(rock + 1 + E_SAMPLE);
}
}
}
int ROCKSAMPLE::GetObservation(const ROCKSAMPLE_STATE& rockstate, int rock) const
{
double distance = COORD::EuclideanDistance(rockstate.AgentPos, RockPos[rock]);
double efficiency = (1 + pow(2, -distance / HalfEfficiencyDistance)) * 0.5;
if (Bernoulli(efficiency))
return rockstate.Rocks[rock].Valuable ? E_GOOD : E_BAD;
else
return rockstate.Rocks[rock].Valuable ? E_BAD : E_GOOD;
}
int ROCKSAMPLE::SelectTarget(const ROCKSAMPLE_STATE& rockstate) const
{
int bestDist = Size * 2;
int bestRock = -1;
for (int rock = 0; rock < NumRocks; ++rock)
{
if (!rockstate.Rocks[rock].Collected
&& rockstate.Rocks[rock].Count >= UncertaintyCount)
{
int dist = COORD::ManhattanDistance(rockstate.AgentPos, RockPos[rock]);
if (dist < bestDist)
bestDist = dist;
}
}
return bestRock;
}
void ROCKSAMPLE::DisplayBeliefs(const BELIEF_STATE& beliefState,
std::ostream& ostr) const
{
}
void ROCKSAMPLE::DisplayState(const STATE& state, std::ostream& ostr) const
{
const ROCKSAMPLE_STATE& rockstate = safe_cast<const ROCKSAMPLE_STATE&>(state);
ostr << endl;
for (int x = 0; x < Size + 2; x++)
ostr << "# ";
ostr << endl;
for (int y = Size - 1; y >= 0; y--)
{
ostr << "# ";
for (int x = 0; x < Size; x++)
{
COORD pos(x, y);
int rock = Grid(pos);
const ROCKSAMPLE_STATE::ENTRY& entry = rockstate.Rocks[rock];
if (rockstate.AgentPos == COORD(x, y))
ostr << "* ";
else if (rock >= 0 && !entry.Collected)
ostr << rock << (entry.Valuable ? "$" : "X");
else
ostr << ". ";
}
ostr << "#" << endl;
}
for (int x = 0; x < Size + 2; x++)
ostr << "# ";
ostr << endl;
}
void ROCKSAMPLE::DisplayObservation(const STATE& state, int observation, std::ostream& ostr) const
{
switch (observation)
{
case E_NONE:
break;
case E_GOOD:
ostr << "Observed good" << endl;
break;
case E_BAD:
ostr << "Observed bad" << endl;
break;
}
}
void ROCKSAMPLE::DisplayAction(int action, std::ostream& ostr) const
{
if (action < E_SAMPLE)
ostr << COORD::CompassString[action] << endl;
if (action == E_SAMPLE)
ostr << "Sample" << endl;
if (action > E_SAMPLE)
ostr << "Check " << action - E_SAMPLE << endl;
}
| 26.053763 | 98 | 0.570642 | [
"vector"
] |
66ce94d82241a3147b6344b072d8530de1e4ce42 | 3,969 | cpp | C++ | UVa/UVa_662_Fast Food.cpp | bishoy-magdy/Competitive-Programming | 689daac9aeb475da3c28aba4a69df394c68a9a34 | [
"MIT"
] | 2 | 2020-04-23T17:47:27.000Z | 2020-04-25T19:40:50.000Z | UVa/UVa_662_Fast Food.cpp | bishoy-magdy/Competitive-Programming | 689daac9aeb475da3c28aba4a69df394c68a9a34 | [
"MIT"
] | null | null | null | UVa/UVa_662_Fast Food.cpp | bishoy-magdy/Competitive-Programming | 689daac9aeb475da3c28aba4a69df394c68a9a34 | [
"MIT"
] | 1 | 2020-06-14T20:52:39.000Z | 2020-06-14T20:52:39.000Z | #include<bits/stdc++.h>
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<list>
#include <algorithm>
#include<vector>
#include<set>
#include <cctype>
#include <cstring>
#include <cstdio>
#include<queue>
#include<stack>
#include<bitset>
#include<time.h>
#include<fstream>
/******************************************************/
using namespace std;
/********************define***************************/
#define ll long long
#define ld long double
#define all(v) ((v).begin()), ((v).end())
#define for_(vec) for(int i=0;i<(int)vec.size();i++)
#define lp(j,n) for(int i=j;i<(int)(n);i++)
#define rlp(j,n) for(int i=j;i>=(int)(n);i--)
#define clr(arr,x) memset(arr,x,sizeof(arr))
#define fillstl(arr,X) fill(arr.begin(),arr.end(),X)
#define pb push_back
#define mp make_pair
#define print_vector(X) for(int i=0;i<X.size();i++)
#define ii pair<int,int>
/********************************************************/
typedef vector<int> vi;
typedef vector<pair<int, int> > vii;
typedef vector<vector<int> > vvi;
typedef vector<ll> vl;
/***********************function************************/
int dx[4]= {1,-1,0,0};
int dy[4]= {0,0,1,-1};
void fast()
{
ios_base::sync_with_stdio(NULL);
cin.tie(0);
cout.tie(0);
}
void online_judge()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
}
const int flag_max=0x3f3f3f3f;
const ll OO=2e9+10 ;
const double EPS = (1e-8);
int dcmp(double x, double y)
{
return fabs(x-y) <= EPS ? 0 : x < y ? -1 : 1;
}
ll gcd(ll a, ll b)
{
return !b ? a : gcd(b, a % b);
}
ll lcm(ll a, ll b)
{
return (a / gcd(a, b)) * b;
}
const ll MOD=1e14+7;
ll Power(ll n,ll deg)
{
if(!deg)return 1;
else if(deg & 1) return (Power(n,deg-1)*n);
else
{
ll half=Power(n,deg/2);
return ((half*half));
}
}
/***********************main_problem***************************************/
vector<int>arr;
int memo[200][30];
int R(int s,int e){
int mid=(s+e)/2 + (s+e)%2;
int ans=0;
int now=arr[mid];
for(int j=s;j<=e;j++){
ans+=abs(arr[j]-arr[mid]);
}
return ans;
}
int solve(int i , int k,int last){
if(i==arr.size())
return 0;
if(k==0){
int F=0;
for(int x=i;x<arr.size();x++)
F+=abs(arr[x]-last);
return F;
}
int &ret=memo[i][k];
if(ret!=-1)
return ret;
ret=1e8;
for(int j=i;j<arr.size();j++){
int mid=(i+j)/2 +(i+j)%2;
ret=min(ret,solve(j+1,k-1,arr[mid])+R(i,j));
}
return ret;
}
void track(int i ,int k ,int last,int testcase){
if(i==arr.size())
return ;
if(k==1){
int mid=((i+1)+arr.size())/2;
if((i+1)==arr.size())
cout<<"Depot "<<testcase<<" at restaurant "<<i+1<<" serves restaurant "<<i+1<<'\n';
else
cout<<"Depot "<<testcase<<" at restaurant "<<mid<<" serves restaurants "<<i+1<<" to "<<arr.size()<<'\n';
return ;
}
int ret=1e7, I,K,LAST;
int S,E;
for(int j=i;j<arr.size();j++){
int mid=(i+j)/2 +(i+j)%2;
int now=solve(j+1,k-1,arr[mid])+R(i,j);
if(now<ret){
ret=now;
S=i+1,E=j+1;
I=j+1,K=k-1,LAST=mid+1;
}
}
int mid=((S+E)/2);
if(S==E)
cout<<"Depot "<<testcase<<" at restaurant "<<mid<<" serves restaurant "<<S<<'\n';
else
cout<<"Depot "<<testcase<<" at restaurant "<<mid<<" serves restaurants "<<S<<" to "<<E<<'\n';
track(I,K,LAST,testcase+1);
}
/***********𝓢𝓣𝓞𝓟 𝓦𝓗𝓔𝓝 𝓨𝓞𝓤 𝓡𝓔𝓐𝓒𝓗 𝓣𝓗𝓔 𝓒𝓞𝓝𝓒𝓔𝓟𝓣 𝓞𝓕 𝓓𝓞𝓝'𝓣 𝓢𝓣𝓞𝓟******************/
int main()
{
fast();
int n,k,t=1;
while(cin>>n>>k && n && k)
{
cout<<"Chain "<<t++<<'\n';
clr(memo,-1);
arr.clear();
for(int i=0;i<n;i++){
int a;
cin>>a;
arr.push_back(a);
}
int total=solve(0,k,0);
track(0,k,0,1);
cout<<"Total distance sum = "<<total<<"\n\n";
}
return 0;
}
| 18.206422 | 112 | 0.489292 | [
"vector"
] |
20395c7142cf4ec250321e3011d623588237b2c5 | 275 | hpp | C++ | src/basicHl.hpp | Oberon00/synth | f4bb576d22108fdfd65bb8f0796cce4aa84349a6 | [
"MIT"
] | 185 | 2016-04-03T16:14:39.000Z | 2021-03-22T20:49:03.000Z | src/basicHl.hpp | Oberon00/synth | f4bb576d22108fdfd65bb8f0796cce4aa84349a6 | [
"MIT"
] | 2 | 2016-04-04T05:50:12.000Z | 2017-01-17T18:12:09.000Z | src/basicHl.hpp | Oberon00/synth | f4bb576d22108fdfd65bb8f0796cce4aa84349a6 | [
"MIT"
] | 10 | 2016-04-03T20:48:01.000Z | 2019-07-07T05:32:13.000Z | #ifndef SYNTH_BASICHL_HPP_INCLUDED
#define SYNTH_BASICHL_HPP_INCLUDED
#include <iosfwd>
#include <vector>
namespace synth {
struct Markup;
void basicHighlightFile(std::istream& f, std::vector<Markup>& markups);
} // namespace synth
#endif // SYNTH_BASICHL_HPP_INCLUDED
| 17.1875 | 71 | 0.785455 | [
"vector"
] |
203c0a680bf70dc5fbc0685cf3d460fc51a2b99d | 6,198 | cc | C++ | addons/differentiation/DynamicsFD.cc | mkudruss/rbdl_derivatives | 0fec930aad4a6fb3084aa5aa2bb27bcfd7409a1e | [
"Zlib"
] | 1 | 2021-02-21T09:31:56.000Z | 2021-02-21T09:31:56.000Z | addons/differentiation/DynamicsFD.cc | mkudruss/rbdl_derivatives | 0fec930aad4a6fb3084aa5aa2bb27bcfd7409a1e | [
"Zlib"
] | null | null | null | addons/differentiation/DynamicsFD.cc | mkudruss/rbdl_derivatives | 0fec930aad4a6fb3084aa5aa2bb27bcfd7409a1e | [
"Zlib"
] | 1 | 2022-03-31T05:03:17.000Z | 2022-03-31T05:03:17.000Z | /*
* RBDL - Rigid Body Dynamics Library
* Copyright (c) 2011-2015 Martin Felis <martin.felis@iwr.uni-heidelberg.de>
*
* Licensed under the zlib license. See LICENSE for more details.
*/
#include "DynamicsFD.h"
#include "FdModelEntry.h"
using namespace RigidBodyDynamics::Math;
using std::vector;
// -----------------------------------------------------------------------------
namespace RigidBodyDynamics {
// -----------------------------------------------------------------------------
namespace FD {
// -----------------------------------------------------------------------------
RBDL_DLLAPI
void ForwardDynamics(
Model &model,
ADModel *fd_model,
const VectorNd &q,
const MatrixNd &q_dirs,
const VectorNd &qdot,
const MatrixNd &qdot_dirs,
const VectorNd &tau,
const MatrixNd &tau_dirs,
VectorNd &qddot,
MatrixNd &fd_qddot,
vector<SpatialVector> const *f_ext,
vector<vector<SpatialVector>> const *f_ext_dirs
) {
assert((f_ext == NULL) == (f_ext_dirs == NULL));
assert(q_dirs.cols() == qdot_dirs.cols()
&& q_dirs.cols() == fd_qddot.cols()
&& tau_dirs.cols() == q_dirs.cols()
&& "q_dirs, qdot_dirs, tau_dirs, fd_qddot have different dimensions");
double h = sqrt(1e-16);
unsigned int ndirs = q_dirs.cols();
ForwardDynamics(model, q, qdot, tau, qddot,f_ext);
VectorNd hd_qddot(qddot);
VectorNd q_dir(q);
VectorNd qdot_dir(qdot);
VectorNd tau_dir(tau);
for(unsigned idir = 0; idir < ndirs; idir++) {
Model * modelh;
if (fd_model) {
modelh = new Model(model);
} else {
modelh = &model;
}
VectorNd qh = q + h * q_dirs.col(idir);
VectorNd qdh = qdot + h * qdot_dirs.col(idir);
VectorNd tauh = tau + h * tau_dirs.col(idir);
vector<SpatialVector> f_exth_;
if (f_ext) {
f_exth_.resize(f_ext->size());
for (unsigned i = 0; i < f_ext->size(); i++) {
f_exth_[i] = (*f_ext)[i] + h * (*f_ext_dirs)[i][idir];
}
}
vector<SpatialVector> const * f_exth = f_ext ? &f_exth_ : NULL;
ForwardDynamics(*modelh, qh, qdh, tauh, hd_qddot, f_exth);
fd_qddot.col(idir) = (hd_qddot - qddot) / h;
if (fd_model) {
computeFDEntry(model, *modelh, h, idir, *fd_model);
delete modelh;
}
}
}
RBDL_DLLAPI
void InverseDynamics(
Model &model,
ADModel *fd_model,
const Math::VectorNd &q,
const Math::MatrixNd &q_dirs,
const Math::VectorNd &qdot,
const Math::MatrixNd &qdot_dirs,
const Math::VectorNd &qddot,
const Math::MatrixNd &qddot_dirs,
Math::VectorNd &tau,
Math::MatrixNd &fd_tau,
vector<SpatialVector> const *f_ext,
vector<vector<SpatialVector>> const *f_ext_dirs
) {
assert(q_dirs.cols() == qdot_dirs.cols() &&
q_dirs.cols() == qddot_dirs.cols() &&
"q_dirs, qdot_dirs, qddot_dirs have different dimensions");
assert( fd_tau.cols() == q_dirs.cols() &&
fd_tau.rows() == tau.rows() &&
"fd_tau and tau have different dimensions");
double h = sqrt(1e-16);
unsigned int ndirs = q_dirs.cols();
InverseDynamics(model, q, qdot, qddot, tau, f_ext);
VectorNd tau_h (tau);
for (unsigned idir = 0; idir < ndirs; idir++) {
Model * modelh;
if (fd_model) {
modelh = new Model(model);
} else {
modelh = &model;
}
vector<SpatialVector> f_exth_;
if (f_ext) {
f_exth_.resize(f_ext->size());
for (unsigned i = 0; i < f_ext->size(); i++) {
f_exth_[i] = (*f_ext)[i] + h * (*f_ext_dirs)[i][idir];
}
}
InverseDynamics(
*modelh, q + h*q_dirs.col(idir),
qdot + h*qdot_dirs.col(idir),
qddot + h*qddot_dirs.col(idir),
tau_h,
f_ext ? &f_exth_ : NULL
);
fd_tau.col(idir) = (tau_h - tau) / h;
if (fd_model) {
computeFDEntry(model, *modelh, h, idir, *fd_model);
delete modelh;
}
}
}
RBDL_DLLAPI
void NonlinearEffects (
Model &model,
ADModel *fd_model,
const Math::VectorNd &q,
const Math::MatrixNd &q_dirs,
const Math::VectorNd &qdot,
const Math::MatrixNd &qdot_dirs,
Math::VectorNd &tau,
Math::MatrixNd &fd_tau
) {
unsigned ndirs = q_dirs.cols();
assert(ndirs == qdot_dirs.cols());
assert(ndirs == fd_tau.cols());
NonlinearEffects (model, q, qdot, tau);
double h = 1.0e-8;
for (unsigned idir = 0; idir < ndirs; idir++) {
Model * modelh;
if (fd_model) {
modelh = new Model(model);
} else {
modelh = &model;
}
VectorNd q_dir = q_dirs.col(idir);
VectorNd qd_dir = qdot_dirs.col(idir);
VectorNd hd_tau(tau.rows());
NonlinearEffects (*modelh, q + h * q_dir, qdot + h * qd_dir, hd_tau);
fd_tau.col(idir) = (hd_tau - tau) / h;
if (fd_model) {
computeFDEntry(model, *modelh, h, idir, *fd_model);
delete modelh;
}
}
}
RBDL_DLLAPI
void CompositeRigidBodyAlgorithm (
Model &model,
ADModel *fd_model,
const VectorNd &q,
const MatrixNd &q_dirs,
MatrixNd &H,
vector<MatrixNd> &fd_H
) {
unsigned const ndirs = q_dirs.cols();
assert(ndirs == fd_H.size());
// value of perturbation
double h = 1.0e-8;
// compute value at current configuration q as nominal value
CompositeRigidBodyAlgorithm(model, q, H, true);
for (unsigned idir = 0; idir < ndirs; idir++) {
// hack to compute finite differences of model quantities
Model *modelh = &model;
if (fd_model) {
modelh = new Model(model);
}
VectorNd q_dir = q_dirs.col(idir);
// compute perturbations along direction
CompositeRigidBodyAlgorithm(*modelh, q+h*q_dir, fd_H[idir], true);
// compute directional derivatives using forward first order differences
fd_H[idir] = (fd_H[idir] - H) / h;
// hack to compute finite differences of model quantities
if (fd_model) {
computeFDEntry(model, *modelh, h, idir, *fd_model);
delete modelh;
}
}
}
// -----------------------------------------------------------------------------
} // namespace FD
// -----------------------------------------------------------------------------
} // namespace RigidBodyDynamics
// -----------------------------------------------------------------------------
| 27.546667 | 80 | 0.574056 | [
"vector",
"model"
] |
203d39a0431ca35a24767d66d43e181904106f37 | 6,326 | cpp | C++ | examples/print_file_result.cpp | akrzemi1/leaf | b643cb9882a40c2d2a26bf92bed9f5eb28488911 | [
"BSL-1.0"
] | null | null | null | examples/print_file_result.cpp | akrzemi1/leaf | b643cb9882a40c2d2a26bf92bed9f5eb28488911 | [
"BSL-1.0"
] | null | null | null | examples/print_file_result.cpp | akrzemi1/leaf | b643cb9882a40c2d2a26bf92bed9f5eb28488911 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2018-2019 Emil Dotchevski and Reverge Studios, Inc.
// 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)
// This is the program presented in https://zajo.github.io/leaf/#introduction-result.
// It reads a text file in a buffer and prints it to std::cout, using LEAF to handle errors.
// This version does not use exception handling. The version that does use exception
// handling is in print_file_eh.cpp.
#include <boost/leaf/result.hpp>
#include <boost/leaf/handle_error.hpp>
#include <boost/leaf/preload.hpp>
#include <boost/leaf/common.hpp>
#include <iostream>
#include <memory>
#include <stdio.h>
namespace leaf = boost::leaf;
// First, we need an enum to define our error codes:
enum error_code
{
bad_command_line = 1,
input_file_open_error,
input_file_size_error,
input_file_read_error,
input_eof_error,
cout_error
};
// To enable LEAF to work with our error_code enum, we need to specialize the is_e_type template:
namespace boost { namespace leaf {
template<> struct is_e_type<error_code>: std::true_type { };
} }
// We will handle all failures in our main function, but first, here are the declarations of the functions it calls, each
// communicating failures using leaf::result<T>:
// Parse the command line, return the file name.
leaf::result<char const *> parse_command_line( int argc, char const * argv[] );
// Open a file for reading.
leaf::result<std::shared_ptr<FILE>> file_open( char const * file_name );
// Return the size of the file.
leaf::result<int> file_size( FILE & f );
// Read size bytes from f into buf.
leaf::result<void> file_read( FILE & f, void * buf, int size );
// The main function, which handles all errors.
int main( int argc, char const * argv[] )
{
return leaf::try_handle_all(
[&]() -> leaf::result<int>
{
LEAF_AUTO(file_name, parse_command_line(argc,argv));
auto load = leaf::preload( leaf::e_file_name{file_name} );
LEAF_AUTO(f, file_open(file_name));
LEAF_AUTO(s, file_size(*f));
std::string buffer( 1 + s, '\0' );
LEAF_CHECK(file_read(*f, &buffer[0], buffer.size()-1));
std::cout << buffer;
std::cout.flush();
if( std::cout.fail() )
return leaf::new_error( cout_error, leaf::e_errno{errno} );
return 0;
},
// Each of the lambdas below is an error handler. LEAF will consider them, in order, and call the first one that matches
// the available error objects.
// This handler will be called if the error includes:
// - an object of type error_code equal to input_file_open_error, and
// - an object of type leaf::e_errno that has .value equal to ENOENT, and
// - an object of type leaf::e_file_name.
[]( leaf::match<error_code, input_file_open_error>, leaf::match<leaf::e_errno, ENOENT>, leaf::e_file_name const & fn )
{
std::cerr << "File not found: " << fn.value << std::endl;
return 1;
},
// This handler will be called if the error includes:
// - an object of type error_code equal to input_file_open_error, and
// - an object of type leaf::e_errno (regardless of its .value), and
// - an object of type leaf::e_file_name.
[]( leaf::match<error_code, input_file_open_error>, leaf::e_errno const & errn, leaf::e_file_name const & fn )
{
std::cerr << "Failed to open " << fn.value << ", errno=" << errn << std::endl;
return 2;
},
// This handler will be called if the error includes:
// - an object of type error_code equal to any of input_file_size_error, input_file_read_error, input_eof_error, and
// - an object of type leaf::e_errno (regardless of its .value), and
// - an object of type leaf::e_file_name.
[]( leaf::match<error_code, input_file_size_error, input_file_read_error, input_eof_error>, leaf::e_errno const & errn, leaf::e_file_name const & fn )
{
std::cerr << "Failed to access " << fn.value << ", errno=" << errn << std::endl;
return 3;
},
// This handler will be called if the error includes:
// - an object of type error_code equal to cout_error, and
// - an object of type leaf::e_errno (regardless of its .value),
[]( leaf::match<error_code, cout_error>, leaf::e_errno const & errn )
{
std::cerr << "Output error, errno=" << errn << std::endl;
return 4;
},
// This handler will be called if the error includes an object of type error_code equal to bad_command_line.
[]( leaf::match<error_code, bad_command_line> )
{
std::cout << "Bad command line argument" << std::endl;
return 5;
},
// This last handler matches any error: it prints diagnostic information to help debug logic errors in the program, since it
// failed to match an appropriate error handler to the error condition it encountered. In this program this handler will
// never be called.
[]( leaf::error_info const & unmatched )
{
std::cerr <<
"Unknown failure detected" << std::endl <<
"Cryptic diagnostic information follows" << std::endl <<
unmatched;
return 6;
} );
}
// Implementations of the functions called by main:
// Parse the command line, return the file name.
leaf::result<char const *> parse_command_line( int argc, char const * argv[] )
{
if( argc==2 )
return argv[1];
else
return leaf::new_error(bad_command_line);
}
// Open a file for reading.
leaf::result<std::shared_ptr<FILE>> file_open( char const * file_name )
{
if( FILE * f = fopen(file_name,"rb") )
return std::shared_ptr<FILE>(f,&fclose);
else
return leaf::new_error(input_file_open_error, leaf::e_errno{errno});
}
// Return the size of the file.
leaf::result<int> file_size( FILE & f )
{
// All exceptions escaping this function will automatically load errno.
auto load = leaf::defer([] { return leaf::e_errno{errno}; });
if( fseek(&f,0,SEEK_END) )
return leaf::new_error(input_file_size_error);
int s = ftell(&f);
if( s==-1L )
return leaf::new_error(input_file_size_error);
if( fseek(&f,0,SEEK_SET) )
return leaf::new_error(input_file_size_error);
return s;
}
// Read size bytes from f into buf.
leaf::result<void> file_read( FILE & f, void * buf, int size )
{
int n = fread(buf,1,size,&f);
if( ferror(&f) )
return leaf::new_error(input_file_read_error, leaf::e_errno{errno});
if( n!=size )
return leaf::new_error(input_eof_error);
return { };
}
| 31.63 | 152 | 0.695068 | [
"object"
] |
204810b871974d79cd5f4235feb091c91384d9f2 | 2,994 | cc | C++ | tools/kbenchmark/Args.cc | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 255 | 2020-05-22T07:45:29.000Z | 2022-03-29T23:58:22.000Z | tools/kbenchmark/Args.cc | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 5,102 | 2020-05-22T07:48:33.000Z | 2022-03-31T23:43:39.000Z | tools/kbenchmark/Args.cc | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 120 | 2020-05-22T07:51:08.000Z | 2022-02-16T19:08:05.000Z | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd. 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 "Args.h"
#include <iostream>
#include <boost/filesystem.hpp>
namespace kbenchmark
{
Args::Args(const int argc, char **argv) noexcept { Initialize(argc, argv); }
void Args::Initialize(const int argc, char **argv)
{
// General options
po::options_description general("General options");
// clang-format off
general.add_options()("help,h", "Display available options")
("config,c", po::value<std::string>(&_config)->required(), "Configuration filename")
("kernel,k", po::value<std::vector<std::string>>(&_kernel)->multitoken()->composing()->required(), "Kernel library name, support multiple kernel libraries")
("reporter,r", po::value<std::string>(&_reporter)->default_value("standard"), "Set reporter types(standard, html, junit, csv)")
("filter,f", po::value<std::string>(&_filter)->default_value(".*"), "Only run benchmarks whose name matches the regular expression pattern")
("verbose,v", po::value<int>(&_verbose)->default_value(0)->implicit_value(true), "Show verbose output")
("output,o", po::value<std::string>(&_output)->default_value(""), "Set additional strings for output file name")
;
// clang-format on
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, general), vm);
try
{
po::notify(vm);
}
catch (const boost::program_options::required_option &e)
{
if (vm.count("help"))
{
std::cout << general << std::endl;
exit(0);
}
else
{
throw e;
}
}
if (vm.count("help"))
{
std::cout << general << std::endl;
exit(0);
}
if (vm.count("config"))
{
if (_config.substr(_config.find_last_of(".") + 1) != "config")
{
std::cerr << "Please specify .config file" << std::endl;
exit(1);
}
if (!boost::filesystem::exists(_config))
{
std::cerr << _config << " file not found" << std::endl;
exit(1);
}
}
if (vm.count("kernel"))
{
for (auto &k : _kernel)
{
if (!boost::filesystem::exists(k))
{
std::cerr << k << " file not found" << std::endl;
exit(1);
}
}
}
if (vm.count("reporter"))
{
if (_reporter != "junit" && _reporter != "csv" && _reporter != "html" &&
_reporter != "standard")
{
std::cerr << "Invalid reporter" << std::endl;
exit(1);
}
}
}
} // namespace kbenchmark
| 27.981308 | 160 | 0.624916 | [
"vector"
] |
204b5d0ef3c79aced9c090dda5aa02c3a4fa4190 | 1,562 | cpp | C++ | Medium/130_Surrounded_Regions.cpp | ShehabMMohamed/LeetCodeCPP | 684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780 | [
"MIT"
] | 1 | 2021-03-15T10:02:10.000Z | 2021-03-15T10:02:10.000Z | Medium/130_Surrounded_Regions.cpp | ShehabMMohamed/LeetCodeCPP | 684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780 | [
"MIT"
] | null | null | null | Medium/130_Surrounded_Regions.cpp | ShehabMMohamed/LeetCodeCPP | 684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780 | [
"MIT"
] | null | null | null | class Solution {
public:
void FloodFill(vector<vector<char>>& board, const int M, const int N, int r, int c) {
if(r < 0 || r >= M || c < 0 || c >= N) return;
if(board[r][c] == '-')
board[r][c] = 'O';
else
return;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
for(int d = 0; d < 4; d++) {
int new_x = r + dx[d];
int new_y = c + dy[d];
FloodFill(board, M, N, new_x, new_y);
}
}
void solve(vector<vector<char>>& board) {
if(board.empty() || board[0].empty()) return;
int M = board.size();
int N = board[0].size();
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
if(board[i][j] == 'O')
board[i][j] = '-';
}
}
// TOP - RIGHT - BOTTOM - LEFT
for(int c = 0; c < N; c++)
if(board[0][c] == '-')
FloodFill(board, M, N, 0, c);
for(int r = 0; r < M; r++)
if(board[r][N-1] == '-')
FloodFill(board, M, N, r, N-1);
for(int c = 0; c < N; c++)
if(board[M-1][c] == '-')
FloodFill(board, M, N, M-1, c);
for(int r = 0; r < M; r++)
if(board[r][0] == '-')
FloodFill(board, M, N, r, 0);
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
if(board[i][j] == '-')
board[i][j] = 'X';
}
}
}
};
| 31.877551 | 89 | 0.34507 | [
"vector"
] |
206200588b1f707cf47f5fbb75f747a42e6cace4 | 19,878 | hpp | C++ | src/applications/utilities/postProcessing/dataConversion/caelusToEnsight/ensightField.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/applications/utilities/postProcessing/dataConversion/caelusToEnsight/ensightField.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/applications/utilities/postProcessing/dataConversion/caelusToEnsight/ensightField.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
InApplication
caelusToEnsight
Description
SourceFiles
ensightField.cpp
\*---------------------------------------------------------------------------*/
#ifndef ensightField_H
#define ensightField_H
#include "ensightMesh.hpp"
#include "fvMeshSubset.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
//- Wrapper to get hold of the field or the subsetted field
template<class Type>
CML::tmp<CML::GeometricField<Type, CML::fvPatchField, CML::volMesh> >
volField
(
const CML::fvMeshSubset&,
const CML::GeometricField<Type, CML::fvPatchField, CML::volMesh>& vf
);
template<class Type>
void ensightField
(
const CML::GeometricField<Type, CML::fvPatchField, CML::volMesh>& vf,
const CML::ensightMesh& eMesh,
const CML::fileName& postProcPath,
const CML::word& prepend,
const CML::label timeIndex,
const bool binary,
const bool nodeValues,
CML::Ostream& ensightCaseFile
);
template<class Type>
void writePatchField
(
const CML::word& fieldName,
const CML::Field<Type>& pf,
const CML::word& patchName,
const CML::ensightMesh& eMesh,
const CML::fileName& postProcPath,
const CML::word& prepend,
const CML::label timeIndex,
CML::Ostream& ensightCaseFile
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "fvMesh.hpp"
#include "volFields.hpp"
#include "OFstream.hpp"
#include "IOmanip.hpp"
#include "itoa.hpp"
#include "volPointInterpolation.hpp"
#include "ensightBinaryStream.hpp"
#include "ensightAsciiStream.hpp"
#include "globalIndex.hpp"
#include "ensightPTraits.hpp"
using namespace CML;
// * * * * * * * * * * * * * * * Global Functions * * * * * * * * * * * * * //
template<class Type>
tmp<GeometricField<Type, fvPatchField, volMesh> >
volField
(
const fvMeshSubset& meshSubsetter,
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
if (meshSubsetter.hasSubMesh())
{
tmp<GeometricField<Type, fvPatchField, volMesh> > tfld
(
meshSubsetter.interpolate(vf)
);
tfld().checkOut();
tfld().rename(vf.name());
return tfld;
}
else
{
return vf;
}
}
template<class Type>
Field<Type> map
(
const Field<Type>& vf,
const labelList& map1,
const labelList& map2
)
{
Field<Type> mf(map1.size() + map2.size());
forAll(map1, i)
{
mf[i] = vf[map1[i]];
}
label offset = map1.size();
forAll(map2, i)
{
mf[i + offset] = vf[map2[i]];
}
return mf;
}
template<class Type>
void writeField
(
const char* key,
const Field<Type>& vf,
ensightStream& ensightFile
)
{
if (returnReduce(vf.size(), sumOp<label>()) > 0)
{
if (Pstream::master())
{
ensightFile.write(key);
for (direction cmpt=0; cmpt<pTraits<Type>::nComponents; cmpt++)
{
ensightFile.write(vf.component(cmpt));
for (int slave=1; slave<Pstream::nProcs(); slave++)
{
IPstream fromSlave(Pstream::scheduled, slave);
scalarField slaveData(fromSlave);
ensightFile.write(slaveData);
}
}
}
else
{
for (direction cmpt=0; cmpt<pTraits<Type>::nComponents; cmpt++)
{
OPstream toMaster(Pstream::scheduled, Pstream::masterNo());
toMaster<< vf.component(cmpt);
}
}
}
}
template<class Type>
bool writePatchField
(
const Field<Type>& pf,
const label patchi,
const label ensightPatchI,
const faceSets& boundaryFaceSet,
const ensightMesh::nFacePrimitives& nfp,
ensightStream& ensightFile
)
{
if (nfp.nTris || nfp.nQuads || nfp.nPolys)
{
if (Pstream::master())
{
ensightFile.writePartHeader(ensightPatchI);
}
writeField
(
"tria3",
Field<Type>(pf, boundaryFaceSet.tris),
ensightFile
);
writeField
(
"quad4",
Field<Type>(pf, boundaryFaceSet.quads),
ensightFile
);
writeField
(
"nsided",
Field<Type>(pf, boundaryFaceSet.polys),
ensightFile
);
return true;
}
else
{
return false;
}
}
template<class Type>
void writePatchField
(
const word& fieldName,
const Field<Type>& pf,
const word& patchName,
const ensightMesh& eMesh,
const fileName& postProcPath,
const word& prepend,
const label timeIndex,
const bool binary,
Ostream& ensightCaseFile
)
{
const Time& runTime = eMesh.mesh().time();
const List<faceSets>& boundaryFaceSets = eMesh.boundaryFaceSets();
const wordList& allPatchNames = eMesh.allPatchNames();
const HashTable<ensightMesh::nFacePrimitives>&
nPatchPrims = eMesh.nPatchPrims();
label ensightPatchI = eMesh.patchPartOffset();
label patchi = -1;
forAll(allPatchNames, i)
{
if (allPatchNames[i] == patchName)
{
patchi = i;
break;
}
ensightPatchI++;
}
word pfName = patchName + '.' + fieldName;
word timeFile = prepend + itoa(timeIndex);
ensightStream* ensightFilePtr = nullptr;
if (Pstream::master())
{
if (timeIndex == 0)
{
ensightCaseFile.setf(ios_base::left);
ensightCaseFile
<< ensightPTraits<Type>::typeName
<< " per element: 1 "
<< setw(15) << pfName
<< (' ' + prepend + "****." + pfName).c_str()
<< nl;
}
// set the filename of the ensight file
fileName ensightFileName(timeFile + "." + pfName);
if (binary)
{
ensightFilePtr = new ensightBinaryStream
(
postProcPath/ensightFileName,
runTime
);
}
else
{
ensightFilePtr = new ensightAsciiStream
(
postProcPath/ensightFileName,
runTime
);
}
}
ensightStream& ensightFile = *ensightFilePtr;
if (Pstream::master())
{
ensightFile.write(ensightPTraits<Type>::typeName);
}
if (patchi >= 0)
{
writePatchField
(
pf,
patchi,
ensightPatchI,
boundaryFaceSets[patchi],
nPatchPrims.find(patchName)(),
ensightFile
);
}
else
{
faceSets nullFaceSets;
writePatchField
(
Field<Type>(),
-1,
ensightPatchI,
nullFaceSets,
nPatchPrims.find(patchName)(),
ensightFile
);
}
if (Pstream::master())
{
delete ensightFilePtr;
}
}
template<class Type>
void ensightField
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
const ensightMesh& eMesh,
const fileName& postProcPath,
const word& prepend,
const label timeIndex,
const bool binary,
Ostream& ensightCaseFile
)
{
Info<< "Converting field " << vf.name() << endl;
word timeFile = prepend + itoa(timeIndex);
const fvMesh& mesh = eMesh.mesh();
const Time& runTime = mesh.time();
const cellSets& meshCellSets = eMesh.meshCellSets();
const List<faceSets>& boundaryFaceSets = eMesh.boundaryFaceSets();
const wordList& allPatchNames = eMesh.allPatchNames();
const wordHashSet& patchNames = eMesh.patchNames();
const HashTable<ensightMesh::nFacePrimitives>&
nPatchPrims = eMesh.nPatchPrims();
const List<faceSets>& faceZoneFaceSets = eMesh.faceZoneFaceSets();
const wordHashSet& faceZoneNames = eMesh.faceZoneNames();
const HashTable<ensightMesh::nFacePrimitives>&
nFaceZonePrims = eMesh.nFaceZonePrims();
const labelList& tets = meshCellSets.tets;
const labelList& pyrs = meshCellSets.pyrs;
const labelList& prisms = meshCellSets.prisms;
const labelList& wedges = meshCellSets.wedges;
const labelList& hexes = meshCellSets.hexes;
const labelList& polys = meshCellSets.polys;
ensightStream* ensightFilePtr = nullptr;
if (Pstream::master())
{
// set the filename of the ensight file
fileName ensightFileName(timeFile + "." + vf.name());
if (binary)
{
ensightFilePtr = new ensightBinaryStream
(
postProcPath/ensightFileName,
runTime
);
}
else
{
ensightFilePtr = new ensightAsciiStream
(
postProcPath/ensightFileName,
runTime
);
}
}
ensightStream& ensightFile = *ensightFilePtr;
if (Pstream::master())
{
if (timeIndex == 0)
{
ensightCaseFile.setf(ios_base::left);
ensightCaseFile
<< ensightPTraits<Type>::typeName
<< " per element: 1 "
<< setw(15) << vf.name()
<< (' ' + prepend + "****." + vf.name()).c_str()
<< nl;
}
ensightFile.write(ensightPTraits<Type>::typeName);
}
if (patchNames.empty())
{
eMesh.barrier();
if (Pstream::master())
{
ensightFile.writePartHeader(1);
}
writeField
(
"hexa8",
map(vf, hexes, wedges),
ensightFile
);
writeField
(
"penta6",
Field<Type>(vf, prisms),
ensightFile
);
writeField
(
"pyramid5",
Field<Type>(vf, pyrs),
ensightFile
);
writeField
(
"tetra4",
Field<Type>(vf, tets),
ensightFile
);
writeField
(
"nfaced",
Field<Type>(vf, polys),
ensightFile
);
}
label ensightPatchI = eMesh.patchPartOffset();
forAll(allPatchNames, patchi)
{
const word& patchName = allPatchNames[patchi];
eMesh.barrier();
if (patchNames.empty() || patchNames.found(patchName))
{
if
(
writePatchField
(
vf.boundaryField()[patchi],
patchi,
ensightPatchI,
boundaryFaceSets[patchi],
nPatchPrims.find(patchName)(),
ensightFile
)
)
{
ensightPatchI++;
}
}
}
// write faceZones, if requested
if (faceZoneNames.size())
{
// Interpolates cell values to faces - needed only when exporting
// faceZones...
GeometricField<Type, fvsPatchField, surfaceMesh> sf
(
linearInterpolate(vf)
);
forAllConstIter(wordHashSet, faceZoneNames, iter)
{
const word& faceZoneName = iter.key();
eMesh.barrier();
label zoneID = mesh.faceZones().findZoneID(faceZoneName);
const faceZone& fz = mesh.faceZones()[zoneID];
// Prepare data to write
label nIncluded = 0;
forAll(fz, i)
{
if (eMesh.faceToBeIncluded(fz[i]))
{
++nIncluded;
}
}
Field<Type> values(nIncluded);
// Loop on the faceZone and store the needed field values
label j = 0;
forAll(fz, i)
{
label faceI = fz[i];
if (mesh.isInternalFace(faceI))
{
values[j] = sf[faceI];
++j;
}
else
{
if (eMesh.faceToBeIncluded(faceI))
{
label patchI = mesh.boundaryMesh().whichPatch(faceI);
const polyPatch& pp = mesh.boundaryMesh()[patchI];
label patchFaceI = pp.whichFace(faceI);
Type value = sf.boundaryField()[patchI][patchFaceI];
values[j] = value;
++j;
}
}
}
if
(
writePatchField
(
values,
zoneID,
ensightPatchI,
faceZoneFaceSets[zoneID],
nFaceZonePrims.find(faceZoneName)(),
ensightFile
)
)
{
ensightPatchI++;
}
}
}
if (Pstream::master())
{
delete ensightFilePtr;
}
}
template<class Type>
void ensightPointField
(
const GeometricField<Type, pointPatchField, pointMesh>& pf,
const ensightMesh& eMesh,
const fileName& postProcPath,
const word& prepend,
const label timeIndex,
const bool binary,
Ostream& ensightCaseFile
)
{
Info<< "Converting field " << pf.name() << endl;
word timeFile = prepend + itoa(timeIndex);
const fvMesh& mesh = eMesh.mesh();
const wordList& allPatchNames = eMesh.allPatchNames();
const wordHashSet& patchNames = eMesh.patchNames();
const wordHashSet& faceZoneNames = eMesh.faceZoneNames();
ensightStream* ensightFilePtr = nullptr;
if (Pstream::master())
{
// set the filename of the ensight file
fileName ensightFileName(timeFile + "." + pf.name());
if (binary)
{
ensightFilePtr = new ensightBinaryStream
(
postProcPath/ensightFileName,
mesh.time()
);
}
else
{
ensightFilePtr = new ensightAsciiStream
(
postProcPath/ensightFileName,
mesh.time()
);
}
}
ensightStream& ensightFile = *ensightFilePtr;
if (Pstream::master())
{
if (timeIndex == 0)
{
ensightCaseFile.setf(ios_base::left);
ensightCaseFile
<< ensightPTraits<Type>::typeName
<< " per node: 1 "
<< setw(15) << pf.name()
<< (' ' + prepend + "****." + pf.name()).c_str()
<< nl;
}
ensightFile.write(ensightPTraits<Type>::typeName);
}
if (eMesh.patchNames().empty())
{
eMesh.barrier();
if (Pstream::master())
{
ensightFile.writePartHeader(1);
}
writeField
(
"coordinates",
Field<Type>(pf.internalField(), eMesh.uniquePointMap()),
ensightFile
);
}
label ensightPatchI = eMesh.patchPartOffset();
forAll(allPatchNames, patchi)
{
const word& patchName = allPatchNames[patchi];
eMesh.barrier();
if (patchNames.empty() || patchNames.found(patchName))
{
const fvPatch& p = mesh.boundary()[patchi];
if
(
returnReduce(p.size(), sumOp<label>())
> 0
)
{
// Renumber the patch points/faces into unique points
labelList pointToGlobal;
labelList uniqueMeshPointLabels;
autoPtr<globalIndex> globalPointsPtr =
mesh.globalData().mergePoints
(
p.patch().meshPoints(),
p.patch().meshPointMap(),
pointToGlobal,
uniqueMeshPointLabels
);
if (Pstream::master())
{
ensightFile.writePartHeader(ensightPatchI);
}
writeField
(
"coordinates",
Field<Type>(pf.internalField(), uniqueMeshPointLabels),
ensightFile
);
ensightPatchI++;
}
}
}
// write faceZones, if requested
if (faceZoneNames.size())
{
forAllConstIter(wordHashSet, faceZoneNames, iter)
{
const word& faceZoneName = iter.key();
eMesh.barrier();
label zoneID = mesh.faceZones().findZoneID(faceZoneName);
const faceZone& fz = mesh.faceZones()[zoneID];
if (returnReduce(fz().nPoints(), sumOp<label>()) > 0)
{
// Renumber the faceZone points/faces into unique points
labelList pointToGlobal;
labelList uniqueMeshPointLabels;
autoPtr<globalIndex> globalPointsPtr =
mesh.globalData().mergePoints
(
fz().meshPoints(),
fz().meshPointMap(),
pointToGlobal,
uniqueMeshPointLabels
);
if (Pstream::master())
{
ensightFile.writePartHeader(ensightPatchI);
}
writeField
(
"coordinates",
Field<Type>
(
pf.internalField(),
uniqueMeshPointLabels
),
ensightFile
);
ensightPatchI++;
}
}
}
if (Pstream::master())
{
delete ensightFilePtr;
}
}
template<class Type>
void ensightField
(
const GeometricField<Type, fvPatchField, volMesh>& vf,
const ensightMesh& eMesh,
const fileName& postProcPath,
const word& prepend,
const label timeIndex,
const bool binary,
const bool nodeValues,
Ostream& ensightCaseFile
)
{
if (nodeValues)
{
tmp<GeometricField<Type, pointPatchField, pointMesh> > pfld
(
volPointInterpolation::New(vf.mesh()).interpolate(vf)
);
pfld().rename(vf.name());
ensightPointField<Type>
(
pfld,
eMesh,
postProcPath,
prepend,
timeIndex,
binary,
ensightCaseFile
);
}
else
{
ensightField<Type>
(
vf,
eMesh,
postProcPath,
prepend,
timeIndex,
binary,
ensightCaseFile
);
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 24.330477 | 79 | 0.500553 | [
"mesh"
] |
20646533b313a0f01151dd19902da2b95467aedb | 2,072 | cpp | C++ | src/dolfin/mesh/Edge.cpp | szmurlor/fiver | 083251420eb934d860c99dcf1eb07ae5b8ba7e8c | [
"Apache-2.0"
] | null | null | null | src/dolfin/mesh/Edge.cpp | szmurlor/fiver | 083251420eb934d860c99dcf1eb07ae5b8ba7e8c | [
"Apache-2.0"
] | null | null | null | src/dolfin/mesh/Edge.cpp | szmurlor/fiver | 083251420eb934d860c99dcf1eb07ae5b8ba7e8c | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2006 Anders Logg
//
// This file is part of DOLFIN.
//
// DOLFIN is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.
//
// Modified by Johan Hoffman 2006.
//
// First added: 2006-06-02
// Last changed: 2011-02-08
#include <cmath>
#include <dolfin/common/types.h>
#include "Vertex.h"
#include "Edge.h"
using namespace dolfin;
//-----------------------------------------------------------------------------
double Edge::length() const
{
const uint* vertices = entities(0);
dolfin_assert(vertices);
const Vertex v0(*_mesh, vertices[0]);
const Vertex v1(*_mesh, vertices[1]);
const Point p0 = v0.point();
const Point p1 = v1.point();
double length(sqrt((p1.x()-p0.x())*(p1.x()-p0.x())
+ (p1.y()-p0.y())*(p1.y()-p0.y())
+ (p1.z()-p0.z())*(p1.z()-p0.z())));
return length;
}
//-----------------------------------------------------------------------------
double Edge::dot(const Edge& edge) const
{
const uint* v0 = entities(0);
const uint* v1 = edge.entities(0);
dolfin_assert(v0);
dolfin_assert(v1);
const MeshGeometry& g = _mesh->geometry();
const double* x00 = g.x(v0[0]);
const double* x01 = g.x(v0[1]);
const double* x10 = g.x(v1[0]);
const double* x11 = g.x(v1[1]);
double sum = 0.0;
const uint gdim = g.dim();
for (uint i = 0; i < gdim; i++)
sum += (x01[i] - x00[i]) * (x11[i] - x10[i]);
return sum;
}
//-----------------------------------------------------------------------------
| 29.6 | 79 | 0.573359 | [
"geometry"
] |
206b4c47d77ba15229599f76cb445f43a96c0dcf | 1,404 | cpp | C++ | Source/RepPhysics/LocationForSync.cpp | slonorib/PhysicsReplication | eb89504dffe1f7da0dfd05d3f845b357c9205413 | [
"MIT"
] | 2 | 2020-11-17T11:49:50.000Z | 2021-08-30T09:19:48.000Z | Source/RepPhysics/LocationForSync.cpp | slonorib/PhysicsReplication | eb89504dffe1f7da0dfd05d3f845b357c9205413 | [
"MIT"
] | null | null | null | Source/RepPhysics/LocationForSync.cpp | slonorib/PhysicsReplication | eb89504dffe1f7da0dfd05d3f845b357c9205413 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "LocationForSync.h"
FLocationForSync::FLocationForSync() :
Location(FVector::ZeroVector),
Rotation(FRotator::ZeroRotator),
LocationQuantizationLevel(EVectorQuantization::RoundWholeNumber),
RotationQuantizationLevel(ERotatorQuantization::ByteComponents)
{
}
bool FLocationForSync::NetSerialize(FArchive& Ar, UPackageMap* Map, bool& bOutSuccess)
{
bOutSuccess &= SerializeQuantizedVector(Ar, Location, LocationQuantizationLevel);
switch (RotationQuantizationLevel)
{
case ERotatorQuantization::ByteComponents:
{
Rotation.SerializeCompressed(Ar);
break;
}
case ERotatorQuantization::ShortComponents:
{
Rotation.SerializeCompressedShort(Ar);
break;
}
}
return true;
}
bool FLocationForSync::SerializeQuantizedVector(FArchive& Ar, FVector& Vector, EVectorQuantization QuantizationLevel)
{
switch (QuantizationLevel)
{
case EVectorQuantization::RoundTwoDecimals:
{
return SerializePackedVector<100, 30>(Vector, Ar);
}
case EVectorQuantization::RoundOneDecimal:
{
return SerializePackedVector<10, 27>(Vector, Ar);
}
default:
{
return SerializePackedVector<1, 24>(Vector, Ar);
}
}
}
| 25.527273 | 117 | 0.675214 | [
"vector"
] |
206c7b3fb44f585aac82ef811629afaf4dcad567 | 4,242 | cxx | C++ | examples/physics/TestEm3/GeantV/src/TestEm3Data.cxx | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2019-05-14T20:24:44.000Z | 2019-12-13T20:27:06.000Z | examples/physics/TestEm3/GeantV/src/TestEm3Data.cxx | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2019-04-18T04:16:24.000Z | 2020-05-19T21:11:50.000Z | examples/physics/TestEm3/GeantV/src/TestEm3Data.cxx | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-04-25T19:53:50.000Z | 2019-05-10T16:17:15.000Z | #include "TestEm3Data.h"
#include <stddef.h>
namespace userapplication {
//
// TestEm3DataPerPrimary
TestEm3DataPerPrimary::TestEm3DataPerPrimary(int numabs) : fNumAbsorbers(numabs)
{
fEdepInAbsorber.resize(fNumAbsorbers, 0.);
fChargedTrackL.resize(fNumAbsorbers, 0.);
fNeutralTrackL.resize(fNumAbsorbers, 0.);
Clear();
}
TestEm3DataPerPrimary::~TestEm3DataPerPrimary()
{
fEdepInAbsorber.clear();
fChargedTrackL.clear();
fNeutralTrackL.clear();
}
void TestEm3DataPerPrimary::Clear()
{
for (int k = 0; k < fNumAbsorbers; k++) {
fChargedTrackL[k] = fNeutralTrackL[k] = fEdepInAbsorber[k] = 0.;
}
fNumChargedSteps = fNumNeutralSteps = 0.;
fNumGammas = fNumElectrons = fNumPositrons = 0.;
}
TestEm3DataPerPrimary &TestEm3DataPerPrimary::operator+=(const TestEm3DataPerPrimary &other)
{
for (int k = 0; k < fNumAbsorbers; k++) {
fChargedTrackL[k] += other.fChargedTrackL[k];
fNeutralTrackL[k] += other.fNeutralTrackL[k];
fEdepInAbsorber[k] += other.fEdepInAbsorber[k];
}
fNumChargedSteps += other.fNumChargedSteps;
fNumNeutralSteps += other.fNumNeutralSteps;
fNumGammas += other.fNumGammas;
fNumElectrons += other.fNumElectrons;
fNumPositrons += other.fNumPositrons;
return *this;
}
//
// TestEm3Data
TestEm3Data::TestEm3Data(int numabs) : fNumAbsorbers(numabs)
{
fEdepInAbsorber.resize(fNumAbsorbers, 0.);
fEdepInAbsorber2.resize(fNumAbsorbers, 0.);
fChargedTrackL.resize(fNumAbsorbers, 0.);
fChargedTrackL2.resize(fNumAbsorbers, 0.);
fNeutralTrackL.resize(fNumAbsorbers, 0.);
fNeutralTrackL2.resize(fNumAbsorbers, 0.);
Clear();
}
TestEm3Data::~TestEm3Data()
{
fEdepInAbsorber.clear();
fEdepInAbsorber2.clear();
fChargedTrackL.clear();
fChargedTrackL2.clear();
fNeutralTrackL.clear();
fNeutralTrackL2.clear();
Clear();
}
void TestEm3Data::Clear()
{
for (int k = 0; k < fNumAbsorbers; k++) {
fChargedTrackL[k] = fNeutralTrackL[k] = fChargedTrackL2[k] = fNeutralTrackL2[k] = 0.;
fEdepInAbsorber[k] = fEdepInAbsorber2[k] = 0.;
}
fNumChargedSteps = fNumNeutralSteps = fNumChargedSteps2 = fNumNeutralSteps2 = 0.;
fNumGammas = fNumElectrons = fNumPositrons = 0.;
}
void TestEm3Data::AddDataPerPrimary(TestEm3DataPerPrimary &data)
{
AddChargedSteps(data.GetChargedSteps());
AddNeutralSteps(data.GetNeutralSteps());
for (int k = 0; k < fNumAbsorbers; k++) {
AddChargedTrackL(data.GetChargedTrackL(k), k);
AddNeutralTrackL(data.GetNeutralTrackL(k), k);
AddEdepInAbsorber(data.GetEdepInAbsorber(k), k);
}
AddGammas(data.GetGammas());
AddElectrons(data.GetElectrons());
AddPositrons(data.GetPositrons());
}
//
// TestEm3DataPerEvent
TestEm3DataPerEvent::TestEm3DataPerEvent(int nprimperevent, int numabs) : fNumPrimaryPerEvent(nprimperevent)
{
fPerPrimaryData.reserve(fNumPrimaryPerEvent);
for (int i = 0; i < fNumPrimaryPerEvent; ++i) {
fPerPrimaryData.push_back(TestEm3DataPerPrimary(numabs));
}
}
void TestEm3DataPerEvent::Clear()
{
for (int i = 0; i < fNumPrimaryPerEvent; ++i) {
fPerPrimaryData[i].Clear();
}
}
TestEm3DataPerEvent &TestEm3DataPerEvent::operator+=(const TestEm3DataPerEvent &other)
{
for (int i = 0; i < fNumPrimaryPerEvent; ++i) {
fPerPrimaryData[i] += other.fPerPrimaryData[i];
}
return *this;
}
//
// TestEm3DataEvents
TestEm3ThreadDataEvents::TestEm3ThreadDataEvents(int nevtbuffered, int nprimperevent, int numabs)
: fNumBufferedEvents(nevtbuffered)
{
fPerEventData.reserve(fNumBufferedEvents);
for (int i = 0; i < fNumBufferedEvents; ++i) {
fPerEventData.push_back(TestEm3DataPerEvent(nprimperevent, numabs));
}
}
bool TestEm3ThreadDataEvents::Merge(int evtslotindx, const TestEm3ThreadDataEvents &other)
{
fPerEventData[evtslotindx] += other.GetDataPerEvent(evtslotindx);
return true;
}
//
// TestEm3ThreadDataRun
bool TestEm3ThreadDataRun::Merge(int /*evtslotindx*/, const TestEm3ThreadDataRun &other)
{
const std::vector<double> &chv = other.GetCHTrackLPerLayer();
const std::vector<double> &edv = other.GetEDepPerLayer();
size_t nLayers = chv.size();
for (size_t i = 0; i < nLayers; ++i) {
fChargedTrackLPerLayer[i] += chv[i];
fEdepPerLayer[i] += edv[i];
}
return true;
}
} // namespace userapplication
| 27.72549 | 108 | 0.727016 | [
"vector"
] |
206ef49625a91f50564019cb88f1fdea685e8e6e | 6,315 | cpp | C++ | stromx/test/DeadlockOperator.cpp | roteroktober/stromx | e081a35114f68a77e99a4761946b8b8c64eb591a | [
"Apache-2.0"
] | null | null | null | stromx/test/DeadlockOperator.cpp | roteroktober/stromx | e081a35114f68a77e99a4761946b8b8c64eb591a | [
"Apache-2.0"
] | null | null | null | stromx/test/DeadlockOperator.cpp | roteroktober/stromx | e081a35114f68a77e99a4761946b8b8c64eb591a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2013 Matthias Fuchs
*
* This file is part of stromx-studio.
*
* Stromx-studio is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Stromx-studio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with stromx-studio. If not, see <http://www.gnu.org/licenses/>.
*/
#include "stromx/test/DeadlockOperator.h"
#include <stromx/runtime/DataProvider.h>
#include <stromx/runtime/Id2DataPair.h>
#include <stromx/runtime/OperatorException.h>
#include <stromx/runtime/Primitive.h>
#include <stromx/runtime/Variant.h>
#ifdef WIN32
#include <Windows.h>
#endif // WIN32
#ifdef UNIX
#include <unistd.h>
#endif // UNIX
#include "stromx/test/Config.h"
using namespace stromx::runtime;
namespace stromx
{
namespace test
{
const std::string DeadlockOperator::TYPE("DeadlockOperator");
const std::string DeadlockOperator::PACKAGE(STROMX_TEST_PACKAGE_NAME);
const Version DeadlockOperator::VERSION(1, 2, 3);
DeadlockOperator::DeadlockOperator()
: OperatorKernel(TYPE, PACKAGE, VERSION,
setupInputs(), setupOutputs(),
setupParameters()),
m_dataHasBeenLocked(false),
m_writeAccess(stromx::runtime::DataContainer(new UInt32()))
{
}
void DeadlockOperator::setParameter(unsigned int id, const Data& value)
{
try
{
switch (id)
{
case LOCK_PARAMETERS:
m_lockParameters = data_cast<Bool>(value);
break;
case LOCK_DATA:
m_lockData = data_cast<Bool>(value);
break;
case DUMMY:
m_dummy = data_cast<UInt8>(value);
break;
case OBTAIN_WRITE_ACCESS:
m_obtainWriteAccess = data_cast<Bool>(value);
break;
default:
throw WrongParameterId(id, *this);
}
}
catch (std::bad_cast&)
{
throw WrongParameterType(*parameters()[id], *this);
}
}
const DataRef DeadlockOperator::getParameter(const unsigned int id) const
{
switch (id)
{
case LOCK_PARAMETERS:
return m_lockParameters;
case LOCK_DATA:
return m_lockData;
case DUMMY:
return m_dummy;
case OBTAIN_WRITE_ACCESS:
return m_obtainWriteAccess;
default:
throw WrongParameterId(id, *this);
}
}
void DeadlockOperator::activate()
{
m_dataHasBeenLocked = false;
}
void DeadlockOperator::execute(DataProvider& provider)
{
Id2DataPair input(INPUT);
provider.receiveInputData(input);
if (m_lockParameters)
{
#ifdef WIN32
Sleep(1000); // sleep 1 second
#endif // WIN32
#ifdef UNIX
sleep(1); // sleep 1 second
#endif // UNIX
}
if (! m_dataHasBeenLocked && m_lockData)
{
m_writeAccess = WriteAccess(input.data());
m_dataHasBeenLocked = true;
}
else if (m_dataHasBeenLocked && ! m_lockData)
{
m_writeAccess = WriteAccess(DataContainer(new UInt32()));
m_dataHasBeenLocked = false;
}
WriteAccess writeAccess;
if (m_obtainWriteAccess)
writeAccess = WriteAccess(input.data());
Id2DataPair output(OUTPUT, input.data());
provider.sendOutputData(output);
}
const std::vector<const Description*> DeadlockOperator::setupInputs()
{
std::vector<const Description*> inputs;
Description* description = 0;
description = new Description(INPUT, Variant::UINT_32);
description->setTitle("Input");
inputs.push_back(description);
return inputs;
}
const std::vector<const Description*> DeadlockOperator::setupOutputs()
{
std::vector<const Description*> outputs;
Description* description = 0;
description = new Description(OUTPUT, Variant::UINT_32);
description->setTitle("Output");
outputs.push_back(description);
return outputs;
}
const std::vector<const Parameter*> DeadlockOperator::setupParameters()
{
std::vector<const Parameter*> parameters;
Parameter* param = new Parameter(LOCK_PARAMETERS, Variant::BOOL);
param->setTitle("Deadlock parameter access");
param->setAccessMode(Parameter::INITIALIZED_WRITE);
parameters.push_back(param);
param = new Parameter(LOCK_DATA, Variant::BOOL);
param->setTitle("Deadlock data access");
param->setAccessMode(Parameter::INITIALIZED_WRITE);
parameters.push_back(param);
param = new Parameter(DUMMY, Variant::UINT_8);
param->setTitle("Dummy parameter");
param->setAccessMode(Parameter::ACTIVATED_WRITE);
parameters.push_back(param);
param = new Parameter(OBTAIN_WRITE_ACCESS, Variant::BOOL);
param->setTitle("Obtain write access to data");
param->setAccessMode(Parameter::INITIALIZED_WRITE);
parameters.push_back(param);
return parameters;
}
}
}
| 32.551546 | 81 | 0.555661 | [
"vector"
] |
2074b446391ddede7fe88ed5fd5571d451cd79e8 | 4,886 | cpp | C++ | Software/GeneralTest/OscillatingProblemTestUnit.cpp | imathsoft/MathSoftDevelopment | 4c449f6e378a942cfc39081739ba4c0aa2dce4de | [
"BSD-4-Clause"
] | null | null | null | Software/GeneralTest/OscillatingProblemTestUnit.cpp | imathsoft/MathSoftDevelopment | 4c449f6e378a942cfc39081739ba4c0aa2dce4de | [
"BSD-4-Clause"
] | null | null | null | Software/GeneralTest/OscillatingProblemTestUnit.cpp | imathsoft/MathSoftDevelopment | 4c449f6e378a942cfc39081739ba4c0aa2dce4de | [
"BSD-4-Clause"
] | null | null | null | #include "CppUnitTest.h"
#include "UnitTestAux.h"
#include "../BVP/Utils/AuxUtils.h"
#include "..\BVP\Problems\OscillatingTestProblem.h"
#include "../BVP/Problems/AutonomousOscillatingProblem.h"
#include "..\BVP\Cannon\HybridCannon.h"
#include "..\BVP\ShootingSimple\BisectionComponent.h"
#include "..\BVP\MultipleShooting\HybridMultipleShootingComponent.h"
using namespace UnitTestAux;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
typedef float_50_noet numTypeMp;
namespace GeneralTest
{
TEST_CLASS(OscillatingProblemTestUnit)
{
public:
TEST_METHOD(OscillatingProblemTestMethod)
{
OscillatingTestProblem<numTypeMp> problem;
auto N = problem.GetNonLin();
Assert::IsTrue(abs(N((numTypeMp)1) - cos((numTypeMp)1)) < std::numeric_limits<numTypeMp>::epsilon(), Message("Function mismatch"));
Assert::IsTrue(abs(N((numTypeMp)3.14) - cos((numTypeMp)3.14)) < std::numeric_limits<numTypeMp>::epsilon(), Message("Function mismatch"));
auto dN = problem.GetDerivNonLin();
Assert::IsTrue(abs(dN((numTypeMp)1) + sin((numTypeMp)1)) < std::numeric_limits<numTypeMp>::epsilon(), Message("First derivative mismatch"));
Assert::IsTrue(abs(dN((numTypeMp)3.14) + sin((numTypeMp)3.14)) < std::numeric_limits<numTypeMp>::epsilon(), Message("First derivative mismatch"));
auto ddN = problem.GetSecondDerivNonLin();
Assert::IsTrue(abs(ddN((numTypeMp)1) + N((numTypeMp)1)) < std::numeric_limits<numTypeMp>::epsilon(), Message("Second derivative mismatch"));
Assert::IsTrue(abs(ddN((numTypeMp)3.14) + N((numTypeMp)3.14)) < std::numeric_limits<numTypeMp>::epsilon(), Message("SEcond derivative mismatch"));
}
TEST_METHOD(OscillatingProblemCanonHybridDoubleTestMethod)
{
double h = 0.01;
OscillatingTestProblem<double> problem;
HybridCannon<double> thc(problem, h, 10*std::numeric_limits<double>::epsilon());
auto result = thc.Shoot(0, 10, 1, 1e6, 1);
auto knots = thc.GetKnotVectorStreight();
Assert::IsTrue(abs(knots[knots.size() - 1].Value + 0.50873075567966530) < std::numeric_limits<double>::epsilon(), Message("Function mismatch"));
Assert::IsTrue(abs(knots[knots.size() - 1].Derivative - 0.69192015740737922) < std::numeric_limits<double>::epsilon(), Message("Derivative mismatch"));
}
TEST_METHOD(OscillatingProblemHybridBisectionDoubleTestMethod)
{
double h = 0.01;
OscillatingTestProblem<double> problem;
std::function<bool(const InitCondition<double>&)> checkFunc =
[](const InitCondition<double>& ic) { return (abs(ic.Value) < 10) && (abs(ic.Argument) < 10); };
HybridCannon<double> cannon(problem, h, 10*std::numeric_limits<double>::epsilon(), checkFunc);
std::function<int(const InitCondition<double>&)> evalFunc =
[](const InitCondition<double>& ic) { return sgn(ic.Value - 1.1); };
BisectionComponent<double> bc(cannon);
Assert::IsTrue(bc.DerivativeBisectionGen(0.0, 10.0, 1.0, 100, 0.0, 1.25, evalFunc));
auto knots = cannon.GetKnotVectorStreight();
Assert::IsTrue(abs(knots[knots.size() - 1].Value - 1.1) < 10*std::numeric_limits<double>::epsilon(), Message("Function mismatch"));
Assert::IsTrue(abs(knots[knots.size() - 1].Derivative + 0.32755849998534936) < std::numeric_limits<double>::epsilon(), Message("Derivative mismatch"));
Assert::IsTrue(abs(knots[0].Derivative - 0.054683724794614211) < std::numeric_limits<double>::epsilon(), Message("Derivative mismatch"));
}
TEST_METHOD(OscillatingProblemMultiShootingHybridDoubleTestMethod)
{
OscillatingTestProblem<double> problem;
auto knots = auxutils::ReadFromFile<InitCondition<double>>("TestData\\OscillatingTestProblemMSInitGuess.txt");
double targetValue = knots[knots.size() - 1].Value;
HybridMultipleShootingComponent<double> HMSComp(problem);
bool succeeded;
std::vector<InitCondition<double>> solution = HMSComp.Run(knots, 0.002, succeeded);
Assert::IsTrue(succeeded, Message("Algorithm has not succeeded"));
Assert::IsTrue(abs(solution[solution.size() - 1].Value - targetValue) < 10*std::numeric_limits<double>::epsilon(),
Message("Function mismatch " + auxutils::ToString(solution[solution.size() - 1].Value - targetValue)));
Assert::IsTrue(abs(solution[solution.size() - 1].Derivative - 1.31696084860275) < 100*std::numeric_limits<double>::epsilon(),
Message("Derivative mismatch " + auxutils::ToString(solution[solution.size() - 1].Derivative)));
Assert::IsTrue(abs(solution[0].Derivative - 1.2576169315833) < 100*std::numeric_limits<double>::epsilon(),
Message("Derivative mismatch " + auxutils::ToString(solution[0].Derivative)));
}
TEST_METHOD(StandardAutonomousOscilatingProblemMultimpeShootingDouble)
{
AutonomousOscillatingProblem<double> problem;
StandardOscillatinProblemMultipleShoothingTest<double,
AutonomousOscillatingProblem<double>>(problem);
}
};
} | 46.980769 | 155 | 0.72718 | [
"vector"
] |
2079963593e94d0ab2daed5be6cbc57e32035e5f | 4,001 | hpp | C++ | src/templates/cascade/nodes.hpp | jpxor/Cascade | 7f80e1dec932b9e205ec06e05c54df355e750776 | [
"MIT"
] | null | null | null | src/templates/cascade/nodes.hpp | jpxor/Cascade | 7f80e1dec932b9e205ec06e05c54df355e750776 | [
"MIT"
] | null | null | null | src/templates/cascade/nodes.hpp | jpxor/Cascade | 7f80e1dec932b9e205ec06e05c54df355e750776 | [
"MIT"
] | null | null | null |
#pragma once
#include <functional>
#include <memory>
#include <future>
namespace Cascade {
template<typename InType>
class Node {
public:
virtual void insert(const InType& val) = 0;
};
template<typename InType, typename OutType>
class CascadeNode : public Node<InType> {
public:
std::vector<std::shared_ptr<Node<OutType>>> child_nodes;
std::function<void(const InType&)> behaviour;
CascadeNode(){}
CascadeNode(const CascadeNode& other) = delete;
CascadeNode(std::function<void(const InType&)> node_behaviour) : behaviour(node_behaviour) {}
~CascadeNode(){}
void dispatch(const OutType& out_val){
if( child_nodes.size() == 1 ){
child_nodes[0]->insert(out_val);
return;
}
std::vector<std::future<void>> futures;
for(auto& child : child_nodes){
Node<OutType>* node = child.get();
futures.emplace_back(std::async( std::launch::async, &Node<OutType>::insert, node, out_val ) );
}
for(auto& future : futures){
future.get();
}
}
void insert(const InType& val) {
if(behaviour) {
return behaviour(val);
}
}
template<typename MType>
std::shared_ptr<CascadeNode<OutType,MType>> map(std::function<MType(const OutType&)> mapper){
auto chnode = std::make_shared<CascadeNode<OutType,MType>>();
chnode->behaviour = [chnode, mapper](const OutType& val){
chnode->dispatch(mapper(val));
};
child_nodes.push_back(chnode);
return chnode;
}
template<typename RType>
std::shared_ptr<CascadeNode<OutType,RType>> reduce(std::function<RType(const RType&, const OutType&)> reducer, RType default_val = 0){
auto chnode = std::make_shared<CascadeNode<OutType,RType>>();
chnode->behaviour = [chnode, reducer, default_val](const OutType& val){
static RType reduced = default_val;
reduced = reducer(reduced, val);
chnode->dispatch(reduced);
};
child_nodes.push_back(chnode);
return chnode;
}
std::shared_ptr<CascadeNode<OutType,OutType>> react(std::function<void(const OutType&)> reaction){
auto chnode = std::make_shared<CascadeNode<OutType,OutType>>();
chnode->behaviour = [chnode, reaction](const OutType& val){
reaction(val);
chnode->dispatch(val);
};
child_nodes.push_back(chnode);
return chnode;
}
std::shared_ptr<CascadeNode<OutType,OutType>> filter(std::function<bool(const OutType&)> predicate){
auto chnode = std::make_shared<CascadeNode<OutType,OutType>>();
chnode->behaviour = [chnode, predicate](const OutType& val){
if(predicate(val)){
chnode->dispatch(val);
}
};
child_nodes.push_back(chnode);
return chnode;
}
std::shared_ptr<CascadeNode<OutType,OutType>> delay(int ms){
auto chnode = std::make_shared<CascadeNode<OutType,OutType>>();
chnode->behaviour = [chnode, ms](const OutType& val){
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
chnode->dispatch(val);
};
child_nodes.push_back(chnode);
return chnode;
}
std::shared_ptr<CascadeNode<OutType,std::vector<OutType>>> buffer(int count){
auto chnode = std::make_shared<CascadeNode<OutType,std::vector<OutType>>>();
chnode->behaviour = [chnode, count](const OutType& val) {
static std::vector<OutType> buffer;
static std::mutex buf_mutex;
std::vector<OutType > tmp_buffer;
{ //critical section
std::lock_guard<std::mutex> guard(buf_mutex);
buffer.push_back(val);
// swap full static buffer with empty local buffer
if (buffer.size() == count) {
tmp_buffer.swap(buffer);
}
}
// push full buffer downstream without blocking
// new elements from being buffered
if (tmp_buffer.size() == count) {
chnode->dispatch(tmp_buffer);
}
};
child_nodes.push_back(chnode);
return chnode;
}
};
template<typename Type>
std::shared_ptr<CascadeNode<Type,Type>> make_node(){
auto node = std::make_shared<CascadeNode<Type,Type>>();
node->behaviour = [node](const Type& val){ node->dispatch(val); };
return node;
}
}
| 28.784173 | 136 | 0.67933 | [
"vector"
] |
2081fde84d15c310aae5c35b22c554e1c140be34 | 2,497 | hpp | C++ | CSGOSimple/features/changer/changer.hpp | GiaNTizmO/bnh_recoded | 78386b09a8f4e83e9995975a76b48803472780f6 | [
"MIT"
] | 2 | 2020-04-15T07:12:36.000Z | 2021-06-15T09:56:11.000Z | CSGOSimple/features/changer/changer.hpp | GiaNTizmO/bnh_recoded | 78386b09a8f4e83e9995975a76b48803472780f6 | [
"MIT"
] | null | null | null | CSGOSimple/features/changer/changer.hpp | GiaNTizmO/bnh_recoded | 78386b09a8f4e83e9995975a76b48803472780f6 | [
"MIT"
] | 1 | 2021-03-30T11:34:25.000Z | 2021-03-30T11:34:25.000Z | #pragma once
#include "../../options.hpp"
#include "../../valve_sdk/sdk.hpp"
#include "../../valve_sdk/csgostructs.hpp"
#include <set>
#include <string>
#include <map>
#include <d3dx9.h>
class Skins {
private:
static auto is_knife(const int i) -> bool {
return (i >= WEAPON_KNIFE_BAYONET && i < GLOVE_STUDDED_BLOODHOUND) || i == WEAPON_KNIFE_T || i == WEAPON_KNIFE;
}
template <typename T>
void PickCurrentWeapon(int* idx, int* vec_idx, std::vector<T> arr) {
if (!g_LocalPlayer) return;
if (!g_EngineClient->IsInGame()) return;
auto weapon = g_LocalPlayer->m_hActiveWeapon();
if (!weapon) return;
short wpn_idx = weapon->m_Item().m_iItemDefinitionIndex();
if (is_knife(wpn_idx)) {
*idx = values::WeaponNamesFull.at(0).definition_index;
*vec_idx = 0;
return;
}
auto wpn_it = std::find_if(arr.begin(), arr.end(), [wpn_idx](const T& a) {
return a.definition_index == wpn_idx;
});
if (wpn_it != arr.end()) {
*idx = wpn_idx;
*vec_idx = std::abs(std::distance(arr.begin(), wpn_it));
}
}
public:
struct skinInfo {
int seed = -1;
int paintkit;
int rarity;
std::string tagName;
std::string shortname; // shortname
std::string name; // full skin name
};
public:
std::unordered_map<std::string, std::set<std::string>> weaponSkins;
std::unordered_map<std::string, skinInfo> skinMap;
std::unordered_map<std::string, std::string> skinNames;
private:
int weapon_index_skins = 7;
int weapon_vector_index_skins = 0;
private:
struct item_setting {
char name[32] = "";
int definition_vector_index = 0;
int definition_index = 1;
int paint_kit_vector_index = 0;
int paint_kit_index = 0;
int definition_override_vector_index = 0;
int definition_override_index = 0;
int seed = 0;
bool enable_stat_track = false;
int stat_trak = 0;
float wear = 0.0f;
};
struct options_t {
std::map<int, item_setting> Items;
std::unordered_map<std::string, std::string> IconOverrides;
};
options_t options;
private:
auto get_icon_override(const std::string original) const -> const char* {
return options.IconOverrides.count(original) ? options.IconOverrides.at(original).data() : nullptr;
};
private:
void erase_override_if_exists_by_index(const int definition_index);
void apply_config_on_attributable_item(C_BaseAttributableItem* item, const item_setting* config, const unsigned xuid_low);
public:
void OnFrameStageNotify(bool frame_end);
public:
void Menu();
void SetupValues();
};
extern Skins* g_SkinChanger; | 29.034884 | 123 | 0.706848 | [
"vector"
] |
20876798d4a29cf1ab65ac0e211b5972e8959ed7 | 24,514 | hpp | C++ | headers/levels.hpp | HJfod/gdit | 3864e43b9b96c69ff57be3c6a2f0e69179e9d84c | [
"MIT"
] | 2 | 2020-10-25T19:57:37.000Z | 2020-10-30T03:34:28.000Z | headers/levels.hpp | HJfod/gdit | 3864e43b9b96c69ff57be3c6a2f0e69179e9d84c | [
"MIT"
] | null | null | null | headers/levels.hpp | HJfod/gdit | 3864e43b9b96c69ff57be3c6a2f0e69179e9d84c | [
"MIT"
] | null | null | null | #include <string>
#include <ShlObj.h>
#include <windows.h>
#include <vector>
#include <fstream>
#include <regex>
#include <algorithm>
#include <stdio.h>
#include <chrono>
#include "main.hpp"
#include "../ext/ZlibHelper.hpp"
#include "../ext/Base64.hpp"
#include "../ext/dirent.h"
#include "../ext/json.hpp"
namespace gd {
namespace decode {
std::string GetCCPath(std::string WHICH) {
wchar_t* localAppData = 0;
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &localAppData);
std::wstring CCW (localAppData);
std::string RESULT ( CCW.begin(), CCW.end() );
RESULT += "\\GeometryDash\\CC" + WHICH + ".dat";
CoTaskMemFree(static_cast<void*>(localAppData));
return RESULT;
}
std::vector<uint8_t> readf(std::string const& path) {
std::vector<uint8_t> buffer;
std::ifstream file(path, std::ios::ate, std::ios::binary);
if (file.is_open()) {
buffer.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read(
reinterpret_cast<char*>(buffer.data()),
buffer.size());
}
return buffer;
}
void DecodeXOR(std::vector<uint8_t>& BYTES, int KEY) {
for (auto& b : BYTES)
b ^= KEY;
}
std::vector<uint8_t> DecodeBase64(const std::string& str) {
gdcrypto::base64::Base64 b64(gdcrypto::base64::URL_SAFE_DICT);
return b64.decode(str);
}
std::string DecompressGZip(const std::vector<uint8_t> str) {
auto buffer = gdcrypto::zlib::inflateBuffer(str);
return std::string(buffer.data(), buffer.data() + buffer.size());
}
std::string DecodeCCLocalLevels() {
std::string CCPATH = decode::GetCCPath("LocalLevels");
std::vector<uint8_t> CCCONTENTS = decode::readf(CCPATH);
std::string c = methods::fread(CCPATH);
if (c._Starts_with("<?xml version=\"1.0\"?>")) {
app::decoded_data.parse<0>(methods::stc(c));
return c;
}
DecodeXOR(CCCONTENTS, 11);
auto XOR = std::string(CCCONTENTS.begin(), CCCONTENTS.end());
std::vector<uint8_t> B64 = DecodeBase64(XOR);
std::string ZLIB = DecompressGZip(B64);
return ZLIB;
}
bool SaveCCLocalLevels() {
methods::fsave(decode::GetCCPath("LocalLevels"), "<?xml version=\"1.0\"?>\n" + methods::xts(&app::decoded_data));
return true;
}
rapidxml::xml_document<>* GetCCLocalLevels() {
if (app::decoded_data.first_node() == 0)
app::decoded_data.parse<0>(methods::stc(DecodeCCLocalLevels()));
return &app::decoded_data;
}
std::string DecodeLevelData(std::string _data) {
return DecompressGZip(DecodeBase64(_data));
}
}
namespace levels {
void LoadLevels() {
if (app::levels.size() == 0) {
gd::decode::GetCCLocalLevels();
rapidxml::xml_node<>* d = app::decoded_data.first_node("plist")->first_node("dict")->first_node("d");
rapidxml::xml_node<>* fs = NULL;
std::vector<rapidxml::xml_node<>*> LIST = {};
for (rapidxml::xml_node<>* child = d->first_node(); child; child = child->next_sibling())
if (std::strcmp(child->name(), "d") == 0)
LIST.push_back(child);
app::levels = LIST;
}
}
std::string GetKey_X(rapidxml::xml_node<>* _lvl, const char* _key) {
for (rapidxml::xml_node<>* child = _lvl->first_node(); child; child = child->next_sibling())
if (std::strcmp(child->name(), "k") == 0)
if (std::strcmp(child->value(), _key) == 0)
return child->next_sibling()->value();
return "";
}
std::string SetKey(std::string *_data, std::string _key, std::string _val) {
int p = _data->find("<k>" + _key + "</k>") - 7 - _key.length();
std::string m = _data->substr(_data->find("<k>" + _key + "</k>") + 7 + _key.length());
std::string t = m.substr(1, 1);
std::string r = "<k>" + _key + "</k><" + t + ">" + _val + "</" + t + ">";
*_data = std::regex_replace(*_data, std::regex(R"(<k>)" + _key + R"(<\/k><.>.*?<\/.>)"), r, std::regex_constants::match_any);
return r;
}
bool SetKey_X(rapidxml::xml_node<>* _lvl, const char* _key, const char* _val, const char* _type = "s") {
for (rapidxml::xml_node<>* child = _lvl->first_node(); child; child = child->next_sibling())
if (std::strcmp(child->name(), "k") == 0)
if (std::strcmp(child->value(), _key) == 0) {
child->next_sibling()->first_node()->value(_val);
return true;
}
std::string n_k ("<k>" + std::string (_key) + "</k><" + std::string (_type) + ">" + std::string (_val) + "</" + std::string (_type) + ">");
rapidxml::xml_document<> n;
n.parse<0>(methods::stc(n_k));
rapidxml::xml_node<>* $k = _lvl->document()->clone_node(n.first_node("k"));
rapidxml::xml_node<>* $t = _lvl->document()->clone_node(n.first_node(_type));
_lvl->append_node($k);
_lvl->append_node($t);
return true;
}
std::string WithoutKey(const std::string DATA, std::string KEY) {
std::regex m ("<k>" + KEY + "</k><.>");
std::smatch cm;
std::regex_search(DATA, cm, m);
if (cm[0] == "") return "";
std::string T_TYPE = ((std::string)cm[0]).substr(((std::string)cm[0]).find_last_of("<") + 1, 1);
std::regex tm ("<k>" + KEY + "</k><" + T_TYPE + ">.*?</" + T_TYPE + ">");
std::smatch tcm;
std::regex_search(DATA, tcm, tm);
std::string VAL = tcm[0];
int L1 = ("<k>" + KEY + "</k><" + T_TYPE + ">").length();
return DATA.substr(0, L1) + DATA.substr(VAL.find_last_of("</") - L1 - 1);
}
rapidxml::xml_node<>* GetLevel(std::string _name, std::string *_err) {
LoadLevels();
for (int i = 0; i < app::levels.size(); i++)
if (methods::lower(GetKey_X(app::levels[i], "k2")) == methods::lower(_name))
return app::levels[i];
*_err = "Could not find level! (Replace spaces in name with _)";
return NULL;
}
int ImportLevel_X(std::string _path, std::string _lvl = "", std::string _name = "") {
std::string lvl;
if (_lvl == "")
lvl = methods::fread(_path);
else lvl = _lvl;
gd::decode::GetCCLocalLevels();
rapidxml::xml_node<>* d = app::decoded_data.first_node("plist")->first_node("dict")->first_node("d");
rapidxml::xml_node<>* fs = NULL;
for (rapidxml::xml_node<>* child = d->first_node(); child; child = child->next_sibling()) {
if (std::strcmp(child->name(), "k") == 0)
if (std::string(child->value()).find("k_") != std::string::npos) {
child->first_node()->value(methods::stc("k_" + std::to_string(std::stoi(std::string(child->value()).substr(2)) + 1)));
if (fs == NULL) fs = child;
}
}
rapidxml::xml_document<> lv;
lv.parse<0>(methods::stc(lvl));
SetKey_X(lv.first_node(), "k2", _name.c_str());
rapidxml::xml_node<>* ln = lv.first_node();
rapidxml::xml_node<>* lnt = app::decoded_data.clone_node(ln);
rapidxml::xml_document<> k_ix;
k_ix.parse<0>(methods::stc("<k>k_0</k>"));
rapidxml::xml_node<>* lk_ix = app::decoded_data.clone_node(k_ix.first_node());
d->insert_node(fs, lk_ix);
d->insert_node(fs, lnt);
gd::decode::SaveCCLocalLevels();
return GDIT_IMPORT_SUCCESS;
}
struct gd_obj {
std::string data;
};
struct obj_group {
std::string obj_type;
std::vector<gd_obj> objs;
};
struct gd_color {
unsigned int id;
std::string data;
};
struct start_obj {
std::vector<gd_color> colors;
nlohmann::json get_data() {
nlohmann::json j = nlohmann::json::array();
for (gd_color c : this->colors)
j.push_back({
{ "id", c.id },
{ "data", c.data }
});
return j;
};
};
std::vector<gd_obj> GetObjects(std::string _decoded_data, std::vector<obj_group>* _ordered = NULL) {
std::string d = _decoded_data.substr(_decoded_data.find(";") + 1);
std::vector<gd_obj> res = {};
std::vector<obj_group> orres = {};
while (d.length() > 0) {
if (d.find(";") == std::string::npos) break;
std::string obj = d.substr(0, d.find(";"));
d = d.substr(obj.length() + 1);
if (obj.empty()) continue;
res.push_back({ obj });
if (_ordered != NULL) {
std::string id = obj.substr(obj.find_first_of(",") + 1);
id = id.substr(0, id.find_first_of(","));
int ix = -1, i = 0;
for (obj_group gr : orres)
if (gr.obj_type == id) ix = i; else i++;
if (ix == -1)
orres.push_back({ id, { { obj } } });
else
orres[ix].objs.push_back({ obj });
}
}
*_ordered = orres;
return res;
}
start_obj GetStartKey(std::string _decoded_data) {
std::string s = _decoded_data.substr(0, _decoded_data.find_first_of(";"));
s = s.substr(s.find_first_of("kS38,") + 5);
s = s.substr(0, s.find_first_of(","));
start_obj res = { {} };
for (std::string ss : methods::split(s, "|")) {
std::vector<std::string> sss = methods::split(ss, "_");
for (int i = 0; i < sss.size(); i += 2)
if (sss[i] == "6")
res.colors.push_back({ std::stoul(sss[i + 1]), ss });
}
return res;
}
}
}
namespace gdit {
nlohmann::json GenerateGDitLevelInfo(rapidxml::xml_node<>* _data) {
std::string song = gd::levels::GetKey_X(_data, "k8");
return {
{ "name", gd::levels::GetKey_X(_data, "k2") },
{ "song", (song == "") ? ("<k>k45</k><i>" + gd::levels::GetKey_X(_data, "k45") + "</i>") : ("<k>k8</k><i>" + song + "</i>") },
{ "init-time", methods::time() }
};
}
int InitGdit(std::string _name, rapidxml::xml_node<>* _lvl, std::string *_rpath, bool nomaster = false) {
std::string path = app::dir::main + "\\" + methods::lower(_name);
if (_mkdir(path.c_str()) != 0)
return GDIT_COULD_NOT_MAKE_DIR;
else {
std::string fpath = path + "\\" + "master\\" + methods::lower(_name) + "." + ext::master + ".";
if (!nomaster)
if (_mkdir((path + "\\" + "master").c_str()) != 0)
return GDIT_COULD_NOT_MAKE_DIR;
else {
methods::fsave(fpath + ext::leveldata, gd::levels::GetKey_X(_lvl, "k4"));
//methods::fsave(fpath + ext::levelinfo, gd::levels::WithoutKey(_lvl, "k4"));
methods::fsave(fpath + "og." + ext::level, methods::xts(_lvl));
methods::fsave(fpath + ext::main, gdit::GenerateGDitLevelInfo(_lvl).dump());
*_rpath = fpath;
}
else *_rpath = path;
return GDIT_INIT_SUCCESS;
}
}
bool VerifyDirHasParts (std::string f, int n) {
return f.substr(f.find_last_of("\\") + 1)._Starts_with("part_");
}
bool VerifyDirIsRepo(std::string _dir, int _type) {
if (_type == GDIT_TYPE_GDIT)
return methods::fexists(_dir + "\\master");
return methods::dread(_dir, &VerifyDirHasParts).size() > 0;
}
std::vector<std::string> GetAllRepos(int _type = GDIT_TYPE_GDIT) {
return methods::dread(app::dir::main.c_str(), &VerifyDirIsRepo, _type);
}
bool GditExists(std::string _name) {
return methods::fexists(app::dir::main + "\\" + _name + "\\master") ||
methods::fexists(app::dir::main + "\\" + _name + "\\parts");
}
std::string GetGditLevel(std::string _name) {
std::string to = methods::workdir() + "\\" + app::dir::copies + "\\" + _name + ".copy." + ext::level;
methods::fcopy(
app::dir::main + "\\" + _name + "\\master\\" + _name + ".master.og." + ext::level, to
);
return to;
}
std::string GetGDitNameFromPath(std::string _path) {
_path = methods::replace(_path, "/", "\\");
std::string sh = _path.substr(_path.find_last_of("\\", _path.length()) + 1);
return sh.substr(0, sh.find_first_of(".", 0));
}
std::string GetGDitNameFromCommit(std::string _path) {
if (!methods::fexists(_path)) return "";
std::string txt = methods::fread(_path);
txt = txt.substr(txt.find("\nDATA ") + 5);
return methods::sanitize(nlohmann::json::parse(txt.substr(txt.find_first_of("\n") + 1,
std::stoi(txt.substr(txt.find_first_of(" "), txt.find_first_of("\n") - txt.find_first_of(" ")))
))["gdit_name"].dump());
}
int AddGditPart(std::string _path, std::string _creator) {
std::string name = GetGDitNameFromPath(_path);
std::string tp = "";
std::string rpath;
std::string gdname = name + "@" + _creator;
if (GditExists(name))
tp = app::dir::main + "\\" + name;
else {
rapidxml::xml_document<> s;
s.parse<0>(methods::stc(methods::fread(_path)));
InitGdit(name, s.first_node(), &rpath, true);
}
tp = tp == "" ? rpath : tp;
if (!methods::fexists(tp + "\\part_" + _creator))
if (_mkdir((tp + "\\part_" + _creator).c_str()) != 0)
return GDIT_COULD_NOT_MAKE_DIR;
methods::fcopy(
_path, tp + "\\part_" + _creator + "\\" + name + ".og." + ext::level
);
methods::fcopy(
_path, tp + "\\part_" + _creator + "\\" + name + ".work." + ext::level
);
methods::fsave(tp + "\\part_" + _creator + "\\" + name + "." + ext::main, nlohmann::json({
{ "name", gdname }
}).dump());
gd::levels::ImportLevel_X(_path, "", gdname);
return GDIT_IMPORT_SUCCESS;
}
int EditPart(std::string _gdit) {
if (app::settings::sval("username") == "")
return GDIT_USERNAME_NOT_SET;
std::string dir = methods::workdir() + "\\" + app::dir::main + "\\" + _gdit + "\\" + "part_" + app::settings::sval("username");
std::string gd_name = methods::sanitize(nlohmann::json::parse(methods::fread(dir + "\\" + _gdit + "." + ext::main))["name"].dump());
std::string data = methods::fread(dir + "\\" + _gdit + ".work." + ext::level);
if (data == "")
return GDIT_PART_WORK_LEVEL_NOT_FOUND;
gd::levels::ImportLevel_X("", data, gd_name);
return GDIT_SUCCESS;
}
int CommitChanges(std::string _gdit, std::string* _out = NULL, bool _c_an = false) {
if (app::settings::sval("username") == "")
return GDIT_USERNAME_NOT_SET;
std::string dir = methods::workdir() + "\\" + app::dir::main + "\\" + _gdit + "\\" + "part_" + app::settings::sval("username");
std::string gd_name = methods::sanitize(nlohmann::json::parse(methods::fread(dir + "\\" + _gdit + "." + ext::main))["name"].dump());
std::string err;
rapidxml::xml_node<>* lvl = gd::levels::GetLevel(gd_name, &err);
if (lvl == NULL) {
*_out = err;
return GDIT_LEVEL_DOESNT_EXIST;
}
std::string olvls = methods::fread(dir + "\\" + _gdit + ".work." + ext::level);
if (olvls == "")
return GDIT_LEVEL_DOESNT_EXIST;
rapidxml::xml_document<> oldc;
oldc.parse<0>(methods::stc(olvls));
rapidxml::xml_node<>* olvl = oldc.first_node();
methods::fsave(dir + "\\" + _gdit + ".work." + ext::level, methods::xts(lvl));
std::string new_k4 = gd::levels::GetKey_X(lvl, "k4");
std::string og_k4 = gd::levels::GetKey_X(olvl, "k4");
bool skip = false;
if (new_k4 == og_k4) {
if (_out != NULL) *_out = "No changes found.\n";
if (_c_an) skip = true; else return GDIT_COMMIT_SUCCESS;
}
std::vector<std::string> obj_removed = {};
std::vector<std::string> obj_added = {};
gd::levels::start_obj obj_start = {};
if (!skip) {
std::vector<gd::levels::obj_group> objs = {};
std::string dec_og = gd::decode::DecodeLevelData(og_k4);
std::string dec_new= gd::decode::DecodeLevelData(new_k4);
std::vector<gd::levels::gd_obj> new_obj = gd::levels::GetObjects(dec_og, &objs);
obj_start = gd::levels::GetStartKey(dec_new);
/*
for (gd::levels::obj_group gr : objs) {
std::cout << gr.obj_type << ":\t [ ";
for (gd::levels::gd_obj o : gr.objs)
std::cout << o.data << "; ";
std::cout << " ]" << std::endl;
}
//*/
std::string d = dec_new.substr(dec_new.find(";") + 1);
int obj_count = 0;
while (d.length() > 0) {
if (d.find(";") == std::string::npos) break;
std::string obj = d.substr(0, d.find(";"));
d = d.substr(obj.length() + 1);
if (obj.empty()) continue;
obj_count++;
std::string id = obj.substr(obj.find_first_of(",") + 1);
id = id.substr(0, id.find_first_of(","));
int ix = -1, i = 0;
for (gd::levels::obj_group gr : objs)
if (gr.obj_type == id) ix = i; else i++;
bool found = false;
int j = 0;
if (ix == -1) {
obj_added.push_back(obj);
continue;
} else for (gd::levels::gd_obj o : objs[ix].objs)
if (o.data == obj) {
found = true;
objs[ix].objs.erase(objs[ix].objs.begin() + j);
break;
} else j++;
if (!found)
obj_added.push_back(obj);
}
/*
std::cout << "new level object count:\t" << obj_count << std::endl;
std::cout << "old level object count:\t" << new_obj.size() << std::endl;
*/
for (gd::levels::obj_group gr : objs)
for (gd::levels::gd_obj go : gr.objs)
obj_removed.push_back(go.data);
}
std::string output_file = "";
nlohmann::json ij;
ij["type"] = GDIT_COMMIT_VERSION;
ij["gdit_name"] = _gdit;
ij["start_color"] = obj_start.get_data();
ij["added"] = obj_added;
ij["removed"] = obj_removed;
output_file += "VERSION " + methods::sanitize(ij["type"].dump()) + "\n";
output_file += "DATA " + std::to_string(ij.dump().length()) + "\n" + ij.dump() + "\n";
methods::fsave(dir + "\\" + methods::time("_") + ".commit." + ext::commit, output_file);
if (_out != NULL && !skip) {
*_out = "Added objects: \t" + std::to_string(obj_added.size()) + "\n";
*_out +="Removed objects: \t" + std::to_string(obj_removed.size()) + "\n";
}
return GDIT_COMMIT_SUCCESS;
}
int ResetCommits(std::string _gdit) {
if (app::settings::sval("username") == "")
return GDIT_USERNAME_NOT_SET;
std::string dir = methods::workdir() + "\\" + app::dir::main + "\\" + _gdit + "\\" + "part_" + app::settings::sval("username");
for (std::string com : methods::dall(methods::workdir() + "\\" + app::dir::main + "\\" + _gdit + "\\" + "part_" + app::settings::sval("username")))
if (com.find(".commit.") != std::string::npos)
remove((methods::workdir() + "\\" + app::dir::main + "\\" + _gdit + "\\" + "part_" + app::settings::sval("username") + "\\" + com).c_str());
methods::fcopy(
dir + "\\" + _gdit + ".og." + ext::level,
dir + "\\" + _gdit + ".work." + ext::level
);
return GDIT_COMMIT_SUCCESS;
}
int MergeCommit(std::string _part_path) {
std::string name = GetGDitNameFromCommit(_part_path);
std::string dir = methods::workdir() + "\\" + app::dir::main + "\\" + name + "\\master";
if (!methods::fexists(dir))
return GDIT_MERGE_MASTER_DOESNT_EXIST;
std::string base = methods::fread(dir + "\\" + name + ".master." + ext::leveldata);
std::string commit = methods::fread(_part_path);
std::string base_data;
if (base._Starts_with("H4sIAAAA")) {
base_data = gd::decode::DecodeLevelData(base);
} else base_data = base;
int s = commit.find_first_of(" ") + 1;
if (std::stoi(commit.substr(s, commit.find_first_of("\n") - s - 1 /* /r */)) != GDIT_COMMIT_VERSION)
return GDIT_MERGE_VERSION_NEWER;
int b = commit.find("\nDATA ") + 6;
nlohmann::json j = nlohmann::json::parse(commit.substr(commit.find_first_of("\n", b) + 1));
methods::range_::super available_colors = { 0, 1500 };
for (gd::levels::gd_color o_s_c : gd::levels::GetStartKey(base_data).colors)
available_colors.exclude(o_s_c.id); // this should prolly work.
// BUT IT NEEDS TESTING!!!!!!!!
// TESTING!!!!!!!!
// TEST THIS
methods::range forbidden_colors = { 1000, 1012 }; // ignore bg, line, etc.
for (nlohmann::json s_c : j["start_color"])
if (!forbidden_colors.contains(s_c["id"]))
if (available_colors.contains(s_c))
{ /* TODO */ }
for (std::string obj : j["removed"])
base_data = methods::remove(base_data, obj + ";", false);
std::vector<int> add_colors = {};
std::string add = "";
for (std::string obj : j["added"]) {
add += methods::sanitize(obj) + ";";
}
base_data += add;
//methods::fsave(dir + "\\" + name + ".master." + ext::leveldata, base_data);
return GDIT_MERGE_SUCCESS;
}
std::string ViewGditLevel(std::string _gdit, bool _og = false) {
gd::decode::GetCCLocalLevels();
std::string dir = methods::workdir() + "\\" + app::dir::main + "\\" + _gdit + "\\master";
if (_og) {
std::string og = methods::fread(dir + "\\" + _gdit + ".master.og." + ext::level);
gd::levels::SetKey(&og, "k2", "view_og@" + _gdit);
gd::levels::ImportLevel_X("", og);
return "Added to your GD levels under the name view_og@" + _gdit;
}
std::string base = methods::fread(dir + "\\" + _gdit + ".master." + ext::leveldata);
nlohmann::json base_info = nlohmann::json::parse(methods::fread(dir + "\\" + _gdit + ".master." + ext::main));
std::string lvl = "<d><k>kCEK</k><i>4</i><k>k4</k><s>" + base
+ "</s><k5>gdit</k5><k>k13</k><t /><k>k21</k><i>2</i>" + base_info["song"].dump() + "</d>";
gd::levels::ImportLevel_X("", lvl, "view@" + _gdit);
return "Added to your GD levels with the name view@" + _gdit;
}
} | 39.795455 | 156 | 0.494778 | [
"object",
"vector"
] |
2087c869bbcdd008f420236e13aa1312fb7622a1 | 3,151 | cpp | C++ | example-360Player/src/ofApp.cpp | kuflex/ofxOpenVR | 1d5c82ff2746dcb2d76b032d71dd0c64b807c01f | [
"MIT"
] | null | null | null | example-360Player/src/ofApp.cpp | kuflex/ofxOpenVR | 1d5c82ff2746dcb2d76b032d71dd0c64b807c01f | [
"MIT"
] | null | null | null | example-360Player/src/ofApp.cpp | kuflex/ofxOpenVR | 1d5c82ff2746dcb2d76b032d71dd0c64b807c01f | [
"MIT"
] | 1 | 2019-03-19T14:39:15.000Z | 2019-03-19T14:39:15.000Z | //Modified example for panoramic player by Kuflex, 2017
// Thanks to @num3ric for sharing this:
// http://discourse.libcinder.org/t/360-vr-video-player-for-ios-in-cinder/294/6
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(false);
ofDisableArbTex();
// We need to pass the method we want ofxOpenVR to call when rending the scene
openVR.setup(std::bind(&ofApp::render, this, std::placeholders::_1));
pano.setup(openVR, "DSCN0143.JPG");
bShowHelp = true;
}
//--------------------------------------------------------------
void ofApp::exit() {
openVR.exit();
}
//--------------------------------------------------------------
void ofApp::update(){
openVR.update();
}
//--------------------------------------------------------------
void ofApp::draw(){
openVR.render();
//openVR.renderDistortion();
openVR.renderScene(vr::Eye_Left);
openVR.drawDebugInfo(10.0f, 500.0f);
// Help
if (bShowHelp) {
_strHelp.str("");
_strHelp.clear();
_strHelp << "HELP (press h to toggle): " << endl;
_strHelp << "Drag and drop a 360 spherical (equirectangular) image to load it in the player. " << endl;
_strHelp << "Toggle OpenVR mirror window (press: m)." << endl;
ofDrawBitmapStringHighlight(_strHelp.str(), ofPoint(10.0f, 20.0f), ofColor(ofColor::black, 100.0f));
}
}
//--------------------------------------------------------------
void ofApp::render(vr::Hmd_Eye nEye) {
openVR.pushMatricesForRender(nEye);
pano.draw();
openVR.popMatricesForRender();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key) {
switch (key) {
case 'h':
bShowHelp = !bShowHelp;
break;
case 'm':
openVR.toggleMirrorWindow();
break;
default:
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo) {
//TODO: Why do we need to parse the path to replace the \ by / in order to work?
std::string path = dragInfo.files[0];
std::replace(path.begin(), path.end(), '\\', '/');
pano.image().load(path);
pano.image().update();
}
| 24.238462 | 105 | 0.452872 | [
"render"
] |
2088483e58e9cf9c4b5ea6ca976c888d3c373d3e | 40,804 | cpp | C++ | B2G/gecko/xpfe/components/directory/nsDirectoryViewer.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/xpfe/components/directory/nsDirectoryViewer.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/xpfe/components/directory/nsDirectoryViewer.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
A directory viewer object. Parses "application/http-index-format"
per Lou Montulli's original spec:
http://www.mozilla.org/projects/netlib/dirindexformat.html
One added change is for a description entry, for when the
target does not match the filename
*/
#include "nsDirectoryViewer.h"
#include "nsIDirIndex.h"
#include "jsapi.h"
#include "nsCOMPtr.h"
#include "nsCRT.h"
#include "nsEscape.h"
#include "nsIEnumerator.h"
#include "nsIRDFService.h"
#include "nsRDFCID.h"
#include "rdf.h"
#include "nsIScriptContext.h"
#include "nsIScriptGlobalObject.h"
#include "nsIServiceManager.h"
#include "nsISupportsArray.h"
#include "nsIXPConnect.h"
#include "nsEnumeratorUtils.h"
#include "nsString.h"
#include "nsXPIDLString.h"
#include "nsReadableUtils.h"
#include "nsITextToSubURI.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIFTPChannel.h"
#include "nsIWindowWatcher.h"
#include "nsIPrompt.h"
#include "nsIAuthPrompt.h"
#include "nsIProgressEventSink.h"
#include "nsIDOMWindow.h"
#include "nsIDOMWindowCollection.h"
#include "nsIDOMElement.h"
#include "nsIStreamConverterService.h"
#include "nsICategoryManager.h"
#include "nsXPCOMCID.h"
#include "nsIDocument.h"
#include "mozilla/Preferences.h"
using namespace mozilla;
static const int FORMAT_HTML = 2;
static const int FORMAT_XUL = 3;
//----------------------------------------------------------------------
//
// Common CIDs
//
static NS_DEFINE_CID(kRDFServiceCID, NS_RDFSERVICE_CID);
// Various protocols we have to special case
static const char kFTPProtocol[] = "ftp://";
//----------------------------------------------------------------------
//
// nsHTTPIndex
//
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsHTTPIndex)
NS_INTERFACE_MAP_ENTRY(nsIHTTPIndex)
NS_INTERFACE_MAP_ENTRY(nsIRDFDataSource)
NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
NS_INTERFACE_MAP_ENTRY(nsIDirIndexListener)
NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
NS_INTERFACE_MAP_ENTRY(nsIFTPEventSink)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIHTTPIndex)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION_1(nsHTTPIndex, mInner)
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsHTTPIndex)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsHTTPIndex)
NS_IMETHODIMP
nsHTTPIndex::GetInterface(const nsIID &anIID, void **aResult )
{
if (anIID.Equals(NS_GET_IID(nsIFTPEventSink))) {
// If we don't have a container to store the logged data
// then don't report ourselves back to the caller
if (!mRequestor)
return NS_ERROR_NO_INTERFACE;
*aResult = static_cast<nsIFTPEventSink*>(this);
NS_ADDREF(this);
return NS_OK;
}
if (anIID.Equals(NS_GET_IID(nsIPrompt))) {
if (!mRequestor)
return NS_ERROR_NO_INTERFACE;
nsCOMPtr<nsIDOMWindow> aDOMWindow = do_GetInterface(mRequestor);
if (!aDOMWindow)
return NS_ERROR_NO_INTERFACE;
nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
return wwatch->GetNewPrompter(aDOMWindow, (nsIPrompt**)aResult);
}
if (anIID.Equals(NS_GET_IID(nsIAuthPrompt))) {
if (!mRequestor)
return NS_ERROR_NO_INTERFACE;
nsCOMPtr<nsIDOMWindow> aDOMWindow = do_GetInterface(mRequestor);
if (!aDOMWindow)
return NS_ERROR_NO_INTERFACE;
nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
return wwatch->GetNewAuthPrompter(aDOMWindow, (nsIAuthPrompt**)aResult);
}
if (anIID.Equals(NS_GET_IID(nsIProgressEventSink))) {
if (!mRequestor)
return NS_ERROR_NO_INTERFACE;
nsCOMPtr<nsIProgressEventSink> sink = do_GetInterface(mRequestor);
if (!sink)
return NS_ERROR_NO_INTERFACE;
*aResult = sink;
NS_ADDREF((nsISupports*)*aResult);
return NS_OK;
}
return NS_ERROR_NO_INTERFACE;
}
NS_IMETHODIMP
nsHTTPIndex::OnFTPControlLog(bool server, const char *msg)
{
NS_ENSURE_TRUE(mRequestor, NS_OK);
nsCOMPtr<nsIScriptGlobalObject> scriptGlobal(do_GetInterface(mRequestor));
NS_ENSURE_TRUE(scriptGlobal, NS_OK);
nsIScriptContext *context = scriptGlobal->GetContext();
NS_ENSURE_TRUE(context, NS_OK);
JSContext* cx = context->GetNativeContext();
NS_ENSURE_TRUE(cx, NS_OK);
JSObject* global = JS_GetGlobalForScopeChain(cx);
NS_ENSURE_TRUE(global, NS_OK);
jsval params[2];
nsString unicodeMsg;
unicodeMsg.AssignWithConversion(msg);
JSAutoRequest ar(cx);
JSString* jsMsgStr = JS_NewUCStringCopyZ(cx, (jschar*) unicodeMsg.get());
params[0] = BOOLEAN_TO_JSVAL(server);
params[1] = STRING_TO_JSVAL(jsMsgStr);
jsval val;
JS_CallFunctionName(cx,
global,
"OnFTPControlLog",
2,
params,
&val);
return NS_OK;
}
NS_IMETHODIMP
nsHTTPIndex::SetEncoding(const char *encoding)
{
mEncoding = encoding;
return(NS_OK);
}
NS_IMETHODIMP
nsHTTPIndex::GetEncoding(char **encoding)
{
NS_PRECONDITION(encoding, "null ptr");
if (! encoding)
return(NS_ERROR_NULL_POINTER);
*encoding = ToNewCString(mEncoding);
if (!*encoding)
return(NS_ERROR_OUT_OF_MEMORY);
return(NS_OK);
}
NS_IMETHODIMP
nsHTTPIndex::OnStartRequest(nsIRequest *request, nsISupports* aContext)
{
nsresult rv;
mParser = do_CreateInstance(NS_DIRINDEXPARSER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
rv = mParser->SetEncoding(mEncoding.get());
if (NS_FAILED(rv)) return rv;
rv = mParser->SetListener(this);
if (NS_FAILED(rv)) return rv;
rv = mParser->OnStartRequest(request,aContext);
if (NS_FAILED(rv)) return rv;
// This should only run once...
// Unless we don't have a container to start with
// (ie called from bookmarks as an rdf datasource)
if (mBindToGlobalObject && mRequestor) {
mBindToGlobalObject = false;
// Now get the content viewer container's script object.
nsCOMPtr<nsIScriptGlobalObject> scriptGlobal(do_GetInterface(mRequestor));
NS_ENSURE_TRUE(scriptGlobal, NS_ERROR_FAILURE);
nsIScriptContext *context = scriptGlobal->GetContext();
NS_ENSURE_TRUE(context, NS_ERROR_FAILURE);
JSContext* cx = context->GetNativeContext();
JSObject* global = JS_GetGlobalForScopeChain(cx);
// Using XPConnect, wrap the HTTP index object...
static NS_DEFINE_CID(kXPConnectCID, NS_XPCONNECT_CID);
nsCOMPtr<nsIXPConnect> xpc(do_GetService(kXPConnectCID, &rv));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIXPConnectJSObjectHolder> wrapper;
rv = xpc->WrapNative(cx,
global,
static_cast<nsIHTTPIndex*>(this),
NS_GET_IID(nsIHTTPIndex),
getter_AddRefs(wrapper));
NS_ASSERTION(NS_SUCCEEDED(rv), "unable to xpconnect-wrap http-index");
if (NS_FAILED(rv)) return rv;
JSObject* jsobj;
rv = wrapper->GetJSObject(&jsobj);
NS_ASSERTION(NS_SUCCEEDED(rv),
"unable to get jsobj from xpconnect wrapper");
if (NS_FAILED(rv)) return rv;
jsval jslistener = OBJECT_TO_JSVAL(jsobj);
// ...and stuff it into the global context
JSAutoRequest ar(cx);
bool ok = JS_SetProperty(cx, global, "HTTPIndex", &jslistener);
NS_ASSERTION(ok, "unable to set Listener property");
if (!ok)
return NS_ERROR_FAILURE;
}
if (!aContext) {
nsCOMPtr<nsIChannel> channel(do_QueryInterface(request));
NS_ASSERTION(channel, "request should be a channel");
// lets hijack the notifications:
channel->SetNotificationCallbacks(this);
// now create the top most resource
nsCOMPtr<nsIURI> uri;
channel->GetURI(getter_AddRefs(uri));
nsAutoCString entryuriC;
uri->GetSpec(entryuriC);
nsCOMPtr<nsIRDFResource> entry;
rv = mDirRDF->GetResource(entryuriC, getter_AddRefs(entry));
NS_ConvertUTF8toUTF16 uriUnicode(entryuriC);
nsCOMPtr<nsIRDFLiteral> URLVal;
rv = mDirRDF->GetLiteral(uriUnicode.get(), getter_AddRefs(URLVal));
Assert(entry, kNC_URL, URLVal, true);
mDirectory = do_QueryInterface(entry);
}
else
{
// Get the directory from the context
mDirectory = do_QueryInterface(aContext);
}
if (!mDirectory) {
request->Cancel(NS_BINDING_ABORTED);
return NS_BINDING_ABORTED;
}
// Mark the directory as "loading"
rv = Assert(mDirectory, kNC_Loading,
kTrueLiteral, true);
if (NS_FAILED(rv)) return rv;
return NS_OK;
}
NS_IMETHODIMP
nsHTTPIndex::OnStopRequest(nsIRequest *request,
nsISupports* aContext,
nsresult aStatus)
{
// If mDirectory isn't set, then we should just bail. Either an
// error occurred and OnStartRequest() never got called, or
// something exploded in OnStartRequest().
if (! mDirectory)
return NS_BINDING_ABORTED;
mParser->OnStopRequest(request,aContext,aStatus);
nsresult rv;
nsXPIDLCString commentStr;
mParser->GetComment(getter_Copies(commentStr));
nsCOMPtr<nsIRDFLiteral> comment;
rv = mDirRDF->GetLiteral(NS_ConvertASCIItoUTF16(commentStr).get(), getter_AddRefs(comment));
if (NS_FAILED(rv)) return rv;
rv = Assert(mDirectory, kNC_Comment, comment, true);
if (NS_FAILED(rv)) return rv;
// hack: Remove the 'loading' annotation (ignore errors)
AddElement(mDirectory, kNC_Loading, kTrueLiteral);
return NS_OK;
}
NS_IMETHODIMP
nsHTTPIndex::OnDataAvailable(nsIRequest *request,
nsISupports* aContext,
nsIInputStream* aStream,
uint64_t aSourceOffset,
uint32_t aCount)
{
// If mDirectory isn't set, then we should just bail. Either an
// error occurred and OnStartRequest() never got called, or
// something exploded in OnStartRequest().
if (! mDirectory)
return NS_BINDING_ABORTED;
return mParser->OnDataAvailable(request, mDirectory, aStream, aSourceOffset, aCount);
}
nsresult
nsHTTPIndex::OnIndexAvailable(nsIRequest* aRequest, nsISupports *aContext,
nsIDirIndex* aIndex)
{
nsCOMPtr<nsIRDFResource> parentRes = do_QueryInterface(aContext);
if (!parentRes) {
NS_ERROR("Could not obtain parent resource");
return(NS_ERROR_UNEXPECTED);
}
const char* baseStr;
parentRes->GetValueConst(&baseStr);
if (! baseStr) {
NS_ERROR("Could not reconstruct base uri");
return NS_ERROR_UNEXPECTED;
}
// we found the filename; construct a resource for its entry
nsAutoCString entryuriC(baseStr);
nsXPIDLCString filename;
nsresult rv = aIndex->GetLocation(getter_Copies(filename));
if (NS_FAILED(rv)) return rv;
entryuriC.Append(filename);
// if its a directory, make sure it ends with a trailing slash.
uint32_t type;
rv = aIndex->GetType(&type);
if (NS_FAILED(rv))
return rv;
bool isDirType = (type == nsIDirIndex::TYPE_DIRECTORY);
if (isDirType && entryuriC.Last() != '/') {
entryuriC.Append('/');
}
nsCOMPtr<nsIRDFResource> entry;
rv = mDirRDF->GetResource(entryuriC, getter_AddRefs(entry));
// At this point, we'll (hopefully) have found the filename and
// constructed a resource for it, stored in entry. So now take a
// second pass through the values and add as statements to the RDF
// datasource.
if (entry && NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIRDFLiteral> lit;
nsString str;
str.AssignWithConversion(entryuriC.get());
rv = mDirRDF->GetLiteral(str.get(), getter_AddRefs(lit));
if (NS_SUCCEEDED(rv)) {
rv = Assert(entry, kNC_URL, lit, true);
if (NS_FAILED(rv)) return rv;
nsXPIDLString xpstr;
// description
rv = aIndex->GetDescription(getter_Copies(xpstr));
if (NS_FAILED(rv)) return rv;
if (xpstr.Last() == '/')
xpstr.Truncate(xpstr.Length() - 1);
rv = mDirRDF->GetLiteral(xpstr.get(), getter_AddRefs(lit));
if (NS_FAILED(rv)) return rv;
rv = Assert(entry, kNC_Description, lit, true);
if (NS_FAILED(rv)) return rv;
// contentlength
int64_t size;
rv = aIndex->GetSize(&size);
if (NS_FAILED(rv)) return rv;
int64_t minus1 = UINT64_MAX;
if (size != minus1) {
int32_t intSize;
LL_L2I(intSize, size);
// XXX RDF should support 64 bit integers (bug 240160)
nsCOMPtr<nsIRDFInt> val;
rv = mDirRDF->GetIntLiteral(intSize, getter_AddRefs(val));
if (NS_FAILED(rv)) return rv;
rv = Assert(entry, kNC_ContentLength, val, true);
if (NS_FAILED(rv)) return rv;
}
// lastmodified
PRTime tm;
rv = aIndex->GetLastModified(&tm);
if (NS_FAILED(rv)) return rv;
if (tm != -1) {
nsCOMPtr<nsIRDFDate> val;
rv = mDirRDF->GetDateLiteral(tm, getter_AddRefs(val));
if (NS_FAILED(rv)) return rv;
rv = Assert(entry, kNC_LastModified, val, true);
}
// filetype
uint32_t type;
rv = aIndex->GetType(&type);
switch (type) {
case nsIDirIndex::TYPE_UNKNOWN:
rv = mDirRDF->GetLiteral(NS_LITERAL_STRING("UNKNOWN").get(), getter_AddRefs(lit));
break;
case nsIDirIndex::TYPE_DIRECTORY:
rv = mDirRDF->GetLiteral(NS_LITERAL_STRING("DIRECTORY").get(), getter_AddRefs(lit));
break;
case nsIDirIndex::TYPE_FILE:
rv = mDirRDF->GetLiteral(NS_LITERAL_STRING("FILE").get(), getter_AddRefs(lit));
break;
case nsIDirIndex::TYPE_SYMLINK:
rv = mDirRDF->GetLiteral(NS_LITERAL_STRING("SYMLINK").get(), getter_AddRefs(lit));
break;
}
if (NS_FAILED(rv)) return rv;
rv = Assert(entry, kNC_FileType, lit, true);
if (NS_FAILED(rv)) return rv;
}
// Since the definition of a directory depends on the protocol, we would have
// to do string comparisons all the time.
// But we're told if we're a container right here - so save that fact
if (isDirType)
Assert(entry, kNC_IsContainer, kTrueLiteral, true);
else
Assert(entry, kNC_IsContainer, kFalseLiteral, true);
// instead of
// rv = Assert(parentRes, kNC_Child, entry, true);
// if (NS_FAILED(rv)) return rv;
// defer insertion onto a timer so that the UI isn't starved
AddElement(parentRes, kNC_Child, entry);
}
return rv;
}
nsresult
nsHTTPIndex::OnInformationAvailable(nsIRequest *aRequest,
nsISupports *aCtxt,
const nsAString& aInfo) {
return NS_ERROR_NOT_IMPLEMENTED;
}
//----------------------------------------------------------------------
//
// nsHTTPIndex implementation
//
nsHTTPIndex::nsHTTPIndex()
: mBindToGlobalObject(true),
mRequestor(nullptr)
{
}
nsHTTPIndex::nsHTTPIndex(nsIInterfaceRequestor* aRequestor)
: mBindToGlobalObject(true),
mRequestor(aRequestor)
{
}
nsHTTPIndex::~nsHTTPIndex()
{
// note: these are NOT statics due to the native of nsHTTPIndex
// where it may or may not be treated as a singleton
if (mTimer)
{
// be sure to cancel the timer, as it holds a
// weak reference back to nsHTTPIndex
mTimer->Cancel();
mTimer = nullptr;
}
mConnectionList = nullptr;
mNodeList = nullptr;
if (mDirRDF)
{
// UnregisterDataSource() may fail; just ignore errors
mDirRDF->UnregisterDataSource(this);
}
}
nsresult
nsHTTPIndex::CommonInit()
{
nsresult rv = NS_OK;
// set initial/default encoding to ISO-8859-1 (not UTF-8)
mEncoding = "ISO-8859-1";
mDirRDF = do_GetService(kRDFServiceCID, &rv);
NS_ASSERTION(NS_SUCCEEDED(rv), "unable to get RDF service");
if (NS_FAILED(rv)) {
return(rv);
}
mInner = do_CreateInstance("@mozilla.org/rdf/datasource;1?name=in-memory-datasource", &rv);
if (NS_FAILED(rv))
return rv;
mDirRDF->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "child"),
getter_AddRefs(kNC_Child));
mDirRDF->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "loading"),
getter_AddRefs(kNC_Loading));
mDirRDF->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "Comment"),
getter_AddRefs(kNC_Comment));
mDirRDF->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "URL"),
getter_AddRefs(kNC_URL));
mDirRDF->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "Name"),
getter_AddRefs(kNC_Description));
mDirRDF->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "Content-Length"),
getter_AddRefs(kNC_ContentLength));
mDirRDF->GetResource(NS_LITERAL_CSTRING(WEB_NAMESPACE_URI "LastModifiedDate"),
getter_AddRefs(kNC_LastModified));
mDirRDF->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "Content-Type"),
getter_AddRefs(kNC_ContentType));
mDirRDF->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "File-Type"),
getter_AddRefs(kNC_FileType));
mDirRDF->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "IsContainer"),
getter_AddRefs(kNC_IsContainer));
rv = mDirRDF->GetLiteral(NS_LITERAL_STRING("true").get(), getter_AddRefs(kTrueLiteral));
if (NS_FAILED(rv)) return(rv);
rv = mDirRDF->GetLiteral(NS_LITERAL_STRING("false").get(), getter_AddRefs(kFalseLiteral));
if (NS_FAILED(rv)) return(rv);
rv = NS_NewISupportsArray(getter_AddRefs(mConnectionList));
if (NS_FAILED(rv)) return(rv);
// note: don't register DS here
return rv;
}
nsresult
nsHTTPIndex::Init()
{
nsresult rv;
// set initial/default encoding to ISO-8859-1 (not UTF-8)
mEncoding = "ISO-8859-1";
rv = CommonInit();
if (NS_FAILED(rv)) return(rv);
// (do this last) register this as a named data source with the RDF service
rv = mDirRDF->RegisterDataSource(this, false);
if (NS_FAILED(rv)) return(rv);
return(NS_OK);
}
nsresult
nsHTTPIndex::Init(nsIURI* aBaseURL)
{
NS_PRECONDITION(aBaseURL != nullptr, "null ptr");
if (! aBaseURL)
return NS_ERROR_NULL_POINTER;
nsresult rv;
rv = CommonInit();
if (NS_FAILED(rv)) return(rv);
// note: don't register DS here (singleton case)
rv = aBaseURL->GetSpec(mBaseURL);
if (NS_FAILED(rv)) return rv;
// Mark the base url as a container
nsCOMPtr<nsIRDFResource> baseRes;
mDirRDF->GetResource(mBaseURL, getter_AddRefs(baseRes));
Assert(baseRes, kNC_IsContainer, kTrueLiteral, true);
return NS_OK;
}
nsresult
nsHTTPIndex::Create(nsIURI* aBaseURL, nsIInterfaceRequestor* aRequestor,
nsIHTTPIndex** aResult)
{
*aResult = nullptr;
nsHTTPIndex* result = new nsHTTPIndex(aRequestor);
if (! result)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = result->Init(aBaseURL);
if (NS_SUCCEEDED(rv))
{
NS_ADDREF(result);
*aResult = result;
}
else
{
delete result;
}
return rv;
}
NS_IMETHODIMP
nsHTTPIndex::GetBaseURL(char** _result)
{
*_result = ToNewCString(mBaseURL);
if (! *_result)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsHTTPIndex::GetDataSource(nsIRDFDataSource** _result)
{
NS_ADDREF(*_result = this);
return NS_OK;
}
// This function finds the destination when following a given nsIRDFResource
// If the resource has a URL attribute, we use that. If not, just use
// the uri.
//
// Do NOT try to get the destination of a uri in any other way
void nsHTTPIndex::GetDestination(nsIRDFResource* r, nsXPIDLCString& dest) {
// First try the URL attribute
nsCOMPtr<nsIRDFNode> node;
GetTarget(r, kNC_URL, true, getter_AddRefs(node));
nsCOMPtr<nsIRDFLiteral> url;
if (node)
url = do_QueryInterface(node);
if (!url) {
const char* temp;
r->GetValueConst(&temp);
dest.Adopt(temp ? nsCRT::strdup(temp) : 0);
} else {
const PRUnichar* uri;
url->GetValueConst(&uri);
dest.Adopt(ToNewUTF8String(nsDependentString(uri)));
}
}
// rjc: isWellknownContainerURI() decides whether a URI is a container for which,
// when asked (say, by the template builder), we'll make a network connection
// to get its contents. For the moment, all we speak is ftp:// URLs, even though
// a) we can get "http-index" mimetypes for really anything
// b) we could easily handle file:// URLs here
// Q: Why don't we?
// A: The file system datasource ("rdf:file"); at some point, the two
// should be perhaps united. Until then, we can't aggregate both
// "rdf:file" and "http-index" (such as with bookmarks) because we'd
// get double the # of answers we really want... also, "rdf:file" is
// less expensive in terms of both memory usage as well as speed
// We use an rdf attribute to mark if this is a container or not.
// Note that we still have to do string comparisons as a fallback
// because stuff like the personal toolbar and bookmarks check whether
// a URL is a container, and we have no attribute in that case.
bool
nsHTTPIndex::isWellknownContainerURI(nsIRDFResource *r)
{
nsCOMPtr<nsIRDFNode> node;
GetTarget(r, kNC_IsContainer, true, getter_AddRefs(node));
if (node) {
bool isContainerFlag;
if (NS_SUCCEEDED(node->EqualsNode(kTrueLiteral, &isContainerFlag)))
return isContainerFlag;
}
nsXPIDLCString uri;
GetDestination(r, uri);
return uri.get() && !strncmp(uri, kFTPProtocol, sizeof(kFTPProtocol) - 1) &&
(uri.Last() == '/');
}
NS_IMETHODIMP
nsHTTPIndex::GetURI(char * *uri)
{
NS_PRECONDITION(uri != nullptr, "null ptr");
if (! uri)
return(NS_ERROR_NULL_POINTER);
if ((*uri = nsCRT::strdup("rdf:httpindex")) == nullptr)
return(NS_ERROR_OUT_OF_MEMORY);
return(NS_OK);
}
NS_IMETHODIMP
nsHTTPIndex::GetSource(nsIRDFResource *aProperty, nsIRDFNode *aTarget, bool aTruthValue,
nsIRDFResource **_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
*_retval = nullptr;
if (mInner)
{
rv = mInner->GetSource(aProperty, aTarget, aTruthValue, _retval);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::GetSources(nsIRDFResource *aProperty, nsIRDFNode *aTarget, bool aTruthValue,
nsISimpleEnumerator **_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->GetSources(aProperty, aTarget, aTruthValue, _retval);
}
else
{
rv = NS_NewEmptyEnumerator(_retval);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::GetTarget(nsIRDFResource *aSource, nsIRDFResource *aProperty, bool aTruthValue,
nsIRDFNode **_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
*_retval = nullptr;
if ((aTruthValue) && (aProperty == kNC_Child) && isWellknownContainerURI(aSource))
{
// fake out the generic builder (i.e. return anything in this case)
// so that search containers never appear to be empty
NS_IF_ADDREF(aSource);
*_retval = aSource;
return(NS_OK);
}
if (mInner)
{
rv = mInner->GetTarget(aSource, aProperty, aTruthValue, _retval);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::GetTargets(nsIRDFResource *aSource, nsIRDFResource *aProperty, bool aTruthValue,
nsISimpleEnumerator **_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->GetTargets(aSource, aProperty, aTruthValue, _retval);
}
else
{
rv = NS_NewEmptyEnumerator(_retval);
}
if ((aProperty == kNC_Child) && isWellknownContainerURI(aSource))
{
bool doNetworkRequest = true;
if (NS_SUCCEEDED(rv) && (_retval))
{
// check and see if we already have data for the search in question;
// if we do, don't bother doing the search again
bool hasResults;
if (NS_SUCCEEDED((*_retval)->HasMoreElements(&hasResults)) &&
hasResults)
doNetworkRequest = false;
}
// Note: if we need to do a network request, do it out-of-band
// (because the XUL template builder isn't re-entrant)
// by using a global connection list and an immediately-firing timer
if (doNetworkRequest && mConnectionList)
{
int32_t connectionIndex = mConnectionList->IndexOf(aSource);
if (connectionIndex < 0)
{
// add aSource into list of connections to make
mConnectionList->AppendElement(aSource);
// if we don't have a timer about to fire, create one
// which should fire as soon as possible (out-of-band)
if (!mTimer)
{
mTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
NS_ASSERTION(NS_SUCCEEDED(rv), "unable to create a timer");
if (NS_SUCCEEDED(rv))
{
mTimer->InitWithFuncCallback(nsHTTPIndex::FireTimer, this, 1,
nsITimer::TYPE_ONE_SHOT);
// Note: don't addref "this" as we'll cancel the
// timer in the httpIndex destructor
}
}
}
}
}
return(rv);
}
nsresult
nsHTTPIndex::AddElement(nsIRDFResource *parent, nsIRDFResource *prop, nsIRDFNode *child)
{
nsresult rv;
if (!mNodeList)
{
rv = NS_NewISupportsArray(getter_AddRefs(mNodeList));
if (NS_FAILED(rv)) return(rv);
}
// order required: parent, prop, then child
mNodeList->AppendElement(parent);
mNodeList->AppendElement(prop);
mNodeList->AppendElement(child);
if (!mTimer)
{
mTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
NS_ASSERTION(NS_SUCCEEDED(rv), "unable to create a timer");
if (NS_FAILED(rv)) return(rv);
mTimer->InitWithFuncCallback(nsHTTPIndex::FireTimer, this, 1,
nsITimer::TYPE_ONE_SHOT);
// Note: don't addref "this" as we'll cancel the
// timer in the httpIndex destructor
}
return(NS_OK);
}
void
nsHTTPIndex::FireTimer(nsITimer* aTimer, void* aClosure)
{
nsHTTPIndex *httpIndex = static_cast<nsHTTPIndex *>(aClosure);
if (!httpIndex) return;
// don't return out of this loop as mTimer may need to be cancelled afterwards
uint32_t numItems = 0;
if (httpIndex->mConnectionList)
{
httpIndex->mConnectionList->Count(&numItems);
if (numItems > 0)
{
nsCOMPtr<nsISupports> isupports;
httpIndex->mConnectionList->GetElementAt((uint32_t)0, getter_AddRefs(isupports));
httpIndex->mConnectionList->RemoveElementAt((uint32_t)0);
nsCOMPtr<nsIRDFResource> aSource;
if (isupports) aSource = do_QueryInterface(isupports);
nsXPIDLCString uri;
if (aSource) {
httpIndex->GetDestination(aSource, uri);
}
if (!uri) {
NS_ERROR("Could not reconstruct uri");
return;
}
nsresult rv = NS_OK;
nsCOMPtr<nsIURI> url;
rv = NS_NewURI(getter_AddRefs(url), uri.get());
nsCOMPtr<nsIChannel> channel;
if (NS_SUCCEEDED(rv) && (url)) {
rv = NS_NewChannel(getter_AddRefs(channel), url, nullptr, nullptr);
}
if (NS_SUCCEEDED(rv) && (channel)) {
channel->SetNotificationCallbacks(httpIndex);
rv = channel->AsyncOpen(httpIndex, aSource);
}
}
}
if (httpIndex->mNodeList)
{
httpIndex->mNodeList->Count(&numItems);
if (numItems > 0)
{
// account for order required: src, prop, then target
numItems /=3;
if (numItems > 10) numItems = 10;
int32_t loop;
for (loop=0; loop<(int32_t)numItems; loop++)
{
nsCOMPtr<nsISupports> isupports;
httpIndex->mNodeList->GetElementAt((uint32_t)0, getter_AddRefs(isupports));
httpIndex->mNodeList->RemoveElementAt((uint32_t)0);
nsCOMPtr<nsIRDFResource> src;
if (isupports) src = do_QueryInterface(isupports);
httpIndex->mNodeList->GetElementAt((uint32_t)0, getter_AddRefs(isupports));
httpIndex->mNodeList->RemoveElementAt((uint32_t)0);
nsCOMPtr<nsIRDFResource> prop;
if (isupports) prop = do_QueryInterface(isupports);
httpIndex->mNodeList->GetElementAt((uint32_t)0, getter_AddRefs(isupports));
httpIndex->mNodeList->RemoveElementAt((uint32_t)0);
nsCOMPtr<nsIRDFNode> target;
if (isupports) target = do_QueryInterface(isupports);
if (src && prop && target)
{
if (prop.get() == httpIndex->kNC_Loading)
{
httpIndex->Unassert(src, prop, target);
}
else
{
httpIndex->Assert(src, prop, target, true);
}
}
}
}
}
bool refireTimer = false;
// check both lists to see if the timer needs to continue firing
if (httpIndex->mConnectionList)
{
httpIndex->mConnectionList->Count(&numItems);
if (numItems > 0)
{
refireTimer = true;
}
else
{
httpIndex->mConnectionList->Clear();
}
}
if (httpIndex->mNodeList)
{
httpIndex->mNodeList->Count(&numItems);
if (numItems > 0)
{
refireTimer = true;
}
else
{
httpIndex->mNodeList->Clear();
}
}
// be sure to cancel the timer, as it holds a
// weak reference back to nsHTTPIndex
httpIndex->mTimer->Cancel();
httpIndex->mTimer = nullptr;
// after firing off any/all of the connections be sure
// to cancel the timer if we don't need to refire it
if (refireTimer)
{
httpIndex->mTimer = do_CreateInstance("@mozilla.org/timer;1");
if (httpIndex->mTimer)
{
httpIndex->mTimer->InitWithFuncCallback(nsHTTPIndex::FireTimer, aClosure, 10,
nsITimer::TYPE_ONE_SHOT);
// Note: don't addref "this" as we'll cancel the
// timer in the httpIndex destructor
}
}
}
NS_IMETHODIMP
nsHTTPIndex::Assert(nsIRDFResource *aSource, nsIRDFResource *aProperty, nsIRDFNode *aTarget,
bool aTruthValue)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->Assert(aSource, aProperty, aTarget, aTruthValue);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::Unassert(nsIRDFResource *aSource, nsIRDFResource *aProperty, nsIRDFNode *aTarget)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->Unassert(aSource, aProperty, aTarget);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::Change(nsIRDFResource *aSource, nsIRDFResource *aProperty,
nsIRDFNode *aOldTarget, nsIRDFNode *aNewTarget)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->Change(aSource, aProperty, aOldTarget, aNewTarget);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::Move(nsIRDFResource *aOldSource, nsIRDFResource *aNewSource,
nsIRDFResource *aProperty, nsIRDFNode *aTarget)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->Move(aOldSource, aNewSource, aProperty, aTarget);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::HasAssertion(nsIRDFResource *aSource, nsIRDFResource *aProperty,
nsIRDFNode *aTarget, bool aTruthValue, bool *_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->HasAssertion(aSource, aProperty, aTarget, aTruthValue, _retval);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::AddObserver(nsIRDFObserver *aObserver)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->AddObserver(aObserver);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::RemoveObserver(nsIRDFObserver *aObserver)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->RemoveObserver(aObserver);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::HasArcIn(nsIRDFNode *aNode, nsIRDFResource *aArc, bool *result)
{
if (!mInner) {
*result = false;
return NS_OK;
}
return mInner->HasArcIn(aNode, aArc, result);
}
NS_IMETHODIMP
nsHTTPIndex::HasArcOut(nsIRDFResource *aSource, nsIRDFResource *aArc, bool *result)
{
if (aArc == kNC_Child && isWellknownContainerURI(aSource)) {
*result = true;
return NS_OK;
}
if (mInner) {
return mInner->HasArcOut(aSource, aArc, result);
}
*result = false;
return NS_OK;
}
NS_IMETHODIMP
nsHTTPIndex::ArcLabelsIn(nsIRDFNode *aNode, nsISimpleEnumerator **_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->ArcLabelsIn(aNode, _retval);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::ArcLabelsOut(nsIRDFResource *aSource, nsISimpleEnumerator **_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
*_retval = nullptr;
nsCOMPtr<nsISupportsArray> array;
rv = NS_NewISupportsArray(getter_AddRefs(array));
if (NS_FAILED(rv)) return rv;
if (isWellknownContainerURI(aSource))
{
array->AppendElement(kNC_Child);
}
if (mInner)
{
nsCOMPtr<nsISimpleEnumerator> anonArcs;
rv = mInner->ArcLabelsOut(aSource, getter_AddRefs(anonArcs));
bool hasResults;
while (NS_SUCCEEDED(rv) &&
NS_SUCCEEDED(anonArcs->HasMoreElements(&hasResults)) &&
hasResults)
{
nsCOMPtr<nsISupports> anonArc;
if (NS_FAILED(anonArcs->GetNext(getter_AddRefs(anonArc))))
break;
array->AppendElement(anonArc);
}
}
return NS_NewArrayEnumerator(_retval, array);
}
NS_IMETHODIMP
nsHTTPIndex::GetAllResources(nsISimpleEnumerator **_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->GetAllResources(_retval);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::IsCommandEnabled(nsISupportsArray *aSources, nsIRDFResource *aCommand,
nsISupportsArray *aArguments, bool *_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->IsCommandEnabled(aSources, aCommand, aArguments, _retval);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::DoCommand(nsISupportsArray *aSources, nsIRDFResource *aCommand,
nsISupportsArray *aArguments)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->DoCommand(aSources, aCommand, aArguments);
}
return(rv);
}
NS_IMETHODIMP
nsHTTPIndex::BeginUpdateBatch()
{
return mInner->BeginUpdateBatch();
}
NS_IMETHODIMP
nsHTTPIndex::EndUpdateBatch()
{
return mInner->EndUpdateBatch();
}
NS_IMETHODIMP
nsHTTPIndex::GetAllCmds(nsIRDFResource *aSource, nsISimpleEnumerator **_retval)
{
nsresult rv = NS_ERROR_UNEXPECTED;
if (mInner)
{
rv = mInner->GetAllCmds(aSource, _retval);
}
return(rv);
}
//----------------------------------------------------------------------
//
// nsDirectoryViewerFactory
//
nsDirectoryViewerFactory::nsDirectoryViewerFactory()
{
}
nsDirectoryViewerFactory::~nsDirectoryViewerFactory()
{
}
NS_IMPL_ISUPPORTS1(nsDirectoryViewerFactory, nsIDocumentLoaderFactory)
NS_IMETHODIMP
nsDirectoryViewerFactory::CreateInstance(const char *aCommand,
nsIChannel* aChannel,
nsILoadGroup* aLoadGroup,
const char* aContentType,
nsISupports* aContainer,
nsISupports* aExtraInfo,
nsIStreamListener** aDocListenerResult,
nsIContentViewer** aDocViewerResult)
{
nsresult rv;
bool viewSource = (PL_strstr(aContentType,"view-source") != 0);
if (!viewSource &&
Preferences::GetInt("network.dir.format", FORMAT_XUL) == FORMAT_XUL) {
// ... and setup the original channel's content type
(void)aChannel->SetContentType(NS_LITERAL_CSTRING("application/vnd.mozilla.xul+xml"));
// This is where we shunt the HTTP/Index stream into our datasource,
// and open the directory viewer XUL file as the content stream to
// load in its place.
// Create a dummy loader that will load a stub XUL document.
nsCOMPtr<nsICategoryManager> catMan(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
if (NS_FAILED(rv))
return rv;
nsXPIDLCString contractID;
rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", "application/vnd.mozilla.xul+xml",
getter_Copies(contractID));
if (NS_FAILED(rv))
return rv;
nsCOMPtr<nsIDocumentLoaderFactory> factory(do_GetService(contractID, &rv));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), "chrome://communicator/content/directory/directory.xul");
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = NS_NewChannel(getter_AddRefs(channel), uri, nullptr, aLoadGroup);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIStreamListener> listener;
rv = factory->CreateInstance(aCommand, channel, aLoadGroup, "application/vnd.mozilla.xul+xml",
aContainer, aExtraInfo, getter_AddRefs(listener),
aDocViewerResult);
if (NS_FAILED(rv)) return rv;
rv = channel->AsyncOpen(listener, nullptr);
if (NS_FAILED(rv)) return rv;
// Create an HTTPIndex object so that we can stuff it into the script context
nsCOMPtr<nsIURI> baseuri;
rv = aChannel->GetURI(getter_AddRefs(baseuri));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIInterfaceRequestor> requestor = do_QueryInterface(aContainer,&rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIHTTPIndex> httpindex;
rv = nsHTTPIndex::Create(baseuri, requestor, getter_AddRefs(httpindex));
if (NS_FAILED(rv)) return rv;
// Now shanghai the stream into our http-index parsing datasource
// wrapper beastie.
listener = do_QueryInterface(httpindex,&rv);
*aDocListenerResult = listener.get();
NS_ADDREF(*aDocListenerResult);
return NS_OK;
}
// setup the original channel's content type
(void)aChannel->SetContentType(NS_LITERAL_CSTRING("text/html"));
// Otherwise, lets use the html listing
nsCOMPtr<nsICategoryManager> catMan(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
if (NS_FAILED(rv))
return rv;
nsXPIDLCString contractID;
rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", "text/html",
getter_Copies(contractID));
if (NS_FAILED(rv))
return rv;
nsCOMPtr<nsIDocumentLoaderFactory> factory(do_GetService(contractID, &rv));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIStreamListener> listener;
if (viewSource) {
rv = factory->CreateInstance("view-source", aChannel, aLoadGroup, "text/html; x-view-type=view-source",
aContainer, aExtraInfo, getter_AddRefs(listener),
aDocViewerResult);
} else {
rv = factory->CreateInstance("view", aChannel, aLoadGroup, "text/html",
aContainer, aExtraInfo, getter_AddRefs(listener),
aDocViewerResult);
}
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIStreamConverterService> scs = do_GetService("@mozilla.org/streamConverters;1", &rv);
if (NS_FAILED(rv)) return rv;
rv = scs->AsyncConvertData("application/http-index-format",
"text/html",
listener,
nullptr,
aDocListenerResult);
if (NS_FAILED(rv)) return rv;
return NS_OK;
}
NS_IMETHODIMP
nsDirectoryViewerFactory::CreateInstanceForDocument(nsISupports* aContainer,
nsIDocument* aDocument,
const char *aCommand,
nsIContentViewer** aDocViewerResult)
{
NS_NOTYETIMPLEMENTED("didn't expect to get here");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDirectoryViewerFactory::CreateBlankDocument(nsILoadGroup *aLoadGroup,
nsIPrincipal *aPrincipal,
nsIDocument **_retval) {
NS_NOTYETIMPLEMENTED("didn't expect to get here");
return NS_ERROR_NOT_IMPLEMENTED;
}
| 28.755462 | 107 | 0.650696 | [
"object"
] |
2089db26e2b080664cad507bc1458bc56ec22270 | 1,473 | cpp | C++ | cpp/08/ex00/main.cpp | maxdesalle/libft | 8845656e1f5cc1fec052cf97fc8f5839b2b590a8 | [
"Unlicense"
] | 3 | 2021-01-06T13:50:12.000Z | 2022-02-28T09:16:15.000Z | cpp/08/ex00/main.cpp | maxdesalle/libft | 8845656e1f5cc1fec052cf97fc8f5839b2b590a8 | [
"Unlicense"
] | null | null | null | cpp/08/ex00/main.cpp | maxdesalle/libft | 8845656e1f5cc1fec052cf97fc8f5839b2b590a8 | [
"Unlicense"
] | 1 | 2020-11-23T12:58:18.000Z | 2020-11-23T12:58:18.000Z | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: maxdesalle <mdesalle@student.s19.be> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/05 10:38:34 by maxdesall #+# #+# */
/* Updated: 2021/11/05 14:33:17 by maxdesall ### ########.fr */
/* */
/* ************************************************************************** */
#include "easyfind.hpp"
int main(void)
{
const int max = 5;
std::array<int, 5> arr = { 0, 1, 2, 3, 4 };
std::vector<int> vec;
std::list<int> lst;
for (size_t i = 0; i < 5; i += 1)
vec.push_back(i);
for (size_t i = 0; i < 5; i += 1)
lst.push_back(i);
for (size_t i = 0; i < max; i += 1)
{
std::cout << easyfind(arr, i) << std::endl;
std::cout << easyfind(vec, i) << std::endl;
std::cout << easyfind(lst, i) << std::endl;
}
try
{
easyfind(arr, -1);
}
catch (std::runtime_error &e)
{
std::cout << e.what();
std::cout << std::endl;
}
return (0);
}
| 32.733333 | 80 | 0.281738 | [
"vector"
] |
208d52008301d0d162eb899ab73acb6362bc8796 | 891 | cc | C++ | leetcode/binary-tree-level-order-traversal-ii.cc | Waywrong/leetcode-solution | 55115aeab4040f5ff84bdce6ffcfe4a98f879616 | [
"MIT"
] | null | null | null | leetcode/binary-tree-level-order-traversal-ii.cc | Waywrong/leetcode-solution | 55115aeab4040f5ff84bdce6ffcfe4a98f879616 | [
"MIT"
] | null | null | null | leetcode/binary-tree-level-order-traversal-ii.cc | Waywrong/leetcode-solution | 55115aeab4040f5ff84bdce6ffcfe4a98f879616 | [
"MIT"
] | null | null | null | // Binary Tree Level Order Traversal
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
if (!root) return res;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
vector<int> vec;
int n = q.size();
for (int i=0; i<n; i++) {
TreeNode *t = q.front();
q.pop();
vec.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
res.push_back(vec);
}
reverse(res.begin(), res.end());
return res;
}
};
| 25.457143 | 59 | 0.462402 | [
"vector"
] |
208e004306253c60d10a278e636fea45c250b4ee | 3,743 | cpp | C++ | SerialPrograms/Source/CommonFramework/Options/EditableTableOption.cpp | Gin890/Arduino-Source | 9047ff584010d8ddc3558068874f16fb3c7bb46d | [
"MIT"
] | 1 | 2022-03-29T18:51:49.000Z | 2022-03-29T18:51:49.000Z | SerialPrograms/Source/CommonFramework/Options/EditableTableOption.cpp | Gin890/Arduino-Source | 9047ff584010d8ddc3558068874f16fb3c7bb46d | [
"MIT"
] | null | null | null | SerialPrograms/Source/CommonFramework/Options/EditableTableOption.cpp | Gin890/Arduino-Source | 9047ff584010d8ddc3558068874f16fb3c7bb46d | [
"MIT"
] | null | null | null | /* Editable Table Option
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include <QJsonValue>
#include <QWidget>
#include <QLineEdit>
#include <QCheckBox>
#include <QHBoxLayout>
#include "EditableTableOption.h"
#include "EditableTableWidget.h"
namespace PokemonAutomation{
EditableTableOption::EditableTableOption(
QString label, const EditableTableFactory& factory,
std::vector<std::unique_ptr<EditableTableRow>> default_value
)
: EditableTableBaseOption(std::move(label), factory, std::move(default_value))
{}
void EditableTableOption::load_json(const QJsonValue& json){
return EditableTableBaseOption::load_current(json);
}
QJsonValue EditableTableOption::to_json() const{
return EditableTableBaseOption::write_current();
}
QString EditableTableOption::check_validity() const{
return EditableTableBaseOption::check_validity();
};
void EditableTableOption::restore_defaults(){
EditableTableBaseOption::restore_defaults();
};
ConfigWidget* EditableTableOption::make_ui(QWidget& parent){
return new EditableTableWidget(parent, *this);
}
QWidget* make_boolean_table_cell(QWidget& parent, bool& value){
QWidget* widget = new QWidget(&parent);
QHBoxLayout* layout = new QHBoxLayout(widget);
layout->setAlignment(Qt::AlignHCenter);
layout->setContentsMargins(0, 0, 0, 0);
QCheckBox* box = new QCheckBox(&parent);
layout->addWidget(box);
box->setChecked(value);
box->connect(
box, &QCheckBox::stateChanged,
box, [&value, box](int){
value = box->isChecked();
}
);
return widget;
}
template<typename T> QWidget* make_integer_table_cell(QWidget& parent, T& value){
QLineEdit* box = new QLineEdit(QString::number(value), &parent);
box->setAlignment(Qt::AlignHCenter);
box->connect(
box, &QLineEdit::textChanged,
box, [&value, box](const QString& text){
bool ok = false;
const int current = (int)text.toLong(&ok);
QPalette palette;
if (ok && current >= std::numeric_limits<T>::min() && current <= std::numeric_limits<int>::max()){
value = (T)current;
palette.setColor(QPalette::Text, Qt::black);
}else{
palette.setColor(QPalette::Text, Qt::red);
}
box->setPalette(palette);
}
);
box->connect(
box, &QLineEdit::editingFinished,
box, [&value, box](){
box->setText(QString::number(value));
}
);
return box;
}
QWidget* make_double_table_cell(QWidget& parent, double& value, double min, double max){
QLineEdit* box = new QLineEdit(QString::number(value), &parent);
box->setAlignment(Qt::AlignHCenter);
box->connect(
box, &QLineEdit::textChanged,
box, [&value, box, min, max](const QString& text){
bool ok = false;
double current = text.toDouble(&ok);
QPalette palette;
if (ok && current >= min && current <= max){
value = current;
palette.setColor(QPalette::Text, Qt::black);
}else{
palette.setColor(QPalette::Text, Qt::red);
}
box->setPalette(palette);
}
);
box->connect(
box, &QLineEdit::editingFinished,
box, [&value, box](){
box->setText(QString::number(value));
}
);
return box;
}
template QWidget* make_integer_table_cell(QWidget& parent, uint16_t& value);
template QWidget* make_integer_table_cell(QWidget& parent, int16_t& value);
}
| 29.944 | 111 | 0.612343 | [
"vector"
] |
209164ce75ca3e21f4a36499efa257f626ad843f | 671 | cpp | C++ | misc/46. Permutations.cpp | lingqtan/myLeetcode | 54cc538b640660c0d64420442466af4df2ed0225 | [
"Apache-2.0"
] | null | null | null | misc/46. Permutations.cpp | lingqtan/myLeetcode | 54cc538b640660c0d64420442466af4df2ed0225 | [
"Apache-2.0"
] | null | null | null | misc/46. Permutations.cpp | lingqtan/myLeetcode | 54cc538b640660c0d64420442466af4df2ed0225 | [
"Apache-2.0"
] | null | null | null | class Solution {
void solve(int status, vector<int>& cur, vector<int>& nums, vector<vector<int> >& ans) {
if (cur.size() == nums.size()) {
ans.push_back(cur);
return;
}
for (int i = 0; i < nums.size(); i++) {
if (status & (1 << i)) continue;
status += 1 << i;
cur.push_back(nums[i]);
solve(status, cur, nums, ans);
status -= 1 << i;
cur.pop_back();
}
}
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> > ans;
vector<int> cur;
solve(0, cur, nums, ans);
return ans;
}
}; | 29.173913 | 92 | 0.460507 | [
"vector"
] |
209819b2093f5ff9a93a676b68409d2c9c883b23 | 4,804 | cpp | C++ | src/samplers/adaptive_sampler.cpp | Twinklebear/tray | eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b | [
"MIT"
] | 61 | 2015-01-01T10:58:21.000Z | 2022-01-05T14:22:15.000Z | src/samplers/adaptive_sampler.cpp | Twinklebear/tray | eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b | [
"MIT"
] | null | null | null | src/samplers/adaptive_sampler.cpp | Twinklebear/tray | eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b | [
"MIT"
] | 3 | 2016-04-11T19:07:47.000Z | 2018-05-31T12:40:50.000Z | #include <iostream>
#include <array>
#include <chrono>
#include <vector>
#include <memory>
#include <random>
#include "linalg/util.h"
#include "samplers/ld_sampler.h"
#include "samplers/adaptive_sampler.h"
AdaptiveSampler::AdaptiveSampler(int x_start, int x_end, int y_start, int y_end, int min_sp, int max_sp, int seed)
: Sampler(x_start, x_end, y_start, y_end, seed), min_spp(round_up_pow2(min_sp)), max_spp(round_up_pow2(max_sp)),
supersample_px(min_spp)
{
if (min_sp % 2 != 0){
std::cout << "Warning: AdaptiveSampler requires power of 2 samples per pixel."
<< " Rounded min_spp up to " << min_spp << std::endl;
}
if (max_sp % 2 != 0){
std::cout << "Warning: AdaptiveSampler requires power of 2 samples per pixel."
<< " Rounded max_spp up to " << max_spp << std::endl;
}
}
AdaptiveSampler::AdaptiveSampler(int x_start, int x_end, int y_start, int y_end, int min_sp, int max_sp)
: AdaptiveSampler(x_start, x_end, y_start, y_end, min_sp, max_sp,
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()).count())
{}
void AdaptiveSampler::get_samples(std::vector<Sample> &samples){
samples.clear();
if (supersample_px == min_spp && !has_samples()){
return;
}
int spp = supersample_px;
//Offset our sample sequence indices by the number of samples already taken
//so previous samples can still be used without introducing a pattern
int offset = supersample_px > min_spp ? supersample_px / 2 : 0;
samples.resize(spp);
std::vector<std::array<float, 2>> pos(spp), lens(spp);
std::vector<float> time(spp);
get_samples(pos.data(), pos.size(), offset);
get_samples(lens.data(), lens.size(), offset);
get_samples(time.data(), time.size(), offset);
auto p = pos.begin();
auto l = lens.begin();
auto t = time.begin();
auto s = samples.begin();
for (; s != samples.end(); ++p, ++l, ++t, ++s){
*s = Sample{*p, *l, *t};
}
for (auto &s : samples){
s.img[0] += x;
s.img[1] += y;
}
}
void AdaptiveSampler::get_samples(std::array<float, 2> *samples, int n_samples, int offset){
LDSampler::sample2d(samples, n_samples, distrib(rng), distrib(rng), offset);
std::shuffle(samples, samples + n_samples, rng);
}
void AdaptiveSampler::get_samples(float *samples, int n_samples, int offset){
LDSampler::sample1d(samples, n_samples, distrib(rng), offset);
std::shuffle(samples, samples + n_samples, rng);
}
int AdaptiveSampler::get_max_spp() const {
return max_spp;
}
bool AdaptiveSampler::report_results(const std::vector<Sample> &samples,
const std::vector<RayDifferential> &rays, const std::vector<Colorf> &colors)
{
if (supersample_px == max_spp || !needs_supersampling(samples, rays, colors)){
supersample_px = min_spp;
++x;
if (x == x_end){
x = x_start;
++y;
}
return true;
}
//Throw away these samples, we need to super sample this pixel
supersample_px *= 2;
return false;
}
std::vector<std::unique_ptr<Sampler>> AdaptiveSampler::get_subsamplers(int w, int h) const {
int x_dim = x_end - x_start;
int y_dim = y_end - y_start;
std::vector<std::unique_ptr<Sampler>> samplers;
if (w > x_dim || h > y_dim){
std::cout << "WARNING: sampler cannot be partitioned to blocks bigger than itself\n";
samplers.emplace_back(std::make_unique<AdaptiveSampler>(*this));
return samplers;
}
//Compute the number of tiles to use in each dimension, we halve the number along x
//and double the number along y until we hit an odd number of x tiles (cols) or
//until the tiles divide the space about evenly
int n_cols = x_dim / w;
int n_rows = y_dim / h;
x_dim /= n_cols;
y_dim /= n_rows;
//Check & warn if the space hasn't been split up evenly
if (x_dim * n_cols != width() || y_dim * n_rows != height()){
std::cout << "WARNING: sampler could not be partitioned equally into"
<< " samplers of the desired dimensions " << w << " x " << h << std::endl;
}
std::minstd_rand seed_rng(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()).count());
std::uniform_int_distribution<int> seed;
for (int j = 0; j < n_rows; ++j){
for (int i = 0; i < n_cols; ++i){
samplers.emplace_back(std::make_unique<AdaptiveSampler>(i * x_dim + x_start,
(i + 1) * x_dim + x_start, j * y_dim + y_start,
(j + 1) * y_dim + y_start, min_spp, max_spp, seed(seed_rng)));
}
}
return samplers;
}
bool AdaptiveSampler::needs_supersampling(const std::vector<Sample>&,
const std::vector<RayDifferential>&, const std::vector<Colorf> &colors)
{
const static float max_contrast = 0.3f;
float lum_avg = 0;
for (const auto &c : colors){
lum_avg += c.luminance();
}
lum_avg /= colors.size();
for (const auto &c : colors){
if (std::abs(c.luminance() - lum_avg) / lum_avg > max_contrast){
return true;
}
}
return false;
}
| 36.120301 | 114 | 0.69234 | [
"vector"
] |
20a33b11f8155a688dfc74a1b6ee186f5c4d8078 | 3,090 | hh | C++ | src/Titon/Route/bootstrap.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 206 | 2015-01-02T20:01:12.000Z | 2021-04-15T09:49:56.000Z | src/Titon/Route/bootstrap.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 44 | 2015-01-02T06:03:43.000Z | 2017-11-20T18:29:06.000Z | src/Titon/Route/bootstrap.hh | titon/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 27 | 2015-01-03T05:51:29.000Z | 2022-02-21T13:50:40.000Z | <?hh
/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/bsd-license.php
* @link http://titon.io
*/
/**
* --------------------------------------------------------------
* Type Aliases
* --------------------------------------------------------------
*
* Defines type aliases that are used by the route package.
*/
namespace Titon\Route {
use Titon\Route\Group as RouteGroup;
type Action = shape('class' => string, 'action' => string);
type ArgumentList = array<mixed>;
type FilterCallback = (function(Router, Route): void);
type FilterMap = Map<string, FilterCallback>;
type GroupCallback = (function(Router, RouteGroup): void);
type GroupList = Vector<RouteGroup>;
type ParamMap = Map<string, mixed>;
type QueryMap = Map<string, mixed>;
type ResourceMap = Map<string, string>;
type RouteCallback = (function(...): mixed);
type RouteMap = Map<string, Route>;
type SegmentMap = Map<string, mixed>;
type Token = shape('token' => string, 'optional' => bool);
type TokenList = Vector<Token>;
}
namespace Titon\Route\Mixin {
use Titon\Route\Route;
type ConditionCallback = (function(Route): bool);
type ConditionList = Vector<ConditionCallback>;
type FilterList = Vector<string>;
type MethodList = Vector<string>;
type PatternMap = Map<string, string>;
}
/**
* --------------------------------------------------------------
* Annotations
* --------------------------------------------------------------
*
* Registers all annotations declared in the route packages.
*/
namespace {
use Titon\Annotation\Registry;
if (class_exists('Titon\Annotation\Annotation')) {
Registry::map('Route', 'Titon\Route\Annotation\Route');
}
}
/**
* --------------------------------------------------------------
* Helper Functions
* --------------------------------------------------------------
*
* Defines global helper functions for common use cases.
*/
namespace {
use Titon\Route\ParamMap;
use Titon\Route\QueryMap;
use Titon\Route\UrlBuilder;
use Titon\Context\Depository;
/**
* @see Titon\Route\UrlBuilder::getAbsoluteUrl()
*/
function current_url(): string {
return builder_context()->getAbsoluteUrl();
}
/**
* @see Titon\Route\UrlBuilder::build()
*/
function url(string $key, ParamMap $params = Map {}, QueryMap $query = Map {}): string {
return builder_context()->build($key, $params, $query);
}
/**
* @see Titon\Route\UrlBuilder::getSegment()
*/
function url_segment(string $segment): mixed {
return builder_context()->getSegment($segment);
}
/**
* Make and return a `UrlBuilder` instance from the depository.
*
* @return \Titon\Route\UrlBuilder
*/
function builder_context(): UrlBuilder {
$builder = Depository::getInstance()->make('Titon\Route\UrlBuilder');
invariant($builder instanceof UrlBuilder, 'Must be a UrlBuilder.');
return $builder;
}
}
| 28.090909 | 92 | 0.561489 | [
"shape",
"vector"
] |
20ae29eb81410e1fe9bab6a5975e1e9212fb91dc | 6,954 | hpp | C++ | libs/bloom-filter/include/bloom_filter/bloom_filter.hpp | marcuswin/ledger | b79c5c4e7e92ff02ea4328fcc0885bf8ded2b8b2 | [
"Apache-2.0"
] | 1 | 2019-09-11T09:46:04.000Z | 2019-09-11T09:46:04.000Z | libs/bloom-filter/include/bloom_filter/bloom_filter.hpp | qati/ledger | e05a8f2d62ea1b79a704867d220cf307ef6b93b9 | [
"Apache-2.0"
] | null | null | null | libs/bloom-filter/include/bloom_filter/bloom_filter.hpp | qati/ledger | e05a8f2d62ea1b79a704867d220cf307ef6b93b9 | [
"Apache-2.0"
] | 1 | 2019-09-19T12:38:46.000Z | 2019-09-19T12:38:46.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "core/bitvector.hpp"
#include <cstddef>
#include <functional>
#include <iterator>
#include <utility>
#include <vector>
namespace fetch {
namespace byte_array {
class ConstByteArray;
}
namespace internal {
class HashSource;
/*
* An ordered collection of hash functions for generating pseudorandom
* std::size_t indices for the Bloom filter. To apply the functions,
* to an input, invoke the factory's operator() and use the resulting
* HashSource.
*
* The factory must be kept alive while its HashSource instances remain
* in use.
*/
class HashSourceFactory
{
private:
using Function =
std::function<std::vector<std::size_t>(fetch::byte_array::ConstByteArray const &)>;
public:
using Functions = std::vector<Function>;
/*
* Construct a factory with the given set of hash functions.
*/
explicit HashSourceFactory(Functions hash_functions);
HashSourceFactory() = delete;
HashSourceFactory(HashSourceFactory const &) = delete;
HashSourceFactory(HashSourceFactory &&) = default;
~HashSourceFactory() = default;
HashSourceFactory &operator=(HashSourceFactory const &) = delete;
HashSourceFactory &operator=(HashSourceFactory &&) = default;
/*
* Create a HashSource which, when iterated, will pass the input parameter
* to the hash functions in sequence.
*/
HashSource operator()(fetch::byte_array::ConstByteArray const &element) const;
private:
Functions hash_functions_;
};
/*
* Represents a sequential application of a HashSourceFactory's hash functions
* to a byte array. Outwardly it may be treated as an immutable, iterable
* collection of std::size_t.
*
* Not thread-safe. Not safe to use after the parent HashSourceFactory
* had been destroyed.
*/
class HashSource
{
public:
using Hashes = std::vector<std::size_t>;
HashSource() = delete;
HashSource(HashSource const &) = delete;
HashSource(HashSource &&) noexcept = default;
~HashSource() = default;
HashSource &operator=(HashSource const &) = delete;
HashSource &operator=(HashSource &&) noexcept = default;
class HashSourceIterator
{
public:
using iterator_category = std::input_iterator_tag;
using value_type = std::size_t const;
using difference_type = std::ptrdiff_t;
using pointer = std::size_t const *;
using reference = std::size_t const &;
~HashSourceIterator() = default;
HashSourceIterator(HashSourceIterator const &) = default;
HashSourceIterator(HashSourceIterator &&) noexcept = default;
HashSourceIterator() = delete;
HashSourceIterator &operator=(HashSourceIterator const &) = default;
HashSourceIterator &operator=(HashSourceIterator &&) noexcept = default;
/*
* Compare iterators for equality. Returns true if the iterators were
* generated by the same HashSource and are pointing at the same hash;
* false otherwise;
*/
bool operator==(HashSourceIterator const &other) const;
/*
* Check if iterators are different. Equivalent to !operator==(other)
*/
bool operator!=(HashSourceIterator const &other) const;
HashSourceIterator &operator++();
std::size_t operator*() const;
private:
explicit HashSourceIterator(HashSource const *source, std::size_t index);
std::size_t hash_index_{};
HashSource const *source_{};
friend class HashSource;
};
HashSourceIterator begin() const;
HashSourceIterator end() const;
HashSourceIterator cbegin() const;
HashSourceIterator cend() const;
private:
HashSource(HashSourceFactory::Functions const & hash_functions,
fetch::byte_array::ConstByteArray const &input);
/*
* Used by instances of HashSourceIterator to retrieve a hash at the given index.
*/
std::size_t getHash(std::size_t index) const;
Hashes data_;
friend class HashSourceFactory;
};
} // namespace internal
class BasicBloomFilter
{
public:
using Functions = internal::HashSourceFactory::Functions;
/*
* Construct a Bloom filter with a default set of hash functions
*/
BasicBloomFilter();
/*
* Construct a Bloom filter with the given set of hash functions
*/
explicit BasicBloomFilter(Functions const &functions);
BasicBloomFilter(BasicBloomFilter const &) = delete;
BasicBloomFilter(BasicBloomFilter &&) = delete;
~BasicBloomFilter() = default;
BasicBloomFilter &operator=(BasicBloomFilter const &) = delete;
BasicBloomFilter &operator=(BasicBloomFilter &&) = default;
/*
* Check if the argument matches the Bloom filter. Returns a pair of
* a Boolean (false if the element had never been added; true if the
* argument had been added or is a false positive) and a positive integer
* which indicates how many bits had to be checked before the function
* returned. The latter number will increase as the filter's performance
* degrades.
*/
std::pair<bool, std::size_t> Match(fetch::byte_array::ConstByteArray const &element) const;
/*
* Set the bits of the Bloom filter corresponding to the argument
*/
void Add(fetch::byte_array::ConstByteArray const &element);
/*
* Empty the Bloom filter (set all bits to zero). Preserves filter size and hash set.
*/
void Reset();
private:
BitVector bits_;
internal::HashSourceFactory hash_source_factory_;
template <typename, typename>
friend struct fetch::serializers::MapSerializer;
};
namespace serializers {
template <typename D>
struct MapSerializer<BasicBloomFilter, D>
{
public:
using Type = BasicBloomFilter;
using DriverType = D;
static const uint8_t BITS = 1;
template <typename T>
static void Serialize(T &map_constructor, Type const &filter)
{
auto map = map_constructor(1);
map.Append(BITS, filter.bits_);
}
template <typename T>
static void Deserialize(T &map, Type &filter)
{
map.ExpectKeyGetValue(BITS, filter.bits_);
}
};
} // namespace serializers
} // namespace fetch
| 29.218487 | 93 | 0.678027 | [
"vector"
] |
20b65b05f6cf1438da11daa73980d8c3625dff54 | 7,183 | cpp | C++ | Source/RPG/Game/Components/RPGEquipmentManagerComponent.cpp | Aboutdept/RPGFramework | 34c5c578e0ca1e455637082587291f6eac1bf35d | [
"BSD-2-Clause"
] | 64 | 2015-01-04T01:47:31.000Z | 2022-03-18T10:12:18.000Z | Source/RPG/Game/Components/RPGEquipmentManagerComponent.cpp | iniside/RPGFramework | 72c83cd9a814ac18b19cfaa7fadbee88417f64e3 | [
"BSD-2-Clause"
] | null | null | null | Source/RPG/Game/Components/RPGEquipmentManagerComponent.cpp | iniside/RPGFramework | 72c83cd9a814ac18b19cfaa7fadbee88417f64e3 | [
"BSD-2-Clause"
] | 39 | 2015-01-20T02:37:56.000Z | 2021-11-27T11:11:13.000Z | // Copyright 1998-2013 Epic Games, Inc. All Rights Reserved.
#include "RPG.h"
#include "../RPGCharacter.h"
#include "../Components/RPGAttributeBaseComponent.h"
#include "RPGEquipmentManagerComponent.h"
URPGEquipmentManagerComponent::URPGEquipmentManagerComponent(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
}
void URPGEquipmentManagerComponent::OnComponentCreated()
{
Super::OnComponentCreated();
EquipmentOwner = GetOwner();
if (EquipmentOwner)
{
TArray<URPGAttributeBaseComponent*> attributeComps;
EquipmentOwner->GetComponents<URPGAttributeBaseComponent>(attributeComps);
for (URPGAttributeBaseComponent* attrComp : attributeComps)
{
attributeComp = attrComp;
break;
}
TArray<USkeletalMeshComponent*> skeletalMeshComps;
EquipmentOwner->GetComponents<USkeletalMeshComponent>(skeletalMeshComps);
for (USkeletalMeshComponent* skelComp : skeletalMeshComps)
{
if (skelComp->GetName() == "ChestMesh")
{
ChestSlotComp = skelComp;
}
if (skelComp->GetName() == "FootMesh")
{
FootSlotComp = skelComp;
}
if (skelComp->GetName() == "HeadMesh")
{
HeadSlotComp = skelComp;
}
}
}
}
void URPGEquipmentManagerComponent::InitializeComponent()
{
Super::InitializeComponent();
EquipmentOwner = GetOwner();
}
void URPGEquipmentManagerComponent::SetCharacterStats(ARPGItem* item)
{
if (item && attributeComp)
{
if(EquipedItems.Num() > 0)
{
if(item->Constitution != 0) //add checks for the rest of the stats.
{
EquipedItems.Sort(URPGEquipmentManagerComponent::ConstPredicate); //sort array so the item with highest stat currently equiped is first
if(item->Constitution > EquipedItems[0]->Constitution)
{
//attributeComp->SubtractConstitution(EquipedItems[0]->Constitution);
//attributeComp->AddConstitution(item->Constitution);
}
}
}
else if (EquipedItems.Num() == 0)
{
if(item->Constitution != 0)
{
//attributeComp->AddConstitution(item->Constitution);
}
}
}
}
void URPGEquipmentManagerComponent::EquipChestItem(ARPGItem* item)
{
if (item && ChestSlotComp)
{
if(item->ItemType == EItemType::Item_Chest) //make sure item is of right type. Just in case. Could be removed later as this check is redundant
{
if(!ChestSlot) //check if something is equiped in target slot
{
if(EquipedItems.Num() == 0) //if there is no item equiped
{
//we can just assign stats from item to the character
SetCharacterStats(item);
ChestSlot = item; //the assign item to the slot
ChestSlotComp->SetSkeletalMesh(item->ChestMesh);
EquipedItems.AddUnique(ChestSlot); //and add to array
return;
}
else //otherwise
{
SetCharacterStats(item); //we check if the current item have higher stat that current equiped
ChestSlot = item; //we just assign our item to the slot
ChestSlotComp->SetSkeletalMesh(item->ChestMesh);
EquipedItems.AddUnique(ChestSlot); //and add to array
}
}
else //something is equiped in chest slot!
{
if(EquipedItems.Num() > 0) //so we assume that array contain more than 0 elements
{
SetCharacterStats(item); //check if the current item have better stat than old ones
EquipedItems.RemoveSingle(ChestSlot); //remove our old item from array
ChestSlot = item; //asign new item
ChestSlotComp->SetSkeletalMesh(item->ChestMesh);
EquipedItems.AddUnique(ChestSlot); //and add it to array
}
}
}
}
}
void URPGEquipmentManagerComponent::EquipFootItem(ARPGItem* item)
{
if (item && FootSlotComp)
{
if(item->ItemType == EItemType::Item_Foot) //make sure item is of right type. Just in case. Could be removed later as this check is redundant
{
if(!FootSlot) //check if something is equiped in target slot
{
if(EquipedItems.Num() == 0) //if there is no item equiped
{
//we can just assign stats from item to the character
SetCharacterStats(item);
FootSlot = item; //the assign item to the slot
EquipedItems.AddUnique(FootSlot); //and add to array
return;
}
else //otherwise
{
SetCharacterStats(item); //we check if the current item have higher stat that current equiped
FootSlot = item; //we just assign our item to the slot
EquipedItems.AddUnique(FootSlot); //and add to array
}
}
else //something is equiped in chest slot!
{
if(EquipedItems.Num() > 0) //so we assume that array contain more than 0 elements
{
SetCharacterStats(item); //check if the current item have better stat than old ones
EquipedItems.RemoveSingle(FootSlot); //remove our old item from array
FootSlot = item; //asign new item
EquipedItems.AddUnique(FootSlot); //and add it to array
}
}
}
}
}
void URPGEquipmentManagerComponent::EquipItem(TSubclassOf<class ARPGItem> item)
{
if(item)
{
FActorSpawnParameters SpawnInfo;
SpawnInfo.bNoCollisionFail = true;
ARPGItem* itemBase = GetWorld()->SpawnActor<ARPGItem>(item, SpawnInfo);
itemBase->ItemOwner = NULL; //we assign current character as owner to item, it might be better to use GetOwner()! as item is either eequiped on character or not.
itemBase->InitializeItem();
//note this currently assume that stats NEVER stack
//actualy negative with positive stats could stack. If there +9 con and -3 con, the end result stat will be +6 con;
//note add UnEquipItem method to handle stat subtraction!
if(itemBase->ItemType == EItemType::Item_Chest)
{
EquipChestItem(itemBase);
}
if(itemBase->ItemType == EItemType::Item_Foot)
{
EquipFootItem(itemBase);
}
}
}
void URPGEquipmentManagerComponent::UnEquipItem(ARPGItem* item)
{
if (item && attributeComp)
{
if(item->Constitution != 0)
{
//attributeComp->SubtractConstitution(item->Constitution);
if(EquipedItems.Num() > 0)
{
for(ARPGItem* itemInArray : EquipedItems)
{
}
}
}
EquipedItems.RemoveSingle(item);
}
}
void URPGEquipmentManagerComponent::EquipWeapon(TSubclassOf<class ARPGWeaponBase> weapon, FName SocketName, TEnumAsByte<EItemSlot> itemSlot)
{
if(weapon)
{
FActorSpawnParameters SpawnInfo;
SpawnInfo.bNoCollisionFail = true;
ARPGWeaponBase* weaponBase = GetWorld()->SpawnActor<ARPGWeaponBase>(weapon, SpawnInfo);
MainWeapon = weaponBase;
switch (itemSlot)
{
case EItemSlot::ChestSlot:
{
//USkeletalMeshComponent* PawnMesh = characterToAttach->Mesh;
USkeletalMeshComponent* weaponMesh = MainWeapon->WeaponMesh;
// USkeletalMesh* weaponMesh = MainWeapon->WeaponMesh;
//characterToAttach->SomeMesh->SetSkeletalMesh(weaponMesh);
weaponMesh->AttachTo(ChestSlotComp, SocketName);
weaponMesh->SetHiddenInGame(false);
break;
}
case EItemSlot::HeadSlot:
{
//USkeletalMeshComponent* PawnMesh = characterToAttach->Mesh;
USkeletalMeshComponent* weaponMesh = MainWeapon->WeaponMesh;
// USkeletalMesh* weaponMesh = MainWeapon->WeaponMesh;
//characterToAttach->SomeMesh->SetSkeletalMesh(weaponMesh);
weaponMesh->AttachTo(HeadSlotComp, SocketName);
weaponMesh->SetHiddenInGame(false);
break;
}
default:
break;
}
}
}
| 29.804979 | 163 | 0.707782 | [
"mesh"
] |
20ba0b35b7353bf62b6299ba7f3468e9c42c2b39 | 776 | cpp | C++ | P2085.cpp | ZayLhy/NOIP | f256c8d706b3ac985de04a5fae77246f44ba5b23 | [
"MIT"
] | null | null | null | P2085.cpp | ZayLhy/NOIP | f256c8d706b3ac985de04a5fae77246f44ba5b23 | [
"MIT"
] | null | null | null | P2085.cpp | ZayLhy/NOIP | f256c8d706b3ac985de04a5fae77246f44ba5b23 | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<queue>
using namespace std;
priority_queue<int> Q;
vector<int> Ans;
int main()
{
int n,m;
cin>>n>>m;
for(int i=1,a,b,c;i<=n;i++){
cin>>a>>b>>c;
for(int j=1;j<=m;j++){
int x=a*j*j+b*j+c;
if(Q.size()<m){
Q.push(x);
}
if(x<Q.top()){
Q.pop();
Q.push(x);
}
if(x>Q.top()){
break;
}
}
}
for(int i=1;i<=m;i++){
Ans.push_back(Q.top());
Q.pop();
}
reverse(Ans.begin(),Ans.end());
for(int i=0;i<m;i++){
cout<<Ans[i]<<" ";
}
cout<<endl;
return 0;
} | 19.4 | 35 | 0.408505 | [
"vector"
] |
20cea8a86941db74bc85ed0ccbf1ecee44442c78 | 10,504 | cc | C++ | p4_pdpi/utils/ir_test.cc | fichtl/sonic-pins | 60d2467b03cf67b9a61be5be7b6840b63dbb9c5b | [
"Apache-2.0"
] | 6 | 2021-12-08T17:29:38.000Z | 2022-02-17T20:36:54.000Z | p4_pdpi/utils/ir_test.cc | fichtl/sonic-pins | 60d2467b03cf67b9a61be5be7b6840b63dbb9c5b | [
"Apache-2.0"
] | 2 | 2022-01-20T08:55:05.000Z | 2022-03-08T18:30:11.000Z | p4_pdpi/utils/ir_test.cc | fichtl/sonic-pins | 60d2467b03cf67b9a61be5be7b6840b63dbb9c5b | [
"Apache-2.0"
] | 5 | 2021-12-10T02:41:52.000Z | 2022-03-03T06:59:23.000Z | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "p4_pdpi/utils/ir.h"
#include <stdint.h>
#include <string>
#include <tuple>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "google/protobuf/util/message_differencer.h"
#include "gtest/gtest.h"
#include "gutil/proto.h"
#include "gutil/status.h"
#include "gutil/status_matchers.h"
#include "p4_pdpi/ir.pb.h"
namespace pdpi {
using ::google::protobuf::util::MessageDifferencer;
TEST(StringToIrValueTest, Okay) {
std::vector<std::tuple<std::string, Format, std::string>> testcases = {
{"abc", Format::STRING, R"pb(str: "abc")pb"},
{"abc", Format::IPV4, R"pb(ipv4: "abc")pb"},
{"abc", Format::IPV6, R"pb(ipv6: "abc")pb"},
{"abc", Format::MAC, R"pb(mac: "abc")pb"},
{"abc", Format::HEX_STRING, R"pb(hex_str: "abc")pb"},
};
for (const auto& [value, format, proto] : testcases) {
ASSERT_OK_AND_ASSIGN(auto actual, FormattedStringToIrValue(value, format));
IrValue expected;
ASSERT_OK(gutil::ReadProtoFromString(proto, &expected));
EXPECT_TRUE(MessageDifferencer::Equals(actual, expected));
}
}
TEST(StringToIrValueTest, InvalidFormatFails) {
ASSERT_FALSE(FormattedStringToIrValue("abc", (Format)-1).ok());
}
TEST(UintToNormalizedByteStringTest, ValidBitwidthValues) {
std::string value;
ASSERT_OK_AND_ASSIGN(value, UintToNormalizedByteString(1, 1));
EXPECT_EQ(value, std::string("\x1"));
}
TEST(UintToNormalizedByteStringTest, InvalidBitwidth) {
EXPECT_EQ(UintToNormalizedByteString(1, 0).status().code(),
absl::StatusCode::kInvalidArgument);
EXPECT_EQ(UintToNormalizedByteString(1, 65).status().code(),
absl::StatusCode::kInvalidArgument);
}
TEST(UintToNormalizedByteStringTest, Valid8BitwidthValue) {
const std::string expected = {"\x11"};
ASSERT_OK_AND_ASSIGN(auto value, UintToNormalizedByteString(0x11, 8));
EXPECT_EQ(value, expected);
}
TEST(UintToNormalizedByteStringTest, Valid16BitwidthValue) {
const std::string expected = "\x11\x22";
ASSERT_OK_AND_ASSIGN(auto value, UintToNormalizedByteString(0x1122, 16));
EXPECT_EQ(value, expected);
}
TEST(UintToNormalizedByteStringTest, Valid32BitwidthValue) {
const std::string expected = "\x11\x22\x33\x44";
ASSERT_OK_AND_ASSIGN(auto value, UintToNormalizedByteString(0x11223344, 32));
EXPECT_EQ(value, expected);
}
TEST(UintToNormalizedByteStringTest, Valid64BitwidthValue) {
const std::string expected = "\x11\x22\x33\x44\x55\x66\x77\x88";
ASSERT_OK_AND_ASSIGN(auto value,
UintToNormalizedByteString(0x1122334455667788, 64));
EXPECT_EQ(value, expected);
}
TEST(UintToNormalizedByteStringAndReverseTest, Valid8BitwidthValue) {
uint64_t expected = 0x11;
ASSERT_OK_AND_ASSIGN(auto str_value, UintToNormalizedByteString(expected, 8));
ASSERT_OK_AND_ASSIGN(auto value, ArbitraryByteStringToUint(str_value, 8));
EXPECT_EQ(value, expected);
}
TEST(UintToNormalizedByteStringAndReverseTest, Valid16BitwidthValue) {
uint64_t expected = 0x1122;
ASSERT_OK_AND_ASSIGN(auto str_value,
UintToNormalizedByteString(expected, 16));
ASSERT_OK_AND_ASSIGN(auto value, ArbitraryByteStringToUint(str_value, 16));
EXPECT_EQ(value, expected);
}
TEST(UintToNormalizedByteStringAndReverseTest, Valid32BitwidthValue) {
uint64_t expected = 0x11223344;
ASSERT_OK_AND_ASSIGN(auto str_value,
UintToNormalizedByteString(expected, 32));
ASSERT_OK_AND_ASSIGN(auto value, ArbitraryByteStringToUint(str_value, 32));
EXPECT_EQ(value, expected);
}
TEST(UintToNormalizedByteStringAndReverseTest, Valid64BitwidthValue) {
uint64_t expected = 0x1122334455667788;
ASSERT_OK_AND_ASSIGN(auto str_value,
UintToNormalizedByteString(expected, 64));
ASSERT_OK_AND_ASSIGN(auto value, ArbitraryByteStringToUint(str_value, 64));
EXPECT_EQ(value, expected);
}
TEST(ArbitraryByteStringToUintAndReverseTest, Valid8BitwidthValue) {
const std::string expected = "1";
ASSERT_OK_AND_ASSIGN(auto uint_value, ArbitraryByteStringToUint(expected, 8));
ASSERT_OK_AND_ASSIGN(auto value, UintToNormalizedByteString(uint_value, 8));
EXPECT_EQ(value, expected);
}
TEST(ArbitraryByteStringToUintAndReverseTest, Valid16BitwidthValue) {
const std::string expected = "12";
ASSERT_OK_AND_ASSIGN(auto uint_value,
ArbitraryByteStringToUint(expected, 16));
ASSERT_OK_AND_ASSIGN(auto value, UintToNormalizedByteString(uint_value, 16));
EXPECT_EQ(value, expected);
}
TEST(ArbitraryByteStringToUintAndReverseTest, Valid32BitwidthValue) {
const std::string expected = "1234";
ASSERT_OK_AND_ASSIGN(auto uint_value,
ArbitraryByteStringToUint(expected, 32));
ASSERT_OK_AND_ASSIGN(auto value, UintToNormalizedByteString(uint_value, 32));
EXPECT_EQ(value, expected);
}
TEST(ArbitraryByteStringToUintAndReverseTest, Valid64BitwidthValue) {
const std::string expected = "12345678";
ASSERT_OK_AND_ASSIGN(auto uint_value,
ArbitraryByteStringToUint(expected, 64));
ASSERT_OK_AND_ASSIGN(auto value, UintToNormalizedByteString(uint_value, 64));
EXPECT_EQ(value, expected);
}
TEST(GetFormatTest, MacAnnotationPass) {
std::vector<std::string> annotations = {"@format(MAC_ADDRESS)"};
ASSERT_OK_AND_ASSIGN(auto format, GetFormat(annotations, kNumBitsInMac,
/*is_sdn_string=*/false));
EXPECT_EQ(format, Format::MAC);
}
TEST(GetFormatTest, MacAnnotationInvalidBitwidth) {
std::vector<std::string> annotations = {"@format(MAC_ADDRESS)"};
auto status_or_format =
GetFormat(annotations, /*bitwidth=*/65, /*is_sdn_string=*/false);
EXPECT_EQ(status_or_format.status().code(),
absl::StatusCode::kInvalidArgument);
}
TEST(GetFormatTest, Ipv4AnnotationPass) {
std::vector<std::string> annotations = {"@format(IPV4_ADDRESS)"};
ASSERT_OK_AND_ASSIGN(auto format, GetFormat(annotations, kNumBitsInIpv4,
/*is_sdn_string=*/false));
EXPECT_EQ(format, Format::IPV4);
}
TEST(GetFormatTest, Ipv4AnnotationInvalidBitwidth) {
std::vector<std::string> annotations = {"@format(IPV4_ADDRESS)"};
auto status_or_format =
GetFormat(annotations, /*bitwidth=*/65, /*is_sdn_string=*/false);
EXPECT_EQ(status_or_format.status().code(),
absl::StatusCode::kInvalidArgument);
}
TEST(GetFormatTest, Ipv6AnnotationPass) {
std::vector<std::string> annotations = {"@format(IPV6_ADDRESS)"};
ASSERT_OK_AND_ASSIGN(auto format, GetFormat(annotations, kNumBitsInIpv6,
/*is_sdn_string=*/false));
EXPECT_EQ(format, Format::IPV6);
}
TEST(GetFormatTest, Ipv6AnnotationInvalidBitwidth) {
std::vector<std::string> annotations = {"@format(IPV6_ADDRESS)"};
auto status_or_format =
GetFormat(annotations, /*bitwidth=*/65, /*is_sdn_string=*/false);
EXPECT_EQ(status_or_format.status().code(),
absl::StatusCode::kInvalidArgument);
}
TEST(GetFormatTest, ConflictingAnnotations) {
std::vector<std::string> annotations = {"@format(IPV6_ADDRESS)",
"@format(IPV4_ADDRESS)"};
auto status_or_format =
GetFormat(annotations, /*bitwidth=*/65, /*is_sdn_string=*/false);
EXPECT_EQ(status_or_format.status().code(),
absl::StatusCode::kInvalidArgument);
}
TEST(GetFormatTest, SdnStringFormat) {
std::vector<std::string> annotations = {};
ASSERT_OK_AND_ASSIGN(auto format, GetFormat(annotations, /*bitwidth=*/65,
/*is_sdn_string=*/true));
EXPECT_EQ(format, Format::STRING);
}
TEST(GetFormatTest, SdnStringFormatConflictingAnnotations) {
std::vector<std::string> annotations = {"@format(IPV4_ADDRESS)"};
auto status_or_format =
GetFormat(annotations, /*bitwidth=*/65, /*is_sdn_string=*/true);
EXPECT_EQ(status_or_format.status().code(),
absl::StatusCode::kInvalidArgument);
}
TEST(GetFormatTest, InvalidAnnotations) {
std::vector<std::string> annotations = {"@format(IPVx_ADDRESS)"};
auto status_or_format =
GetFormat(annotations, /*bitwidth=*/65, /*is_sdn_string=*/false);
EXPECT_EQ(status_or_format.status().code(),
absl::StatusCode::kInvalidArgument);
}
TEST(IsAllZerosTest, TestZeros) {
EXPECT_TRUE(IsAllZeros("\x00\x00\x00\x00"));
EXPECT_FALSE(IsAllZeros("\x01\x00\x00\x00"));
}
TEST(IntersectionTest, UnequalLengths) {
const auto status_or_result =
Intersection("\x41\x42\x43", "\x41\x42\x43\x44");
EXPECT_EQ(status_or_result.status().code(),
absl::StatusCode::kInvalidArgument);
}
TEST(IntersectionTest, NoChange) {
std::string expected = "\x41\x42\x43";
ASSERT_OK_AND_ASSIGN(const auto& result,
Intersection(expected, "\xff\xff\xff"));
EXPECT_EQ(result, expected);
}
TEST(IntersectionTest, AllZeros) {
std::string input = "\x41\x42\x43";
ASSERT_OK_AND_ASSIGN(const auto& result,
Intersection(input, std::string("\x00\x00\x00", 3)));
EXPECT_TRUE(IsAllZeros(result));
}
TEST(PrefixLenToMaskTest, PrefixLenTooLong) {
const auto status_or_result = PrefixLenToMask(33, 32);
EXPECT_EQ(status_or_result.status().code(),
absl::StatusCode::kInvalidArgument);
}
TEST(PrefixLenToMaskTest, Ipv4Test) {
ASSERT_OK_AND_ASSIGN(const auto result, PrefixLenToMask(23, 32));
std::string expected("\xff\xff\xfe\x00", 4);
EXPECT_EQ(result, expected);
}
TEST(PrefixLenToMaskTest, Ipv6Test) {
ASSERT_OK_AND_ASSIGN(const auto result, PrefixLenToMask(96, 128));
std::string expected(
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00", 16);
EXPECT_EQ(result, expected);
}
TEST(PrefixLenToMaskTest, GenericValueTest) {
ASSERT_OK_AND_ASSIGN(const auto result, PrefixLenToMask(23, 33));
std::string expected("\x01\xff\xff\xfc\x00", 5);
EXPECT_EQ(result, expected);
}
} // namespace pdpi
| 36.85614 | 80 | 0.717917 | [
"vector"
] |
20d0c30d57cfc304e9358f5e99deae1cb79fbb4b | 8,274 | cpp | C++ | src/ukf.cpp | immortaltw/Unscented-Kalman-Filter-Project | 8e66a9e803439a9e1b6697fdfd0b4297752d47d5 | [
"MIT"
] | null | null | null | src/ukf.cpp | immortaltw/Unscented-Kalman-Filter-Project | 8e66a9e803439a9e1b6697fdfd0b4297752d47d5 | [
"MIT"
] | null | null | null | src/ukf.cpp | immortaltw/Unscented-Kalman-Filter-Project | 8e66a9e803439a9e1b6697fdfd0b4297752d47d5 | [
"MIT"
] | null | null | null | #include "ukf.h"
#include "Eigen/Dense"
#include <exception>
using Eigen::MatrixXd;
using Eigen::VectorXd;
/**
* Initializes Unscented Kalman filter
*/
UKF::UKF() {
// if this is false, laser measurements will be ignored (except during init)
use_laser_ = true;
// if this is false, radar measurements will be ignored (except during init)
use_radar_ = true;
// initial state vector
x_ = VectorXd(5);
// initial covariance matrix
P_ = MatrixXd(5, 5);
// Process noise standard deviation longitudinal acceleration in m/s^2
std_a_ = 3;
// Process noise standard deviation yaw acceleration in rad/s^2
std_yawdd_ = 0.9;
/**
* DO NOT MODIFY measurement noise values below.
* These are provided by the sensor manufacturer.
*/
// Laser measurement noise standard deviation position1 in m
std_laspx_ = 0.15;
// Laser measurement noise standard deviation position2 in m
std_laspy_ = 0.15;
// Radar measurement noise standard deviation radius in m
std_radr_ = 0.3;
// Radar measurement noise standard deviation angle in rad
std_radphi_ = 0.03;
// Radar measurement noise standard deviation radius change in m/s
std_radrd_ = 0.3;
/**
* End DO NOT MODIFY section for measurement noise values
*/
// Lots of initialization...
is_initialized_ = false;
time_us_ = 0;
n_aug_ = 7;
n_x_ = 5;
weights_ = VectorXd(2 * n_aug_ + 1);
lambda_ = 3 - n_aug_;
x_.fill(0.0);
Xsig_pred_ = MatrixXd(n_x_, 2*n_aug_+1);
P_ << MatrixXd::Identity(n_x_, n_x_);
}
UKF::~UKF() {}
void UKF::ProcessMeasurement(MeasurementPackage meas_package) {
/**
* Driver method for UKF.
*/
// Handle first measurement
if (!is_initialized_) {
is_initialized_ = true;
if (meas_package.sensor_type_ == MeasurementPackage::LASER) {
x_(0) = meas_package.raw_measurements_(0);
x_(1) = meas_package.raw_measurements_(1);
} else {
x_(2) = meas_package.raw_measurements_(0);
x_(3) = meas_package.raw_measurements_(1);
}
time_us_ = meas_package.timestamp_;
return;
}
double delta_t_ = (meas_package.timestamp_ - time_us_) / 1000000.0;
time_us_ = meas_package.timestamp_;
Prediction(delta_t_);
if (meas_package.sensor_type_ == MeasurementPackage::LASER) {
UpdateLidar(meas_package);
return;
} else if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
UpdateRadar(meas_package);
return;
}
throw new std::runtime_error("Unrecongized sensor type.");
}
void UKF::Prediction(double delta_t) {
/**
* Estimate the object's location.
* Modify the state vector, x_. Predict sigma points, the state,
* and the state covariance matrix.
*/
// Generate augmented sigma points at current epoch
VectorXd x_aug = VectorXd(n_aug_);
MatrixXd P_aug = MatrixXd(n_aug_, n_aug_);
MatrixXd Xsig_aug = MatrixXd(n_aug_, 2*n_aug_+1);
// predicted state vector
VectorXd xp_ = VectorXd(5);
// predicted state covariance matrix
MatrixXd Pp_ = MatrixXd(5, 5);
x_aug.fill(0.0);
x_aug.head(n_x_) = x_;
P_aug.fill(0.0);
P_aug.topLeftCorner(5, 5) = P_;
P_aug(5, 5) = std_a_*std_a_;
P_aug(6, 6) = std_yawdd_*std_yawdd_;
MatrixXd A = P_aug.llt().matrixL();
Xsig_aug.col(0) = x_aug;
MatrixXd second_term = sqrt(lambda_ + n_aug_) * A;
for (int i=1; i<=n_aug_; ++i) {
Xsig_aug.col(i) = x_aug + second_term.col(i - 1);
Xsig_aug.col(i + n_aug_) = x_aug - second_term.col(i - 1);
}
// Predict sigma point
for (int i=0; i<2*n_aug_+1; ++i) {
double p_x = Xsig_aug(0,i);
double p_y = Xsig_aug(1,i);
double v = Xsig_aug(2,i);
double yaw = Xsig_aug(3,i);
double yawd = Xsig_aug(4,i);
double nu_a = Xsig_aug(5,i);
double nu_yawdd = Xsig_aug(6,i);
double px_p, py_p;
// avoid division by zero
if (fabs(yawd) > 0.001) {
px_p = v/yawd * (sin(yaw + yawd * delta_t) - sin(yaw));
py_p = v/yawd * (-cos(yaw + yawd * delta_t) + cos(yaw));
} else {
px_p = v * cos(yaw) * delta_t;
py_p = v * sin(yaw) * delta_t;
}
px_p = p_x + px_p + .5 * delta_t * delta_t * cos(yaw) * nu_a;
py_p = p_y + py_p + .5 * delta_t * delta_t * sin(yaw) * nu_a;
double v_p = v + delta_t * nu_a;
double yaw_p = yaw + yawd * delta_t + .5 * delta_t * delta_t * nu_yawdd;
double yawd_p = yawd + delta_t * nu_yawdd;
Xsig_pred_(0,i) = px_p;
Xsig_pred_(1,i) = py_p;
Xsig_pred_(2,i) = v_p;
Xsig_pred_(3,i) = yaw_p;
Xsig_pred_(4,i) = yawd_p;
}
// Get predicted mean and covariance
// set weights
weights_(0) = (double)lambda_/(lambda_+n_aug_);
for (int i=1; i<2*n_aug_+1; ++i) {
weights_(i) = .5/(lambda_+n_aug_);
}
// predict state mean
xp_.fill(0.0);
for (int i=0; i<2*n_aug_+1; ++i) {
xp_ = xp_ + weights_(i) * Xsig_pred_.col(i);
}
Pp_.fill(0.0);
// predict state covariance matrix
for (int i=0; i<2*n_aug_+1; ++i) {
VectorXd diff = Xsig_pred_.col(i) - xp_;
while (diff(3)> M_PI) diff(3)-=2.*M_PI;
while (diff(3)<-M_PI) diff(3)+=2.*M_PI;
Pp_ = Pp_ + weights_(i) * diff * diff.transpose();
}
x_ = xp_;
P_ = Pp_;
}
void UKF::UpdateLidar(MeasurementPackage meas_package) {
/**
* Use lidar data to update the belief
* about the object's position. Modify the state vector, x_, and
* covariance, P_.
* You can also calculate the lidar NIS, if desired.
*/
int n_z = 2;
VectorXd z = meas_package.raw_measurements_;
// - create matrix for sigma points in measurement space
MatrixXd Zsig = MatrixXd(n_z, 2*n_aug_+1);
// - residual covariance matrix R
MatrixXd R = MatrixXd(n_z,n_z);
R.fill(0.0);
R(0, 0) = std_laspx_*std_laspx_;
R(1, 1) = std_laspy_*std_laspy_;
for (int i=0; i<2*n_aug_+1; ++i) {
double px = Xsig_pred_(0, i);
double py = Xsig_pred_(1, i);
// transform sigma points into measurement space
Zsig(0, i) = px;
Zsig(1, i) = py;
}
UpdateSensorMeas(n_z, z, Zsig, R);
}
void UKF::UpdateRadar(MeasurementPackage meas_package) {
/**
* Use radar data to update the belief
* about the object's position. Modify the state vector, x_, and
* covariance, P_.
*/
int n_z = 3;
VectorXd z = meas_package.raw_measurements_;
// - create matrix for sigma points in measurement space
MatrixXd Zsig = MatrixXd(n_z, 2*n_aug_+1);
// - measurement noise covariance matrix R
MatrixXd R = MatrixXd(n_z,n_z);
R.fill(0.0);
R(0, 0) = std_radr_*std_radr_;
R(1, 1) = std_radphi_*std_radphi_;
R(2, 2) = std_radrd_*std_radrd_;
for (int i=0; i<2*n_aug_+1; ++i) {
double px = Xsig_pred_(0, i);
double py = Xsig_pred_(1, i);
double v = Xsig_pred_(2, i);
double phi = Xsig_pred_(3, i);
// transform sigma points into measurement space
double ro = sqrt(px*px + py*py);
double psi = atan2(py, px);
double rod = (px*cos(phi)*v + py*sin(phi)*v)/ro;
Zsig(0, i) = ro;
Zsig(1, i) = psi;
Zsig(2, i) = rod;
}
UpdateSensorMeas(n_z, z, Zsig, R);
}
void UKF::UpdateSensorMeas(int n_z, VectorXd &z, MatrixXd &Zsig, MatrixXd &R) {
// - mean predicted measurement
VectorXd z_pred = VectorXd(n_z);
// - measurement covariance matrix S
MatrixXd S = MatrixXd(n_z,n_z);
// - cross-corellation matrix Tc
MatrixXd Tc = MatrixXd(n_x_, n_z);
// Initial matrics
z_pred.fill(0.0);
S.fill(0.0);
Tc.fill(0.0);
for (int i=0; i<2*n_aug_+1; ++i) {
// calculate mean predicted measurement
z_pred = z_pred + weights_(i) * Zsig.col(i);
}
// calculate innovation covariance matrix S
for (int i=0; i<2*n_aug_+1; ++i) {
VectorXd z_diff = Zsig.col(i) - z_pred;
// angle normalization
while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;
S = S + weights_(i) * z_diff * z_diff.transpose();
}
S = S + R;
// Update
// - calculate cross correlation matrix
for (int i=0; i<2*n_aug_+1; ++i) {
VectorXd x_diff = Xsig_pred_.col(i) - x_;
VectorXd z_diff = Zsig.col(i) - z_pred;
Tc = Tc + weights_(i) * x_diff * z_diff.transpose();
}
// - calculate Kalman gain K;
MatrixXd K = Tc * S.inverse();
// - update state mean and covariance matrix
x_ = x_ + K * (z - z_pred);
P_ = P_ - K*S*K.transpose();
} | 26.519231 | 79 | 0.633188 | [
"object",
"vector",
"transform"
] |
20d78f26aa96a8110a5588edfe1ed815192a3cb2 | 3,907 | cpp | C++ | ECS/src/ECS/Managers/SystemManager.cpp | maxbrundev/OpenGL-Modern-ECS-GameEngine | 9924bacb35e20cd76b68ae79c6cf40a1b34ec4c0 | [
"MIT"
] | 2 | 2020-09-28T18:54:50.000Z | 2020-11-21T19:20:54.000Z | ECS/src/ECS/Managers/SystemManager.cpp | maxbrundev/OpenGL-Modern-ECS-GameEngine | 9924bacb35e20cd76b68ae79c6cf40a1b34ec4c0 | [
"MIT"
] | null | null | null | ECS/src/ECS/Managers/SystemManager.cpp | maxbrundev/OpenGL-Modern-ECS-GameEngine | 9924bacb35e20cd76b68ae79c6cf40a1b34ec4c0 | [
"MIT"
] | 2 | 2019-04-07T19:11:00.000Z | 2019-12-03T13:05:07.000Z | #include "ecs_stdafx.h"
#include "ECS/Managers/SystemManager.h"
#include "ECS/Types.h"
#include "Utils/algorithm.h"
using namespace ECS;
SystemManager::SystemManager()
{
}
SystemManager::~SystemManager()
{
}
void SystemManager::FixedUpdate(const double fixed_dt_ms)
{
for (ISystem_ptr system : this->m_systemWorkOrder)
{
// increase interval since last update
system->m_timeSinceLastUpdate = fixed_dt_ms;
if (system->m_enabled == true)
{
system->FixedUpdate(fixed_dt_ms);
}
}
}
/**
* \brief
* \param dt_ms
*/
void SystemManager::Update(const double dt_ms)
{
for (ISystem_ptr system : this->m_systemWorkOrder)
{
// increase interval since last update
system->m_timeSinceLastUpdate = dt_ms;
// check systems update state
system->m_needsUpdate = (system->m_updateInterval < 0.0f) || ((system->m_updateInterval > 0.0f) && (system->m_timeSinceLastUpdate > system->m_updateInterval));
if (system->m_enabled == true && system->m_needsUpdate == true)
{
system->PreUpdate(dt_ms);
}
}
for (ISystem_ptr system : this->m_systemWorkOrder)
{
if (system->m_enabled == true && system->m_needsUpdate == true)
{
system->Update(dt_ms);
system->m_timeSinceLastUpdate = 0.0f;
}
}
for (ISystem_ptr system : this->m_systemWorkOrder)
{
if (system->m_enabled == true && system->m_needsUpdate == true)
{
system->PostUpdate(dt_ms);
}
}
}
void SystemManager::UpdateSystemWorkOrder()
{
const size_t systemsCount = this->m_systemDependencyTable.size();
// create index array
std::vector<int> indices(systemsCount);
for (size_t i = 0; i < systemsCount; ++i)
indices[i] = static_cast<int>(i);
// determine vertex-groups
std::vector<std::vector<SystemTypeID>> vertexGroups;
std::vector<SystemPriority> groupPriority;
while (!indices.empty())
{
SystemTypeID index = indices.back();
indices.pop_back();
if (index == -1)
continue;
std::vector<SystemTypeID> group;
std::vector<SystemTypeID> member;
SystemPriority currentGroupPriority = LOWEST_SYSTEM_PRIORITY;
member.push_back(index);
while (!member.empty())
{
index = member.back();
member.pop_back();
for (int i = 0; i < static_cast<int>(indices.size()); ++i)
{
if (indices[i] != -1 && (this->m_systemDependencyTable[i][index] == true || this->m_systemDependencyTable[index][i] == true))
{
member.push_back(i);
indices[i] = -1;
}
}
group.push_back(index);
const ISystem_ptr sys = this->m_systemTable[index];
currentGroupPriority = std::max((sys != nullptr ? sys->m_priority : NORMAL_SYSTEM_PRIORITY), currentGroupPriority);
}
vertexGroups.push_back(group);
groupPriority.push_back(currentGroupPriority);
}
const size_t vertexGroupsCount = vertexGroups.size();
// do a topological sort on groups w.r.t. to groups priority!
std::vector<int> vertex_states(systemsCount, 0);
std::multimap<SystemPriority, std::vector<SystemTypeID>> sortedVertexGroups;
for (size_t i = 0; i < vertexGroupsCount; ++i)
{
auto g = vertexGroups[i];
std::vector<SystemTypeID> order;
for (size_t j = 0; j < g.size(); ++j)
{
if (vertex_states[g[j]] == 0)
Utils::Algo::depthFirstSearch<SystemTypeID>(g[j], vertex_states, this->m_systemDependencyTable, order);
}
std::reverse(order.begin(), order.end());
sortedVertexGroups.insert(std::pair<SystemPriority, std::vector<SystemTypeID>>(std::numeric_limits<SystemPriority>::max() - groupPriority[i], order));
}
// re-build system work order
this->m_systemWorkOrder.clear();
for (auto group : sortedVertexGroups)
{
for (auto m : group.second)
{
const ISystem_ptr sys = this->m_systemTable[m];
if (sys != nullptr)
{
this->m_systemWorkOrder.push_back(sys);
}
}
}
}
| 23.823171 | 162 | 0.659841 | [
"vector"
] |
2227f8b6ead67390689c6339e3b152f58310249f | 11,977 | hpp | C++ | VSDataReduction/VSSimpleCutsCalc.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | VSDataReduction/VSSimpleCutsCalc.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | VSDataReduction/VSSimpleCutsCalc.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-mode:c++; mode:font-lock;-*-
/*! \file VSSimpleCutsCalc.hpp
Class for applying simple box cuts.
\author Matthew Wood \n
UCLA \n
mdwood@astro.ucla.edu \n
\version 1.0
\date 07/08/2007
$Id: VSSimpleCutsCalc.hpp,v 3.9 2008/12/04 02:34:57 matthew Exp $
*/
#ifndef VSSIMPLECUTSCALC_HPP
#define VSSIMPLECUTSCALC_HPP
#include<VSCutsData.hpp>
#include<VSEventData.hpp>
#include<VSCutsCalc.hpp>
#include<VSOptions.hpp>
#include<VSH5DatumElement.hpp>
namespace VERITAS
{
// ==========================================================================
// VSSimpleCut
// ==========================================================================
template<typename T>
class VSSimpleCut
{
public:
VSSimpleCut();
VSSimpleCut(const std::string& _datum_element_name);
virtual ~VSSimpleCut();
virtual bool evaluateCut(const T& datum) = 0;
virtual std::string print() = 0;
std::string getName() { return m_datum_element->getName(); }
void initialize(const std::string& datum_element_name)
{
delete m_datum_element;
m_datum_element =
VSH5DatumElement<T>::createDatumElement(datum_element_name);
}
static bool isRangedCut(VSOctaveH5ReaderStruct* reader)
{
std::string cut_type;
reader->readString("cut_type",cut_type);
if(cut_type == "ranged")
return true;
else
return false;
}
static bool isPatternCut(VSOctaveH5ReaderStruct* reader)
{
std::string cut_type;
reader->readString("cut_type",cut_type);
if(cut_type == "pattern")
return true;
else
return false;
}
virtual bool save(VSOctaveH5WriterStruct* writer) = 0;
virtual bool load(VSOctaveH5ReaderStruct* reader) = 0;
VSH5DatumElement<T>* m_datum_element;
};
template< typename T >
VSSimpleCut<T>::VSSimpleCut():
m_datum_element(NULL)
{
}
template< typename T >
VSSimpleCut<T>::VSSimpleCut(const std::string& _datum_element_name):
m_datum_element(NULL)
{
m_datum_element =
VSH5DatumElement<T>::createDatumElement(_datum_element_name);
}
template< typename T >
VSSimpleCut<T>::~VSSimpleCut()
{
delete m_datum_element;
}
// ==========================================================================
// VSSimpleRangedCut
// ==========================================================================
template<typename T>
class VSSimpleRangedCut : public VSSimpleCut<T>
{
public:
VSSimpleRangedCut();
VSSimpleRangedCut(const std::string& _datum_element_name,
const std::string& _lo_cut, const std::string& _hi_cut);
VSSimpleRangedCut(const std::string& _datum_element_name,
double _lo_cut, bool _has_lo_cut,
double _hi_cut, bool _has_hi_cut);
virtual ~VSSimpleRangedCut() { }
bool evaluateCut(const T& datum);
bool save(VSOctaveH5WriterStruct* writer);
bool load(VSOctaveH5ReaderStruct* reader);
std::string print()
{
std::ostringstream os;
os << std::setw(30)
<< VSH5DatumElementParser::getElement(datum_element_name);
if(has_lo_cut)
os << std::setw(20) << lo_cut;
else
os << std::setw(20) << "-";
if(has_hi_cut)
os << std::setw(20) << hi_cut;
else
os << std::setw(20) << "-";
return os.str();
}
double getLoCut() { return lo_cut; }
std::string getLoCutString()
{
if(has_lo_cut)
return VSDataConverter::toString(lo_cut,true);
else
return "-";
}
double getHiCut() { return hi_cut; }
std::string getHiCutString()
{
if(has_hi_cut)
return VSDataConverter::toString(hi_cut,true);
else
return "-";
}
bool hasLoCut() { return has_lo_cut;}
bool hasHiCut() { return has_hi_cut; }
static void _compose(VSOctaveH5CompositeDefinition& c)
{
H5_ADDMEMBER(c,VSSimpleRangedCut,datum_element_name);
H5_ADDMEMBER(c,VSSimpleRangedCut,lo_cut);
H5_ADDMEMBER(c,VSSimpleRangedCut,hi_cut);
H5_ADDMEMBER(c,VSSimpleRangedCut,has_lo_cut);
H5_ADDMEMBER(c,VSSimpleRangedCut,has_hi_cut);
}
private:
VSSimpleRangedCut(const VSSimpleRangedCut& cut);
VSSimpleRangedCut& operator=(const VSSimpleRangedCut& cut);
std::string datum_element_name;
double lo_cut;
double hi_cut;
bool has_lo_cut;
bool has_hi_cut;
};
template< typename T >
VSSimpleRangedCut<T>::VSSimpleRangedCut():
VSSimpleCut<T>(), lo_cut(), hi_cut(), has_lo_cut(), has_hi_cut()
{
}
template< typename T >
VSSimpleRangedCut<T>::
VSSimpleRangedCut(const std::string& _datum_element_name,
double _lo_cut, bool _has_lo_cut,
double _hi_cut, bool _has_hi_cut):
VSSimpleCut<T>(_datum_element_name),
datum_element_name(_datum_element_name),
lo_cut(_lo_cut),hi_cut(_hi_cut),
has_lo_cut(_has_lo_cut),has_hi_cut(_has_hi_cut)
{
}
template< typename T >
VSSimpleRangedCut<T>::
VSSimpleRangedCut(const std::string& _datum_element_name,
const std::string& _lo_cut,
const std::string& _hi_cut):
VSSimpleCut<T>(_datum_element_name),
datum_element_name(_datum_element_name)
{
if(_lo_cut == "-" || _lo_cut.empty())
has_lo_cut = false;
else
{
has_lo_cut = true;
VSDatumConverter<double>::fromString(lo_cut,_lo_cut.c_str());
}
if(_hi_cut == "-" || _hi_cut.empty())
has_hi_cut = false;
else
{
has_hi_cut = true;
VSDatumConverter<double>::fromString(hi_cut,_hi_cut.c_str());
}
}
template< typename T >
bool VSSimpleRangedCut<T>::evaluateCut(const T& datum)
{
double x;
if(!VSSimpleCut<T>::m_datum_element->getValue(datum,x))
return false;
if((has_lo_cut && x < lo_cut) || (has_hi_cut && x >hi_cut))
return false;
else
return true;
}
template< typename T >
bool VSSimpleRangedCut<T>::save(VSOctaveH5WriterStruct* writer)
{
writer->writeString("cut_type","ranged");
if(!writer->writeCompositeHere(*this))
return false;
else
return true;
}
template< typename T >
bool VSSimpleRangedCut<T>::load(VSOctaveH5ReaderStruct* reader)
{
std::string cut_type;
reader->readString("cut_type",cut_type);
vsassert(cut_type == "ranged");
reader->readCompositeHere(*this);
VSSimpleCut<T>::initialize(datum_element_name);
return true;
}
// ==========================================================================
// VSSimplePatternCut
// ==========================================================================
template<typename T>
class VSSimplePatternCut : public VSSimpleCut<T>
{
public:
VSSimplePatternCut();
VSSimplePatternCut(const std::string& _datum_element_name,
const std::string& _patterns);
virtual ~VSSimplePatternCut() { }
bool evaluateCut(const T& datum);
bool save(VSOctaveH5WriterStruct* writer);
bool load(VSOctaveH5ReaderStruct* reader);
std::string print()
{
std::ostringstream os;
os << std::setw(30)
<< VSH5DatumElementParser::getElement(datum_element_name);
std::string patterns_string;
if(exclusive)
patterns_string += "!";
patterns_string += VSDataConverter::toString(patterns);
os << std::setw(20) << patterns_string;
return os.str();
}
static void _compose(VSOctaveH5CompositeDefinition& c)
{
H5_ADDMEMBER(c,VSSimplePatternCut,datum_element_name);
H5_ADDMEMBER(c,VSSimplePatternCut,exclusive);
}
private:
VSSimplePatternCut(const VSSimplePatternCut& cut);
VSSimplePatternCut& operator=(const VSSimplePatternCut& cut);
std::string datum_element_name;
bool exclusive;
std::vector< unsigned > patterns;
};
template< typename T >
VSSimplePatternCut<T>::VSSimplePatternCut():
VSSimpleCut<T>(), exclusive(), patterns()
{
}
template< typename T >
VSSimplePatternCut<T>::
VSSimplePatternCut(const std::string& _datum_element_name,
const std::string& _patterns):
VSSimpleCut<T>(_datum_element_name),
datum_element_name(_datum_element_name),
exclusive(),
patterns()
{
if(_patterns.substr(0,1) == "!")
{
exclusive = true;
VSDatumConverter< std::vector<unsigned> >::
fromString(patterns,_patterns.substr(1,_patterns.size()-1).c_str());
}
else
{
exclusive = false;
VSDatumConverter< std::vector<unsigned> >::
fromString(patterns,_patterns.c_str());
}
}
template< typename T >
bool VSSimplePatternCut<T>::evaluateCut(const T& datum)
{
double x;
if(!VSSimpleCut<T>::m_datum_element->getValue(datum,x)) return false;
for(std::vector< unsigned >::iterator itr = patterns.begin();
itr != patterns.end(); ++itr)
{
if(exclusive && (unsigned)lround(x) == *itr) return false;
else if(!exclusive && (unsigned)lround(x) == *itr) return true;
}
if(exclusive) return true;
else return false;
}
template< typename T >
bool VSSimplePatternCut<T>::save(VSOctaveH5WriterStruct* writer)
{
writer->writeString("cut_type","pattern");
writer->writeVector("patterns",patterns);
if(!writer->writeCompositeHere(*this))
return false;
else
return true;
}
template< typename T >
bool VSSimplePatternCut<T>::load(VSOctaveH5ReaderStruct* reader)
{
std::string cut_type;
reader->readString("cut_type",cut_type);
vsassert(cut_type == "pattern");
reader->readVector("patterns",patterns);
reader->readCompositeHere(*this);
VSSimpleCut<T>::initialize(datum_element_name);
return true;
}
// ==========================================================================
// VSSimpleCutsCalc
// ==========================================================================
class VSSimpleCutsCalc : public VSCutsCalc
{
public:
class Options
{
public:
typedef triple<std::string,std::string,std::string> Triple;
typedef std::pair<std::string,std::string> Pair;
Options():
simple_ranged_cuts(), simple_pattern_cuts(), simple_cuts_file(),
nscope(2)
{}
std::vector< Triple > simple_ranged_cuts;
std::vector< Pair > simple_pattern_cuts;
std::string simple_cuts_file;
unsigned nscope;
};
typedef VSSimpleCut<VSEventArrayDatum> ArrayCut;
typedef VSSimpleCut<VSEventScopeDatum> ScopeCut;
VSSimpleCutsCalc(const Options& opt = s_default_options);
virtual ~VSSimpleCutsCalc();
void getCutResults(VSArrayCutsDatum& cut_results,
const VSEventArrayDatum& event);
virtual void clear()
{
m_array_cuts.clear();
m_scope_cuts.clear();
}
virtual bool load(VSOctaveH5ReaderStruct* reader);
virtual bool load(const std::string& text_file);
virtual bool save(VSOctaveH5WriterStruct* writer);
virtual void getScopeParamSet(std::set< std::string >& scope_set);
virtual void getArrayParamSet(std::set< std::string >& array_set);
bool evaluateArrayCuts(const VSEventArrayDatum& event);
bool evaluateScopeCuts(unsigned iscope, const VSEventScopeDatum& scope);
void print();
void dump(std::ostream& stream) const;
void loadRangedCut(const std::string& datum_element,
const std::string& lo_cut,
const std::string& hi_cut);
void loadPatternCut(const std::string& datum_element,
const std::string& pattern);
static void configure(VSOptions& options,
const std::string& profile = "",
const std::string& opt_prefix = "");
private:
Options m_options;
std::vector< ArrayCut* > m_array_cuts;
std::vector< std::vector< ScopeCut* > > m_scope_cuts;
static Options s_default_options;
};
}
#endif // defined VSSIMPLECUTSCALC_HPP
| 26.674833 | 79 | 0.622693 | [
"vector"
] |
2237bb4550776a9e4cef25d29287fe29fb67e4da | 974 | cpp | C++ | ProgramFlow/FoorLoop/main.cpp | simonefinelli/Cpp-Notes | be66770e762092d79cbe7a09197b06c2962fd65f | [
"MIT"
] | null | null | null | ProgramFlow/FoorLoop/main.cpp | simonefinelli/Cpp-Notes | be66770e762092d79cbe7a09197b06c2962fd65f | [
"MIT"
] | null | null | null | ProgramFlow/FoorLoop/main.cpp | simonefinelli/Cpp-Notes | be66770e762092d79cbe7a09197b06c2962fd65f | [
"MIT"
] | null | null | null | // Section 9
// For loop
#include <iostream>
#include <vector>
using namespace std;
int main() {
// for (int i {}; i < 10; i++)
// cout << i << endl;
// for (int i {100}; i < 300; i+=50)
// cout << i << endl;
// for (int i {10}; i > 0; i--)
// cout << i << endl;
// for (int i {10}; i <= 100; i+=10) {
// if (i % 15 == 0)
// cout << i << endl;
// }
// for (int i {}, j {8}; i <= 5; i++, j--)
// cout << i << " + " << j << " = " << i + j << endl;
// for (int i {1}; i <= 100; i++) {
// cout << i << " ";
// if (i % 10 == 0)
// cout << endl;
// }
//
// cout << endl;
//
// // same as before
// for (int i {1}; i <= 100; i++)
// cout << i << ((i % 10 == 0) ? "\n" : " ");
vector<int> nums {10, 20, 30, 40, 50};
for (unsigned i {}; i < nums.size(); i++)
cout << nums.at(i) << endl;
cout << endl;
return 0;
} | 20.723404 | 60 | 0.349076 | [
"vector"
] |
223cc4c8b203733981cbe12180d370cfb59483f6 | 1,263 | hpp | C++ | include/MCL/ReadSeamedObj.hpp | mattoverby/mclgeom | d3ecd2a878900f33ba1412b8d82e643895201e51 | [
"MIT"
] | null | null | null | include/MCL/ReadSeamedObj.hpp | mattoverby/mclgeom | d3ecd2a878900f33ba1412b8d82e643895201e51 | [
"MIT"
] | 1 | 2021-12-26T22:44:01.000Z | 2022-02-09T02:54:23.000Z | include/MCL/ReadSeamedObj.hpp | mattoverby/mclgeom | d3ecd2a878900f33ba1412b8d82e643895201e51 | [
"MIT"
] | null | null | null | // Copyright Matt Overby 2021.
// Distributed under the MIT License.
#ifndef MCL_READSEAMEDOBJ_HPP
#define MCL_READSEAMEDOBJ_HPP 1
#include <Eigen/Core>
#include <vector>
// TODO my own readOBJ to remove igl dependency
#include <igl/readOBJ.h>
namespace mcl
{
static inline bool read_seamed_obj(
std::string filename,
Eigen::MatrixXd &V3D, // 3D vertices
Eigen::MatrixXd &VTC, // 2D UV tex init, if found
Eigen::MatrixXi &F)
{
using namespace Eigen;
MatrixXd V3D_, vN_unused;
MatrixXi F3D_, fN_unused;
bool read_success = igl::readOBJ(
filename,
V3D_, VTC, vN_unused,
F3D_, F, fN_unused);
if (!read_success) { return false; }
if (VTC.rows() > 0 && F.rows() > 0)
{
// Create 3D verts from F so face meshes match
std::vector<bool> filled(VTC.rows(),false);
V3D = MatrixXd::Zero(VTC.rows(),3);
if(F3D_.rows() != F.rows()){ return false; }
int nf = F3D_.rows();
for(int i=0; i<nf; i++)
{
for(int j:{0,1,2})
{
int f = F3D_(i,j);
int f_uv = F(i,j);
if(!filled[f_uv])
{
V3D.row(f_uv) = V3D_.row(f);
filled[f_uv] = true;
}
}
}
}
else
{
F = F3D_;
VTC = V3D_.block(0,0,V3D_.rows(),2);
V3D = V3D_;
}
if( F.minCoeff() > 0 ){ F.array() -= 1; }
return true;
}
} // end ns mcl
#endif | 18.850746 | 50 | 0.622328 | [
"vector",
"3d"
] |
2248af13c24742c1c75d144b008d8c60333cd607 | 1,554 | cc | C++ | src/cudauvm/CondFormats/SiPixelGainCalibrationForHLTGPU.cc | alexstrel/pixeltrack-standalone | 0b625eef0ef0b5c0f018d9b466457c5575b3442c | [
"Apache-2.0"
] | 9 | 2021-03-02T08:40:18.000Z | 2022-01-24T14:31:40.000Z | src/cudauvm/CondFormats/SiPixelGainCalibrationForHLTGPU.cc | alexstrel/pixeltrack-standalone | 0b625eef0ef0b5c0f018d9b466457c5575b3442c | [
"Apache-2.0"
] | 158 | 2020-03-22T19:46:40.000Z | 2022-03-24T09:51:35.000Z | src/cudauvm/CondFormats/SiPixelGainCalibrationForHLTGPU.cc | alexstrel/pixeltrack-standalone | 0b625eef0ef0b5c0f018d9b466457c5575b3442c | [
"Apache-2.0"
] | 26 | 2020-03-20T15:18:41.000Z | 2022-03-14T16:58:07.000Z | #include <cstring>
#include <cuda.h>
#include "CondFormats/SiPixelGainCalibrationForHLTGPU.h"
#include "CondFormats/SiPixelGainForHLTonGPU.h"
#include "CUDACore/cudaCheck.h"
#include "CUDACore/deviceCount.h"
#include "CUDACore/ScopedSetDevice.h"
#include "CUDACore/StreamCache.h"
SiPixelGainCalibrationForHLTGPU::SiPixelGainCalibrationForHLTGPU(SiPixelGainForHLTonGPU const& gain,
std::vector<char> const& gainData) {
cudaCheck(cudaMallocManaged(&gainForHLT_, sizeof(SiPixelGainForHLTonGPU)));
*gainForHLT_ = gain;
cudaCheck(cudaMallocManaged(&gainData_, gainData.size()));
gainForHLT_->v_pedestals = gainData_;
std::memcpy(gainData_, gainData.data(), gainData.size());
for (int device = 0, ndev = cms::cuda::deviceCount(); device < ndev; ++device) {
#ifndef CUDAUVM_DISABLE_ADVISE
cudaCheck(cudaMemAdvise(gainForHLT_, sizeof(SiPixelGainForHLTonGPU), cudaMemAdviseSetReadMostly, device));
cudaCheck(cudaMemAdvise(gainData_, gainData.size(), cudaMemAdviseSetReadMostly, device));
#endif
#ifndef CUDAUVM_DISABLE_PREFETCH
cms::cuda::ScopedSetDevice guard{device};
auto stream = cms::cuda::getStreamCache().get();
cudaCheck(cudaMemPrefetchAsync(gainForHLT_, sizeof(SiPixelGainForHLTonGPU), device, stream.get()));
cudaCheck(cudaMemPrefetchAsync(gainData_, gainData.size(), device, stream.get()));
#endif
}
}
SiPixelGainCalibrationForHLTGPU::~SiPixelGainCalibrationForHLTGPU() {
cudaCheck(cudaFree(gainForHLT_));
cudaCheck(cudaFree(gainData_));
}
| 40.894737 | 110 | 0.749035 | [
"vector"
] |
224b559c5677a6ee262ab06abad1e936c717198c | 1,464 | cpp | C++ | Magical Stones I/main.cpp | nickbel7/IEEEXtreme14.0-codenames | 58500b10d8e2f577bfe5175e9ae6dc74479e7e3f | [
"MIT"
] | 1 | 2021-10-21T04:54:22.000Z | 2021-10-21T04:54:22.000Z | Magical Stones I/main.cpp | nickbel7/IEEEXtreme14.0-codenames | 58500b10d8e2f577bfe5175e9ae6dc74479e7e3f | [
"MIT"
] | null | null | null | Magical Stones I/main.cpp | nickbel7/IEEEXtreme14.0-codenames | 58500b10d8e2f577bfe5175e9ae6dc74479e7e3f | [
"MIT"
] | 2 | 2020-10-06T16:37:35.000Z | 2020-10-24T11:09:06.000Z | #include <iostream>
#include <vector>
using namespace std;
int main() {
int N, input, Q;
cin >> N;
vector<int> spell;
vector<bool> tel;
vector<bool> temp;
vector<int> rocks;
for(int i=0; i<N; ++i){
tel.push_back(true);
temp.push_back(false);
}
for(int i=0; i<N; ++i){
cin >> input;
spell.push_back(input-1);
}
int count=0;
bool flag;
while(true){
for(int i=0; i<N; ++i){
temp[i] = false;
}
for(int i=0; i<N; ++i){
if(tel[i] == true)
temp[spell[i]] = true;
}
flag = false;
for(int i=0; i<N; ++i){
if(temp[i] != tel[i] ){
flag = true;
break;
}
}
if(!flag)
break;
for(int i=0; i<N; ++i){
tel[i] = temp[i];
if(tel[i])
count++;
}
rocks.push_back(count);
count = 0;
}
cin >> Q;
bool could = false;
int ans=0;
for(int i=0; i < Q; ++i){
could = false;
cin >> input;
for(int i=0; i<rocks.size(); ++i){
if(input == rocks[i]){
could = true;
ans = i+1;
break;
}
}
if(could)
cout << ans << endl;
else{
ans = -1;
cout << ans << endl;
}
}
return 0;
}
| 19.52 | 42 | 0.373634 | [
"vector"
] |
224c9a787881a19f735f8aeb71e4485ff3dc201a | 14,753 | cpp | C++ | base/cluster/mgmt/cluscfg/basecluster/cbaseclusterform.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/cluster/mgmt/cluscfg/basecluster/cbaseclusterform.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/cluster/mgmt/cluscfg/basecluster/cbaseclusterform.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1999-2001 Microsoft Corporation
//
// Module Name:
// CBaseClusterForm.cpp
//
// Description:
// Contains the definition of the CBaseClusterForm class.
//
// Maintained By:
// David Potter (DavidP) 14-JUN-2001
// Vij Vasu (Vvasu) 08-MAR-2000
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Include Files
//////////////////////////////////////////////////////////////////////////////
// The precompiled header.
#include "Pch.h"
// The header file of this class.
#include "CBaseClusterForm.h"
// For the CClusSvcAccountConfig action
#include "CClusSvcAccountConfig.h"
// For the CClusNetCreate action
#include "CClusNetCreate.h"
// For the CClusDiskForm action
#include "CClusDiskForm.h"
// For the CClusDBForm action
#include "CClusDBForm.h"
// For the CClusSvcCreate action
#include "CClusSvcCreate.h"
// For the CNodeConfig action
#include "CNodeConfig.h"
//////////////////////////////////////////////////////////////////////////
// Macros definitions
//////////////////////////////////////////////////////////////////////////
// The minimum amount of free space in bytes, required by the
// localquorum resource (5 Mb)
#define LOCALQUORUM_MIN_FREE_DISK_SPACE 5242880
// Name of the file system required by the local quorum resource
#define LOCALQUORUM_FILE_SYSTEM L"NTFS"
//////////////////////////////////////////////////////////////////////////////
//++
//
// CBaseClusterForm::CBaseClusterForm
//
// Description:
// Constructor of the CBaseClusterForm class.
//
// This function also stores the parameters that are required for
// creating a cluster.
//
// Arguments:
// pbcaiInterfaceIn
// Pointer to the interface class for this library.
//
// pszClusterNameIn
// Name of the cluster to be formed.
//
// pcccServiceAccountIn
// Specifies the account to be used as the cluster service account.
//
// dwClusterIPAddressIn
// dwClusterIPSubnetMaskIn
// pszClusterIPNetworkIn
// Specifies the IP address and network of the cluster IP address.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// CConfigError
// If the OS version is incorrect or if the installation state
// of the cluster binaries is wrong.
//
// CRuntimeError
// If any of the APIs fail.
//
//--
//////////////////////////////////////////////////////////////////////////////
CBaseClusterForm::CBaseClusterForm(
CBCAInterface * pbcaiInterfaceIn
, const WCHAR * pcszClusterNameIn
, const WCHAR * pszClusterBindingStringIn
, IClusCfgCredentials * pcccServiceAccountIn
, DWORD dwClusterIPAddressIn
, DWORD dwClusterIPSubnetMaskIn
, const WCHAR * pszClusterIPNetworkIn
)
: BaseClass(
pbcaiInterfaceIn
, pcszClusterNameIn
, pszClusterBindingStringIn
, pcccServiceAccountIn
, dwClusterIPAddressIn
)
, m_dwClusterIPAddress( dwClusterIPAddressIn )
, m_dwClusterIPSubnetMask( dwClusterIPSubnetMaskIn )
, m_strClusterIPNetwork( pszClusterIPNetworkIn )
{
TraceFunc( "" );
LogMsg( "[BC] The current cluster configuration task is: Create a Cluster." );
CStatusReport srInitForm(
PBcaiGetInterfacePointer()
, TASKID_Major_Configure_Cluster_Services
, TASKID_Minor_Initializing_Cluster_Form
, 0, 1
, IDS_TASK_FORM_INIT
);
// Send the next step of this status report.
srInitForm.SendNextStep( S_OK );
//
// Write parameters to log file.
//
LogMsg(
"[BC] Cluster IP Address => %d.%d.%d.%d"
, ( m_dwClusterIPAddress & 0x000000FF )
, ( m_dwClusterIPAddress & 0x0000FF00 ) >> 8
, ( m_dwClusterIPAddress & 0x00FF0000 ) >> 16
, ( m_dwClusterIPAddress & 0xFF000000 ) >> 24
);
LogMsg(
"[BC] Subnet Mask => %d.%d.%d.%d"
, ( m_dwClusterIPSubnetMask & 0x000000FF )
, ( m_dwClusterIPSubnetMask & 0x0000FF00 ) >> 8
, ( m_dwClusterIPSubnetMask & 0x00FF0000 ) >> 16
, ( m_dwClusterIPSubnetMask & 0xFF000000 ) >> 24
);
LogMsg( "[BC] Cluster IP Network name => '%s'", m_strClusterIPNetwork.PszData() );
//
// Perform a sanity check on the parameters used by this class
//
if ( ( pszClusterIPNetworkIn == NULL ) || ( *pszClusterIPNetworkIn == L'\0' ) )
{
LogMsg( "[BC] The cluster IP Network name is invalid. Throwing an exception." );
THROW_CONFIG_ERROR( THR( E_INVALIDARG ), IDS_ERROR_INVALID_IP_NET );
} // if: the cluster IP network name is empty
//
// Make sure that there is enough free space under the cluster directory.
// The quorum logs for the localquorum resource will be under this directory.
//
{
BOOL fSuccess;
ULARGE_INTEGER uliFreeBytesAvailToUser;
ULARGE_INTEGER uliTotalBytes;
ULARGE_INTEGER uliTotalFree;
ULARGE_INTEGER uliRequired;
uliRequired.QuadPart = LOCALQUORUM_MIN_FREE_DISK_SPACE;
fSuccess = GetDiskFreeSpaceEx(
RStrGetClusterInstallDirectory().PszData()
, &uliFreeBytesAvailToUser
, &uliTotalBytes
, &uliTotalFree
);
if ( fSuccess == 0 )
{
DWORD sc = TW32( GetLastError() );
LogMsg( "[BC] Error %#08x occurred trying to get free disk space. Throwing an exception.", sc );
THROW_RUNTIME_ERROR(
HRESULT_FROM_WIN32( sc )
, IDS_ERROR_GETTING_FREE_DISK_SPACE
);
} // if: GetDiskFreeSpaceEx failed
LogMsg(
"[BC] Free space required = %#x%08x bytes. Available = %#x%08x bytes."
, uliRequired.HighPart
, uliRequired.LowPart
, uliFreeBytesAvailToUser.HighPart
, uliFreeBytesAvailToUser.LowPart
);
if ( uliFreeBytesAvailToUser.QuadPart < uliRequired.QuadPart )
{
LogMsg( "[BC] There isn't enough free space for the Local Quorum resource. The cluster create operation cannot proceed (throwing an exception)." );
THROW_CONFIG_ERROR(
HRESULT_FROM_WIN32( THR( ERROR_DISK_FULL ) )
, IDS_ERROR_INSUFFICIENT_DISK_SPACE
);
} // if: there isn't enough free space for localquorum.
LogMsg( "[BC] There is enough free space for the Local Quorum resource. The cluster create operation can proceed." );
}
/*
//
// KB: Vij Vasu (VVasu) 07-SEP-2000. Localquorum no longer needs NTFS disks
// The code below has been commented out since it is no longer required that
// localquorum resources use NTFS disks. This was confirmed by SunitaS.
//
//
// Make sure that the drive on which the cluster binaries are installed has NTFS
// on it. This is required by the localquorum resource.
//
{
WCHAR szVolumePathName[ MAX_PATH ];
WCHAR szFileSystemName[ MAX_PATH ];
BOOL fSuccess;
fSuccess = GetVolumePathName(
RStrGetClusterInstallDirectory().PszData()
, szVolumePathName
, ARRAYSIZE( szVolumePathName )
);
if ( fSuccess == 0 )
{
DWORD sc = TW32( GetLastError() );
LogMsg( "[BC] Error %#08x occurred trying to get file system type. The cluster create operation cannot proceed (throwing an exception).", sc );
THROW_RUNTIME_ERROR(
HRESULT_FROM_WIN32( sc )
, IDS_ERROR_GETTING_FILE_SYSTEM
);
} // if: GetVolumePathName failed
LogMsg( "[BC] The volume path name of the disk on which the cluster binaries reside is '%ws'.", szVolumePathName );
fSuccess = GetVolumeInformationW(
szVolumePathName // root directory
, NULL // volume name buffer
, 0 // length of name buffer
, NULL // volume serial number
, NULL // maximum file name length
, NULL // file system options
, szFileSystemName // file system name buffer
, ARRAYSIZE( szFileSystemName ) // length of file system name buffer
);
if ( fSuccess == 0 )
{
DWORD sc = TW32( GetLastError() );
LogMsg( "[BC] Error %#08x occurred trying to get file system type. The cluster create operation cannot proceed (throwing an exception).", sc );
THROW_RUNTIME_ERROR(
HRESULT_FROM_WIN32( sc )
, IDS_ERROR_GETTING_FILE_SYSTEM
);
} // if: GetVolumeInformation failed
LogMsg(
"[BC] The file system on '%ws' is '%ws'. Required file system is '%s'."
, szVolumePathName
, szFileSystemName
, LOCALQUORUM_FILE_SYSTEM
);
if ( NStringCchCompareNoCase( szFileSystemName, RTL_NUMBER_OF( szFileSystemName ), LOCALQUORUM_FILE_SYSTEM, RTL_NUMBER_OF( LOCALQUORUM_FILE_SYSTEM ) ) != 0 )
{
LogMsg( "[BC] LocalQuorum resource cannot be created on non-NTFS disk '%ws'. The cluster create operation cannot proceed (throwing an exception).", szVolumePathName );
// MUSTDO - must define proper HRESULT for this error. ( Vvasu - 10 Mar 2000 )
THROW_CONFIG_ERROR(
HRESULT_FROM_WIN32( TW32( ERROR_UNRECOGNIZED_MEDIA ) )
, IDS_ERROR_INCORRECT_INSTALL_STATE
);
} // if: the file system is not correct.
LogMsg( "[BC] LocalQuorum resource will be created on disk '%ws'. The cluster create operation can proceed.", szVolumePathName );
}
*/
//
// Create a list of actions to be performed.
// The order of appending actions is significant.
//
// Add the action to configure the cluster service account.
RalGetActionList().AppendAction( new CClusSvcAccountConfig( this ) );
// Add the action to create the ClusNet service.
RalGetActionList().AppendAction( new CClusNetCreate( this ) );
// Add the action to create the ClusDisk service.
RalGetActionList().AppendAction( new CClusDiskForm( this ) );
// Add the action to create the cluster database.
RalGetActionList().AppendAction( new CClusDBForm( this ) );
// Add the action to perform miscellaneous tasks.
RalGetActionList().AppendAction( new CNodeConfig( this ) );
// Add the action to create the ClusSvc service.
RalGetActionList().AppendAction( new CClusSvcCreate( this ) );
// Indicate if rollback is possible or not.
SetRollbackPossible( RalGetActionList().FIsRollbackPossible() );
// Indicate that a cluster should be formed during commit.
SetAction( eCONFIG_ACTION_FORM );
// Send the last step of a status report.
srInitForm.SendNextStep( S_OK );
LogMsg( "[BC] Initialization for creating a cluster has completed." );
TraceFuncExit();
} //*** CBaseClusterForm::CBaseClusterForm
//////////////////////////////////////////////////////////////////////////////
//++
//
// CBaseClusterForm::~CBaseClusterForm
//
// Description:
// Destructor of the CBaseClusterForm class
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
CBaseClusterForm::~CBaseClusterForm( void ) throw()
{
TraceFunc( "" );
TraceFuncExit();
} //*** CBaseClusterForm::~CBaseClusterForm
//////////////////////////////////////////////////////////////////////////////
//++
//
// CBaseClusterForm::Commit
//
// Description:
// Create the cluster.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// CRuntimeError
// If any of the APIs fail.
//
// Any exceptions thrown by functions called.
//
//--
//////////////////////////////////////////////////////////////////////////////
void
CBaseClusterForm::Commit( void )
{
TraceFunc( "" );
CStatusReport srFormingCluster(
PBcaiGetInterfacePointer()
, TASKID_Major_Configure_Cluster_Services
, TASKID_Minor_Commit_Forming_Node
, 0, 1
, IDS_TASK_FORMING_CLUSTER
);
LogMsg( "[BC] Initiating a cluster create operation." );
// Send the next step of this status report.
srFormingCluster.SendNextStep( S_OK );
// Call the base class commit routine. This commits the action list.
BaseClass::Commit();
// If we are here, then everything went well.
SetCommitCompleted( true );
// Send the last step of this status report.
srFormingCluster.SendLastStep( S_OK );
TraceFuncExit();
} //*** CBaseClusterForm::Commit
//////////////////////////////////////////////////////////////////////////////
//++
//
// void
// CBaseClusterForm::Rollback
//
// Description:
// Performs the rolls back of the action committed by this object.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Exceptions Thrown:
// Any exceptions thrown by functions called.
//
//--
//////////////////////////////////////////////////////////////////////////////
void
CBaseClusterForm::Rollback( void )
{
TraceFunc( "" );
// Rollback the actions.
BaseClass::Rollback();
SetCommitCompleted( false );
TraceFuncExit();
} //*** CBaseClusterForm::Rollback
| 32.495595 | 180 | 0.537992 | [
"object"
] |
224fa20d62b9683c5c0ac78c7655d6e8fc131405 | 2,397 | cpp | C++ | turbo_transformers/layers/bert_pooler.cpp | xcnick/TurboTransformers | 48b6ba09af2219616c6b97cc5c09222408e080c2 | [
"BSD-3-Clause"
] | 1 | 2020-06-07T06:24:41.000Z | 2020-06-07T06:24:41.000Z | turbo_transformers/layers/bert_pooler.cpp | xcnick/TurboTransformers | 48b6ba09af2219616c6b97cc5c09222408e080c2 | [
"BSD-3-Clause"
] | null | null | null | turbo_transformers/layers/bert_pooler.cpp | xcnick/TurboTransformers | 48b6ba09af2219616c6b97cc5c09222408e080c2 | [
"BSD-3-Clause"
] | 1 | 2021-01-04T11:10:40.000Z | 2021-01-04T11:10:40.000Z | // Copyright (C) 2020 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.
// See the AUTHORS file for names of contributors.
#include "turbo_transformers/layers/bert_pooler.h"
#include <loguru.hpp>
#include "turbo_transformers/core/memory.h"
#include "turbo_transformers/layers/kernels/activation.h"
#include "turbo_transformers/layers/kernels/mat_mul.h"
namespace turbo_transformers {
namespace layers {
void BertPooler::operator()(const core::Tensor& input_tensor,
core::Tensor* output_tensor) const {
TT_ENFORCE_EQ(input_tensor.n_dim(), 2, "input's dim should be 2, not %d",
input_tensor.n_dim());
output_tensor->Reshape<float>({input_tensor.shape(0), dense_weight_.shape(0)},
input_tensor.device_type(),
input_tensor.device_id());
kernels::MatMul(input_tensor, false, dense_weight_, false, 1.0, output_tensor,
0.0);
kernels::AddBiasAct<float, kernels::ActivationType::Tanh>(dense_bias_,
output_tensor);
}
void BertPooler::EnforceShapeAndType() const {
TT_ENFORCE_EQ(dense_weight_.n_dim(), 2, "dense weight must be matrix");
TT_ENFORCE_EQ(dense_bias_.n_dim(), 1, "dense bias must be vector");
TT_ENFORCE_EQ(dense_weight_.shape(0), dense_bias_.shape(0),
"weight and bias shape mismatch %d, %d", dense_weight_.shape(0),
dense_bias_.shape(0));
if (loguru::current_verbosity_cutoff() >= 3) {
std::ostringstream os;
os << ">>>>>>>>>>>> query_weight <<<<<<<<<<<<" << std::endl;
dense_weight_.Print<float>(os);
os << ">>>>>>>>>>>> query_bias <<<<<<<<<<<<" << std::endl;
dense_bias_.Print<float>(os);
LOG_S(3) << os.str();
}
}
} // namespace layers
} // namespace turbo_transformers
| 41.327586 | 80 | 0.659992 | [
"shape",
"vector"
] |
225b7f020bc4e1191491556ef96b4d9264e2db96 | 1,489 | cpp | C++ | src/function/table/version/pragma_version.cpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | null | null | null | src/function/table/version/pragma_version.cpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | 7 | 2020-08-25T22:24:16.000Z | 2020-09-06T00:16:49.000Z | src/function/table/version/pragma_version.cpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | null | null | null | #include "duckdb/function/table/sqlite_functions.hpp"
#include "duckdb/main/database.hpp"
namespace duckdb {
struct PragmaVersionData : public TableFunctionData {
PragmaVersionData() : done(false) {
}
bool done;
};
static unique_ptr<FunctionData> pragma_version_bind(ClientContext &context, vector<Value> &inputs,
unordered_map<string, Value> &named_parameters,
vector<LogicalType> &return_types, vector<string> &names) {
names.push_back("library_version");
return_types.push_back(LogicalType::VARCHAR);
names.push_back("source_id");
return_types.push_back(LogicalType::VARCHAR);
return make_unique<PragmaVersionData>();
}
static void pragma_version_info(ClientContext &context, vector<Value> &input, DataChunk &output,
FunctionData *dataptr) {
auto &data = *((PragmaVersionData *)dataptr);
assert(input.size() == 0);
if (data.done) {
// finished returning values
return;
}
output.SetCardinality(1);
output.SetValue(0, 0, DuckDB::LibraryVersion());
output.SetValue(1, 0, DuckDB::SourceID());
data.done = true;
}
void PragmaVersion::RegisterFunction(BuiltinFunctions &set) {
set.AddFunction(TableFunction("pragma_version", {}, pragma_version_bind, pragma_version_info, nullptr));
}
const char *DuckDB::SourceID() {
return DUCKDB_SOURCE_ID;
}
const char *DuckDB::LibraryVersion() {
return "DuckDB";
}
} // namespace duckdb
| 29.78 | 111 | 0.689053 | [
"vector"
] |
2263045591732ee6a69f831e224cd9177b1aab47 | 2,206 | cxx | C++ | Rendering/OpenGL2/Testing/Cxx/TestSDL2.cxx | txwhhny/vtk | 854d9aa87b944bc9079510515996406b98b86f7c | [
"BSD-3-Clause"
] | 1,755 | 2015-01-03T06:55:00.000Z | 2022-03-29T05:23:26.000Z | Rendering/OpenGL2/Testing/Cxx/TestSDL2.cxx | txwhhny/vtk | 854d9aa87b944bc9079510515996406b98b86f7c | [
"BSD-3-Clause"
] | 29 | 2015-04-23T20:58:30.000Z | 2022-03-02T16:16:42.000Z | Rendering/OpenGL2/Testing/Cxx/TestSDL2.cxx | txwhhny/vtk | 854d9aa87b944bc9079510515996406b98b86f7c | [
"BSD-3-Clause"
] | 1,044 | 2015-01-05T22:48:27.000Z | 2022-03-31T02:38:26.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: Mace.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkActor.h"
#include "vtkConeSource.h"
#include "vtkGlyph3D.h"
#include "vtkNew.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkSDL2OpenGLRenderWindow.h"
#include "vtkSDL2RenderWindowInteractor.h"
#include "vtkSphereSource.h"
int TestSDL2(int argc, char* argv[])
{
vtkNew<vtkRenderer> renderer;
vtkNew<vtkSDL2OpenGLRenderWindow> renWin;
renWin->AddRenderer(renderer);
vtkNew<vtkSDL2RenderWindowInteractor> iren;
iren->SetRenderWindow(renWin);
vtkNew<vtkSphereSource> sphere;
sphere->SetThetaResolution(8);
sphere->SetPhiResolution(8);
vtkNew<vtkPolyDataMapper> sphereMapper;
sphereMapper->SetInputConnection(sphere->GetOutputPort());
vtkNew<vtkActor> sphereActor;
sphereActor->SetMapper(sphereMapper);
vtkNew<vtkConeSource> cone;
cone->SetResolution(6);
vtkNew<vtkGlyph3D> glyph;
glyph->SetInputConnection(sphere->GetOutputPort());
glyph->SetSourceConnection(cone->GetOutputPort());
glyph->SetVectorModeToUseNormal();
glyph->SetScaleModeToScaleByVector();
glyph->SetScaleFactor(0.25);
vtkNew<vtkPolyDataMapper> spikeMapper;
spikeMapper->SetInputConnection(glyph->GetOutputPort());
vtkNew<vtkActor> spikeActor;
spikeActor->SetMapper(spikeMapper);
renderer->AddActor(sphereActor);
renderer->AddActor(spikeActor);
renderer->SetBackground(0.2, 0.3, 0.4);
renWin->SetSize(300, 300);
// interact with data
renWin->Render();
int retVal = vtkRegressionTestImage(renWin);
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
| 29.413333 | 75 | 0.705349 | [
"render"
] |
22670480b5d6229154d5b622025102fc0c0da4fb | 6,105 | cpp | C++ | Device/Sample/BLE/BLE.cpp | tencentyun/xiaowei-device-sdk | 09bf2e4a992158a853b650024ce124390274bf5a | [
"MIT"
] | 28 | 2018-05-11T09:10:40.000Z | 2021-11-23T09:16:42.000Z | Device/Sample/BLE/BLE.cpp | tencentyun/xiaowei-device-sdk | 09bf2e4a992158a853b650024ce124390274bf5a | [
"MIT"
] | 1 | 2019-01-16T11:33:26.000Z | 2019-01-16T11:33:26.000Z | Device/Sample/BLE/BLE.cpp | tencentyun/xiaowei-device-sdk | 09bf2e4a992158a853b650024ce124390274bf5a | [
"MIT"
] | 6 | 2018-05-11T09:09:06.000Z | 2019-01-04T01:42:58.000Z | /*
* Tencent is pleased to support the open source community by making XiaoweiSDK Demo Codes available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the MIT License (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://opensource.org/licenses/MIT
*
* 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 "BLE.h"
#include "TXCAudioMsg.h"
#include "json.h"
#include <sstream>
unsigned long long m_id = 0;
std::string ConvertBLEInfoToJson(ble_device_info* info)
{
std::string strBLE = "";
json::Object jsonValue;
if(info->name !=NULL) {
jsonValue["name"] = info->name;
}
if(info->address !=NULL) {
jsonValue["address"] = info->address;
}
jsonValue["state"] = (int)info->state;
jsonValue["major"] = (int)info->major;
strBLE = json::Serialize(jsonValue);
return strBLE;
}
std::string ConvertBLEInfoListToJson(ble_device_info* info, unsigned int count)
{
std::string strBLE = "";
json::Array devices;
for(int i = 0;i<count;i++)
{
json::Object jsonValue;
if(info[i].name !=NULL) {
jsonValue["name"] = info[i].name;
}
if(info[i].address !=NULL) {
jsonValue["address"] = info[i].address;
}
jsonValue["state"] = (int)info[i].state;
jsonValue["major"] = (int)info[i].major;
devices.push_back(jsonValue);
}
strBLE = json::Serialize(devices);
return strBLE;
}
// ble_result_info
void send_ble_result_2_app(std::string event, unsigned int result, std::string device)
{
if(m_id == 0) {
return;
}
std::string msg ;
json::Object jsonValue;
jsonValue["event"] = event;
jsonValue["result"] = (int)result;
jsonValue["time"] = eventTime;
if(device.length()>0) {
jsonValue["device"] = device;
}
msg = json::Serialize(jsonValue);
log_notice("send_ble_result_2_app %s",msg.c_str());
unsigned int cookie;
TXCA_PARAM_CC_MSG cc_msg = {0};
cc_msg.business_name = "蓝牙";
cc_msg.msg = msg.c_str();
cc_msg.msg_len = msg.length();
txca_send_c2c_msg(m_id, &cc_msg, &cookie);
}
void on_ble_open()
{
send_ble_result_2_app("BLE_OPEN", 0, "");
}
void on_ble_close()
{
send_ble_result_2_app("BLE_CLOSE", 0, "");
}
void on_ble_bond(ble_device_info* device)
{
send_ble_result_2_app("BLE_BOND", 0, ConvertBLEInfoToJson(device));
}
void on_ble_unbond(ble_device_info* device)
{
send_ble_result_2_app("BLE_UNBOND", 0, ConvertBLEInfoToJson(device));
}
void on_ble_connected(bool connected, ble_device_info* device)
{
send_ble_result_2_app("BLE_CONNECT", connected ? 0 : 1, ConvertBLEInfoToJson(device));
}
void on_ble_discovery(ble_device_info* device, unsigned int count)
{
send_ble_result_2_app("BLE_DISCOVERY", 0, ConvertBLEInfoListToJson(device, count));
}
ble_notify m_callback;
// 在 on_cc_msg_notify 收到消息的时候,根据tx_ai_cc_msg的 business_name 分发,如果是"蓝牙",将其放到这里处理
void on_cc_msg(unsigned long long from, const char* msg, unsigned int msg_len){
m_id = from;
std::string ble_event = msg;
json::Value jsonValue = json::Deserialize(ble_event);
json::Object jsonObject = jsonValue.ToObject();
std::string event;
std::string address;
Util::JsonUtil::JsonGetString(event, jsonObject, "event");
Util::JsonUtil::JsonGetString(address, jsonObject, "address");
if(event == "BLE_OPEN") {
if(m_callback.open_ble){
bool ret = m_callback.open_ble();
if(!ret) {
send_ble_result_2_app(event, 1, "");
}
}
} else if(event == "BLE_CLOSE") {
if(m_callback.close_ble){
bool ret = m_callback.close_ble();
if(!ret) {
send_ble_result_2_app(event, 1, "");
}
}
} else if(event == "BLE_GET_STATE") {
if(m_callback.is_ble_open && m_callback.on_get_current_connected_ble_device){
bool open = m_callback.is_ble_open();
ble_device_info* device = m_callback.on_get_current_connected_ble_device();
send_ble_result_2_app(event, open ? 0 : 1, ConvertBLEInfoToJson(device));
}
} else if(event == "BLE_DISCOVERY") {
if(m_callback.start_discovery){
bool ret = m_callback.start_discovery();
if(!ret) {
send_ble_result_2_app(event, 1, "");
}
}
} else if(event == "BLE_BOND") {
if(m_callback.bond){
bool ret = m_callback.bond(address.c_str());
if(!ret) {
ble_device_info device = {0};
device.address = address.c_str();
send_ble_result_2_app(event, 1, ConvertBLEInfoToJson(&device));
}
}
} else if(event == "BLE_UNBOND") {
if(m_callback.un_bond){
bool ret = m_callback.un_bond(address.c_str());
if(!ret) {
ble_device_info device = {0};
device.address = address.c_str();
send_ble_result_2_app(event, 1, ConvertBLEInfoToJson(&device));
}
}
} else if(event == "BLE_CONNECT") {
if(m_callback.connect){
bool ret = m_callback.connect(address.c_str());
if(!ret) {
ble_device_info device = {0};
device.address = address.c_str();
send_ble_result_2_app(event, 1, ConvertBLEInfoToJson(&device));
}
}
}
}
void config_ble_notify(ble_notify* callback)
{
if(callback != NULL){
memcpy(&m_callback, callback, sizeof(m_callback));
} else {
memset(&m_callback, 0, sizeof(m_callback));
}
}
| 29.635922 | 102 | 0.61638 | [
"object"
] |
227f2e545b8e8c7d1a5906ceccde702da480c398 | 2,513 | cpp | C++ | convolution/src/mask.cpp | fpeterek/dzo | d046a3c53bc66ee4fa7897394422570c1ef8f07a | [
"MIT"
] | null | null | null | convolution/src/mask.cpp | fpeterek/dzo | d046a3c53bc66ee4fa7897394422570c1ef8f07a | [
"MIT"
] | null | null | null | convolution/src/mask.cpp | fpeterek/dzo | d046a3c53bc66ee4fa7897394422570c1ef8f07a | [
"MIT"
] | null | null | null | //
// Created by fpeterek on 08.10.21.
//
#include "mask.hpp"
#include <fstream>
#include <sstream>
#include <iostream>
static std::vector<float> tokenize(const std::string & str) {
std::vector<float> vec;
std::stringstream ss(str);
while (ss) {
float f;
ss >> f;
vec.emplace_back(f);
ss.ignore(1);
}
return vec;
}
static float sum(const std::vector<std::vector<float>> & mask) {
float sum = 0.0;
for (const auto & vec : mask) {
for (const float coeff : vec) {
sum += std::abs(coeff);
}
}
return sum;
}
static auto normalize(const std::vector<std::vector<float>> & mask) {
const float total = sum(mask);
std::vector<std::vector<float>> copy = mask;
if (total == 0) {
return copy;
}
for (size_t y = 0; y < mask.size(); ++y) {
for (size_t x = 0; x < mask.front().size(); ++x) {
copy[y][x] /= total;
}
}
return copy;
}
static std::string getMaskName(const std::string & filename) {
const auto period = filename.find_last_of('.');
const auto fslash = filename.find_last_of('/');
const auto len = period - fslash;
return filename.substr(fslash, len);
}
Mask Mask::loadFromFile(const std::string & filename) {
std::ifstream in(filename);
const auto maskname = getMaskName(filename);
std::vector<std::vector<float>> result;
while (in) {
std::string line;
std::getline(in, line);
if (not line.empty()) {
result.emplace_back(tokenize(line));
}
}
return { normalize(result), maskname };
}
Mask::Mask(std::vector<std::vector<float>> mask, std::string name) : mask(std::move(mask)), _name(std::move(name)) { }
size_t Mask::width() const {
return mask.empty() ? 0 : mask.front().size();
}
size_t Mask::height() const {
return mask.size();
}
size_t Mask::leftOffset() const {
return width() / 2;
}
size_t Mask::topOffset() const {
return height() / 2;
}
float Mask::at(size_t y, size_t x) const {
return mask[y][x];
}
float Mask::operator[](std::pair<size_t, size_t> idx) const {
const auto [y, x] = idx;
return at(y, x);
}
Mask::Mask(Mask && other) noexcept : mask(std::move(other.mask)), _name(std::move(other._name)) { }
Mask & Mask::operator=(Mask && other) noexcept {
mask = std::move(other.mask);
_name = std::move(other._name);
return *this;
}
const std::string & Mask::name() const {
return _name;
}
| 20.941667 | 118 | 0.584162 | [
"vector"
] |
2287379c552573eadc9bd9bc796b4c792fa21db9 | 19,025 | cpp | C++ | src/talos-control-manager.cpp | olivier-stasse/sot-talos-balance | 8749650fc5f512a04c349f447a0cfb0d9e0e1e05 | [
"BSD-2-Clause"
] | null | null | null | src/talos-control-manager.cpp | olivier-stasse/sot-talos-balance | 8749650fc5f512a04c349f447a0cfb0d9e0e1e05 | [
"BSD-2-Clause"
] | null | null | null | src/talos-control-manager.cpp | olivier-stasse/sot-talos-balance | 8749650fc5f512a04c349f447a0cfb0d9e0e1e05 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2014, Andrea Del Prete, LAAS-CNRS
*
* This file is part of sot-torque-control.
* sot-torque-control is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* sot-torque-control 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 sot-torque-control. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sot/talos_balance/talos-control-manager.hh>
#include <sot/core/debug.hh>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/all-commands.h>
#include <sot/core/stop-watch.hh>
#include <sot/talos_balance/utils/statistics.hh>
using namespace sot::talos_balance;
namespace dynamicgraph
{
namespace sot
{
namespace talos_balance
{
namespace dynamicgraph = ::dynamicgraph;
using namespace dynamicgraph;
using namespace dynamicgraph::command;
using namespace std;
using namespace dg::sot::talos_balance;
//Size to be aligned "-------------------------------------------------------"
#define PROFILE_PWM_DESIRED_COMPUTATION "Control manager "
#define PROFILE_DYNAMIC_GRAPH_PERIOD "Control period "
#define INPUT_SIGNALS m_u_maxSIN
#define OUTPUT_SIGNALS m_uSOUT << m_u_safeSOUT
/// Define EntityClassName here rather than in the header file
/// so that it can be used by the macros DEFINE_SIGNAL_**_FUNCTION.
typedef TalosControlManager EntityClassName;
/* --- DG FACTORY ---------------------------------------------------- */
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(TalosControlManager,
"TalosControlManager");
/* ------------------------------------------------------------------- */
/* --- CONSTRUCTION -------------------------------------------------- */
/* ------------------------------------------------------------------- */
TalosControlManager::
TalosControlManager(const std::string& name)
: Entity(name)
,CONSTRUCT_SIGNAL_IN(u_max, dynamicgraph::Vector)
,CONSTRUCT_SIGNAL_OUT(u, dynamicgraph::Vector, m_u_maxSIN)
,CONSTRUCT_SIGNAL_OUT(u_safe, dynamicgraph::Vector, m_uSOUT << m_u_maxSIN)
,m_robot_util(RefVoidRobotUtil())
,m_initSucceeded(false)
,m_emergency_stop_triggered(false)
,m_is_first_iter(true)
,m_iter(0)
,m_sleep_time(0.0)
{
Entity::signalRegistration( INPUT_SIGNALS << OUTPUT_SIGNALS);
/* Commands. */
addCommand("init",
makeCommandVoid2(*this, &TalosControlManager::init,
docCommandVoid2("Initialize the entity.",
"Time period in seconds (double)",
"Robot reference (string)")));
addCommand("addCtrlMode",
makeCommandVoid1(*this, &TalosControlManager::addCtrlMode,
docCommandVoid1("Create an input signal with name 'ctrl_x' where x is the specified name.",
"Name (string)")));
addCommand("ctrlModes",
makeCommandVoid0(*this, &TalosControlManager::ctrlModes,
docCommandVoid0("Get a list of all the available control modes.")));
addCommand("setCtrlMode",
makeCommandVoid2(*this, &TalosControlManager::setCtrlMode,
docCommandVoid2("Set the control mode for a joint.",
"(string) joint name",
"(string) control mode")));
addCommand("getCtrlMode",
makeCommandVoid1(*this, &TalosControlManager::getCtrlMode,
docCommandVoid1("Get the control mode of a joint.",
"(string) joint name")));
addCommand("resetProfiler",
makeCommandVoid0(*this, &TalosControlManager::resetProfiler,
docCommandVoid0("Reset the statistics computed by the profiler (print this entity to see them).")));
addCommand("addEmergencyStopSIN",
makeCommandVoid1(*this, &TalosControlManager::addEmergencyStopSIN,
docCommandVoid1("Add emergency signal input from another entity that can stop the control if necessary.",
"(string) signal name : 'emergencyStop_' + name")));
addCommand("isEmergencyStopTriggered", makeDirectGetter(*this,&m_emergency_stop_triggered, docDirectGetter("Check whether emergency stop is triggered","bool")));
}
void TalosControlManager::init(const double & dt,
const std::string &robotRef)
{
if(dt<=0.0)
return SEND_MSG("Timestep must be positive", MSG_TYPE_ERROR);
m_dt = dt;
m_emergency_stop_triggered = false;
m_initSucceeded = true;
vector<string> package_dirs;
std::string localName(robotRef);
if (!isNameInRobotUtil(localName))
{
SEND_MSG("You should have a robotUtil pointer initialized before",MSG_TYPE_ERROR);
}
else
{
m_robot_util = getRobotUtil(localName);
}
m_numDofs = m_robot_util->m_nbJoints + 6;
//TalosControlManager::setLoggerVerbosityLevel((dynamicgraph::LoggerVerbosity) 4);
m_jointCtrlModes_current.resize(m_numDofs);
m_jointCtrlModes_previous.resize(m_numDofs);
m_jointCtrlModesCountDown.resize(m_numDofs,0);
}
/* ------------------------------------------------------------------- */
/* --- SIGNALS ------------------------------------------------------- */
/* ------------------------------------------------------------------- */
DEFINE_SIGNAL_OUT_FUNCTION(u,dynamicgraph::Vector)
{
if(!m_initSucceeded)
{
SEND_MSG("Cannot compute signal u before initialization!",MSG_TYPE_WARNING);
return s;
}
if(m_is_first_iter)
m_is_first_iter = false;
if(s.size()!=(Eigen::VectorXd::Index) m_numDofs)
s.resize(m_numDofs);
{
// trigger computation of all ctrl inputs
for(unsigned int i=0; i<m_ctrlInputsSIN.size(); i++)
(*m_ctrlInputsSIN[i])(iter);
int cm_id, cm_id_prev;
for(unsigned int i=0; i<m_numDofs; i++)
{
cm_id = m_jointCtrlModes_current[i].id;
if(cm_id<0)
{
SEND_MSG("You forgot to set the control mode of joint "+toString(i), MSG_TYPE_ERROR_STREAM);
continue;
}
const dynamicgraph::Vector& ctrl = (*m_ctrlInputsSIN[cm_id])(iter);
assert(ctrl.size()==m_numDofs);
if(m_jointCtrlModesCountDown[i]==0)
s(i) = ctrl(i);
else
{
cm_id_prev = m_jointCtrlModes_previous[i].id;
const dynamicgraph::Vector& ctrl_prev = (*m_ctrlInputsSIN[cm_id_prev])(iter);
assert(ctrl_prev.size()==m_numDofs);
double alpha = m_jointCtrlModesCountDown[i]/CTRL_MODE_TRANSITION_TIME_STEP;
// SEND_MSG("Joint "+toString(i)+" changing ctrl mode from "+toString(cm_id_prev)+
// " to "+toString(cm_id)+" alpha="+toString(alpha),MSG_TYPE_DEBUG);
s(i) = alpha*ctrl_prev(i) + (1-alpha)*ctrl(i);
m_jointCtrlModesCountDown[i]--;
if(m_jointCtrlModesCountDown[i]==0)
{
SEND_MSG("Joint "+toString(i)+" changed ctrl mode from "+toString(cm_id_prev)+
" to "+toString(cm_id),MSG_TYPE_INFO);
updateJointCtrlModesOutputSignal();
}
}
}
}
// usleep(1e6*m_sleep_time);
// if(m_sleep_time>=0.1)
// {
// for(unsigned int i=0; i<m_ctrlInputsSIN.size(); i++)
// {
// const dynamicgraph::Vector& ctrl = (*m_ctrlInputsSIN[i])(iter);
// SEND_MSG(toString(iter)+") tau =" +toString(ctrl,1,4," ")+m_ctrlModes[i], MSG_TYPE_ERROR);
// }
// }
return s;
}
DEFINE_SIGNAL_OUT_FUNCTION(u_safe,dynamicgraph::Vector)
{
if(!m_initSucceeded)
{
SEND_WARNING_STREAM_MSG("Cannot compute signal u_safe before initialization!");
return s;
}
if(s.size()!=(Eigen::VectorXd::Index) m_numDofs)
s.resize(m_numDofs);
const dynamicgraph::Vector& u = m_uSOUT(iter);
const dynamicgraph::Vector& ctrl_max = m_u_maxSIN(iter);
for(size_t i=0; i<m_emergencyStopVector.size(); i++)
{
if ((* m_emergencyStopVector[i]).isPlugged() && (* m_emergencyStopVector[i])(iter))
{
m_emergency_stop_triggered = true;
SEND_MSG("t = " + toString(iter) + ": Emergency Stop has been triggered by an external entity: " + (*m_emergencyStopVector[i]).getName(), MSG_TYPE_ERROR);
}
}
if(!m_emergency_stop_triggered)
{
for(unsigned int i=0; i<m_numDofs; i++)
{
if(fabs(u(i)) > ctrl_max(i))
{
m_emergency_stop_triggered = true;
SEND_MSG("t = " + toString(iter) + ": Joint " + toString(i) + " desired control is too large: "+ toString(u(i))+" > "+toString(ctrl_max(i)), MSG_TYPE_ERROR_STREAM);
break;
}
}
}
s = u;
if(m_emergency_stop_triggered)
s.setZero();
return s;
}
/* --- COMMANDS ---------------------------------------------------------- */
void TalosControlManager::addCtrlMode(const string& name)
{
// check there is no other control mode with the same name
for(unsigned int i=0;i<m_ctrlModes.size(); i++)
if(name==m_ctrlModes[i])
return SEND_MSG("It already exists a control mode with name "+name, MSG_TYPE_ERROR);
// create a new input signal to read the new control
m_ctrlInputsSIN.push_back(new SignalPtr<dynamicgraph::Vector, int>(NULL,
getClassName()+"("+getName()+")::input(dynamicgraph::Vector)::ctrl_"+name));
// create a new output signal to specify which joints are controlled with the new
// control mode
m_jointsCtrlModesSOUT.push_back(new Signal<dynamicgraph::Vector, int>(
getClassName()+"("+getName()+")::output(dynamicgraph::Vector)::joints_ctrl_mode_"+name));
// add the new control mode to the list of available control modes
m_ctrlModes.push_back(name);
// register the new signals and add the new signal dependecy
Eigen::VectorXd::Index i = m_ctrlModes.size()-1;
m_uSOUT.addDependency(*m_ctrlInputsSIN[i]);
m_u_safeSOUT.addDependency(*m_ctrlInputsSIN[i]);
Entity::signalRegistration(*m_ctrlInputsSIN[i]);
Entity::signalRegistration(*m_jointsCtrlModesSOUT[i]);
updateJointCtrlModesOutputSignal();
}
void TalosControlManager::ctrlModes()
{
SEND_MSG(toString(m_ctrlModes), MSG_TYPE_INFO);
}
void TalosControlManager::setCtrlMode(const string& jointName, const string& ctrlMode)
{
CtrlMode cm;
if(convertStringToCtrlMode(ctrlMode,cm)==false)
return;
if(jointName=="all")
{
for(unsigned int i=0; i<m_numDofs; i++)
setCtrlMode(i,cm);
}
else
{
// decompose strings like "rk-rhp-lhp-..."
std::stringstream ss(jointName);
std::string item;
std::list<int> jIdList;
unsigned int i;
while (std::getline(ss, item, '-'))
{
SEND_MSG("parsed joint : "+item, MSG_TYPE_INFO);
if(convertJointNameToJointId(item,i))
jIdList.push_back(i);
}
for (std::list<int>::iterator it=jIdList.begin(); it != jIdList.end(); ++it)
setCtrlMode(*it,cm);
}
updateJointCtrlModesOutputSignal();
}
void TalosControlManager::setCtrlMode(const int jid, const CtrlMode& cm)
{
if(m_jointCtrlModesCountDown[jid]!=0)
return SEND_MSG("Cannot change control mode of joint "+toString(jid)+
" because its previous ctrl mode transition has not terminated yet: "+
toString(m_jointCtrlModesCountDown[jid]), MSG_TYPE_ERROR);
if(cm.id==m_jointCtrlModes_current[jid].id)
return SEND_MSG("Cannot change control mode of joint "+toString(jid)+
" because it has already the specified ctrl mode", MSG_TYPE_ERROR);
if(m_jointCtrlModes_current[jid].id<0)
{
// first setting of the control mode
m_jointCtrlModes_previous[jid] = cm;
m_jointCtrlModes_current[jid] = cm;
}
else
{
m_jointCtrlModesCountDown[jid] = CTRL_MODE_TRANSITION_TIME_STEP;
m_jointCtrlModes_previous[jid] = m_jointCtrlModes_current[jid];
m_jointCtrlModes_current[jid] = cm;
}
}
void TalosControlManager::getCtrlMode(const std::string& jointName)
{
if(jointName=="all")
{
stringstream ss;
for(unsigned int i=0; i<m_numDofs; i++)
ss<<toString(i) <<" "<<m_jointCtrlModes_current[i]<<"; ";
SEND_MSG(ss.str(),MSG_TYPE_INFO);
return;
}
unsigned int i;
if(convertJointNameToJointId(jointName,i)==false)
return;
SEND_MSG("The control mode of joint "+jointName+" is "+m_jointCtrlModes_current[i].name,MSG_TYPE_INFO);
}
void TalosControlManager::resetProfiler()
{
getProfiler().reset_all();
getStatistics().reset_all();
}
// void TalosControlManager::setStreamPrintPeriod(const double & s)
// {
// getLogger().setStreamPrintPeriod(s);
// }
void TalosControlManager::setSleepTime(const double &seconds)
{
if(seconds<0.0)
return SEND_MSG("Sleep time cannot be negative!", MSG_TYPE_ERROR);
m_sleep_time = seconds;
}
void TalosControlManager::addEmergencyStopSIN(const string& name)
{
SEND_MSG("New emergency signal input emergencyStop_" + name + " created",MSG_TYPE_INFO);
// create a new input signal
m_emergencyStopVector.push_back(new SignalPtr<bool, int>(NULL, getClassName()+"("+getName()+")::input(bool)::emergencyStop_"+name));
// register the new signals and add the new signal dependecy
Eigen::Index i = m_emergencyStopVector.size()-1;
m_u_safeSOUT.addDependency(* m_emergencyStopVector[i]);
Entity::signalRegistration(* m_emergencyStopVector[i]);
}
/* --- PROTECTED MEMBER METHODS ---------------------------------------------------------- */
void TalosControlManager::updateJointCtrlModesOutputSignal()
{
if (m_numDofs==0)
{
SEND_MSG("You should call init first. The size of the vector is unknown.", MSG_TYPE_ERROR);
return;
}
dynamicgraph::Vector cm(m_numDofs);
for(unsigned int i=0; i<m_jointsCtrlModesSOUT.size(); i++)
{
for(unsigned int j=0; j<m_numDofs; j++)
{
cm(j) = 0;
if((unsigned int)m_jointCtrlModes_current[j].id == i)
cm(j) = 1;
// during the transition between two ctrl modes they both result active
if(m_jointCtrlModesCountDown[j]>0 && (unsigned int)m_jointCtrlModes_previous[j].id == i)
cm(j) = 1;
}
m_jointsCtrlModesSOUT[i]->setConstant(cm);
}
}
bool TalosControlManager::convertStringToCtrlMode(const std::string& name, CtrlMode& cm)
{
// Check if the ctrl mode name exists
for(unsigned int i=0;i<m_ctrlModes.size(); i++)
if(name==m_ctrlModes[i])
{
cm = CtrlMode(i,name);
return true;
}
SEND_MSG("The specified control mode does not exist", MSG_TYPE_ERROR);
SEND_MSG("Possible control modes are: "+toString(m_ctrlModes), MSG_TYPE_INFO);
return false;
}
bool TalosControlManager::convertJointNameToJointId(const std::string& name, unsigned int& id)
{
// Check if the joint name exists
int jid = int(m_robot_util->get_id_from_name(name)); // cast needed due to bug in robot-utils
jid += 6; // Take into account the FF
if (jid<0)
{
SEND_MSG("The specified joint name does not exist: "+name, MSG_TYPE_ERROR);
std::stringstream ss;
for(size_t it=0; it<m_numDofs; it++)
ss<< toString(it) <<", ";
SEND_MSG("Possible joint names are: "+ss.str(), MSG_TYPE_INFO);
return false;
}
id = (unsigned int )jid;
return true;
}
/*
bool TalosControlManager::isJointInRange(unsigned int id, double q)
{
const JointLimits & JL = m_robot_util->get_joint_limits_from_id((Index)id);
double jl= JL.lower;
if(q<jl)
{
SEND_MSG("Desired joint angle "+toString(q)+" is smaller than lower limit: "+toString(jl),MSG_TYPE_ERROR);
return false;
}
double ju = JL.upper;
if(q>ju)
{
SEND_MSG("Desired joint angle "+toString(q)+" is larger than upper limit: "+toString(ju),MSG_TYPE_ERROR);
return false;
}
return true;
}
*/
/* ------------------------------------------------------------------- */
/* --- ENTITY -------------------------------------------------------- */
/* ------------------------------------------------------------------- */
void TalosControlManager::display(std::ostream& os) const
{
os << "TalosControlManager "<<getName();
try
{
getProfiler().report_all(3, os);
}
catch (ExceptionSignal e) {}
}
} // namespace talos_balance
} // namespace sot
} // namespace dynamicgraph
| 38.512146 | 178 | 0.554008 | [
"vector"
] |
228d39d0bef9ffb39a109cc9691c227c21df3ec1 | 3,949 | hpp | C++ | include/snd/storage/circular_buffer.hpp | colugomusic/snd | 3ecb87581870b14e62893610d027516aea48ff3c | [
"MIT"
] | 18 | 2020-08-26T11:33:50.000Z | 2021-04-13T15:57:28.000Z | include/snd/storage/circular_buffer.hpp | colugomusic/snd | 3ecb87581870b14e62893610d027516aea48ff3c | [
"MIT"
] | 1 | 2021-05-16T17:11:57.000Z | 2021-05-16T17:25:17.000Z | include/snd/storage/circular_buffer.hpp | colugomusic/snd | 3ecb87581870b14e62893610d027516aea48ff3c | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <array>
#include <vector>
namespace snd {
namespace storage {
template <class T, class Allocator = std::allocator<T>>
class CircularBuffer
{
public:
using Data = std::vector<T, Allocator>;
template <bool Const = false>
class iterator
{
public:
using self_type = iterator;
using value_type = T;
using data_type = typename std::conditional_t<Const, const Data*, Data*>;
using reference = typename std::conditional_t<Const, T const&, T&>;
using pointer = typename std::conditional_t<Const, T const*, T*>;
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::int32_t;
iterator(data_type data, typename Data::size_type pos) : data_(data), pos_(difference_type(pos)) {}
self_type operator++()
{
pos_++;
if (pos_ >= data_->size()) pos_ -= difference_type(data_->size());
return *this;
}
self_type operator++(int)
{
self_type result(*this);
++(*this);
return result;
}
self_type operator--()
{
pos_--;
if (pos_ < 0) pos_ += difference_type(data_->size());
return *this;
}
self_type operator--(int)
{
self_type result(*this);
--(*this);
return result;
}
self_type operator+(difference_type n)
{
return self_type(data_, (pos_ + n) % data_->size());
}
self_type operator-(difference_type n)
{
const auto new_pos = (pos_ - n) % data_->size();
if (new_pos < 0) new_pos += difference_type(data_->size());
return self_type(data_, new_pos);
}
reference operator*() const
{
return data_->at(pos_);
}
pointer operator->() const
{
return &(data_->at(pos_));
}
template<bool _Const = Const>
std::enable_if_t<!_Const, reference> operator*()
{
return data_->at(pos_);
}
template<bool _Const = Const>
std::enable_if_t<!_Const, pointer> operator->()
{
return &(data_->at(pos_));
}
bool operator==(const self_type& rhs)
{
return data_ == rhs.data_ && pos_ == rhs.pos_;
}
bool operator!=(const self_type& rhs)
{
return data_ != rhs.data_ || pos_ != rhs.pos_;
}
private:
data_type data_ = nullptr;
difference_type pos_ = 0;
};
CircularBuffer() = default;
CircularBuffer(typename Data::size_type size)
: data_(size)
{
}
void resize(typename Data::size_type size)
{
data_.resize(size);
}
void fill(T value)
{
std::fill(data_.begin(), data_.end(), value);
}
typename Data::size_type size() const { return data_.size(); }
T& operator[](typename Data::size_type idx) { return data_[idx % data_.size()]; }
const T& at(typename Data::size_type idx) const { return data_.at(idx % data_.size()); }
auto begin() { return iterator<false>(&data_, 0); }
auto end() { return iterator<false>(&data_, 0); }
auto begin() const { return iterator<true>(&data_, 0); }
auto end() const { return iterator<true>(&data_, 0); }
private:
Data data_;
};
template <class T, size_t ROWS, class Allocator = std::allocator<T>>
class CircularBufferArray
{
using Buffers = std::array<CircularBuffer<T, Allocator>, ROWS>;
Buffers buffers_;
public:
CircularBufferArray() = default;
CircularBufferArray(typename CircularBuffer<T>::Data::size_type size)
{
resize(size);
}
void resize(typename CircularBuffer<T>::Data::size_type size)
{
for (auto& buffer : buffers_)
{
buffer.resize(size);
}
}
void fill(T value)
{
for (auto& buffer : buffers_)
{
buffer.fill(value);
}
}
typename Buffers::size_type size() const { return buffers_[0].size(); }
CircularBuffer<T, Allocator>& operator[](typename Buffers::size_type idx)
{
return buffers_[idx];
}
const CircularBuffer<T, Allocator>& operator[](typename Buffers::size_type idx) const
{
return buffers_.at(idx);
}
template <int Row, class InputIt>
bool write(InputIt first, InputIt last, typename CircularBuffer<T>::Data::size_type pos)
{
return buffers_[Row].write(first, last, pos);
}
};
}}
| 19.263415 | 101 | 0.660927 | [
"vector"
] |
229bd7bab4e4de4a22b406b6ddda4126db4ce886 | 5,283 | cxx | C++ | libs/capture/details/capture_device_impl.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | libs/capture/details/capture_device_impl.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | libs/capture/details/capture_device_impl.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | #include "capture_device_impl.h"
namespace capture {
/// attach instance to device based on serial
capture_device_impl::~capture_device_impl()
{
}
/// return whether device object is attached to a device
bool capture_device_impl::is_attached() const
{
return false;
}
/// set the pan value of a device that supports pan and return whether this was possible
CaptureResult capture_device_impl::set_pan(float angle_in_degrees) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_tilt(float angle_in_degrees) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_roll(float angle_in_degrees) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_zoom(float factor) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_near_field_mode(bool on) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_auto_exposure(bool on) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_auto_white_balance(bool on) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_backlight_compensation(bool on) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_live_view(bool on) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_ae_mode_index(int index) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_focus_mode_index(int index) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_focus(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_aperture(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_exposure(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_gain(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_white_balance(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_power_line_frequency_index(int index) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_brightness(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_contrast(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_hue(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_sharpness(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_gamma(float value) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_quality_index(int index) { return CR_PROPERTY_UNSUPPORTED; }
CaptureResult capture_device_impl::set_color_image_format(const image_format& format) { return CR_FAILURE; }
CaptureResult capture_device_impl::set_color_stream_format(const image_stream_format& format) { return CR_FAILURE; }
CaptureResult capture_device_impl::set_depth_image_format(const image_format& format) { return CR_FAILURE; }
CaptureResult capture_device_impl::set_depth_stream_format(const image_stream_format& format) { return CR_FAILURE; }
CaptureResult capture_device_impl::set_infrared_image_format(const image_format& format) { return CR_FAILURE; }
CaptureResult capture_device_impl::set_infrared_stream_format(const image_stream_format& format) { return CR_FAILURE; }
/// Retrieve the next acceleration measurement. If no measurement is available wait up to time_out milliseconds. Return whether a measurement has been retrieved.
CaptureResult capture_device_impl::measure_acceleration(accelerometer_measurement& m, unsigned time_out) { return CR_FAILURE; }
/// prepare streaming of the specified input streams but do not yet start streaming, remember the capture processor
CaptureResult capture_device_impl::prepare_streaming(InputStreams input_streams, capture_processor* cp) { return CR_FAILURE; }
/// trigger a previously prepared streaming
CaptureResult capture_device_impl::trigger_streaming() { return CR_FAILURE; }
/// start streaming of the specified input streams. For each frame call the process_frame method of the passed capture processor.
CaptureResult capture_device_impl::start_streaming(InputStreams input_streams, capture_processor* cp) { return CR_FAILURE; }
/// stop streaming
CaptureResult capture_device_impl::stop_streaming() { return CR_FAILURE; }
/// prepare shooting a single image, adjust automatic properties like focus or white balance
CaptureResult capture_device_impl::prepare_shooting(InputStreams input_streams, capture_processor* cp) { return CR_FAILURE; }
/// trigger a previously prepared shooting
CaptureResult capture_device_impl::trigger_shooting() { return CR_FAILURE; }
/// prepare and shoot a single frame and call the process_frame method of the capture processor as soon as frame is available
CaptureResult capture_device_impl::shoot_image(InputStreams input_streams, capture_processor* cp) { return CR_FAILURE; }
/// prepare and shoot a sequence of nr_frames frames and call the process_frame method of the capture processor once for each captured frame
CaptureResult capture_device_impl::shoot_image_sequence(InputStreams input_streams, unsigned nr_frames, capture_processor* fp) { return CR_FAILURE; }
}
| 70.44 | 162 | 0.831535 | [
"object"
] |
229fa6392042116e984045056745b6cc6f98a37e | 906 | cc | C++ | cs247/gtkmm-examples/MVC/main.cc | shalecraig/Notes | 624378484a066504c55addffa4a27bd8f5e5d13b | [
"MIT"
] | 14 | 2015-01-16T18:31:43.000Z | 2020-05-10T03:11:28.000Z | cs247/gtkmm-examples/MVC/main.cc | shalecraig/Notes | 624378484a066504c55addffa4a27bd8f5e5d13b | [
"MIT"
] | null | null | null | cs247/gtkmm-examples/MVC/main.cc | shalecraig/Notes | 624378484a066504c55addffa4a27bd8f5e5d13b | [
"MIT"
] | 7 | 2015-04-01T22:53:25.000Z | 2021-03-20T00:23:09.000Z | /*
* MVC example of GTKmm program
*
* Displays top card of sorted deck of cards. When "next" button is clicked,
* the next card is displayed on top of deck. When the "reset" button is
* clicked, the top card of a full sorted deck is displayed
*
* Created by Jo Atlee on 06/07/09.
* Copyright 2009 UW. All rights reserved.
*
*/
#include <gtkmm/main.h>
#include "model.h"
#include "controller.h"
#include "view.h"
int main( int argc, char * argv[] ) {
Gtk::Main kit( argc, argv ); // Initialize gtkmm with the command line arguments, as appropriate.
Model model; // Create model
Controller controller( &model ); // Create controller
View view( &controller, &model ); // Create the view -- is passed handle to controller and model
Gtk::Main::run( view ); // Show the window and return when it is closed.
return 0;
} // main
| 32.357143 | 107 | 0.643488 | [
"model"
] |
22a4ec0a3e010b341725649ba257fa75147b2c3a | 9,075 | cpp | C++ | src/IECore/ModelCache.cpp | gcodebackups/cortex-vfx | 72fa6c6eb3327fce4faf01361c8fcc2e1e892672 | [
"BSD-3-Clause"
] | 5 | 2016-07-26T06:09:28.000Z | 2022-03-07T03:58:51.000Z | src/IECore/ModelCache.cpp | turbosun/cortex | 4bdc01a692652cd562f3bfa85f3dae99d07c0b15 | [
"BSD-3-Clause"
] | null | null | null | src/IECore/ModelCache.cpp | turbosun/cortex | 4bdc01a692652cd562f3bfa85f3dae99d07c0b15 | [
"BSD-3-Clause"
] | 3 | 2015-03-25T18:45:24.000Z | 2020-02-15T15:37:18.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2013, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "OpenEXR/ImathBoxAlgo.h"
#include "IECore/ModelCache.h"
#include "IECore/FileIndexedIO.h"
#include "IECore/HeaderGenerator.h"
#include "IECore/VisibleRenderable.h"
using namespace IECore;
using namespace Imath;
//////////////////////////////////////////////////////////////////////////
// Implementation
//////////////////////////////////////////////////////////////////////////
// Register FileIndexedIO as the handler for .mdc files so that people
// can use the filename constructor as a convenience over the IndexedIO
// constructor.
static IndexedIO::Description<FileIndexedIO> extensionDescription( ".mdc" );
static InternedString headerEntry("header");
static InternedString rootEntry("root");
static InternedString boundEntry("bound");
static InternedString transformEntry("transform");
static InternedString objectEntry("object");
static InternedString childrenEntry("children");
class ModelCache::Implementation : public RefCounted
{
public :
Implementation( IndexedIOPtr indexedIO )
: m_indexedIO( indexedIO ), m_path( "/" ), m_explicitBound( false )
{
if( m_indexedIO->openMode() & IndexedIO::Append )
{
throw InvalidArgumentException( "Append mode not supported" );
}
if( m_indexedIO->openMode() & IndexedIO::Write )
{
ObjectPtr header = HeaderGenerator::header();
header->save( m_indexedIO, headerEntry );
m_indexedIO->subdirectory( rootEntry, IndexedIO::CreateIfMissing )->removeAll();
}
m_indexedIO = m_indexedIO->subdirectory( rootEntry );
}
virtual ~Implementation()
{
// write out the bound if necessary.
if( m_indexedIO->openMode() & ( IndexedIO::Write | IndexedIO::Append ) )
{
m_indexedIO->write( boundEntry, m_bound.min.getValue(), 6 );
// propagate the bound to our parent.
if( m_parent && !m_parent->m_explicitBound )
{
Box3d transformedBound = transform( m_bound, m_transform );
m_parent->m_bound.extendBy( transformedBound );
}
}
}
const std::string &path() const
{
return m_path;
}
const std::string &name() const
{
return m_indexedIO->currentEntryId();
}
Imath::Box3d readBound() const
{
Box3d result;
double *resultAddress = result.min.getValue();
m_indexedIO->read( boundEntry, resultAddress, 6 );
return result;
}
void writeBound( const Imath::Box3d &bound )
{
m_bound = bound;
m_explicitBound = true;
}
Imath::M44d readTransform() const
{
M44d result;
if ( m_indexedIO->hasEntry( transformEntry ) )
{
double *resultAddress = result.getValue();
m_indexedIO->read( transformEntry, resultAddress, 16 );
}
return result;
}
void writeTransform( const Imath::M44d &transform )
{
m_transform = transform;
if( transform != M44d() )
{
m_indexedIO->write( transformEntry, transform.getValue(), 16 );
}
}
ObjectPtr readObject() const
{
return ( hasObject() ) ? Object::load( m_indexedIO, objectEntry ) : 0;
}
void writeObject( const IECore::Object *object )
{
object->save( m_indexedIO, objectEntry );
const VisibleRenderable *renderable = runTimeCast<const VisibleRenderable>( object );
if( renderable && !m_explicitBound )
{
Box3f bf = renderable->bound();
Box3d bd(
V3d( bf.min.x, bf.min.y, bf.min.z ),
V3f( bf.max.x, bf.max.y, bf.max.z )
);
m_bound.extendBy( bd );
}
}
bool hasObject() const
{
return m_indexedIO->hasEntry( objectEntry );
}
void childNames( IndexedIO::EntryIDList &childNames ) const
{
ConstIndexedIOPtr children = m_indexedIO->subdirectory( childrenEntry, IndexedIO::NullIfMissing );
if ( !children )
{
// it's ok for an entry to not have children
return;
}
children->entryIds( childNames, IndexedIO::Directory );
}
ModelCachePtr writableChild( const std::string &childName )
{
std::string childPath = m_path;
if( childPath != "/" )
{
childPath += "/";
}
childPath += childName;
IndexedIOPtr child = m_indexedIO->subdirectory( childrenEntry, IndexedIO::CreateIfMissing );
child = child->subdirectory( childName, IndexedIO::CreateIfMissing );
ModelCachePtr result = new ModelCache(
new Implementation(
child,
childPath,
this
)
);
return result;
}
ConstModelCachePtr readableChild( const std::string &childName ) const
{
std::string childPath = m_path;
if( childPath != "/" )
{
childPath += "/";
}
childPath += childName;
IndexedIOPtr child = m_indexedIO->subdirectory( childrenEntry );
child = child->subdirectory( childName );
ModelCachePtr result = new ModelCache(
new Implementation(
child,
childPath,
0 // read only so no need for parent for bounds propagation
)
);
return result;
}
private :
Implementation( IndexedIOPtr indexedIO, const std::string &path, ImplementationPtr parent )
: m_indexedIO( indexedIO ), m_path( path ), m_explicitBound( false ), m_parent( parent )
{
}
IndexedIOPtr m_indexedIO;
std::string m_path;
// accumulated into during writing, and written out in the destructor
Box3d m_bound;
bool m_explicitBound; // bound was specified by writeBound(), and overrides implicit bounds
M44d m_transform;
// stored during writing so we can propagate bounds
ImplementationPtr m_parent;
};
//////////////////////////////////////////////////////////////////////////
// ModelCache
//////////////////////////////////////////////////////////////////////////
ModelCache::ModelCache( const std::string &fileName, IndexedIO::OpenMode mode )
{
IndexedIOPtr indexedIO = IndexedIO::create( fileName, IndexedIO::rootPath, mode );
m_implementation = new Implementation( indexedIO );
}
ModelCache::ModelCache( IECore::IndexedIOPtr indexedIO )
{
m_implementation = new Implementation( indexedIO );
}
ModelCache::ModelCache( ImplementationPtr implementation )
: m_implementation( implementation )
{
}
ModelCache::~ModelCache()
{
}
const std::string &ModelCache::path() const
{
return m_implementation->path();
}
const std::string &ModelCache::name() const
{
return m_implementation->name();
}
Imath::Box3d ModelCache::readBound() const
{
return m_implementation->readBound();
}
void ModelCache::writeBound( const Imath::Box3d &bound )
{
m_implementation->writeBound( bound );
}
Imath::M44d ModelCache::readTransform() const
{
return m_implementation->readTransform();
}
void ModelCache::writeTransform( const Imath::M44d &transform )
{
m_implementation->writeTransform( transform );
}
ObjectPtr ModelCache::readObject() const
{
return m_implementation->readObject();
}
void ModelCache::writeObject( const IECore::Object *object )
{
m_implementation->writeObject( object );
}
bool ModelCache::hasObject() const
{
return m_implementation->hasObject();
}
void ModelCache::childNames( IndexedIO::EntryIDList &childNames ) const
{
m_implementation->childNames( childNames );
}
ModelCachePtr ModelCache::writableChild( const IndexedIO::EntryID &childName )
{
return m_implementation->writableChild( childName );
}
ConstModelCachePtr ModelCache::readableChild( const IndexedIO::EntryID &childName ) const
{
return m_implementation->readableChild( childName );
}
| 28.009259 | 101 | 0.673168 | [
"object",
"transform"
] |
22b3bfaed144d9eadd7e8f5e0add16133fe33624 | 3,047 | cpp | C++ | src/metadata/MetaStruct.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | 11 | 2020-10-13T11:50:29.000Z | 2022-02-27T11:47:34.000Z | src/metadata/MetaStruct.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | 15 | 2020-10-07T18:01:27.000Z | 2021-07-08T09:09:13.000Z | src/metadata/MetaStruct.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | 2 | 2020-10-07T21:29:06.000Z | 2020-10-14T18:02:17.000Z | //MIT License
//Copyright (c) 2020 bexoft GmbH (mail@bexoft.de)
//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 "finalmq/metadata/MetaStruct.h"
namespace finalmq {
MetaStruct::MetaStruct()
{
}
MetaStruct::MetaStruct(const std::string& typeName, const std::string& description, const std::vector<MetaField>& fields)
: m_typeName(typeName)
, m_description(description)
{
for (size_t i = 0 ; i < fields.size(); ++i)
{
addField(fields[i]);
}
}
MetaStruct::MetaStruct(const std::string& typeName, const std::string& description, std::vector<MetaField>&& fields)
: m_typeName(typeName)
, m_description(description)
{
for (size_t i = 0 ; i < fields.size(); ++i)
{
addField(std::move(fields[i]));
}
}
void MetaStruct::setTypeName(const std::string& typeName)
{
m_typeName = typeName;
}
const std::string& MetaStruct::getTypeName() const
{
return m_typeName;
}
void MetaStruct::setDescription(const std::string& description)
{
m_description = description;
}
const std::string& MetaStruct::getDescription() const
{
return m_description;
}
const MetaField* MetaStruct::getFieldByIndex(ssize_t index) const
{
if (index >= 0 && index < static_cast<int>(m_fields.size()))
{
return m_fields[index].get();
}
return nullptr;
}
const MetaField* MetaStruct::getFieldByName(const std::string& name) const
{
auto it = m_name2Field.find(name);
if (it != m_name2Field.end())
{
return it->second.get();
}
return nullptr;
}
void MetaStruct::addField(const MetaField& field)
{
addField(MetaField(field));
}
void MetaStruct::addField(MetaField&& field)
{
if (m_name2Field.find(field.name) != m_name2Field.end())
{
// field already added
return;
}
field.index = static_cast<int>(m_fields.size());
std::shared_ptr<MetaField> f = std::make_shared<MetaField>(std::move(field));
m_fields.emplace_back(f);
m_name2Field.emplace(f->name, f);
}
} // namespace finalmq
| 25.391667 | 121 | 0.702658 | [
"vector"
] |
22b63b244c62c7f8a5662ed758af0c6ac92830ea | 35,607 | cpp | C++ | src/game/gamesys/SysCvar.cpp | AMS21/PreyRun | 3efc9d70228bcfb8bc18f6ff23a05c8be1e45101 | [
"MIT"
] | 2 | 2018-08-30T23:48:22.000Z | 2021-04-07T19:16:18.000Z | src/game/gamesys/SysCvar.cpp | AMS21/PreyRun | 3efc9d70228bcfb8bc18f6ff23a05c8be1e45101 | [
"MIT"
] | null | null | null | src/game/gamesys/SysCvar.cpp | AMS21/PreyRun | 3efc9d70228bcfb8bc18f6ff23a05c8be1e45101 | [
"MIT"
] | null | null | null | // Copyright (C) 2004 Id Software, Inc.
//
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
#include "../../framework/BuildVersion.h" // HUMANHEAD mdl
/*
All game cvars should be defined here.
*/
#ifdef HUMANHEAD // HUMANHEAD
idCVar g_tips("g_tips", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "allow hud tips to display");
idCVar g_jawflap("g_jawflap", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "controls jawflapping");
idCVar g_wicked("g_wicked", "0", CVAR_GAME | CVAR_BOOL, "if wicked mode is active");
idCVar g_casino("g_casino", "0", CVAR_GAME | CVAR_BOOL, "if casino mode is active");
idCVar g_roadhouseCompleted("g_roadhouseCompleted", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "if roadhouse map has been completed once");
idCVar g_precache("com_precache", "1", CVAR_BOOL | CVAR_SYSTEM | CVAR_NOCHEAT, "if on, precaches needed resources"); // HUMANHEAD pdm: game side version
idCVar g_debugProjections("g_debugProjections", "0", CVAR_GAME | CVAR_BOOL, "Shows projection windings");
idCVar g_showProjectileLaunchPoint("g_showProjectileLaunchPoint", "0", CVAR_GAME | CVAR_BOOL, "Shows position of projectile origin");
idCVar p_tripwireDebug("p_tripwireDebug", "0", CVAR_GAME | CVAR_BOOL, "Show tripwire trace");
idCVar p_playerPhysicsDebug("p_playerPhysicsDebug", "0", CVAR_GAME | CVAR_INTEGER, "Show player physics gravity alignment info");
idCVar p_camRotRateScale("p_camRotRateScale", "1.3", CVAR_GAME | CVAR_FLOAT, "Used to scale delta time thats passed into camera interpolator");
idCVar p_camInterpDebug("p_camInterpDebug", "0", CVAR_GAME | CVAR_INTEGER, "1: Shows lerp info, 2: Shows slerp info");
idCVar p_iterRotMoveNumIterations("p_iterRotMoveNumIterations", "5", CVAR_GAME | CVAR_INTEGER, "Per frame, the number of attempts to align the players bbox if unaligned to gravity");
idCVar p_iterRotMoveTransDist("p_iterRotMoveTransDist", "20", CVAR_GAME | CVAR_FLOAT, "Distance to translate per player bbox alignment attempt");
idCVar p_disableCamInterp("p_disableCamInterp", "0", CVAR_GAME | CVAR_BOOL, "Disable camera interpolator");
idCVar p_mountedGunDebug("p_mountedGunDebug", "0", CVAR_GAME | CVAR_INTEGER, "Shows debug info for mountedgun");
idCVar g_mbNumBlurs("g_mbNumBlurs", "5", CVAR_GAME | CVAR_INTEGER, "Number of images used in motion blur effect");
idCVar g_mbFrameSpan("g_mbFrameSpan", "10", CVAR_GAME | CVAR_FLOAT, "Motion blur: time each image spans");
idCVar g_postEventsDebug("g_postEventsDebug", "0", CVAR_GAME | CVAR_BOOL, "for showing all posted events");
idCVar g_debugger("g_debugger", "0", CVAR_GAME | CVAR_INTEGER, "In-game debugger (1=on, 2=interactive)");
idCVar g_nodormant("g_nodormant", "0", CVAR_GAME | CVAR_BOOL, "Disallow any dormant logic");
idCVar g_robustDormantAll("g_robustDormantAll", "0", CVAR_GAME | CVAR_BOOL, "All dormant checks check all areas");
idCVar g_dormanttests("g_dormanttests", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar pm_wallwalkstepsize("pm_wallwalkstepsize", "8", CVAR_GAME | CVAR_FLOAT, "Step size while wallwalking");
idCVar g_vehicleDebug("g_vehicleDebug", "0", CVAR_GAME | CVAR_INTEGER, "print out vehicle physics debug info");
idCVar sys_SavedPosition("sys_savedPosition", "", CVAR_GAME | CVAR_ARCHIVE, "saved position used by getpos/putpos");
idCVar g_crosshair("g_crosshair", "1", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "Which crosshair to use (0=off)", 0, 8);
idCVar g_springConstant("g_springConstant", "200000", CVAR_GAME | CVAR_FLOAT, "Modify factor for bind controller tension");
idCVar ai_debugBrain("ai_debugBrain", "0", CVAR_GAME | CVAR_INTEGER, "");
idCVar ai_debugActions("ai_debugAction", "0", CVAR_GAME | CVAR_INTEGER, "");
idCVar ai_talonAttack("ai_talonAttack", "1", CVAR_GAME | CVAR_INTEGER, "Enable Talon's attacks");
idCVar ai_debugPath("ai_debugPath", "0", CVAR_GAME | CVAR_INTEGER, "Draw general-purpose pathfinding debug info");
idCVar ai_hideSkipThink("ai_hideSkipThink", "1", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "Hidden monsters don't think at all");
idCVar g_debugAFs("g_debugAFs", "0", CVAR_GAME | CVAR_INTEGER, "print out info on what the ragdolls are doing");
idCVar g_debugFX("g_debugFX", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_showDormant("g_showDormant", "0", CVAR_GAME | CVAR_BOOL, "1= Prints out msgs when an entity goes dormant");
idCVar ai_showNoAAS("ai_showNoAAS", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "1= Show when monsters do not have AAS available (shows a ?)");
idCVar ai_printSpeech("ai_printSpeech", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "1= Draw hunter speech sounds");
idCVar ai_skipSpeech("ai_skipSpeech", "0", CVAR_GAME | CVAR_BOOL, "1= Do not use the AI speech system");
idCVar ai_skipThink("ai_skipThink", "0", CVAR_GAME | CVAR_BOOL, "1= Do not execute hhAI::Think() fxn");
idCVar g_useDDA("g_useDDA", "1", CVAR_GAME | CVAR_BOOL, "Whether to use dda system");
idCVar g_debugMatter("g_debugmatter", "0", CVAR_GAME | CVAR_INTEGER, "turns on matter based debugging, 2=include wallwalk traces");
idCVar g_debugImpulse("g_debugimpulse", "0", CVAR_GAME | CVAR_BOOL, "turns on impulse debugging");
idCVar sys_forceCache("sys_forceCache", "0", CVAR_BOOL | CVAR_SYSTEM, "force resource caching even when developer is on"); //HUMANHEAD mdc - added for developer cache skipping
idCVar g_showGamePortals("g_showGamePortals", "0", CVAR_GAME | CVAR_INTEGER, "draw game portal connections");
idCVar g_showValidSoundAreas("g_showValidSoundAreas", "0", CVAR_GAME | CVAR_INTEGER, "draw valid sound areas");
idCVar g_testModelPitch("g_testModelPitch", "0", CVAR_GAME | CVAR_FLOAT, "pitch of angle of test model");
idCVar g_printDDA("g_printDDA", "0", CVAR_GAME | CVAR_BOOL, "Prints DDA information to the console");
#if GOLD
idCVar g_trackDDA("g_trackDDA", "0", CVAR_GAME | CVAR_BOOL, "Whether to track detailed statistics as the player goes through a level");
idCVar g_dumpDDA("g_dumpDDA", "0", CVAR_GAME | CVAR_BOOL, "Whether to automatically dump DDA tracking statistics on level change");
idCVar g_maxEntitiesWarning("g_maxEntitiesWarning", "0", CVAR_GAME | CVAR_INTEGER, "max number of entities before warning is displayed");
#else
idCVar g_trackDDA("g_trackDDA", "1", CVAR_GAME | CVAR_BOOL, "Whether to track detailed statistics as the player goes through a level");
idCVar g_dumpDDA("g_dumpDDA", "0", CVAR_GAME | CVAR_BOOL, "Whether to automatically dump DDA tracking statistics on level change");
idCVar g_maxEntitiesWarning("g_maxEntitiesWarning", "3596", CVAR_GAME | CVAR_INTEGER, "max number of entities before warning is displayed");
#endif
idCVar g_showEntityCount("g_showEntityCount", "0", CVAR_GAME | CVAR_BOOL, "1=show entity count");
idCVar g_expensiveMS("g_expensiveMS", "0.1", CVAR_GAME | CVAR_FLOAT, "ms of think to be considered expensive by debugger");
idCVar g_runMapCycle("g_runMapCycle", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "whether to run the map cycling script (g_mapcycle)");
idCVar g_forceSingleSmokeView("g_forceSingleSmokeView", "0", CVAR_GAME | CVAR_BOOL, "do not consider multiple views for smoke system");
#if GERMAN_VERSION
idCVar g_nogore("g_nogore", "1", CVAR_GAME | CVAR_BOOL | CVAR_ROM, "Disables gore");
#else
idCVar g_nogore("g_nogore", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "Disables gore");
#endif
#endif //HUMANHEAD END
//HUMANHEAD rww - only supported types
//const char *si_gameTypeArgs[] = { "singleplayer", "deathmatch", "Tourney", "Team DM", "Last Man", "cooperative", NULL };
const char *si_gameTypeArgs[] = { "singleplayer", "deathmatch", "Team DM", NULL };
//HUMANHEAD END
const char *si_readyArgs[] = { "Not Ready", "Ready", NULL };
const char *si_spectateArgs[] = { "Play", "Spectate", NULL };
// HUMANHEAD pdm: removed
//const char *ui_skinArgs[] = { "skins/characters/player/marine_mp", "skins/characters/player/marine_mp_red", "skins/characters/player/marine_mp_blue", "skins/characters/player/marine_mp_green", "skins/characters/player/marine_mp_yellow", NULL };
const char *ui_teamArgs[] = { "Red", "Blue", NULL };
struct gameVersion_s
{
gameVersion_s(void) { sprintf(string, "Prey-1.0.%d-%s/%s%s %s %s %s", BUILD_NUMBER, ENGINE_VERSION, PR_BUILD_CONFIGURATION, ID_VERSIONTAG, BUILD_STRING, PR_CMPL_DATE, PR_CMPL_TIME); }
char string[256];
} gameVersion;
idCVar g_version("g_version", gameVersion.string, CVAR_GAME | CVAR_ROM, "game version");
// noset vars
idCVar gamename("gamename", ENGINE_VERSION, CVAR_GAME | CVAR_SERVERINFO | CVAR_ROM, "");
idCVar gamedate("gamedate", PR_CMPL_DATE, CVAR_GAME | CVAR_ROM, "");
// server info
//HUMANHEAD rww - changed defaults for si_name, si_map, si_maxPlayers
idCVar si_name("si_name", "Preyrun Server", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "name of the server");
//HUMANHEAD rww - removed unsupported game types from description
idCVar si_gameType("si_gameType", si_gameTypeArgs[0], CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "game type - singleplayer, deathmatch, or Team DM", si_gameTypeArgs, idCmdSystem::ArgCompletion_String<si_gameTypeArgs>);
idCVar si_map("si_map", "dmshuttle2", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "map to be played next on server", idCmdSystem::ArgCompletion_MapName);
idCVar si_maxPlayers("si_maxPlayers", "8", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_INTEGER, "max number of players allowed on the server", 1, 8);
idCVar si_fragLimit("si_fragLimit", "10", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_INTEGER, "frag limit", 1, MP_PLAYER_MAXFRAGS);
idCVar si_timeLimit("si_timeLimit", "10", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_INTEGER, "time limit in minutes", 0, 60);
idCVar si_teamDamage("si_teamDamage", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL, "enable team damage");
idCVar si_warmup("si_warmup", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL, "do pre-game warmup");
idCVar si_usePass("si_usePass", "0", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL, "enable client password checking");
idCVar si_pure("si_pure", "1", CVAR_GAME | CVAR_SERVERINFO | CVAR_BOOL, "server is pure and does not allow modified data");
idCVar si_spectators("si_spectators", "1", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_BOOL, "allow spectators or require all clients to play");
idCVar si_serverURL("si_serverURL", "", CVAR_GAME | CVAR_SERVERINFO | CVAR_ARCHIVE, "where to reach the server admins and get information about the server");
// user info
// HUMANHEAD pdm - changed defaults for ui_name
idCVar ui_name("ui_name", "Tommy", CVAR_GAME | CVAR_USERINFO | CVAR_ARCHIVE, "player name");
// HUMANHEAD pdm: removed
//idCVar ui_skin( "ui_skin", ui_skinArgs[ 0 ], CVAR_GAME | CVAR_USERINFO | CVAR_ARCHIVE, "player skin", ui_skinArgs, idCmdSystem::ArgCompletion_String<ui_skinArgs> );
idCVar ui_team("ui_team", ui_teamArgs[0], CVAR_GAME | CVAR_USERINFO | CVAR_ARCHIVE, "player team", ui_teamArgs, idCmdSystem::ArgCompletion_String<ui_teamArgs>);
idCVar ui_autoSwitch("ui_autoSwitch", "1", CVAR_GAME | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "auto switch weapon");
idCVar ui_autoReload("ui_autoReload", "1", CVAR_GAME | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "auto reload weapon");
idCVar ui_showGun("ui_showGun", "1", CVAR_GAME | CVAR_USERINFO | CVAR_ARCHIVE | CVAR_BOOL, "show gun");
idCVar ui_ready("ui_ready", si_readyArgs[0], CVAR_GAME | CVAR_USERINFO, "player is ready to start playing", idCmdSystem::ArgCompletion_String<si_readyArgs>);
idCVar ui_spectate("ui_spectate", si_spectateArgs[0], CVAR_GAME | CVAR_USERINFO, "play or spectate", idCmdSystem::ArgCompletion_String<si_spectateArgs>);
idCVar ui_chat("ui_chat", "0", CVAR_GAME | CVAR_USERINFO | CVAR_BOOL | CVAR_ROM | CVAR_CHEAT, "player is chatting");
//HUMANHEAD rww
idCVar ui_modelNum("ui_modelNum", "0", CVAR_GAME | CVAR_USERINFO | CVAR_ARCHIVE, "player model");
//HUMANHEAD END
// change anytime vars
idCVar developer("developer", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar r_aspectRatio("r_aspectRatio", "0", CVAR_RENDERER | CVAR_INTEGER | CVAR_ARCHIVE, "aspect ratio of view:\n0 = 4:3\n1 = 16:9\n2 = 16:10", 0, 2);
idCVar g_cinematic("g_cinematic", "1", CVAR_GAME | CVAR_BOOL, "skips updating entities that aren't marked 'cinematic' '1' during cinematics");
idCVar g_cinematicMaxSkipTime("g_cinematicMaxSkipTime", "600", CVAR_GAME | CVAR_FLOAT, "# of seconds to allow game to run when skipping cinematic. prevents lock-up when cinematic doesn't end.", 0, 3600);
idCVar g_muzzleFlash("g_muzzleFlash", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "show muzzle flashes");
idCVar g_projectileLights("g_projectileLights", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "show dynamic lights on projectiles");
idCVar g_bloodEffects("g_bloodEffects", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "show blood splats, sprays and gibs");
idCVar g_doubleVision("g_doubleVision", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "show double vision when taking damage");
idCVar g_monsters("g_monsters", "1", CVAR_GAME | CVAR_BOOL, "");
idCVar g_decals("g_decals", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "show decals such as bullet holes");
idCVar g_knockback("g_knockback", "1000", CVAR_GAME | CVAR_INTEGER, "");
//idCVar g_skill( "g_skill", "1", CVAR_GAME | CVAR_INTEGER, "" ); // HUMANHEAD pdm: skill not used
idCVar g_nightmare("g_nightmare", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "if nightmare mode is allowed");
idCVar g_gravity("g_gravity", DEFAULT_GRAVITY_STRING, CVAR_GAME | CVAR_FLOAT, "");
idCVar g_skipFX("g_skipFX", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_skipParticles("g_skipParticles", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_ragdollDecals("g_ragdollDecals", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "ragdolls leave blood splats");
idCVar g_disasm("g_disasm", "0", CVAR_GAME | CVAR_BOOL, "disassemble script into base/script/disasm.txt on the local drive when script is compiled");
idCVar g_debugBounds("g_debugBounds", "0", CVAR_GAME | CVAR_BOOL, "checks for models with bounds > 2048");
idCVar g_debugAnim("g_debugAnim", "-1", CVAR_GAME | CVAR_INTEGER, "displays information on which animations are playing on the specified entity number. set to -1 to disable.");
idCVar g_debugMove("g_debugMove", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_debugDamage("g_debugDamage", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_debugWeapon("g_debugWeapon", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_debugScript("g_debugScript", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_debugMover("g_debugMover", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_debugTriggers("g_debugTriggers", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_debugCinematic("g_debugCinematic", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_stopTime("g_stopTime", "0", CVAR_GAME | CVAR_BOOL, "");
/* HUMANHEAD pdm: not used
idCVar g_damageScale( "g_damageScale", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE, "scale final damage on player by this factor" );
idCVar g_armorProtection( "g_armorProtection", "0.3", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE, "armor takes this percentage of damage" );
idCVar g_armorProtectionMP( "g_armorProtectionMP", "0.6", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE, "armor takes this percentage of damage in mp" );
idCVar g_useDynamicProtection( "g_useDynamicProtection", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE, "scale damage and armor dynamically to keep the player alive more often" );
idCVar g_healthTakeTime( "g_healthTakeTime", "5", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "how often to take health in nightmare mode" );
idCVar g_healthTakeAmt( "g_healthTakeAmt", "5", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "how much health to take in nightmare mode" );
idCVar g_healthTakeLimit( "g_healthTakeLimit", "25", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "how low can health get taken in nightmare mode" );
*/
idCVar g_showPVS("g_showPVS", "0", CVAR_GAME | CVAR_INTEGER, "", 0, 2);
idCVar g_showTargets("g_showTargets", "0", CVAR_GAME | CVAR_BOOL, "draws entities and thier targets. hidden entities are drawn grey.");
idCVar g_showTriggers("g_showTriggers", "0", CVAR_GAME | CVAR_BOOL, "draws trigger entities (orange) and thier targets (green). disabled triggers are drawn grey.");
idCVar g_showCollisionWorld("g_showCollisionWorld", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_showCollisionModels("g_showCollisionModels", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_showCollisionTraces("g_showCollisionTraces", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_maxShowDistance("g_maxShowDistance", "128", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_showEntityInfo("g_showEntityInfo", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_showviewpos("g_showviewpos", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_showcamerainfo("g_showcamerainfo", "0", CVAR_GAME | CVAR_ARCHIVE, "displays the current frame # for the camera when playing cinematics");
idCVar g_showTestModelFrame("g_showTestModelFrame", "0", CVAR_GAME | CVAR_BOOL, "displays the current animation and frame # for testmodels");
idCVar g_showActiveEntities("g_showActiveEntities", "0", CVAR_GAME | CVAR_BOOL, "draws boxes around thinking entities. dormant entities (outside of pvs) are drawn yellow. non-dormant are green.");
idCVar g_showEnemies("g_showEnemies", "0", CVAR_GAME | CVAR_BOOL, "draws boxes around monsters that have targeted the the player");
idCVar g_artificialPlayerCount("g_artificialPlayerCount", "0", CVAR_GAME | CVAR_INTEGER, "spawns artificial players"); //HUMANHEAD rww
idCVar g_frametime("g_frametime", "0", CVAR_GAME | CVAR_BOOL, "displays timing information for each game frame");
idCVar g_timeentities("g_timeEntities", "0", CVAR_GAME | CVAR_FLOAT, "when non-zero, shows entities whose think functions exceeded the # of milliseconds specified");
idCVar ai_debugScript("ai_debugScript", "-1", CVAR_GAME | CVAR_INTEGER, "displays script calls for the specified monster entity number");
idCVar ai_debugMove("ai_debugMove", "0", CVAR_GAME | CVAR_BOOL, "draws movement information for monsters");
idCVar ai_debugTrajectory("ai_debugTrajectory", "0", CVAR_GAME | CVAR_BOOL, "draws trajectory tests for monsters");
idCVar ai_testPredictPath("ai_testPredictPath", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar ai_showCombatNodes("ai_showCombatNodes", "0", CVAR_GAME | CVAR_BOOL, "draws attack cones for monsters");
idCVar ai_showPaths("ai_showPaths", "0", CVAR_GAME | CVAR_BOOL, "draws path_* entities");
idCVar ai_showObstacleAvoidance("ai_showObstacleAvoidance", "0", CVAR_GAME | CVAR_INTEGER, "draws obstacle avoidance information for monsters. if 2, draws obstacles for player, as well", 0, 2, idCmdSystem::ArgCompletion_Integer<0, 2>);
idCVar ai_blockedFailSafe("ai_blockedFailSafe", "1", CVAR_GAME | CVAR_BOOL, "enable blocked fail safe handling");
idCVar g_dvTime("g_dvTime", "1", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_dvAmplitude("g_dvAmplitude", "0.001", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_dvFrequency("g_dvFrequency", "0.5", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_kickTime("g_kickTime", "1", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_kickAmplitude("g_kickAmplitude", "0.0001", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_blobTime("g_blobTime", "1", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_blobSize("g_blobSize", "1", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_testHealthVision("g_testHealthVision", "0", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_editEntityMode("g_editEntityMode", "0", CVAR_GAME | CVAR_INTEGER, "0 = off\n"
"1 = lights\n"
"2 = sounds\n"
"3 = articulated figures\n"
"4 = particle systems\n"
"5 = monsters\n"
"6 = entity names\n"
"7 = entity models", 0, 7, idCmdSystem::ArgCompletion_Integer<0, 7>);
idCVar g_dragEntity("g_dragEntity", "0", CVAR_GAME | CVAR_BOOL, "allows dragging physics objects around by placing the crosshair over them and holding the fire button");
idCVar g_dragDamping("g_dragDamping", "0.5", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_dragShowSelection("g_dragShowSelection", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_dropItemRotation("g_dropItemRotation", "", CVAR_GAME, "");
idCVar g_vehicleVelocity("g_vehicleVelocity", "1000", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_vehicleForce("g_vehicleForce", "50000", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_vehicleSuspensionUp("g_vehicleSuspensionUp", "32", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_vehicleSuspensionDown("g_vehicleSuspensionDown", "20", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_vehicleSuspensionKCompress("g_vehicleSuspensionKCompress", "200", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_vehicleSuspensionDamping("g_vehicleSuspensionDamping", "400", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_vehicleTireFriction("g_vehicleTireFriction", "0.8", CVAR_GAME | CVAR_FLOAT, "");
idCVar ik_enable("ik_enable", "1", CVAR_GAME | CVAR_BOOL, "enable IK");
idCVar ik_debug("ik_debug", "0", CVAR_GAME | CVAR_BOOL, "show IK debug lines");
idCVar af_useLinearTime("af_useLinearTime", "1", CVAR_GAME | CVAR_BOOL, "use linear time algorithm for tree-like structures");
idCVar af_useImpulseFriction("af_useImpulseFriction", "0", CVAR_GAME | CVAR_BOOL, "use impulse based contact friction");
idCVar af_useJointImpulseFriction("af_useJointImpulseFriction", "0", CVAR_GAME | CVAR_BOOL, "use impulse based joint friction");
idCVar af_useSymmetry("af_useSymmetry", "1", CVAR_GAME | CVAR_BOOL, "use constraint matrix symmetry");
idCVar af_skipSelfCollision("af_skipSelfCollision", "0", CVAR_GAME | CVAR_BOOL, "skip self collision detection");
idCVar af_skipLimits("af_skipLimits", "0", CVAR_GAME | CVAR_BOOL, "skip joint limits");
idCVar af_skipFriction("af_skipFriction", "0", CVAR_GAME | CVAR_BOOL, "skip friction");
idCVar af_forceFriction("af_forceFriction", "-1", CVAR_GAME | CVAR_FLOAT, "force the given friction value");
idCVar af_maxLinearVelocity("af_maxLinearVelocity", "128", CVAR_GAME | CVAR_FLOAT, "maximum linear velocity");
idCVar af_maxAngularVelocity("af_maxAngularVelocity", "1.57", CVAR_GAME | CVAR_FLOAT, "maximum angular velocity");
idCVar af_timeScale("af_timeScale", "1", CVAR_GAME | CVAR_FLOAT, "scales the time");
idCVar af_jointFrictionScale("af_jointFrictionScale", "0", CVAR_GAME | CVAR_FLOAT, "scales the joint friction");
idCVar af_contactFrictionScale("af_contactFrictionScale", "0", CVAR_GAME | CVAR_FLOAT, "scales the contact friction");
idCVar af_highlightBody("af_highlightBody", "", CVAR_GAME, "name of the body to highlight");
idCVar af_highlightConstraint("af_highlightConstraint", "", CVAR_GAME, "name of the constraint to highlight");
idCVar af_showTimings("af_showTimings", "0", CVAR_GAME | CVAR_BOOL, "show articulated figure cpu usage");
idCVar af_showConstraints("af_showConstraints", "0", CVAR_GAME | CVAR_BOOL, "show constraints");
idCVar af_showConstraintNames("af_showConstraintNames", "0", CVAR_GAME | CVAR_BOOL, "show constraint names");
idCVar af_showConstrainedBodies("af_showConstrainedBodies", "0", CVAR_GAME | CVAR_BOOL, "show the two bodies contrained by the highlighted constraint");
idCVar af_showPrimaryOnly("af_showPrimaryOnly", "0", CVAR_GAME | CVAR_BOOL, "show primary constraints only");
idCVar af_showTrees("af_showTrees", "0", CVAR_GAME | CVAR_BOOL, "show tree-like structures");
idCVar af_showLimits("af_showLimits", "0", CVAR_GAME | CVAR_BOOL, "show joint limits");
idCVar af_showBodies("af_showBodies", "0", CVAR_GAME | CVAR_BOOL, "show bodies");
idCVar af_showBodyNames("af_showBodyNames", "0", CVAR_GAME | CVAR_BOOL, "show body names");
idCVar af_showMass("af_showMass", "0", CVAR_GAME | CVAR_BOOL, "show the mass of each body");
idCVar af_showTotalMass("af_showTotalMass", "0", CVAR_GAME | CVAR_BOOL, "show the total mass of each articulated figure");
idCVar af_showInertia("af_showInertia", "0", CVAR_GAME | CVAR_BOOL, "show the inertia tensor of each body");
idCVar af_showVelocity("af_showVelocity", "0", CVAR_GAME | CVAR_BOOL, "show the velocity of each body");
idCVar af_showActive("af_showActive", "0", CVAR_GAME | CVAR_BOOL, "show tree-like structures of articulated figures not at rest");
idCVar af_testSolid("af_testSolid", "1", CVAR_GAME | CVAR_BOOL, "test for bodies initially stuck in solid");
idCVar rb_showTimings("rb_showTimings", "0", CVAR_GAME | CVAR_BOOL, "show rigid body cpu usage");
idCVar rb_showBodies("rb_showBodies", "0", CVAR_GAME | CVAR_BOOL, "show rigid bodies");
idCVar rb_showMass("rb_showMass", "0", CVAR_GAME | CVAR_BOOL, "show the mass of each rigid body");
idCVar rb_showInertia("rb_showInertia", "0", CVAR_GAME | CVAR_BOOL, "show the inertia tensor of each rigid body");
idCVar rb_showVelocity("rb_showVelocity", "0", CVAR_GAME | CVAR_BOOL, "show the velocity of each rigid body");
idCVar rb_showActive("rb_showActive", "0", CVAR_GAME | CVAR_BOOL, "show rigid bodies that are not at rest");
// The default values for player movement cvars are set in def/player.def
idCVar pm_jumpheight("pm_jumpheight", "48", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "approximate hieght the player can jump");
idCVar pm_stepsize("pm_stepsize", "16", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "maximum height the player can step up without jumping");
idCVar pm_crouchspeed("pm_crouchspeed", "80", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while crouched");
idCVar pm_walkspeed("pm_walkspeed", "140", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while walking");
idCVar pm_runspeed("pm_runspeed", "220", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while running");
idCVar pm_noclipspeed("pm_noclipspeed", "200", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while in noclip");
idCVar pm_spectatespeed("pm_spectatespeed", "450", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "speed the player can move while spectating");
idCVar pm_spectatebbox("pm_spectatebbox", "32", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "size of the spectator bounding box");
idCVar pm_usecylinder("pm_usecylinder", "0", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_BOOL, "use a cylinder approximation instead of a bounding box for player collision detection");
idCVar pm_minviewpitch("pm_minviewpitch", "-89", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "amount player's view can look up (negative values are up)");
idCVar pm_maxviewpitch("pm_maxviewpitch", "89", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "amount player's view can look down");
idCVar pm_stamina("pm_stamina", "24", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "length of time player can run");
idCVar pm_staminathreshold("pm_staminathreshold", "45", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "when stamina drops below this value, player gradually slows to a walk");
idCVar pm_staminarate("pm_staminarate", "0.75", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "rate that player regains stamina. divide pm_stamina by this value to determine how long it takes to fully recharge.");
idCVar pm_crouchheight("pm_crouchheight", "38", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "height of player's bounding box while crouched");
idCVar pm_crouchviewheight("pm_crouchviewheight", "32", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "height of player's view while crouched");
idCVar pm_normalheight("pm_normalheight", "74", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "height of player's bounding box while standing");
idCVar pm_normalviewheight("pm_normalviewheight", "68", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "height of player's view while standing");
idCVar pm_deadheight("pm_deadheight", "20", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "height of player's bounding box while dead");
idCVar pm_deadviewheight("pm_deadviewheight", "10", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "height of player's view while dead");
idCVar pm_crouchrate("pm_crouchrate", "0.87", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "time it takes for player's view to change from standing to crouching");
idCVar pm_bboxwidth("pm_bboxwidth", "32", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "x/y size of player's bounding box");
idCVar pm_crouchbob("pm_crouchbob", "0.5", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "bob much faster when crouched");
idCVar pm_walkbob("pm_walkbob", "0.3", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "bob slowly when walking");
idCVar pm_runbob("pm_runbob", "0.4", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "bob faster when running");
idCVar pm_runpitch("pm_runpitch", "0.002", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "");
idCVar pm_runroll("pm_runroll", "0.005", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "");
idCVar pm_bobup("pm_bobup", "0.002", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, ""); // HUMANHEAD: was 0.005
idCVar pm_bobpitch("pm_bobpitch", "0.002", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "");
idCVar pm_bobroll("pm_bobroll", "0.002", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "");
idCVar pm_thirdPersonRange("pm_thirdPersonRange", "80", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "camera distance from player in 3rd person");
idCVar pm_thirdPersonHeight("pm_thirdPersonHeight", "0", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "height of camera from normal view height in 3rd person");
idCVar pm_thirdPersonAngle("pm_thirdPersonAngle", "0", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_FLOAT, "direction of camera from player in 3rd person in degrees (0 = behind player, 180 = in front)");
idCVar pm_thirdPersonClip("pm_thirdPersonClip", "1", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_BOOL, "clip third person view into world space");
idCVar pm_thirdPerson("pm_thirdPerson", "0", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_BOOL, "enables third person view");
idCVar pm_thirdPersonDeath("pm_thirdPersonDeath", "0", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_BOOL, "enables third person view when player dies");
idCVar pm_modelView("pm_modelView", "0", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_INTEGER, "draws camera from POV of player model (1 = always, 2 = when dead)", 0, 2, idCmdSystem::ArgCompletion_Integer<0, 2>);
idCVar pm_airTics("pm_air", "1800", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_INTEGER, "how long in milliseconds the player can go without air before he starts taking damage");
//HUMANHEAD rww
idCVar pm_thirdPersonDeathMP("pm_thirdPersonDeathMP", "1", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_BOOL, "enables third person view when player dies in mp");
//HUMANHEAD END
//HUMANHEAD rww
idCVar g_showAimHealth("g_showAimHealth", "0", CVAR_GAME | CVAR_BOOL, "health display of target (gameplay testing)");
//HUMANHEAD END
idCVar g_showPlayerShadow("g_showPlayerShadow", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "enables shadow of player model");
idCVar g_showHud("g_showHud", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "");
idCVar g_showProjectilePct("g_showProjectilePct", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "enables display of player hit percentage");
idCVar g_showBrass("g_showBrass", "1", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "enables ejected shells from weapon");
idCVar g_gun_x("g_gunX", "0", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_gun_y("g_gunY", "0", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_gun_z("g_gunZ", "0", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_viewNodalX("g_viewNodalX", "0", CVAR_GAME | CVAR_FLOAT, "");
idCVar g_viewNodalZ("g_viewNodalZ", "0", CVAR_GAME | CVAR_FLOAT, "");
// PreyRun Edit BEGIN
/* Original:
idCVar g_fov("g_fov", "90", CVAR_GAME | CVAR_INTEGER | CVAR_NOCHEAT, "");
*/
// Edited Version:
idCVar g_fov("g_fov", "90", CVAR_GAME | CVAR_INTEGER | CVAR_NOCHEAT | CVAR_ARCHIVE, "");
// PreyRun Edit END
idCVar g_skipViewEffects("g_skipViewEffects", "0", CVAR_GAME | CVAR_BOOL, "skip damage and other view effects");
idCVar g_mpWeaponAngleScale("g_mpWeaponAngleScale", "0", CVAR_GAME | CVAR_FLOAT, "Control the weapon sway in MP");
idCVar g_testParticle("g_testParticle", "0", CVAR_GAME | CVAR_INTEGER, "test particle visualation, set by the particle editor");
idCVar g_testParticleName("g_testParticleName", "", CVAR_GAME, "name of the particle being tested by the particle editor");
idCVar g_testModelRotate("g_testModelRotate", "0", CVAR_GAME, "test model rotation speed");
idCVar g_testPostProcess("g_testPostProcess", "", CVAR_GAME, "name of material to draw over screen");
idCVar g_testModelAnimate("g_testModelAnimate", "0", CVAR_GAME | CVAR_INTEGER, "test model animation,\n"
"0 = cycle anim with origin reset\n"
"1 = cycle anim with fixed origin\n"
"2 = cycle anim with continuous origin\n"
"3 = frame by frame with continuous origin\n"
"4 = play anim once", 0, 4, idCmdSystem::ArgCompletion_Integer<0, 4>);
idCVar g_testModelBlend("g_testModelBlend", "0", CVAR_GAME | CVAR_INTEGER, "number of frames to blend");
idCVar g_testDeath("g_testDeath", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_exportMask("g_exportMask", "", CVAR_GAME | CVAR_ARCHIVE, ""); // HUMANHEAD: made archive
idCVar g_flushSave("g_flushSave", "0", CVAR_GAME | CVAR_BOOL, "1 = don't buffer file writing for save games.");
idCVar aas_test("aas_test", "0", CVAR_GAME | CVAR_INTEGER, "");
idCVar aas_showAreas("aas_showAreas", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar aas_showPath("aas_showPath", "0", CVAR_GAME | CVAR_INTEGER, "");
idCVar aas_showFlyPath("aas_showFlyPath", "0", CVAR_GAME | CVAR_INTEGER, "");
idCVar aas_showWallEdges("aas_showWallEdges", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar aas_showHideArea("aas_showHideArea", "0", CVAR_GAME | CVAR_INTEGER, "");
idCVar aas_pullPlayer("aas_pullPlayer", "0", CVAR_GAME | CVAR_INTEGER, "");
idCVar aas_randomPullPlayer("aas_randomPullPlayer", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar aas_goalArea("aas_goalArea", "0", CVAR_GAME | CVAR_INTEGER, "");
idCVar aas_showPushIntoArea("aas_showPushIntoArea", "0", CVAR_GAME | CVAR_BOOL, "");
idCVar g_password("g_password", "", CVAR_GAME | CVAR_ARCHIVE, "game password");
idCVar password("password", "", CVAR_GAME | CVAR_NOCHEAT, "client password used when connecting");
idCVar g_countDown("g_countDown", "10", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "pregame countdown in seconds", 4, 3600);
idCVar g_gameReviewPause("g_gameReviewPause", "10", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_INTEGER | CVAR_ARCHIVE, "scores review time in seconds (at end game)", 2, 3600);
idCVar g_TDMArrows("g_TDMArrows", "1", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_BOOL, "draw arrows over teammates in team deathmatch");
idCVar g_balanceTDM("g_balanceTDM", "1", CVAR_GAME | CVAR_BOOL, "maintain even teams");
idCVar net_clientPredictGUI("net_clientPredictGUI", "1", CVAR_GAME | CVAR_BOOL, "test guis in networking without prediction");
idCVar g_voteFlags("g_voteFlags", "0", CVAR_GAME | CVAR_NETWORKSYNC | CVAR_INTEGER | CVAR_ARCHIVE, "vote flags. bit mask of votes not allowed on this server\n"
"bit 0 (+1) restart now\n"
"bit 1 (+2) time limit\n"
"bit 2 (+4) frag limit\n"
"bit 3 (+8) game type\n"
"bit 4 (+16) kick player\n"
"bit 5 (+32) change map\n"
"bit 6 (+64) spectators\n"
"bit 7 (+128) next map");
idCVar g_mapCycle("g_mapCycle", "mapcycle", CVAR_GAME | CVAR_ARCHIVE, "map cycling script for multiplayer games - see mapcycle.scriptcfg");
// HUMANHEAD pdm: removed
//idCVar mod_validSkins( "mod_validSkins", "skins/characters/player/marine_mp;skins/characters/player/marine_mp_green;skins/characters/player/marine_mp_blue;skins/characters/player/marine_mp_red;skins/characters/player/marine_mp_yellow", CVAR_GAME | CVAR_ARCHIVE, "valid skins for the game" );
idCVar net_serverDownload("net_serverDownload", "0", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "enable server download redirects. 0: off 1: redirect to si_serverURL 2: use builtin download. see net_serverDl cvars for configuration");
idCVar net_serverDlBaseURL("net_serverDlBaseURL", "", CVAR_GAME | CVAR_ARCHIVE, "base URL for the download redirection");
idCVar net_serverDlTable("net_serverDlTable", "", CVAR_GAME | CVAR_ARCHIVE, "pak names for which download is provided, seperated by ;");
| 88.136139 | 299 | 0.757997 | [
"model",
"solid"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.